diff --git a/src/lib/velum-project.ts b/src/lib/velum-project.ts index 30ad43b..05b901e 100644 --- a/src/lib/velum-project.ts +++ b/src/lib/velum-project.ts @@ -12,6 +12,7 @@ export type { ProjectWhitelistEntry } from "./project-whitelist"; export type ProjectRule = { type: "BEGRIFF" | "PERSON" | "ORG" | "ORT" | "FIRMA" | "KUNDE"; value: string }; export type ProjectFile = { relPath: string; absPath: string; kind: "text" | "document"; size: number }; +export type SkippedProjectFile = { path: string; reason: string }; export type RunFile = { source: string; output: string; kind: ProjectFile["kind"] }; export type ProjectRun = { version: 2; @@ -61,6 +62,15 @@ async function isBinary(path: string): Promise { } finally { await file.close(); } } +async function isOfficeArchive(path: string): Promise { + const file = await fs.open(path, "r"); + try { + const header = Buffer.alloc(4); + const { bytesRead } = await file.read(header, 0, header.length, 0); + return bytesRead === 4 && header.equals(Buffer.from([0x50, 0x4b, 0x03, 0x04])); + } finally { await file.close(); } +} + export function projectDataRoot(projectPath: string, support = environment.supportPath): string { return join(support, "velum-projects", projectIdFor(projectPath)); } @@ -176,32 +186,41 @@ export function forceMasks(rules: ProjectRule[]): Record { } export async function scanProjectFiles(root: string, maxSize = 20 * 1024 * 1024): Promise<{ - files: ProjectFile[]; skipped: string[]; + files: ProjectFile[]; skipped: SkippedProjectFile[]; }> { const files: ProjectFile[] = []; - const skipped: string[] = []; + const skipped: SkippedProjectFile[] = []; + const skip = (path: string, reason: string) => skipped.push({ path, reason }); async function walk(directory: string): Promise { for (const entry of await fs.readdir(directory, { withFileTypes: true })) { const path = join(directory, entry.name); const relPath = relative(root, path).split(sep).join("/"); - if (entry.isSymbolicLink()) { skipped.push(relPath); continue; } + if (entry.isSymbolicLink()) { skip(relPath, "Symbolischer Link"); continue; } if (entry.isDirectory()) { - if (EXCLUDES.has(entry.name)) { skipped.push(relPath); continue; } + if (EXCLUDES.has(entry.name)) { skip(relPath, "Ausgeschlossener Ordner"); continue; } await walk(path); continue; } if (!entry.isFile()) continue; + if (entry.name.startsWith("~$") || entry.name.startsWith("._")) { + skip(relPath, "Temporäre Office-/macOS-Datei"); + continue; + } if (entry.name === ".env" || entry.name.startsWith(".env.") || SECRET_EXTENSIONS.has(extname(entry.name).toLowerCase())) { - skipped.push(relPath); + skip(relPath, "Vertraulicher Dateityp"); continue; } const stat = await fs.stat(path); - if (stat.size > maxSize) { skipped.push(relPath); continue; } + if (stat.size > maxSize) { skip(relPath, "Datei zu groß"); continue; } const kind = DOCUMENTS.has(extname(path).toLowerCase()) ? "document" : "text"; + if (kind === "document" && extname(path).toLowerCase() !== ".pdf" && !(await isOfficeArchive(path))) { + skip(relPath, "Kein lesbares Office-ZIP-Archiv (beschädigt, verschlüsselt oder falsche Endung)"); + continue; + } if (kind === "text") { - if (await isBinary(path)) { skipped.push(relPath); continue; } + if (await isBinary(path)) { skip(relPath, "Binärdatei"); continue; } try { new TextDecoder("utf-8", { fatal: true }).decode(await fs.readFile(path)); } - catch { skipped.push(relPath); continue; } + catch { skip(relPath, "Keine gültige UTF-8-Textdatei"); continue; } } files.push({ relPath, absPath: path, kind, size: stat.size }); } diff --git a/src/pseudonymize-project-files.tsx b/src/pseudonymize-project-files.tsx index 8616df9..e12b1d3 100644 --- a/src/pseudonymize-project-files.tsx +++ b/src/pseudonymize-project-files.tsx @@ -12,7 +12,7 @@ import { loadProjectWhitelist, matchesPreviousOutput, replaceProjectFilesInPlace, resolveWithin, safeRelativePath, saveProjectRules, saveProjectEntityTypes, saveProjectWhitelist, saveRun, scanProjectFiles, toUtf16Offsets, whitelistKey, } from "./lib/velum-project"; -import type { ProjectFile, ProjectRule, ProjectWhitelistEntry, RunFile } from "./lib/velum-project"; +import type { ProjectFile, ProjectRule, ProjectWhitelistEntry, RunFile, SkippedProjectFile } from "./lib/velum-project"; import { canonicalPerson, filenameScanText, groupReviewHits, makeTextBatches, mappingForSelection, mergePeople, spansBySegment, withoutPlaceholderHits, withoutWhitelistedHits, withoutWhitelistedRules, @@ -30,7 +30,7 @@ type PathDraft = { key: string; value: string; hits: Hit[] }; type Preview = { drafts: Draft[]; retained: Array<{ file: ProjectFile; hash: string }>; paths: PathDraft[]; mapping: PlaceholderMapping; previousMapping: PlaceholderMapping; matchModes?: Record; hits: Hit[]; entityTypes: EntityType[]; - skipped: number; sourceInPlace: boolean }; + skipped: SkippedProjectFile[]; sourceInPlace: boolean }; const typeLabels: Record = { PERSON: "Personen", ORT: "Orte", ORG: "Organisationen", FIRMA: "Firmen", @@ -66,6 +66,12 @@ function textFromBytes(data: Buffer): string { return new TextDecoder("utf-8", { fatal: true }).decode(data); } +function isUnreadableDocument(error: unknown): boolean { + const message = error instanceof Error ? error.message : ""; + return /request failed: 422\b/i.test(message) + && /konnte nicht gelesen werden|not a zip file|BadZipFile/i.test(message); +} + function contentHits(file: ProjectFile, spans: Array<{ start: number; end: number; type: string; score: number; placeholder: string; original: string; }>, text: string): Hit[] { @@ -96,7 +102,7 @@ function pathSegments(files: ProjectFile[]): PathDraft[] { } async function prepare(root: string, files: ProjectFile[], rules: ProjectRule[], whitelist: ProjectWhitelistEntry[], entityTypes: EntityType[], - skipped: number, onProgress: (message: string) => void): Promise { + skipped: SkippedProjectFile[], onProgress: (message: string) => void): Promise { await requireProjectCapabilities(); const masks = forceMasks(withoutWhitelistedRules(rules, whitelist)); const latestEntry = (await listRuns(root))[0]; @@ -150,13 +156,27 @@ async function prepare(root: string, files: ProjectFile[], rules: ProjectRule[], for (const [index, draft] of documents.entries()) { onProgress(`Dokumente analysieren: ${index + 1}/${documents.length}`); const data = await fs.readFile(draft.file.absPath); - const result = await pseudonymizeDocument(basename(draft.file.relPath), data, mapping, masks, undefined, entityTypes); - mapping = result.mapping; - addHits(draft, documentHits(draft.file, result.hits)); + try { + const result = await pseudonymizeDocument(basename(draft.file.relPath), data, mapping, masks, undefined, entityTypes); + mapping = result.mapping; + addHits(draft, documentHits(draft.file, result.hits)); + } catch (error) { + if (!isUnreadableDocument(error)) { + throw new Error(`${draft.file.relPath}: ${error instanceof Error ? error.message : String(error)}`); + } + skipped.push({ path: draft.file.relPath, reason: "Office-/PDF-Inhalt konnte nicht gelesen werden" }); + drafts.splice(drafts.indexOf(draft), 1); + draftsByPath.delete(draft.file.relPath); + } } // Recheck names even when an in-place file's contents are unchanged. An // earlier run may have masked the content but left the filename clear. - const paths = pathSegments(files); + const eligibleFiles = [...drafts.map((draft) => draft.file), ...retained.map((item) => item.file)]; + if (!eligibleFiles.length) { + const first = skipped[0]; + throw new Error(`Keine lesbaren Dateien im Projektordner gefunden.${first ? ` Übersprungen: ${first.path} (${first.reason}).` : ""}`); + } + const paths = pathSegments(eligibleFiles); const knownTerms = [...Object.keys(mapping), ...Object.values(mapping).map((entry) => entry.original), ...withoutWhitelistedRules(rules, whitelist).map((rule) => rule.value)]; const pathBatches = makeTextBatches(paths.map((path) => ({ @@ -427,12 +447,19 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje setStage("merge")} /> } /> + {props.preview.skipped.length > 0 && + } />} /> + } {[...byType].map(([type, entries]) => selectedGroups.has(entry.key)).length}/${entries.length}`}> {entries.map((group) => ; } +function SkippedFiles(props: { files: SkippedProjectFile[] }) { + return + + {props.files.map((file) => )} + + ; +} + export default function Command() { const { push } = useNavigation(); const [root, setRoot] = useState(""); @@ -556,9 +591,12 @@ export default function Command() { await saveProjectRules(root, parsed); toast.title = "Dateien werden erfasst"; const scan = await scanProjectFiles(root); - if (!scan.files.length) throw new Error("Keine geeigneten Dateien im Projektordner gefunden."); + if (!scan.files.length) { + const first = scan.skipped[0]; + throw new Error(`Keine geeigneten Dateien im Projektordner gefunden.${first ? ` Übersprungen: ${first.path} (${first.reason}).` : ""}`); + } const currentWhitelist = await loadProjectWhitelist(root); - const preview = await prepare(root, scan.files, parsed, currentWhitelist, selectedTypes, scan.skipped.length, + const preview = await prepare(root, scan.files, parsed, currentWhitelist, selectedTypes, scan.skipped, (message) => { toast.title = message; }); toast.style = Toast.Style.Success; toast.title = `${groupReviewHits(preview.hits).length} Zuordnungen zur Prüfung`; diff --git a/tests/velum-project.test.ts b/tests/velum-project.test.ts index 6f48615..4bffbfb 100644 --- a/tests/velum-project.test.ts +++ b/tests/velum-project.test.ts @@ -99,6 +99,24 @@ describe("Velum-Projektstände", () => { expect(await project.loadProjectEntityTypes(other, support)).toBeNull(); }); + it("überspringt temporäre und falsch benannte Office-Dateien vor der API-Analyse", async () => { + const root = await fs.mkdtemp(join(tmpdir(), "velum-office-scan-test-")); + roots.push(root); + await fs.writeFile(join(root, "Notiz.txt"), "Nur ein künstlicher Testtext"); + await fs.writeFile(join(root, "Bericht.xlsx"), "Kein Excel-Archiv"); + await fs.writeFile(join(root, "~$Entwurf.xlsx"), "Sperrdatei"); + await fs.writeFile(join(root, "._Tabelle.xlsx"), "AppleDouble"); + await fs.writeFile(join(root, "Gültig.xlsx"), Buffer.from([0x50, 0x4b, 0x03, 0x04, 0x00])); + + const scan = await project.scanProjectFiles(root); + expect(scan.files.map((file) => file.relPath)).toEqual(["Gültig.xlsx", "Notiz.txt"]); + expect(scan.skipped).toEqual(expect.arrayContaining([ + { path: "Bericht.xlsx", reason: expect.stringContaining("Office-ZIP-Archiv") }, + { path: "~$Entwurf.xlsx", reason: "Temporäre Office-/macOS-Datei" }, + { path: "._Tabelle.xlsx", reason: "Temporäre Office-/macOS-Datei" }, + ])); + }); + it("stellt aktuelle In-Place-Dateien aus dem Projektordner und frühere Stände aus dem Snapshot bereit", async () => { const root = await fs.mkdtemp(join(tmpdir(), "velum-current-source-test-")); roots.push(root);