From 4591ead8c810bd87fdcabffd0688b3ccf0485fff Mon Sep 17 00:00:00 2001 From: muena Date: Mon, 30 Nov 2026 16:11:44 +0100 Subject: [PATCH] feat: add standalone document pseudonymization to Raycast --- README.md | 36 +++- package.json | 12 +- src/document-result.tsx | 53 +++++ src/documents.ts | 180 +++++++++++++++++ src/pseudonymize-text.tsx | 147 ++++++++++++-- src/summarize-meeting-notes.tsx | 335 ++++++++++++++++++++++++++++++++ src/types.ts | 16 ++ src/velum.ts | 31 +++ tests/documents.test.cjs | 259 ++++++++++++++++++++++++ 9 files changed, 1050 insertions(+), 19 deletions(-) create mode 100644 src/document-result.tsx create mode 100644 src/documents.ts create mode 100644 src/summarize-meeting-notes.tsx create mode 100644 tests/documents.test.cjs diff --git a/README.md b/README.md index 93d55d9..946bab1 100644 --- a/README.md +++ b/README.md @@ -40,10 +40,36 @@ Jeder AI-Befehl pseudonymisiert die Eingabe via Velum, zeigt einen Confirm-Schri ### Pseudonymisieren -- `Text pseudonymisieren` (View) — Text manuell eingeben, Sitzung und Entitätstypen wählen, Mapping inspizieren. +- `Text oder Dokument pseudonymisieren` (View) — Text manuell eingeben oder ein Office-/PDF-Dokument auswählen, Sitzung und Entitätstypen wählen, Mapping inspizieren. - `Markierten Text pseudonymisieren` (No-View) — Schnellbefehl: aktuelle Selektion wird pseudonymisiert und je nach Preference kopiert oder eingefügt. - `Zwischenablage pseudonymisieren` (No-View) — analog für den Zwischenablage-Inhalt. +Im View-Befehl unter **Eingabe → Office-Dokument oder PDF** sind DOCX, XLSX, PPTX +und PDF bis 20 MiB auswählbar. Die Bildauswahl gilt pro Aufruf: + +- **Datenschutz-Platzhalter** (`placeholder`) ist der Standard bei jedem neuen Aufruf. +- **Bilder vollständig entfernen** (`remove`) entfernt die Bildobjekte. +- **Bilder behalten** (`keep`) übernimmt Office-Bilder unverändert und zeigt vor dem + Aufruf sowie im Ergebnis einen deutlichen Datenschutz-Warnhinweis. + +Die Bildbehandlung erfolgt ausschließlich im Velum-Backend, ohne OCR oder zusätzliche +Modelle. Bei Platzhaltern bleiben Position und Größe soweit unterstützt erhalten. +PDF wird als Word-Dokument neu aufgebaut; dort bleiben Bildpositionen nicht erhalten. +Nicht sicher bereinigbare Inhalte werden abgewiesen. Entfernte Bilder lassen sich +mit dem Mapping nicht wiederherstellen. + +Das Ergebnis zeigt Bildzähler und sämtliche Backend-Warnungen. Die Zuordnung wird in +der gewählten Velum-Sitzung gespeichert. Die verarbeitete Kopie liegt im gewählten +Ausgabeordner oder standardmäßig neben dem Original und lässt sich im Finder anzeigen +oder öffnen. Vorhandene Dateien werden niemals überschrieben; Namenskollisionen +erhalten einen nummerierten Zusatz. + +Dieser Flow benötigt ein Backend mit `document_image_policy: true` unter +`/api/project-capabilities`. Die Extension übermittelt `image_policy` explizit an +`/api/pseudonymize-document` und prüft dessen Bestätigung. Ältere Backends werden vor +dem Upload abgewiesen. Es gibt keinen automatischen Rückfall auf einen Textaufruf +oder unbereinigte Bilder. Die Schnellbefehle verarbeiten weiterhin Text. + ### Wiederherstellen - `Text wiederherstellen` (View) — Platzhalter-Text und Sitzung wählen, Originale per Velum oder lokal einsetzen. @@ -78,7 +104,13 @@ Die Extension läuft auf der stabilen Raycast-Version sowie der 2.0 Beta. Für d npm install npm run dev # ray develop — live reload, lädt die Extension in den lokalen Raycast npm run lint -npm run build # ray build -e dist +npm run build # ray build -e dist -o dist: erzeugt nur lokale Artefakte +node --test tests/*.test.cjs # Dokumenttransport, Bildoptionen, sichere Dateiausgabe ``` Voraussetzungen: macOS, Node 22+, Raycast (Pro für die AI-Befehle). + +`build` schreibt ausdrücklich in `dist/` und ersetzt keine installierte Extension. +Raycasts CLI verwendet ohne `-o` standardmäßig den gemeinsamen Installationsordner +der Extension `velum`; bei mehreren Checkouts können dadurch Befehle einer anderen +Velum-Version verschwinden. `dev` aktualisiert die Installation bewusst. diff --git a/package.json b/package.json index d880918..2bfe73e 100644 --- a/package.json +++ b/package.json @@ -29,6 +29,12 @@ "description": "Aus Notizen, Stichpunkten oder einem Transkript ein strukturiertes Briefing per Raycast-KI erstellen — pseudonymisiert.", "mode": "view" }, + { + "name": "summarize-meeting-notes", + "title": "Meeting Notes strukturieren", + "description": "Aus Meeting-Notizen in Prosa eine sauber strukturierte Zusammenfassung (Kontext, Teilnehmer, Themen, Entscheidungen, Action Items) per Raycast-KI erstellen — pseudonymisiert.", + "mode": "view" + }, { "name": "extract-action-items", "title": "Action Items extrahieren", @@ -49,8 +55,8 @@ }, { "name": "pseudonymize-text", - "title": "Text pseudonymisieren", - "description": "Eingegebenen, markierten oder Zwischenablage-Text pseudonymisieren.", + "title": "Text oder Dokument pseudonymisieren", + "description": "Text oder Office-/PDF-Dokumente pseudonymisieren, mit wählbarer Bildbehandlung.", "mode": "view" }, { @@ -203,7 +209,7 @@ } ], "scripts": { - "build": "ray build -e dist", + "build": "ray build -e dist -o dist", "dev": "ray develop", "fix-lint": "ray lint --fix", "lint": "ray lint", diff --git a/src/document-result.tsx b/src/document-result.tsx new file mode 100644 index 0000000..3c3f6c0 --- /dev/null +++ b/src/document-result.tsx @@ -0,0 +1,53 @@ +import { Action, ActionPanel, Detail } from "@raycast/api"; +import type { PseudonymizeDocumentResponse, VelumSession } from "./types"; +import { markdownCodeBlock, mappingSummary, sessionSubtitle } from "./ui"; + +export function DocumentResult({ + result, + session, + path, +}: { + result: PseudonymizeDocumentResponse; + session: VelumSession; + path: string; +}) { + const warnings = result.warnings.flatMap((warning) => [ + "> " + warning.replace(/\n/g, "\n> "), + "", + ]); + return ( + + + + + + } + /> + ); +} diff --git a/src/documents.ts b/src/documents.ts new file mode 100644 index 0000000..6cbea43 --- /dev/null +++ b/src/documents.ts @@ -0,0 +1,180 @@ +import { File } from "node:buffer"; +import { link, mkdtemp, open, rm, writeFile } from "node:fs/promises"; +import { basename, extname, join, parse, win32 } from "node:path"; +import type { + ImagePolicy, + PlaceholderMapping, + PseudonymizeDocumentResponse, +} from "./types"; + +export const DOCUMENT_TYPES: Record = { + ".docx": + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + ".pptx": + "application/vnd.openxmlformats-officedocument.presentationml.presentation", + ".pdf": "application/pdf", +}; +export const KEEP_IMAGE_WARNING = + "Achtung: Bilder wurden unverändert übernommen und können sensible Informationen enthalten. Bildinhalte werden nicht auf personenbezogene Daten geprüft."; +const MAX_UPLOAD_BYTES = 20 * 1024 * 1024; +const MAX_OUTPUT_BYTES = 128 * 1024 * 1024; + +export async function documentForm( + filePath: string, + mapping: PlaceholderMapping, + entityTypes?: string[], + imagePolicy: ImagePolicy = "placeholder", +): Promise { + if (!["placeholder", "remove", "keep"].includes(imagePolicy)) { + throw new Error("Ungültige Bildbehandlung."); + } + const type = DOCUMENT_TYPES[extname(filePath).toLowerCase()]; + if (!type) + throw new Error("Bitte eine DOCX-, XLSX-, PPTX- oder PDF-Datei auswählen."); + const source = await open(filePath, "r"); + try { + const stat = await source.stat(); + if (!stat.isFile() || stat.size === 0) + throw new Error("Bitte eine nicht leere Datei auswählen."); + if (stat.size > MAX_UPLOAD_BYTES) + throw new Error("Datei zu groß (maximal 20 MiB)."); + const data = await source.readFile(); + if (!data.length || data.length > MAX_UPLOAD_BYTES) + throw new Error("Datei ist leer oder zu groß."); + const form = new FormData(); + form.append("file", new File([data], basename(filePath), { type })); + form.append("mapping", JSON.stringify(mapping)); + if (entityTypes !== undefined) + form.append("entity_types", JSON.stringify(entityTypes)); + form.append("image_policy", imagePolicy); + return form; + } finally { + await source.close(); + } +} + +function documentBytes(result: PseudonymizeDocumentResponse): Buffer { + const name = result.filename; + const extension = typeof name === "string" ? extname(name).toLowerCase() : ""; + if ( + typeof name !== "string" || + !name || + name !== basename(name) || + name !== win32.basename(name) || + [...name].some( + (character) => + character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127, + ) || + extension === ".pdf" || + !DOCUMENT_TYPES[extension] || + result.content_type !== DOCUMENT_TYPES[extension] + ) { + throw new Error( + "Backend hat einen ungültigen Office-Dateinamen oder Dateityp geliefert.", + ); + } + const encoded = result.file_base64; + if ( + typeof encoded !== "string" || + !encoded || + encoded.length > Math.ceil(MAX_OUTPUT_BYTES / 3) * 4 || + encoded.length % 4 !== 0 || + !/^[A-Za-z0-9+/]*={0,2}$/.test(encoded) + ) { + throw new Error("Backend hat ungültige Dokumentdaten geliefert."); + } + const data = Buffer.from(encoded, "base64"); + if ( + data.length > MAX_OUTPUT_BYTES || + data.toString("base64") !== encoded || + !data.subarray(0, 4).equals(Buffer.from("PK\x03\x04", "binary")) + ) { + throw new Error("Backend hat kein lesbares Office-Paket geliefert."); + } + return data; +} + +export function validateDocumentResponse( + result: PseudonymizeDocumentResponse, + requestedPolicy: ImagePolicy, +): PseudonymizeDocumentResponse { + if (!result || result.image_policy !== requestedPolicy) { + throw new Error( + "Das Backend bestätigt die gewählte Bildbehandlung nicht. Bitte Velum aktualisieren.", + ); + } + for (const count of [ + result.entity_count, + result.segment_count, + result.images_replaced, + result.images_removed, + result.media_parts_removed, + ]) { + if (!Number.isSafeInteger(count) || count < 0) + throw new Error( + "Backend hat keine gültigen Dokument- und Bildzähler geliefert.", + ); + } + if ( + !Array.isArray(result.warnings) || + result.warnings.some((item) => typeof item !== "string") + ) { + throw new Error("Backend hat keine gültigen Bildwarnungen geliefert."); + } + if ( + !result.mapping || + typeof result.mapping !== "object" || + Array.isArray(result.mapping) || + Object.values(result.mapping).some( + (entry) => + !entry || + typeof entry.original !== "string" || + typeof entry.type !== "string", + ) + ) { + throw new Error("Backend hat keine gültige Zuordnung geliefert."); + } + documentBytes(result); + return { + ...result, + warnings: + requestedPolicy === "keep" && + !result.warnings.includes(KEEP_IMAGE_WARNING) + ? [KEEP_IMAGE_WARNING, ...result.warnings] + : result.warnings, + }; +} + +/** Never overwrite the input or an earlier export, even across concurrent runs. */ +export async function saveDocumentCopy( + result: PseudonymizeDocumentResponse, + outputDirectory: string, +): Promise { + const data = documentBytes(result); + const { name, ext } = parse(result.filename); + const temporaryDirectory = await mkdtemp(join(outputDirectory, ".velum-")); + try { + const temporaryFile = join(temporaryDirectory, "document"); + await writeFile(temporaryFile, data, { flag: "wx", mode: 0o600 }); + for (let index = 0; index < 1000; index++) { + const path = join( + outputDirectory, + index ? `${name} (${index})${ext}` : result.filename, + ); + try { + // Publish the finished file atomically and exclusively. An interrupted + // write cannot leave a truncated final document or replace an original. + await link(temporaryFile, path); + return path; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + } + } + throw new Error( + "Zu viele gleichnamige Ausgabedateien. Bitte einen anderen Ausgabeordner wählen.", + ); + } finally { + await rm(temporaryDirectory, { recursive: true, force: true }); + } +} diff --git a/src/pseudonymize-text.tsx b/src/pseudonymize-text.tsx index 6b7ab04..2be927e 100644 --- a/src/pseudonymize-text.tsx +++ b/src/pseudonymize-text.tsx @@ -11,6 +11,9 @@ import { } from "@raycast/api"; import { getSelectedTextSafely } from "./selection"; import { useEffect, useMemo, useState } from "react"; +import { dirname } from "node:path"; +import { DocumentResult } from "./document-result"; +import { saveDocumentCopy } from "./documents"; import { createSession, getActiveSessionId, @@ -19,23 +22,36 @@ import { setActiveSession, updateSessionMapping, } from "./sessions"; -import type { EntityType, PseudonymizeResponse, VelumSession } from "./types"; +import type { + EntityType, + ImagePolicy, + PseudonymizeResponse, + VelumSession, +} from "./types"; import { markdownCodeBlock, mappingSummary, NEW_SESSION_ID, sessionSubtitle, } from "./ui"; -import { getEntityTypes, pseudonymize } from "./velum"; +import { getEntityTypes, pseudonymize, pseudonymizeDocument } from "./velum"; type FormValues = { - text: string; + text?: string; + inputMode: "text" | "document"; + files?: string[]; + outputDirectory?: string[]; + imagePolicy?: ImagePolicy; sessionId: string; entityTypes: string[]; }; export default function Command() { const [text, setText] = useState(""); + const [inputMode, setInputMode] = useState("text"); + const [imagePolicy, setImagePolicy] = useState("placeholder"); + const [files, setFiles] = useState([]); + const [isSubmitting, setIsSubmitting] = useState(false); const [sessions, setSessions] = useState([]); const [activeSessionId, setActiveSessionId] = useState(); const [entityTypes, setEntityTypes] = useState([]); @@ -79,6 +95,7 @@ export default function Command() { }); return; } + setInputMode("text"); setText(selected); } @@ -91,19 +108,26 @@ export default function Command() { }); return; } + setInputMode("text"); setText(clipboardText); } async function handleSubmit(values: FormValues) { - const input = values.text.trim(); - if (!input) { + if (isSubmitting || isLoading) return; + const isDocument = values.inputMode === "document"; + const input = (values.text ?? "").trim(); + const filePath = values.files?.[0]; + if (isDocument ? !filePath : !input) { await showToast({ style: Toast.Style.Failure, - title: "Text zum Pseudonymisieren eingeben", + title: isDocument + ? "Dokument zum Pseudonymisieren auswählen" + : "Text zum Pseudonymisieren eingeben", }); return; } + setIsSubmitting(true); const toast = await showToast({ style: Toast.Style.Animated, title: "Pseudonymisiere…", @@ -115,6 +139,36 @@ export default function Command() { ? await createSession() : ((await getSession(values.sessionId)) ?? (await createSession())); await setActiveSession(session.id); + if (isDocument && filePath) { + const result = await pseudonymizeDocument( + filePath, + session.mapping, + values.entityTypes, + values.imagePolicy ?? "placeholder", + ); + const updatedSession = await updateSessionMapping( + session.id, + result.mapping, + values.entityTypes, + ); + const path = await saveDocumentCopy( + result, + values.outputDirectory?.[0] ?? dirname(filePath), + ); + toast.style = Toast.Style.Success; + toast.title = result.warnings.length + ? "Dokument mit Warnhinweis bereit" + : "Dokument pseudonymisiert"; + toast.message = `${result.images_replaced} Bilder ersetzt · ${result.images_removed} entfernt`; + push( + , + ); + return; + } const result = await pseudonymize( input, session.mapping, @@ -135,12 +189,14 @@ export default function Command() { toast.style = Toast.Style.Failure; toast.title = "Pseudonymisierung fehlgeschlagen"; toast.message = error instanceof Error ? error.message : String(error); + } finally { + setIsSubmitting(false); } } return (
} > - + + + + + {inputMode === "text" ? ( + + ) : ( + <> + + + setImagePolicy(value as ImagePolicy)} + > + + + + + + + + + )} , , , ersetzt.", + "", + STRICT_PLACEHOLDER_RULE, + "", + "Aufgabe: Verwandle den Fließtext in eine SAUBER STRUKTURIERTE, deutschsprachige Meeting-Zusammenfassung in Markdown.", + "Ziehe Struktur, Verantwortlichkeiten, Entscheidungen und Aufgaben aus der Prosa heraus — verdichte, ohne Inhalte zu erfinden.", + "", + "Verwende GENAU diese Abschnitte in dieser Reihenfolge:", + "", + "## Kontext", + "Ein kurzer Absatz (2–4 Sätze): Worum ging es im Meeting, Anlass, Rahmen. Datum/Ort nur, wenn aus dem Text ableitbar (sonst weglassen).", + "", + "## Teilnehmer", + "- Stichpunktliste der beteiligten Platzhalter, jeweils mit Rolle/Funktion (falls aus dem Text ableitbar).", + "- Format pro Zeile: `- — Rolle/Funktion`", + "", + "## Themen & Diskussion", + "Pro behandeltem Thema ein eigener Unter-Absatz:", + "### ", + "Ein kurzer Absatz (2–5 Sätze), der Kernaussagen, Positionen und Argumente verdichtet. Wer hat was gesagt — nur wenn relevant. Keine wörtlichen Zitate, außer sie sind im Quelltext markiert.", + "", + "## Entscheidungen", + "- Eine Stichpunktliste mit jeweils einer klar formulierten Entscheidung pro Zeile.", + "- Nur tatsächlich getroffene Entscheidungen; keine Vorschläge oder Überlegungen.", + "", + "## Action Items", + "Markdown-Tabelle mit GENAU dieser Kopfzeile:", + "| Aufgabe | Verantwortlich | Deadline | Status |", + "| --- | --- | --- | --- |", + "- Status MUSS gesetzt sein, genau einer von: „offen“, „abgeschlossen“. „abgeschlossen“ nur wenn der Text die Erledigung explizit beschreibt.", + "- Verantwortlich als Platzhalter (z. B. ); wenn nicht ableitbar: „—“.", + "- Deadline nur, wenn ein konkretes Datum/Zeitraum genannt ist; sonst leer lassen. Niemals Deadlines erfinden.", + "- Wenn keine Action Items vorkommen, schreibe stattdessen die einzelne Zeile: „Keine Action Items.“", + "", + "## Offene Punkte", + "- Stichpunktliste der Themen, die NICHT abschließend geklärt wurden bzw. Klärungsbedarf haben.", + "", + "## Nächste Schritte", + "Ein kurzer Absatz (1–3 Sätze): Wie geht es nach diesem Meeting weiter? Nur wenn aus dem Text ableitbar.", + "", + "Regeln:", + 'Wenn ein Abschnitt im Text nicht vorkommt, schreibe „—" als einzigen Inhalt darunter.', + "Nichts erfinden, nichts ausschmücken — strikt am Quelltext bleiben.", + "Antworte ausschließlich in Markdown, ohne einleitende Floskeln und ohne umschließende Code-Fences (keine ``` Zeilen am Anfang oder Ende).", + extra, + "", + "--- Meeting-Notizen (pseudonymisiert, Prosa) ---", + pseudonymizedText, + "--- Ende ---", + ].join("\n"); +} + +type FormValues = { + text: string; + sessionId: string; + entityTypes: string[]; + model: string; + creativity: Creativity; + instructions: string; +}; + +export default function Command() { + const [text, setText] = useState(""); + const [sessions, setSessions] = useState([]); + const [activeSessionId, setActiveSessionId] = useState(); + const [entityTypes, setEntityTypes] = useState([]); + const [selectedEntityTypes, setSelectedEntityTypes] = useState([]); + const [model, setModel] = useState(DEFAULT_MODEL); + const [isLoading, setIsLoading] = useState(true); + const { push } = useNavigation(); + + useEffect(() => { + async function load() { + const [loadedSessions, activeId, lastModel] = await Promise.all([ + listSessions(), + getActiveSessionId(), + getLastUsedModel(), + ]); + setSessions(loadedSessions); + setActiveSessionId(activeId); + setModel(lastModel); + + const selection = await getSelectedTextSafely(); + if (selection && selection.trim()) { + setText(selection); + } + + try { + const loadedEntityTypes = await getEntityTypes(); + setEntityTypes(loadedEntityTypes); + setSelectedEntityTypes(loadedEntityTypes); + } catch { + setEntityTypes([]); + } finally { + setIsLoading(false); + } + } + load(); + }, []); + + const defaultSessionId = useMemo( + () => activeSessionId || sessions[0]?.id || NEW_SESSION_ID, + [activeSessionId, sessions], + ); + + async function loadSelectedText() { + const selected = await getSelectedTextSafely(); + if (!selected) { + await showToast({ + style: Toast.Style.Failure, + title: "Kein markierter Text gefunden", + }); + return; + } + setText(selected); + } + + async function loadClipboardText() { + const clipboardText = await Clipboard.readText(); + if (!clipboardText) { + await showToast({ + style: Toast.Style.Failure, + title: "Zwischenablage enthält keinen Text", + }); + return; + } + setText(clipboardText); + } + + async function handleSubmit(values: FormValues) { + const input = values.text.trim(); + if (!input) { + await showToast({ + style: Toast.Style.Failure, + title: "Meeting-Notizen eingeben", + }); + return; + } + + void setLastUsedModel(values.model); + + const toast = await showToast({ + style: Toast.Style.Animated, + title: "Pseudonymisiere…", + }); + + try { + const session = + values.sessionId === NEW_SESSION_ID + ? await createSession() + : ((await getSession(values.sessionId)) ?? (await createSession())); + await setActiveSession(session.id); + + const rawResult = await pseudonymize( + input, + session.mapping, + values.entityTypes, + ); + const pseudoResult = normalizePseudonymizeResponse(rawResult); + const updatedSession = await updateSessionMapping( + session.id, + pseudoResult.mapping, + pseudoResult.selected_entity_types, + ); + + toast.style = Toast.Style.Success; + toast.title = "Pseudonymisiert"; + toast.message = `${pseudoResult.entity_count} Zuordnungen`; + + push( + , + ); + } catch (error) { + toast.style = Toast.Style.Failure; + toast.title = "Pseudonymisierung fehlgeschlagen"; + toast.message = error instanceof Error ? error.message : String(error); + } + } + + return ( + + + + + + } + > + + + + {sessions.map((session) => ( + + ))} + + {entityTypes.length > 0 ? ( + + {entityTypes.map((entityType) => ( + + ))} + + ) : null} + + {MODEL_OPTIONS.map((option) => ( + + ))} + + + {CREATIVITY_OPTIONS.map((value) => ( + + ))} + + + + ); +} diff --git a/src/types.ts b/src/types.ts index 8362e55..90dd1eb 100644 --- a/src/types.ts +++ b/src/types.ts @@ -27,6 +27,22 @@ export type DepseudonymizeResponse = { replacements_made: number; }; +export type ImagePolicy = "placeholder" | "remove" | "keep"; + +export type PseudonymizeDocumentResponse = { + filename: string; + content_type: string; + file_base64: string; + mapping: PlaceholderMapping; + entity_count: number; + segment_count: number; + image_policy: ImagePolicy; + images_replaced: number; + images_removed: number; + media_parts_removed: number; + warnings: string[]; +}; + export type VelumSession = { id: string; name: string; diff --git a/src/velum.ts b/src/velum.ts index d8b8681..2fc270b 100644 --- a/src/velum.ts +++ b/src/velum.ts @@ -1,10 +1,13 @@ import { fetchWithAuth } from "./auth"; import { getPreferences } from "./preferences"; +import { documentForm, validateDocumentResponse } from "./documents"; import type { DepseudonymizeResponse, EntityType, PlaceholderMapping, PseudonymizeResponse, + ImagePolicy, + PseudonymizeDocumentResponse, } from "./types"; function escapeRegExp(value: string): string { @@ -142,3 +145,31 @@ export async function depseudonymize( return parseJsonResponse(response); } + +export async function pseudonymizeDocument( + filePath: string, + mapping: PlaceholderMapping, + entityTypes?: EntityType[], + imagePolicy: ImagePolicy = "placeholder", +): Promise { + const capabilitiesResponse = await fetchWithAuth( + apiUrl("/api/project-capabilities"), + ); + const capabilities = await parseJsonResponse<{ + document_image_policy?: boolean; + }>(capabilitiesResponse); + if (capabilities.document_image_policy !== true) { + throw new Error( + "Das Backend unterstützt die Bildbehandlung noch nicht. Bitte Velum aktualisieren.", + ); + } + const body = await documentForm(filePath, mapping, entityTypes, imagePolicy); + const response = await fetchWithAuth(apiUrl("/api/pseudonymize-document"), { + method: "POST", + body, + }); + return validateDocumentResponse( + await parseJsonResponse(response), + imagePolicy, + ); +} diff --git a/tests/documents.test.cjs b/tests/documents.test.cjs new file mode 100644 index 0000000..8d6401e --- /dev/null +++ b/tests/documents.test.cjs @@ -0,0 +1,259 @@ +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", + ]); +});