[208] Anonymitäts-Tor an allen Export-Einstiegen: Berichte, Bild-/Rendering-Exporte, CLI (--ignore-anonymity), KI-Export; Dateiname nach Wiederherstellen

This commit is contained in:
Claude committed 2026-11-14 08:31:00 +00:00
1 parent 7954ab647f
commit be000985ed
21 files changed
+260 -59

No files matched your search

+10 -3
View File
@@ -223,9 +223,16 @@ Kennwort, anonym) als PDF; Austausch mit Fachplanern über DXF/IFC.
Einzelwort ab 5 Zeichen, allgemeine Wörter („Haus“, „Wohnen“ …) und blosse Zahlen zählen nicht. Dialog `ui/AnonymityDialog.tsx` listet Bereich,
Fundstelle, Text, Begriff; „Trotzdem exportieren“ / „Abbrechen“ (Overlay, kein `window.confirm`). Kopfdaten waren schon leer (PDF-Info nur Kennwort,
Producer/Datum neutralisiert — auch „Dossier“ bleibt weg, weil Programm + Version + Datum die Herkunft eingrenzen; IFC-Kopf/IfcOwnerHistory, DXF-Kopf, STEP):
keine Lücke gefunden. Tests: Rust `competition` (Treffer je Textort, Fehlalarme, Umlaute), vitest `competitionCheck`, e2e `competition`. Offen: Berichte-PDF
(Flächen, Raumbuch …) und Bild-/Rendering-Exporte laufen nicht durch das Tor; Prüfung läuft nur im Dialog-Weg (CLI/KI-Werkzeuge nicht); der
Dateiname der Ausgabe wird nur beim Direkt-Export geprüft; nicht in der Tauri-App/auf dem Mac geprüft.
keine Lücke gefunden. Tests: Rust `competition` (Treffer je Textort, Fehlalarme, Umlaute), vitest `competitionCheck`, e2e `competition`. **Nachtrag (14.11., spät)**: das Tor
hängt jetzt an allen Export-Einstiegen der Oberfläche: Berichte (Fläche, Raumbuch, Kosten, Öffnungen, Bauteile, Programm, Flächenbilanz) als CSV und PDF,
3D-Bild-PNG, Rendering (PNG, .blend, Blender-Paket), Kamerafahrt-Video, Layout-Ordner-PDF, KI-Werkzeug-Speichern; `runWithAnonymityGate` für
Knopf-Handler, Dateiname der Ausgabe wird mitgeprüft. Bild-/Video-/Rendering-Dateinamen nutzen jetzt den Kennwort-Namen (`exportProjectName`)
statt `project.name`. Vitest `state/anonymityGate.entries.test.ts` gleicht ab: jede Oberflächen-Datei mit Datei-Ausgabe ruft das Tor auf
(neue Einstiege fallen dort auf). CLI: bei anonymer Abgabe prüfen plan/section/elevation/dxf/dwg/ifc/obj/stl/glb/gltf/step/schedule/kennzahlen/
raumprogramm/render/blend/model3d den Freitext, Treffer auf stderr, Exit-Code 3, `--ignore-anonymity` übergeht (Test in `cli.test.ts`);
KI-/MCP-Werkzeug `export` ohne `save` liefert bei Treffern nichts aus (Argument `ignoreAnonymity`). Der Projekt-Dateiname ist auch nach
Autosave-Wiederherstellen und Browser-/Electron-Start-Öffnen Suchbegriff, beim „Neu“ wird er gelöscht. Offen: `dossier-cli convert` prüft nicht;
BCF-Export bewusst ohne Tor; nicht in der Tauri-App/auf dem Mac geprüft (Dialog-Weg nur per Code-Abgleich, kein e2e für die neuen Knöpfe).
- [61] Raumprogramm gegen Modell und Flächennachweis SIA 416 als Tabelle/Layout-Element ([70]); Kennzahlen (GF, GV, HNF/GF, Fassadenanteil).
- 3D-Bilder für die Abgabe: hochaufgelöster PNG-Export (Perspektive, Axonometrie, Schatten), Sonnenstand; [205] Pausfolie.
- [199]/[204] Plan- und App-Review-Reste im Darstellungsbereich 1:500/1:200 schliessen.
+25
View File
@@ -52,6 +52,31 @@ describe("dossier-cli", () => {
expect(await run([broken, "plan", "--out", join(dir, "haengend.svg")])).toBe(0);
});
it("anonyme Abgabe: Export prüft den Freitext, Treffer brechen ab, --ignore-anonymity übergeht ([208])", async () => {
const anon = join(dir, "seeblick-meierhofer.obp");
const p = {
...sampleProject,
name: "Seeblick Meierhofer",
competition: { anonymous: true, keyword: "FALKE 7", identifiers: "" },
rooms: [{ ...sampleProject.rooms![0], name: "Büro Seeblick Meierhofer" }, ...sampleProject.rooms!.slice(1)],
};
writeFileSync(anon, serializeProject(p as typeof sampleProject));
const err = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
try {
const target = join(dir, "anon.svg");
expect(await run([anon, "plan", "--out", target])).toBe(3);
expect(existsSync(target)).toBe(false);
expect(err.mock.calls.map((c) => String(c[0])).join("")).toContain("Anonyme Abgabe");
expect(await run([anon, "info"])).toBe(0); // kein Export
expect(await run([anon, "plan", "--out", target, "--ignore-anonymity"])).toBe(0);
expect(existsSync(target)).toBe(true);
} finally {
err.mockRestore();
}
// Nicht anonym: keine Prüfung.
expect(await run([file, "plan", "--out", join(dir, "nicht-anon.svg")])).toBe(0);
});
it("Plan als SVG", async () => {
const out = join(dir, "eg.svg");
expect(await call("plan", "--out", out)).toBe(0);
+31 -1
View File
@@ -101,6 +101,8 @@ import {
areaReportToSvg,
buildAreaReportPdf,
exportProjectName,
isAnonymous,
anonymityFindings,
sunPosition,
shadowPolygons,
projectLatLon,
@@ -476,7 +478,8 @@ export async function run(argv: string[]): Promise<number> {
" dossier-cli pointcloud-info <datei> [--voxel 0.05] [--max 2000000]\n" +
" dossier-cli bcf-info <datei.bcfzip>\n" +
" dossier-cli pdf-info <datei.pdf> [--page 1]\n" +
" dossier-cli mcp --app [--port 7979] [--token schlüssel] (MCP-Brücke zur offenen App)\n",
" dossier-cli mcp --app [--port 7979] [--token schlüssel] (MCP-Brücke zur offenen App)\n" +
" Anonyme Wettbewerbs-Abgabe: Exporte prüfen den Freitext (Exit 3 bei Treffern); --ignore-anonymity übergeht die Prüfung\n",
);
return 2;
}
@@ -903,9 +906,36 @@ async function importSyntheticContext(base: Project, args: Args, rows: Array<[st
return cur;
}
/** Befehle, die eine Ausgabe-Datei erzeugen (für die Anonymitäts-Prüfung einer Wettbewerbs-Abgabe, [208]). */
const EXPORT_COMMANDS = new Set(["plan", "section", "elevation", "dxf", "dwg", "ifc", "obj", "stl", "glb", "gltf", "step", "stp", "schedule", "kennzahlen", "raumprogramm", "render", "blend", "model3d"]);
/**
* [208] Anonyme Abgabe: vor einem Export den Freitext prüfen. Treffer stehen auf stderr; ohne `--ignore-anonymity`
* bricht der Befehl mit Exit-Code 3 ab. Gibt den Exit-Code zurück, `0` = weiter.
*/
function anonymityGate(project: Project, file: string, command: string, args: Args): number {
if (!EXPORT_COMMANDS.has(command) || !isAnonymous(project)) return 0;
const texts = [] as { area: string; place: string; text: string }[];
const target = args.flags.get("out");
if (target && target !== "-" && target !== "true") texts.push({ area: "export", place: "fileName", text: basename(target) });
const findings = anonymityFindings(project, { fileName: file.startsWith(":") ? "" : basename(file), texts });
if (findings.length === 0) return 0;
const lines = findings.map((f) => ` ${f.area} / ${f.place}: „${f.text}" enthält „${f.term}" (${f.kind})`);
const ignore = args.flags.has("ignore-anonymity") && args.flags.get("ignore-anonymity") !== "false";
process.stderr.write(`Anonyme Abgabe: ${findings.length} Treffer im Freitext:\n${lines.join("\n")}\n`);
if (ignore) {
process.stderr.write("Hinweis: --ignore-anonymity gesetzt, Export läuft trotzdem.\n");
return 0;
}
process.stderr.write("Export abgebrochen (zum Übergehen: --ignore-anonymity).\n");
return 3;
}
/** Führt EINEN Befehl gegen ein geladenes Projekt aus (Rückgabe = Exit-Code). */
async function execute(project: Project, file: string, command: string, rest: string[], args: Args): Promise<number> {
const scale = Number(args.flags.get("scale") ?? 100);
const blocked = anonymityGate(project, file, command, args);
if (blocked !== 0) return blocked;
// [257] `bench --context`: vorher synthetische Kontext-Importe (Kataster, Höhenlinien, Gebäudenetze) ins Projekt laden.
const contextRows: Array<[string, number]> = [];
if (command === "bench" && args.flags.has("context")) {
+1 -1
View File
@@ -81,7 +81,7 @@ export const AI_TOOLS: AiToolDef[] = [
"Exportiert Grundriss als SVG (format=svg) oder PDF (pdf, nur App) bzw. das Modell als IFC (ifc). Liefert den Inhalt " +
"(PDF base64); mit save=true öffnet die App den Speichern-Dialog und die Nutzerin wählt den Ort.",
inputSchema: obj(
{ format: { type: "string", enum: ["svg", "pdf", "ifc"] }, level: { type: "string" }, scale: { type: "number" }, save: { type: "boolean" } },
{ format: { type: "string", enum: ["svg", "pdf", "ifc"] }, level: { type: "string" }, scale: { type: "number" }, save: { type: "boolean" }, ignoreAnonymity: { type: "boolean" } },
["format"],
),
},
+10
View File
@@ -105,6 +105,16 @@ describe("KI-Werkzeuge (gemeinsame Liste)", () => {
expect((await callAiTool(host, "export", { format: "svg", save: true })).isError).toBe(true); // Speichern nur mit Dialog
expect((await callAiTool(host, "gibtsnicht", {})).isError).toBe(true);
});
it("anonyme Abgabe: Export mit Freitext-Treffern wird nicht ausgeliefert, ignoreAnonymity übergeht ([208])", async () => {
const { host } = fakeHost(false);
const real = host.project();
const anon = { ...real, name: "Seeblick Meierhofer", competition: { anonymous: true, keyword: "FALKE 7", identifiers: "" }, rooms: [{ ...real.rooms![0], name: "Büro Seeblick Meierhofer" }, ...real.rooms!.slice(1)] } as Project;
const h: AiHost = { ...host, project: () => anon };
const blocked = await callAiTool(h, "export", { format: "svg" });
expect(blocked.isError).toBe(true);
expect(textOf(blocked)).toContain("Anonyme Abgabe");
expect(textOf(await callAiTool(h, "export", { format: "svg", ignoreAnonymity: true }))).toContain("<svg");
});
});
describe("Brücken-Anmeldung", () => {
+12 -1
View File
@@ -17,6 +17,8 @@ import { computeKennzahlen, checkRoomProgram } from "../analysis/kennzahlen";
import { computeAreaTable, computeIvhb } from "../analysis/areaTable";
import { checkSiteRules } from "../analysis/siteRules";
import { loadFileio } from "../engine/fileioWasm";
import { anonymityFindings } from "../export/competitionCheck";
import { exportProjectName } from "../export/competitionIdentity";
import { documentFor } from "./document";
import { validateProject, projectWarnings, type CoreOp } from "./ops";
import { aiText, aiToolDef, randomHex, type AiToolResult } from "./aiToolDefs";
@@ -174,7 +176,7 @@ const appOnly = (name: string) => err(`${name}: nur mit der laufenden App (dossi
async function exportTool(host: AiHost, project: Project, args: Record<string, unknown>): Promise<AiToolResult> {
const format = String(args.format);
const stem = project.name || "projekt";
const stem = exportProjectName(project) || "projekt";
const scale = Number(args.scale ?? 100);
if (args.save === true && !host.save) return err("save: Speichern nur in der App (Dialog, Ort wählt die Nutzerin)");
let data: string | Uint8Array;
@@ -199,6 +201,15 @@ async function exportTool(host: AiHost, project: Project, args: Record<string, u
}
file = `${stem}-${lvl.name}.${format}`;
} else return err(`export: unbekanntes Format ${format}`);
// [208] Anonyme Abgabe: Ohne `save` gibt das Werkzeug die Daten direkt an die KI zurück — Freitext vorher prüfen.
// (Mit `save` fragt die App selbst im Anonymitäts-Dialog nach.)
if (args.save !== true && args.ignoreAnonymity !== true) {
const found = anonymityFindings(project, { texts: [{ area: "export", place: "fileName", text: file }] });
if (found.length > 0) {
const lines = found.slice(0, 20).map((f) => `${f.area} / ${f.place}: „${f.text}" enthält „${f.term}"`);
return err(`Anonyme Abgabe: ${found.length} Treffer im Freitext, Export nicht ausgeliefert (mit ignoreAnonymity=true übergehen):\n${lines.join("\n")}`);
}
}
if (args.save === true) {
const ok = await host.save!(data, file, mime);
return ok ? aiText(`gespeichert: ${file}`) : err("Speichern abgebrochen");
+9 -6
View File
@@ -12,6 +12,7 @@ import { exportProjectName, areaReportToCsv, buildAreaReport, buildAreaReportPdf
import type { AgfBasis } from "../core";
import { DEFAULT_AREA_INPUTS, ivhbOptionsOf, type AreaInputs } from "./areaInputs";
import { downloadCsv } from "./downloadFile";
import { runWithAnonymityGate } from "../state/anonymityGate";
import { useStore } from "../state/appStore";
const BASES: AgfBasis[] = ["ngf", "gf", "nf"];
@@ -29,11 +30,13 @@ export function AreaTableSection() {
const stem = `${exportProjectName(project) || "projekt"}-flaechen`;
const exportPdf = () => {
try {
buildAreaReportPdf(report).save(`${stem}.pdf`);
} catch {
notify(t("areas.exportPdf.fail"));
}
runWithAnonymityGate(project, [`${stem}.pdf`], () => {
try {
buildAreaReportPdf(report).save(`${stem}.pdf`);
} catch {
notify(t("areas.exportPdf.fail"));
}
});
};
return (
@@ -41,7 +44,7 @@ export function AreaTableSection() {
<div className="balance-head">
<span className="balance-section-label">{t("areas.title")}</span>
<span className="area-actions">
<button type="button" className="balance-export" onClick={() => downloadCsv(`${stem}.csv`, areaReportToCsv(report))}>
<button type="button" className="balance-export" onClick={() => runWithAnonymityGate(project, [`${stem}.csv`], () => downloadCsv(`${stem}.csv`, areaReportToCsv(report)))}>
{t("areas.exportCsv")}
</button>
<button type="button" className="balance-export" onClick={exportPdf}>
+9 -6
View File
@@ -13,6 +13,7 @@ import { exportProjectName, areaReportToCsv, buildAreaReportPdf, buildCostReport
import type { CostBasis, CostEstimate, CostGroup, CostMethod, CostResult } from "../core";
import type { Project } from "../model/types";
import { downloadCsv } from "./downloadFile";
import { runWithAnonymityGate } from "../state/anonymityGate";
import { useStore } from "../state/appStore";
const BASES: CostBasis[] = ["method", "gv", "gf", "hnf", "facade", "roof", "lump"];
@@ -73,13 +74,15 @@ export function CostEstimateSection() {
const patchGroup = (i: number, g: Partial<CostGroup>, key: string) =>
update((e) => ({ ...e, groups: e.groups.map((x, j) => (j === i ? { ...x, ...g } : x)) }), `${key}.${i}`);
const exportCsv = () => downloadCsv(`${stem}.csv`, areaReportToCsv(buildCostReport(project, res)));
const exportCsv = () => runWithAnonymityGate(project, [`${stem}.csv`], () => downloadCsv(`${stem}.csv`, areaReportToCsv(buildCostReport(project, res))));
const exportPdf = () => {
try {
buildAreaReportPdf(buildCostReport(project, res)).save(`${stem}.pdf`);
} catch {
notify(t("costs.export.fail"));
}
runWithAnonymityGate(project, [`${stem}.pdf`], () => {
try {
buildAreaReportPdf(buildCostReport(project, res)).save(`${stem}.pdf`);
} catch {
notify(t("costs.export.fail"));
}
});
};
const pctLabel = (v: number) => `${Number.isInteger(v) ? v.toFixed(0) : v.toFixed(1)} %`;
const sumRow = (label: string, n: number, testId: string, total = false, code = "") => (
+9 -6
View File
@@ -6,6 +6,7 @@ import { useMemo } from "react";
import { t } from "../i18n";
import { exportProjectName, areaReportToCsv, buildAreaReportPdf, buildElementReport, elementSchedule } from "../core";
import { downloadCsv } from "./downloadFile";
import { runWithAnonymityGate } from "../state/anonymityGate";
import { useStore } from "../state/appStore";
export function ElementScheduleSection() {
@@ -14,11 +15,13 @@ export function ElementScheduleSection() {
const rows = useMemo(() => elementSchedule(project), [project]);
const stem = `${exportProjectName(project) || "projekt"}-bauteile`;
const exportPdf = () => {
try {
buildAreaReportPdf(buildElementReport(project)).save(`${stem}.pdf`);
} catch {
notify(t("openings.exportPdf.fail"));
}
runWithAnonymityGate(project, [`${stem}.pdf`], () => {
try {
buildAreaReportPdf(buildElementReport(project)).save(`${stem}.pdf`);
} catch {
notify(t("openings.exportPdf.fail"));
}
});
};
return (
<div className="area-section element-section" data-element-schedule>
@@ -26,7 +29,7 @@ export function ElementScheduleSection() {
<span className="balance-section-label">{t("elemSchedule.title")}</span>
{rows.length > 0 && (
<span className="area-actions">
<button type="button" className="balance-export" onClick={() => downloadCsv(`${stem}.csv`, areaReportToCsv(buildElementReport(project)))}>
<button type="button" className="balance-export" onClick={() => runWithAnonymityGate(project, [`${stem}.csv`], () => downloadCsv(`${stem}.csv`, areaReportToCsv(buildElementReport(project))))}>
{t("openings.exportCsv")}
</button>
<button type="button" className="balance-export" onClick={exportPdf}>
+9 -6
View File
@@ -11,6 +11,7 @@ import { exportProjectName, areaReportToCsv, buildAreaReportPdf, buildOpeningRep
import type { OpeningScheduleRow } from "../core";
import type { Opening, Project } from "../model/types";
import { downloadCsv } from "./downloadFile";
import { runWithAnonymityGate } from "../state/anonymityGate";
import { useStore } from "../state/appStore";
type TextField = "mark" | "fireRating" | "soundClass" | "burglaryClass" | "notes";
@@ -37,11 +38,13 @@ export function OpeningScheduleSection() {
const setExternal = (id: string, value: string) => patch(id, { isExternal: value === "" ? undefined : value === "ext" }, "isExternal");
const exportPdf = () => {
try {
buildAreaReportPdf(buildOpeningReport(project)).save(`${stem}.pdf`);
} catch {
notify(t("openings.exportPdf.fail"));
}
runWithAnonymityGate(project, [`${stem}.pdf`], () => {
try {
buildAreaReportPdf(buildOpeningReport(project)).save(`${stem}.pdf`);
} catch {
notify(t("openings.exportPdf.fail"));
}
});
};
const select = (r: OpeningScheduleRow) => host.onSelectScheduleRow(r.kind === "door" ? "Tür" : "Fenster", r.id, r.floorId);
@@ -55,7 +58,7 @@ export function OpeningScheduleSection() {
<span className="balance-section-label">{t("openings.title")}</span>
{rows.length > 0 && (
<span className="area-actions">
<button type="button" className="balance-export" onClick={() => downloadCsv(`${stem}.csv`, areaReportToCsv(buildOpeningReport(project)))}>
<button type="button" className="balance-export" onClick={() => runWithAnonymityGate(project, [`${stem}.csv`], () => downloadCsv(`${stem}.csv`, areaReportToCsv(buildOpeningReport(project))))}>
{t("openings.exportCsv")}
</button>
<button type="button" className="balance-export" onClick={exportPdf}>
+9 -6
View File
@@ -15,6 +15,7 @@ import { exportProjectName, addProgramSheetOps, areaReportToCsv, buildAreaReport
import type { CompareRow, CompareSum, Light } from "../core";
import type { Project } from "../model/types";
import { downloadCsv } from "./downloadFile";
import { runWithAnonymityGate } from "../state/anonymityGate";
const fmt = (n: number, d = 1) => n.toLocaleString("de-CH", { minimumFractionDigits: d, maximumFractionDigits: d });
/** Mit Vorzeichen; was auf die angezeigte Stelle zu 0 rundet, bleibt ohne Vorzeichen. */
@@ -59,11 +60,13 @@ export function ProgramCompareSection({ statusLabel }: { statusLabel: (status: C
};
const exportPdf = () => {
try {
buildAreaReportPdf(buildProgramReport(project)).save(`${stem}.pdf`);
} catch {
notify(t("program.compare.exportPdf.fail"));
}
runWithAnonymityGate(project, [`${stem}.pdf`], () => {
try {
buildAreaReportPdf(buildProgramReport(project)).save(`${stem}.pdf`);
} catch {
notify(t("program.compare.exportPdf.fail"));
}
});
};
const generate = () => {
@@ -83,7 +86,7 @@ export function ProgramCompareSection({ statusLabel }: { statusLabel: (status: C
<div className="balance-head">
<span className="balance-section-label">{t("program.compare.title")}</span>
<span className="area-actions">
<button type="button" className="balance-export" onClick={() => downloadCsv(`${stem}.csv`, areaReportToCsv(buildProgramReport(project)))}>
<button type="button" className="balance-export" onClick={() => runWithAnonymityGate(project, [`${stem}.csv`], () => downloadCsv(`${stem}.csv`, areaReportToCsv(buildProgramReport(project))))}>
{t("program.compare.exportCsv")}
</button>
<button type="button" className="balance-export" onClick={exportPdf}>
+2 -1
View File
@@ -19,6 +19,7 @@ import { OpeningScheduleSection } from "./OpeningScheduleSection";
import { ElementScheduleSection } from "./ElementScheduleSection";
import { RoomBookSection } from "./RoomBookSection";
import { downloadCsv } from "./downloadFile";
import { runWithAnonymityGate } from "../state/anonymityGate";
/** Löst je Raum die anrechenbare (Netto-)Fläche + Kategorie auf. */
function roomAreas(rooms: Room[]): { category: Room["siaCategory"]; area: number }[] {
@@ -66,7 +67,7 @@ export function RoomBalancePanel() {
area: evaluateRoom(r.boundary, r.siaCategory, { bulge: r.boundaryBulge }).netArea,
})),
);
downloadCsv("flaechenbilanz.csv", csv);
runWithAnonymityGate(project, ["flaechenbilanz.csv"], () => downloadCsv("flaechenbilanz.csv", csv));
};
return (
+9 -6
View File
@@ -7,6 +7,7 @@ import { useMemo } from "react";
import { t } from "../i18n";
import { exportProjectName, areaReportToCsv, buildAreaReportPdf, buildRoomBookReport, hasSlope, roomBook, usageLabel } from "../core";
import { downloadCsv } from "./downloadFile";
import { runWithAnonymityGate } from "../state/anonymityGate";
import { useStore } from "../state/appStore";
const m2 = (v: number) => v.toFixed(2);
@@ -19,11 +20,13 @@ export function RoomBookSection() {
const stem = `${exportProjectName(project) || "projekt"}-raumbuch`;
const exportPdf = () => {
try {
buildAreaReportPdf(buildRoomBookReport(project)).save(`${stem}.pdf`);
} catch {
notify(t("roomBook.exportPdf.fail"));
}
runWithAnonymityGate(project, [`${stem}.pdf`], () => {
try {
buildAreaReportPdf(buildRoomBookReport(project)).save(`${stem}.pdf`);
} catch {
notify(t("roomBook.exportPdf.fail"));
}
});
};
return (
@@ -32,7 +35,7 @@ export function RoomBookSection() {
<span className="balance-section-label">{t("roomBook.title")}</span>
{book.rows.length > 0 && (
<span className="area-actions">
<button type="button" className="balance-export" onClick={() => downloadCsv(`${stem}.csv`, areaReportToCsv(buildRoomBookReport(project)))}>
<button type="button" className="balance-export" onClick={() => runWithAnonymityGate(project, [`${stem}.csv`], () => downloadCsv(`${stem}.csv`, areaReportToCsv(buildRoomBookReport(project))))}>
{t("roomBook.exportCsv")}
</button>
<button type="button" className="balance-export" onClick={exportPdf}>
+5 -1
View File
@@ -11,6 +11,7 @@ import { connectAiBridge, type AiBridgeStatus } from "../net/aiBridge";
import { buildPlanPdf } from "../export/exportPdf";
import { saveBinaryFile, saveTextFile } from "../native/saveFile";
import { getState, setState } from "./appStore";
import { confirmAnonymousExport } from "./anonymityGate";
import type { Selection, SelectionKind } from "./selection";
export interface AiLogEntry {
@@ -197,7 +198,10 @@ export const appHost: AiHost = {
const doc = await buildPlanPdf(plan, { scaleDenominator: scale, paper: "a3", orientation: "landscape", title });
return new Uint8Array(doc.output("arraybuffer"));
},
save: (data, name, mime) => (typeof data === "string" ? saveTextFile(data, name, mime) : saveBinaryFile(data, name, mime)),
// [208] Anonyme Abgabe: Freitext vorher prüfen (Dialog in der App), bei Abbruch wird nicht gespeichert.
save: async (data, name, mime) =>
(await confirmAnonymousExport(getState().project, [name])) &&
(typeof data === "string" ? saveTextFile(data, name, mime) : saveBinaryFile(data, name, mime)),
};
/** Ein Aufruf der Brücke: Pause prüfen, ausführen, protokollieren. */
+66
View File
@@ -0,0 +1,66 @@
// [208] Abgleich: Jede Stelle der Oberfläche, die eine Datei ausgibt (Berichte, Bilder, Pakete, Pläne …), ruft das
// Anonymitäts-Tor (`anonymityGate.ts`) auf. Neue Export-Einstiege fallen hier auf, bevor sie ohne Prüfung ausgeliefert werden.
import { describe, expect, it } from "vitest";
import { readdirSync, readFileSync, statSync } from "node:fs";
import { join, relative } from "node:path";
const SRC = join(process.cwd(), "src");
function walk(dir: string, out: string[] = []): string[] {
for (const f of readdirSync(dir)) {
const p = join(dir, f);
if (statSync(p).isDirectory()) walk(p, out);
else if (/\.tsx?$/.test(f) && !/\.test\.tsx?$/.test(f)) out.push(p);
}
return out;
}
/** Aufrufe, die eine Datei an die Nutzerin ausgeben. */
const SINKS = /\b(saveBinaryFile|saveTextFile|saveTextWithCompanion|downloadCsv|downloadFile|savePlanPdf|savePlanSvg|savePlanDxf)\(|buildAreaReportPdf\(.*\)\.save\(/;
const GATE = /confirmAnonymousExport|runWithAnonymityGate/;
/** Bewusst ohne Tor: Schreiber selbst, Zusammenarbeit (BCF, keine Abgabe), CLI/MCP (eigene Prüfung). */
const EXEMPT = [
/^native\//,
/^export\//,
/^cli\//,
/^core\//,
/^panels\/downloadFile\.ts$/,
/^panels\/BcfPanel\.tsx$/,
/^state\/anonymityGate\.ts$/,
];
describe("Anonymitäts-Tor", () => {
it("jede Datei mit Export-Aufruf in der Oberfläche ruft das Tor auf", () => {
const missing: string[] = [];
for (const file of walk(SRC)) {
const rel = relative(SRC, file).replace(/\\/g, "/");
if (EXEMPT.some((r) => r.test(rel))) continue;
const text = readFileSync(file, "utf8");
if (SINKS.test(text) && !GATE.test(text)) missing.push(rel);
}
expect(missing).toEqual([]);
});
it("das Tor ist in den bekannten Einstiegen angeschlossen", () => {
const expected = [
"state/useExportHandlers.ts", // Plan-PDF/SVG/DXF
"state/useProjectFileActions.ts", // CSV/IFC/OBJ/STL/GLB/STEP
"state/publishActions.ts", // Publikation
"state/panelHost/layoutsHost.ts", // Layout-Ordner als PDF
"state/aiAccess.ts", // KI-Werkzeuge (Speichern)
"ui/ImageExportDialog.tsx", // 3D-Bild PNG
"ui/RenderDialog.tsx", // Rendering PNG, .blend, Blender-Paket
"ui/CameraTourDialog.tsx", // Kamerafahrt (Video)
"panels/AreaTableSection.tsx",
"panels/RoomBookSection.tsx",
"panels/CostEstimateSection.tsx",
"panels/OpeningScheduleSection.tsx",
"panels/ElementScheduleSection.tsx",
"panels/ProgramCompareSection.tsx",
"panels/RoomBalancePanel.tsx",
];
for (const rel of expected) expect(GATE.test(readFileSync(join(SRC, rel), "utf8")), rel).toBe(true);
});
});
+7
View File
@@ -65,3 +65,10 @@ export async function confirmAnonymousExport(project: Project, outputFileNames:
emit();
});
}
/** Führt `run` erst nach bestandener Prüfung aus (Knopf-Handler der Berichte, Bild-Exporte …); bei Abbruch passiert nichts. */
export function runWithAnonymityGate(project: Project, outputFileNames: string[], run: () => void | Promise<void>): void {
void confirmAnonymousExport(project, outputFileNames).then((ok) => {
if (ok) return run();
});
}
+6 -3
View File
@@ -8,6 +8,7 @@ import { folderPdfBytes } from "../../export/layoutPdf";
import { addPublishSetOps, addWbwSetOps, deletePublishSetOps, patchPublishSetOps, publishSet, setCompetitionOps } from "../publishActions";
import { openLayoutTab } from "../tabNavigation";
import { saveBinaryFile } from "../../native/saveFile";
import { runWithAnonymityGate } from "../anonymityGate";
import { createPosterMaster, findPosterMaster, posterTemplate } from "../../model/posterTemplates";
import type { FlatHostOpts, HostPart } from "./types";
@@ -155,9 +156,11 @@ export function buildLayoutsHost(c: FlatHostOpts) {
onExportFolderPdf: (folderId) => {
const folder = (project.layoutFolders ?? []).find((f) => f.id === folderId);
const name = folder?.name?.trim() || "layouts";
void folderPdfBytes(project, folderId).then((bytes) => {
if (bytes) return saveBinaryFile(bytes, `${name}.pdf`, "application/pdf");
});
runWithAnonymityGate(project, [`${name}.pdf`], () =>
folderPdfBytes(project, folderId).then((bytes) => {
if (bytes) void saveBinaryFile(bytes, `${name}.pdf`, "application/pdf");
}),
);
},
onMoveLayoutToFolder: (layoutId, folderId) => {
applyChange((p) => fieldOps(p, "layouts", moveLayoutToFolder(p.layouts ?? [], layoutId, folderId)));
+3 -1
View File
@@ -202,7 +202,7 @@ export function useProjectFileActions(
useEffect(() => offerRecovery(null), []);
const onRecoverRestore = () => {
if (!recovery) return;
openProjectOrReport(recovery.text, notify); // bleibt „ungespeichert" bis zum Speichern
if (openProjectOrReport(recovery.text, notify)) setAnonymityProjectFileName(recovery.path); // [208] bleibt „ungespeichert" bis zum Speichern
setRecovery(null);
};
const onRecoverDiscard = () => {
@@ -504,6 +504,7 @@ export function useProjectFileActions(
}
openedProjectPathRef.current = null;
savePathRef.current = null;
setAnonymityProjectFileName(null); // [208] der alte Dateiname ist kein Suchbegriff mehr
projectLockOwnedRef.current = false;
};
// Übernimmt ein per Pfad geöffnetes Projekt (Tauri-Fluss): parst, prüft grob
@@ -655,6 +656,7 @@ export function useProjectFileActions(
if (!loaded) return;
releaseCurrentProjectLock();
lastSavedProjectRef.current = loaded;
setAnonymityProjectFileName(file.name); // [208] Browser/Electron-Start: kein Pfad, aber der Dateiname
});
};
r.readAsText(file);
+6 -1
View File
@@ -10,6 +10,8 @@ import { getState } from "../state/appStore";
import { cancelCameraTour, currentTourKeys, getTourSettings, playCameraTour, recordCameraTour, setTourSettings } from "../state/cameraTourActions";
import { setCameraTourDialogOpener } from "../state/cameraTourDialogHook";
import { saveBinaryFile } from "../native/saveFile";
import { runWithAnonymityGate } from "../state/anonymityGate";
import { exportProjectName } from "../core";
import { getViewportCanvas } from "../viewport/cameraBridge";
import { availableVideoFormats, videoFileName } from "../viewport/videoRecorder";
import type { TourMode } from "../viewport/cameraTour";
@@ -82,7 +84,10 @@ export const CameraTourDialogHost = memo(function CameraTourDialogHost() {
if (!res) return;
try {
const bytes = new Uint8Array(await res.blob.arrayBuffer());
if (await saveBinaryFile(bytes, videoFileName(getState().project.name, res.ext), res.blob.type || "video/webm")) getState().notify(t("tour.saved"), "info");
const name = videoFileName(exportProjectName(getState().project) || "projekt", res.ext);
runWithAnonymityGate(getState().project, [name], async () => {
if (await saveBinaryFile(bytes, name, res.blob.type || "video/webm")) getState().notify(t("tour.saved"), "info");
});
} catch (err) {
getState().notify(t("tour.recordFailed", { reason: err instanceof Error ? err.message : String(err) }), "warning");
}
+7 -3
View File
@@ -7,7 +7,8 @@
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useModalFocus } from "./modalFocus";
import { t } from "../i18n";
import { paperPixels } from "../core";
import { exportProjectName, paperPixels } from "../core";
import { runWithAnonymityGate } from "../state/anonymityGate";
import { getState } from "../state/appStore";
import { setImageExportDialogOpener } from "../state/imageExportDialogHook";
import { defaultTargetLayout, placeImageOnLayout } from "../state/layoutImageActions";
@@ -155,10 +156,13 @@ export const ImageExportDialogHost = memo(function ImageExportDialogHost() {
if (transparent && !img.transparent) setMessage(t("image3d.noTransparency"));
};
const fileName = () => imageFileName(getState().project.name, result?.width ?? 0, result?.height ?? 0);
const fileName = () => imageFileName(exportProjectName(getState().project) || "projekt", result?.width ?? 0, result?.height ?? 0);
const save = async () => {
if (!result) return;
if (await saveBinaryFile(result.png, fileName(), "image/png")) getState().notify(t("image3d.saved"), "info");
const name = fileName();
runWithAnonymityGate(getState().project, [name], async () => {
if (await saveBinaryFile(result.png, name, "image/png")) getState().notify(t("image3d.saved"), "info");
});
};
const placeInLayout = () => {
if (!result) return;
+15 -7
View File
@@ -19,6 +19,7 @@ import {
type BlenderHost,
type RenderCameraChoice,
type RenderCameraSpec,
exportProjectName,
} from "../core";
import { getState } from "../state/appStore";
import { setRenderDialogOpener } from "../state/renderDialogHook";
@@ -26,6 +27,7 @@ import { getBlenderPath, setBlenderPath } from "../state/blenderSettings";
import { buildPackage, currentRenderCamera, openInBlender, packageAsZip, renderHost, renderWithBlender, saveBlendWithBlender } from "../state/renderAction";
import { openExternalUrl } from "../native/blender";
import { saveBinaryFile } from "../native/saveFile";
import { runWithAnonymityGate } from "../state/anonymityGate";
import { defaultTargetLayout, placeImageOnLayout } from "../state/layoutImageActions";
type SizeId = "hd" | "uhd" | "a4" | "a3" | "a2" | "custom";
@@ -236,8 +238,10 @@ export const RenderDialogHost = memo(function RenderDialogHost() {
st.notify(t("render.blend.opened"), "info");
} else {
const res = await saveBlendWithBlender(host, pkg, hooks);
const name = `${(st.project.name || "projekt").replace(/[^\w.-]+/g, "_")}.blend`;
if (await saveBinaryFile(res.blend, name, "application/octet-stream")) st.notify(t("render.blend.saved"), "info");
const name = `${(exportProjectName(st.project) || "projekt").replace(/[^\w.-]+/g, "_")}.blend`;
runWithAnonymityGate(st.project, [name], async () => {
if (await saveBinaryFile(res.blend, name, "application/octet-stream")) st.notify(t("render.blend.saved"), "info");
});
}
setPhase("setup");
} catch (err) {
@@ -255,8 +259,10 @@ export const RenderDialogHost = memo(function RenderDialogHost() {
try {
const pkg = await buildPackage(st.project, request());
const bytes = await packageAsZip(pkg);
const name = `${(st.project.name || "projekt").replace(/[^\w.-]+/g, "_")}-render.zip`;
if (await saveBinaryFile(bytes, name, "application/zip")) st.notify(t("render.zip.saved"), "info");
const name = `${(exportProjectName(st.project) || "projekt").replace(/[^\w.-]+/g, "_")}-render.zip`;
runWithAnonymityGate(st.project, [name], async () => {
if (await saveBinaryFile(bytes, name, "application/zip")) st.notify(t("render.zip.saved"), "info");
});
setPhase("setup");
} catch (err) {
setPhase("error");
@@ -269,7 +275,7 @@ export const RenderDialogHost = memo(function RenderDialogHost() {
if (!png) return;
const st = getState();
const layout = (st.project.layouts ?? []).find((l) => l.id === layoutTarget);
const name = `${(st.project.name || "projekt").replace(/[^\w.-]+/g, "_")}-rendering.png`;
const name = `${(exportProjectName(st.project) || "projekt").replace(/[^\w.-]+/g, "_")}-rendering.png`;
if (layout && placeImageOnLayout(layout.id, name, png)) st.notify(t("render.toLayout.done", { name: layout.name }), "info");
else st.notify(t("render.toLayout.none"), "warning");
};
@@ -277,8 +283,10 @@ export const RenderDialogHost = memo(function RenderDialogHost() {
const savePng = async () => {
if (!png) return;
const st = getState();
const name = `${(st.project.name || "projekt").replace(/[^\w.-]+/g, "_")}-rendering.png`;
if (await saveBinaryFile(png, name, "image/png")) st.notify(t("render.saved"), "info");
const name = `${(exportProjectName(st.project) || "projekt").replace(/[^\w.-]+/g, "_")}-rendering.png`;
runWithAnonymityGate(st.project, [name], async () => {
if (await saveBinaryFile(png, name, "image/png")) st.notify(t("render.saved"), "info");
});
};
const camLabel = cameraKey !== "live" ? t("render.camera.saved", { name: cameras.find((c) => c.id === cameraKey)?.name ?? "" }) : "preset" in camera ? t("render.camera.preset", { name: t(`view3d.${camera.preset === "right" ? "side" : camera.preset}` as never) }) : t("render.camera.view");