diff --git a/CLAUDE.md b/CLAUDE.md index 7b729ee0..f56d6ddf 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -14,6 +14,7 @@ Anzeige nur über die zwei Rust-Engines `render2d` und `render3d` (WebGPU/Metal) ansehen") — Zahlen allein reichen nicht. 5. **Abschliessen:** kleine Commits, Nachricht deutsch, beginnt mit den IDs (`[63] Baurecht: …`), ohne Co-Authored-By-Zeile. `TODO.md` im selben Commit nachführen (Stand + Datum + was offen bleibt). + Gewollte Änderung an Plan/Schnitt/Ansicht/3D: `npx vitest run -u src/plan/golden.test.ts`, Diff in `src/plan/__golden__` im Commit prüfen ([119]). 6. **Ehrlich berichten:** was geprüft wurde und was nicht (z. B. „nicht in der Tauri-App getestet"). ``` diff --git a/NOTICE b/NOTICE index 79f4f97a..cb6d45fd 100644 --- a/NOTICE +++ b/NOTICE @@ -1,5 +1,9 @@ Dossier — Hinweise zu übernommenem und eingebundenem Fremdcode ([51]) +Material Symbols (Icon-Font, npm-Paket material-symbols, https://github.com/marella/material-symbols; Schrift von Google, + https://github.com/google/material-design-icons), Apache-2.0 + Lokal gebündelt (src/main.tsx), statt von fonts.googleapis.com geladen ([117]). + acadrust (https://github.com/hakanaktt/acadrust), MPL-2.0 Abhängigkeit von src-tauri/fileio (DXF/DWG lesen und schreiben), unverändert eingebunden. Der DWG-Code von acadrust ist aus ACadSharp portiert: diff --git a/TODO.md b/TODO.md index 635a507e..c0b28cd9 100644 --- a/TODO.md +++ b/TODO.md @@ -1041,10 +1041,20 @@ Frage: WebGPU weiterführen oder wie BIMCraft CPU + native GPU? Prüfung des ganzen Programms (Rust-Kern, TS-Hülle, Build/Sicherheit), nur Code gelesen. -- ○ **[116] Speichern absturzsicher.** `native/saveFile.ts:49` überschreibt direkt; Temp-Datei + Umbenennen - (Rust-Befehl), `.obp~`-Sicherung; Autosave erst nach erfolgreichem Umbenennen löschen. · S -- ○ **[117] CSP setzen.** `tauri.conf.json` hat `"csp": null`; strikte CSP (`script-src 'self' 'wasm-unsafe-eval'`, - `connect-src` = netFetch-Hosts + ipc). Rich-Text-`innerHTML` prüfen. · S +- ✅ **[116] Speichern absturzsicher.** 3.11.: Rust-Befehl `save_atomic` (`src-tauri/src/atomic_save.rs`): + `.tmp` schreiben + fsync, Vorversion als `~` kopieren, Umbenennen, Ordner-fsync; Fehler lassen die + Datei unberührt. `saveProjectFile` nutzt ihn (`saveTextFile(..., atomic)`); bei Fehler `SaveError` + `notify` + (`project.save.failed`), Autosave-Kopie bleibt, sonst Löschen erst nach Erfolg. Offen: nur Projektdatei + (Exporte/`saveBinaryFile` schreiben weiter direkt); in der Tauri-App nicht von Hand geprüft; Electron + schreibt keine Dateien (Browser-Download), daher keine Änderung; keine Wiederherstellungs-UI für `.obp~`. · S +- ✅ **[117] CSP setzen.** (3.11.) Eine Quelle `scripts/csp.cjs` (`script-src 'self' 'wasm-unsafe-eval'`, `worker-src 'self' blob:`, + `style-src` mit `'unsafe-inline'` für React-Inline-Styles (Icon-Font seit 3.11. lokal gebündelt: `material-symbols`, kein Google-Fonts-Host mehr), `connect-src` = ipc + netFetch-Hosts + + localhost/127.0.0.1 + ws://127.0.0.1 für die KI-Brücke). Tauri: `tauri.conf.json` (`devCsp: null`, Test `src/net/csp.test.ts` + gleicht mit `csp.cjs` und `ALLOWED_HOSTS` ab); Electron: Antwort-Header nur gepackt; Browser/e2e: Meta-Tag nur im Vite-Build + (Dev-HMR unberührt). `e2e/csp.spec.ts` prüft Plan/Schnitt/Ansicht/3D auf CSP-Verletzungen. Rich-Text: Text war schon + escaped; Farbe/Schriftname/Ausrichtung/Zeilenhöhe aus Dateien jetzt per Positivliste (`safeCssColor`, `safeFontFamily`). + Offen: nicht in der Tauri-App (macOS) und nicht im gepackten Electron geprüft (`'self'` unter `file://` ungeprüft); + `'unsafe-inline'` bei Stilen bleibt; Material-Symbols-Font kommt noch von Google Fonts (lokal bündeln würde zwei Hosts sparen). · S - ◐ **[118] Wiederanlauf nach Kern-Panic.** (3.11.) `core()` (`engine/coreWasm.ts`) hüllt alle Kern-Exporte: ein Trap (`RuntimeError`/`unreachable`) baut sofort eine frische Instanz aus dem übersetzten Modul (`__dossier_reinit`, ergänzt von `scripts/build-core.mjs` = `npm run build:core`), jedes `ProjectDocument` @@ -1056,8 +1066,9 @@ Prüfung des ganzen Programms (Rust-Kern, TS-Hülle, Build/Sicherheit), nur Code Offen: Undo-Verlauf geht beim Neustart verloren (Meldung sagt es) — Wiederaufbau per Op-Log wäre der nächste Schritt; nur im Linux-Container (vitest/Node) geprüft, nicht in Tauri/Electron (synchrones `new WebAssembly.Instance` im Haupt-Thread). · M -- ○ **[119] Referenz-Ausgaben (golden).** Plan-Puffer/SVG/Schnitt/Ansicht der Musterprojekte als Snapshot; - seit TS gelöscht ist, fehlt die Bitgleich-Referenz. · M +- ✅ **[119] Referenz-Ausgaben (golden).** 3.11.: `src/plan/golden.test.ts` — beide Musterprojekte: Grundriss je Geschoss + (1:100, 1:50), Schnitt, Ansicht, 3D-Zusammenfassung als Digest (Zähler, Rahmen, Hash gerundeter Zahlen) in + `src/plan/__golden__/`; Update mit `vitest -u`. Nur Linux geprüft; Hash deckt Detailabweichungen ab, Diff zeigt nur Zähler. · M - ○ **[120] macOS in CI.** `cargo check --features native2d`, Bildvergleich Metal ↔ WebGPU. · M - ○ **[121] App.tsx zerlegen, Neurendern stoppen.** `App.tsx:365` abonniert ganzes Projekt, 0× `memo`; Abschnitte in Hooks/Komponenten, Panels lesen den Store selbst; Nebenfenster bekommen Ops statt Projekt. · L @@ -1073,8 +1084,9 @@ Prüfung des ganzen Programms (Rust-Kern, TS-Hülle, Build/Sicherheit), nur Code - ○ **[127] 3D-Booleans klären:** BSP in `fileio/csg.rs` stilllegen, Manifold vs. truck dokumentieren. · S - ○ **[128] Restlogik nach Rust:** Griffe (`useGripEditing.ts`), `layoutModel.ts`, Kollisions-Vorprüfung, `exportStep.projectSolidSpecs`. · L -- ○ **[129] Grenze schärfen:** React-freies `t()` (Kern importiert `i18n` → React), `net/` in `CORE_DIRS`, - transitive Importe prüfen. · S +- ✅ **[129] Grenze schärfen.** (3.11.) `i18n/translate.ts` (React-frei: `t`, Sprache, Wörterbücher), `i18n/index.ts` re-exportiert + und hält nur `useT`; Kern-Dateien importieren `i18n/translate`. `net/` in `CORE_DIRS`, neuer Test prüft transitive + relative Importe (Ausnahmelisten leer). · S - ○ **[130] Kleinkram:** eine generische Fenster-Brücke statt 5 Kopien; Auswahl als ein `Selection`-Objekt statt 12 Felder; `primitives.tsx` auf Overlay zurückschneiden; Cargo-Workspace + cargo-deny; NOTICE (OFL-Schriften, wgpu, Tauri, React, pdf.js, lcms). · M diff --git a/e2e/csp.spec.ts b/e2e/csp.spec.ts new file mode 100644 index 00000000..b2b8a603 --- /dev/null +++ b/e2e/csp.spec.ts @@ -0,0 +1,37 @@ +// [117] Strikte CSP (Meta-Tag im Build, s. vite.config.ts / scripts/csp.cjs): Musterhaus öffnen, Plan, Schnitt, +// Ansicht und 3D besuchen — es darf keine CSP-Verletzung geben (Konsole oder securitypolicyviolation). +import { discardIfAsked, expect, fileMenu, startNewProject, test } from "./app"; + +test("keine CSP-Verletzung bei Plan, Schnitt, Ansicht und 3D", async ({ page }) => { + test.setTimeout(120_000); + const violations: string[] = []; + page.on("console", (m) => { + const t = m.text(); + if (/Content Security Policy|violates the following|^CSPV /i.test(t)) violations.push(t.slice(0, 300)); + }); + await page.addInitScript(() => { + document.addEventListener("securitypolicyviolation", (e) => { + console.warn(`CSPV ${e.violatedDirective} ${e.blockedURI}`); + }); + }); + + await startNewProject(page); + expect(await page.locator('meta[http-equiv="Content-Security-Policy"]').count(), "CSP-Meta-Tag im Build").toBe(1); + await fileMenu(page, /Musterhaus \(komplex\)/); + await discardIfAsked(page); + await expect(page.locator(".project-name")).toHaveText("Musterhaus komplex", { timeout: 30_000 }); + + for (const name of ["Schnitt A-A", "Ansicht Süd"]) { + await page + .getByRole("tablist", { name: "Zeichnungen" }) + .getByRole("tab", { name: `${name} Ausschnitt-Tab löschen`, exact: true }) + .click(); + await expect(page.locator("svg.plan-svg").first()).toBeVisible({ timeout: 30_000 }); + } + await page.getByRole("button", { name: "Axonometrie", exact: true }).click(); + await expect(page.getByText(/^Perspektive · /)).toBeVisible({ timeout: 30_000 }); + await page.getByRole("button", { name: "Grundriss", exact: true }).click(); + await expect(page.locator("svg.plan-svg").first()).toBeVisible({ timeout: 30_000 }); + + expect(violations).toEqual([]); +}); diff --git a/index.html b/index.html index c4cecd6d..c6df196e 100644 --- a/index.html +++ b/index.html @@ -3,14 +3,7 @@ - - - - + `https://${h}`); + +const DIRECTIVES = { + "default-src": ["'self'"], + // 'wasm-unsafe-eval': WASM-Module (Kern, render2d/3d, truck). Kein 'unsafe-eval', kein Inline-Skript. + "script-src": ["'self'", "'wasm-unsafe-eval'"], + // Import-Worker (DXF/IFC/Mesh/Punktwolke) und pdf.js-Worker: Modul-URLs aus dem eigenen Bundle. + "worker-src": ["'self'", "blob:"], + // React setzt viele Inline-`style`-Attribute -> 'unsafe-inline' (nur Stile, keine Skripte). + "style-src": ["'self'", "'unsafe-inline'"], + "font-src": ["'self'", "data:"], + "img-src": ["'self'", "data:", "blob:", ...https], + "media-src": ["'self'", "blob:"], + "connect-src": [ + "'self'", + "ipc:", + "http://ipc.localhost", + "blob:", + "data:", + ...https, + "http://localhost:*", + "http://127.0.0.1:*", + "ws://127.0.0.1:*", // KI-Brücke (net/aiBridge.ts) + ], + "object-src": ["'none'"], + "base-uri": ["'self'"], + "form-action": ["'none'"], +}; + +/** Die Richtlinie als Header-/Meta-Text. */ +function buildCsp() { + return Object.entries(DIRECTIVES) + .map(([k, v]) => `${k} ${v.join(" ")}`) + .join("; "); +} + +module.exports = { buildCsp, NET_HOSTS }; diff --git a/scripts/electron-main.cjs b/scripts/electron-main.cjs index 22961d80..dae7d395 100644 --- a/scripts/electron-main.cjs +++ b/scripts/electron-main.cjs @@ -6,6 +6,7 @@ const { app, BrowserWindow, Menu, ipcMain } = require("electron"); const path = require("node:path"); +const { buildCsp } = require("./csp.cjs"); // Randloses App-Fenster wie chromium-shell.sh (--app=…): keine native // Menüleiste (File/Edit/View/Window), kein Fensterrahmen. Minimieren/ @@ -66,7 +67,16 @@ ipcMain.handle("window:is-maximized", (event) => { return BrowserWindow.fromWebContents(event.sender)?.isMaximized() ?? false; }); -app.whenReady().then(createWindow); +app.whenReady().then(() => { + // [117] CSP als Antwort-Header — nur gepackt: der Dev-Server (Vite HMR) braucht Inline-Skripte. + if (!isDev) { + const { session } = require("electron"); + session.defaultSession.webRequest.onHeadersReceived((details, cb) => { + cb({ responseHeaders: { ...details.responseHeaders, "Content-Security-Policy": [buildCsp()] } }); + }); + } + createWindow(); +}); app.on("window-all-closed", () => { if (process.platform !== "darwin") app.quit(); diff --git a/src-tauri/src/atomic_save.rs b/src-tauri/src/atomic_save.rs new file mode 100644 index 00000000..bd30c547 --- /dev/null +++ b/src-tauri/src/atomic_save.rs @@ -0,0 +1,98 @@ +// Absturzsicheres Speichern ([116]): erst `.tmp` im selben Ordner schreiben und +// auf den Datentraeger zwingen (fsync), dann die bisherige Datei als `~` +// (eine Generation) sichern und die Temp-Datei per Umbenennen an den Zielpfad setzen. +// Bricht irgendein Schritt ab, bleibt die urspruengliche Datei unveraendert. + +use std::fs::{self, File}; +use std::io::Write; +use std::path::{Path, PathBuf}; + +fn with_suffix(path: &Path, suffix: &str) -> PathBuf { + let mut s = path.as_os_str().to_os_string(); + s.push(suffix); + PathBuf::from(s) +} + +/// Schreibt `content` atomar nach `path`; die Vorversion landet in `~`. +pub fn save_atomic_impl(path: &Path, content: &[u8]) -> Result<(), String> { + let tmp = with_suffix(path, ".tmp"); + let backup = with_suffix(path, "~"); + let write_tmp = || -> std::io::Result<()> { + let mut f = File::create(&tmp)?; + f.write_all(content)?; + f.sync_all() + }; + if let Err(e) = write_tmp() { + let _ = fs::remove_file(&tmp); + return Err(format!("Temp-Datei schreiben: {e}")); + } + // Vorversion sichern (Kopie statt Umbenennen: der Zielpfad existiert so zu jedem Zeitpunkt). + if path.exists() { + if let Err(e) = fs::copy(path, &backup) { + let _ = fs::remove_file(&tmp); + return Err(format!("Sicherung anlegen: {e}")); + } + } + if let Err(e) = fs::rename(&tmp, path) { + let _ = fs::remove_file(&tmp); + return Err(format!("Umbenennen: {e}")); + } + // Ordner-Eintrag sichern (unter Windows nicht moeglich, dort best effort). + if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) { + if let Ok(d) = File::open(dir) { + let _ = d.sync_all(); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tmpdir(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("dossier-atomic-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + fs::create_dir_all(&d).unwrap(); + d + } + + #[test] + fn neue_datei_ohne_sicherung() { + let d = tmpdir("neu"); + let p = d.join("a.obp"); + save_atomic_impl(&p, b"eins").unwrap(); + assert_eq!(fs::read(&p).unwrap(), b"eins"); + assert!(!with_suffix(&p, "~").exists()); + assert!(!with_suffix(&p, ".tmp").exists()); + fs::remove_dir_all(&d).unwrap(); + } + + #[test] + fn ueberschreiben_legt_sicherung_an() { + let d = tmpdir("ueber"); + let p = d.join("a.obp"); + save_atomic_impl(&p, b"eins").unwrap(); + save_atomic_impl(&p, b"zwei").unwrap(); + assert_eq!(fs::read(&p).unwrap(), b"zwei"); + assert_eq!(fs::read(with_suffix(&p, "~")).unwrap(), b"eins"); + save_atomic_impl(&p, b"drei").unwrap(); + assert_eq!(fs::read(with_suffix(&p, "~")).unwrap(), b"zwei"); + assert!(!with_suffix(&p, ".tmp").exists()); + fs::remove_dir_all(&d).unwrap(); + } + + #[test] + fn fehler_laesst_original_unberuehrt() { + let d = tmpdir("fehler"); + let p = d.join("a.obp"); + save_atomic_impl(&p, b"original").unwrap(); + // Ein Ordner an der Stelle der Temp-Datei laesst das Schreiben scheitern. + fs::create_dir(with_suffix(&p, ".tmp")).unwrap(); + assert!(save_atomic_impl(&p, b"neu").is_err()); + assert_eq!(fs::read(&p).unwrap(), b"original"); + // Nicht existierender Zielordner: Fehler, nichts angelegt. + assert!(save_atomic_impl(&d.join("nope").join("b.obp"), b"x").is_err()); + fs::remove_dir_all(&d).unwrap(); + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 6340b2c0..0430c5ef 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -16,6 +16,9 @@ mod native_embed; // App-Instanzen (OS-Advisory-Lock via `fs4`, siehe lock.rs). mod lock; +// Absturzsicheres Speichern ([116]): Temp-Datei + fsync + Umbenennen, `~` als Sicherung. +mod atomic_save; + use std::path::PathBuf; use tauri::State; @@ -31,6 +34,12 @@ fn acquire_project_lock( lock::acquire(&state, &PathBuf::from(path)) } +/// Schreibt eine Projektdatei atomar ([116]); die Vorversion bleibt als `~` erhalten. +#[tauri::command] +fn save_atomic(path: String, content: String) -> Result<(), String> { + atomic_save::save_atomic_impl(&PathBuf::from(path), content.as_bytes()) +} + /// Gibt einen von dieser Instanz gehaltenen Lock frei. No-op, wenn der Pfad /// nicht gelockt war. #[tauri::command] @@ -280,7 +289,8 @@ pub fn run() { push_native_scene, push_native_walls, acquire_project_lock, - release_project_lock + release_project_lock, + save_atomic ]); #[cfg(not(any(feature = "native2d", feature = "native3d")))] let builder = builder.invoke_handler(tauri::generate_handler![ @@ -295,7 +305,8 @@ pub fn run() { native2d_frame, native2d_texts, acquire_project_lock, - release_project_lock + release_project_lock, + save_atomic ]); builder diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index daeed467..6a2493e2 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -21,7 +21,8 @@ } ], "security": { - "csp": null + "csp": "default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; worker-src 'self' blob:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; img-src 'self' data: blob: https://ambientcg.com https://api.ambientcg.com https://geo.admin.ch https://api3.geo.admin.ch https://wms.geo.admin.ch https://data.geo.admin.ch https://overpass-api.de https://nominatim.openstreetmap.org; media-src 'self' blob:; connect-src 'self' ipc: http://ipc.localhost blob: data: https://ambientcg.com https://api.ambientcg.com https://geo.admin.ch https://api3.geo.admin.ch https://wms.geo.admin.ch https://data.geo.admin.ch https://overpass-api.de https://nominatim.openstreetmap.org http://localhost:* http://127.0.0.1:* ws://127.0.0.1:*; object-src 'none'; base-uri 'self'; form-action 'none'", + "devCsp": null } }, "bundle": { diff --git a/src/analysis/roomProgramSheet.ts b/src/analysis/roomProgramSheet.ts index df5e6f22..b85da43e 100644 --- a/src/analysis/roomProgramSheet.ts +++ b/src/analysis/roomProgramSheet.ts @@ -10,7 +10,7 @@ // Der Aufruf gehört in EIN `setProject` (ein Undo-Schritt). import type { Drawing2D, DrawingLevel, Project } from "../model/types"; -import { t } from "../i18n"; +import { t } from "../i18n/translate"; import { applyOps } from "../core/ops"; import type { CoreOp } from "../core/ops"; import { addItems } from "../core/opsBuild"; diff --git a/src/core/boundary.test.ts b/src/core/boundary.test.ts index 645cc719..89393d31 100644 --- a/src/core/boundary.test.ts +++ b/src/core/boundary.test.ts @@ -1,7 +1,8 @@ // Wächter für die Kern/Hülle-Grenze (docs/core-ui-split.md, Phase A). Es gibt kein ESLint im // Projekt — die Regeln laufen deshalb als Test über die Importzeilen aller Quelldateien. // -// 1. Der KERN (model, geometry, plan, io, export, analysis, materials, text, engine) importiert +// 1. Der KERN (core, model, geometry, plan, io, export, analysis, materials, text, engine, net) — auch +// transitiv über relative Importe importiert // nie die HÜLLE (ui, panels, views, menus, editors, viewport, native, tools, state, commands, // App) und nie React/Zustand/Tauri statisch. // 2. Die HÜLLE holt Funktionen aus `plan/` und `geometry/` nur über die Fassade `src/core`. @@ -14,7 +15,7 @@ import { readdirSync, readFileSync, statSync } from "node:fs"; import { dirname, join, normalize, relative, sep } from "node:path"; const SRC = join(process.cwd(), "src"); -const CORE_DIRS = new Set(["core", "model", "geometry", "plan", "io", "export", "analysis", "materials", "text", "engine"]); +const CORE_DIRS = new Set(["core", "model", "geometry", "plan", "io", "export", "analysis", "materials", "text", "engine", "net"]); const SHELL_DIRS = new Set(["ui", "panels", "views", "menus", "editors", "viewport", "native", "tools", "state", "commands"]); const FACADE_DIRS = new Set(["plan", "geometry"]); const FORBIDDEN_PACKAGES = /^(react|react-dom|zustand|@tauri-apps\/.*)$/; @@ -80,6 +81,43 @@ describe("Kern/Hülle-Grenze", () => { expect(violations).toEqual([]); }); + it("der Kern erreicht transitiv keine Hülle und keine UI-Pakete", () => { + const violations: string[] = []; + const resolve = (target: string): string | null => { + for (const c of [`${target}.ts`, `${target}.tsx`, `${target}/index.ts`, `${target}/index.tsx`, target]) { + const abs = join(SRC, c); + try { + if (statSync(abs).isFile()) return abs; + } catch { + /* nächster Kandidat */ + } + } + return null; + }; + for (const root of files) { + if (!CORE_DIRS.has(top(root))) continue; + const seen = new Set([root]); + const queue: Array<{ file: string; path: string[] }> = [{ file: root, path: [] }]; + while (queue.length) { + const { file, path } = queue.shift()!; + for (const i of importsOf(file)) { + const tt = i.target?.split("/")[0]; + const chain = () => [relative(SRC, root), ...path, i.target ?? i.spec].join(" → "); + if (tt && (SHELL_DIRS.has(tt) || tt === "App" || tt === "main")) violations.push(chain()); + else if (!i.target && FORBIDDEN_PACKAGES.test(i.spec)) violations.push(chain()); + else if (i.target) { + const next = resolve(i.target); + if (next && !seen.has(next) && !/\.test\.tsx?$/.test(next)) { + seen.add(next); + queue.push({ file: next, path: [...path, i.target] }); + } + } + } + } + } + expect([...new Set(violations)]).toEqual([]); + }); + it("die Hülle holt plan/ und geometry/ nur über die Fassade src/core", () => { const violations: string[] = []; for (const f of files) { diff --git a/src/export/areaReport.ts b/src/export/areaReport.ts index 66321116..67bce144 100644 --- a/src/export/areaReport.ts +++ b/src/export/areaReport.ts @@ -11,7 +11,7 @@ import { jsPDF } from "jspdf"; import type { Project } from "../model/types"; -import { t } from "../i18n"; +import { t } from "../i18n/translate"; import { core } from "../engine/coreWasm"; import { computeAreaTable, computeIvhb } from "../analysis/areaTable"; import type { AreaRow, IvhbOptions } from "../analysis/areaTable"; diff --git a/src/export/elementSchedule.ts b/src/export/elementSchedule.ts index 02d0d058..104e0c8e 100644 --- a/src/export/elementSchedule.ts +++ b/src/export/elementSchedule.ts @@ -4,7 +4,7 @@ // (wie die Fenster-/Türliste, `openingSchedule.ts`). import type { Layer, Project } from "../model/types"; -import { t } from "../i18n"; +import { t } from "../i18n/translate"; import { documentFor } from "../core/document"; import type { AreaReport, Cell, ReportRow } from "./areaReport"; diff --git a/src/export/layoutPdf.ts b/src/export/layoutPdf.ts index 2cc81923..be2a7312 100644 --- a/src/export/layoutPdf.ts +++ b/src/export/layoutPdf.ts @@ -13,7 +13,7 @@ import { jsPDF } from "jspdf"; import "svg2pdf.js"; import type { Layout, LayoutPaperFormat, MasterLayout, Project } from "../model/types"; -import { t } from "../i18n"; +import { t } from "../i18n/translate"; import { legendPlan, legendPrintSvg } from "./legendSvg"; import { categoryLayerGroups, enablePdfLayers, type PdfLayers } from "./pdfLayers"; import { generatePlan, type Plan } from "../plan/generatePlan"; diff --git a/src/export/openingSchedule.ts b/src/export/openingSchedule.ts index e89670fc..b00a43c3 100644 --- a/src/export/openingSchedule.ts +++ b/src/export/openingSchedule.ts @@ -4,7 +4,7 @@ // (`areaReport.ts`: `areaReportToCsv` / `areaReportToSvg` / `buildAreaReportPdf`). import type { Project } from "../model/types"; -import { t } from "../i18n"; +import { t } from "../i18n/translate"; import { documentFor } from "../core/document"; import type { AreaReport, Cell, ReportRow, ReportSection } from "./areaReport"; diff --git a/src/export/programReport.ts b/src/export/programReport.ts index c71772c2..0bbd1826 100644 --- a/src/export/programReport.ts +++ b/src/export/programReport.ts @@ -3,7 +3,7 @@ // Die Zahlen rechnet der Kern (`analysis/roomProgram.ts`); hier nur die Beschriftung mit `t()`. import type { Project } from "../model/types"; -import { t } from "../i18n"; +import { t } from "../i18n/translate"; import { compareRoomProgram } from "../analysis/roomProgram"; import type { CompareSum, Light } from "../analysis/roomProgram"; import type { AreaReport, Cell, ReportRow, ReportSection } from "./areaReport"; diff --git a/src/export/sheetTable.ts b/src/export/sheetTable.ts index 5080949e..d734d831 100644 --- a/src/export/sheetTable.ts +++ b/src/export/sheetTable.ts @@ -5,7 +5,7 @@ import type { jsPDF } from "jspdf"; import type { Layout, LayoutTable, LayoutTableSource, Project } from "../model/types"; -import { t } from "../i18n"; +import { t } from "../i18n/translate"; import { documentFor } from "../core/document"; export type { LayoutTable, LayoutTableSource }; diff --git a/src/i18n/de.ts b/src/i18n/de.ts index f559683e..75fad19e 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -2384,6 +2384,7 @@ export const de = { "startup.previousCrashed": "Dossier wurde beim letzten Mal nicht sauber beendet. Ungesicherte Arbeit wird beim Öffnen zur Wiederherstellung angeboten.", "project.open.failed": "Projekt konnte nicht geöffnet werden.", "core.restarted": "Interner Fehler im Kern – der Vorgang wurde abgebrochen, das Projekt ist wiederhergestellt. Der Rückgängig-Verlauf wurde dabei geleert.", + "project.save.failed": "Projekt konnte nicht gespeichert werden; die Datei und die Wiederherstellungskopie bleiben unverändert.", "menu.native.clashCheck": "Kollisionsprüfung …", "menu.native.kennzahlen": "Kennzahlen und Raumprogramm …", "kennzahlen.summary": "GF {gf} m² · aGF {agf} m² · GV {gv} m³", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index bdbd513f..4417c4b4 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -2334,6 +2334,7 @@ export const en: Record = { "startup.previousCrashed": "Dossier did not shut down cleanly last time. Unsaved work is offered for recovery when you open it.", "project.open.failed": "Project could not be opened.", "core.restarted": "Internal error in the core – the operation was aborted and the project has been restored. The undo history was cleared.", + "project.save.failed": "Project could not be saved; the file and the recovery copy are unchanged.", "menu.native.clashCheck": "Clash detection …", "menu.native.kennzahlen": "Key figures and room programme …", "kennzahlen.summary": "GFA {gf} m² · usable {agf} m² · volume {gv} m³", diff --git a/src/i18n/index.ts b/src/i18n/index.ts index 44ae4316..2dd14c9f 100644 --- a/src/i18n/index.ts +++ b/src/i18n/index.ts @@ -1,94 +1,15 @@ -// i18n-Schicht — eine einzige Übersetzungsfunktion `t(key, params?)` plus ein -// optionaler React-Hook `useT`. Default-Sprache ist Deutsch; das deutsche -// Wörterbuch (de.ts) hält die EXAKTEN bisherigen UI-Texte, sodass die Umstellung -// optisch nichts ändert. en.ts beweist die Übersetzbarkeit. -// -// Bewusst minimal gehalten: ein modulweiter „current language" + Wörterbuch- -// Lookup mit {param}-Interpolation. Kein Provider-Zwang — t(...) ist überall -// direkt aufrufbar; useT() liefert dieselbe Funktion und re-rendert Komponenten -// beim Sprachwechsel (subscribe), falls je ein Umschalter gebaut wird. -// -// Identifier/Keys bleiben englisch (DOSSIER-Namespacing); nur die Wörterbuch- -// Werte sind übersetzbarer Text. +// i18n-Fassade: React-freier Kern in ./translate (für Kern-Module), dazu der React-Hook `useT`. import { useSyncExternalStore } from "react"; -import { de } from "./de"; -import { en } from "./en"; -import type { TranslationKey } from "./de"; +import { getLanguage, subscribeLanguage, t } from "./translate"; -export type { TranslationKey } from "./de"; - -/** Unterstützte Sprachen. Default ist „de". */ -export type Language = "de" | "en"; - -/** Wörterbücher je Sprache. de ist die Quelle der Keys (Default-Sprache). */ -const DICTS: Record> = { de, en }; - -/** Werte für die Platzhalter-Interpolation (`{name}` → params.name). */ -export type TParams = Record; - -// ── Modulweiter Sprachzustand + Abonnenten (für useT) ────────────────────── - -let currentLanguage: Language = "de"; -const listeners = new Set<() => void>(); - -/** Aktuell gewählte Sprache. */ -export function getLanguage(): Language { - return currentLanguage; -} - -/** - * Sprache umschalten. Benachrichtigt abonnierte Komponenten (useT), damit sie - * mit den neuen Texten neu rendern. (Noch kein UI-Umschalter — die Naht ist - * aber vorhanden und verdrahtet.) - */ -export function setLanguage(lang: Language): void { - if (lang === currentLanguage) return; - currentLanguage = lang; - for (const l of listeners) l(); -} - -// ── Kern: Lookup + Interpolation ─────────────────────────────────────────── - -/** Ersetzt `{name}`-Platzhalter im Wert durch die übergebenen Parameter. */ -function interpolate(value: string, params?: TParams): string { - if (!params) return value; - return value.replace(/\{(\w+)\}/g, (match, name: string) => - name in params ? String(params[name]) : match, - ); -} - -/** - * Übersetzt einen Key in der aktuellen Sprache mit optionaler {param}- - * Interpolation. Fehlt der Key in der gewählten Sprache, greift Deutsch als - * Fallback; fehlt er auch dort, wird der Key selbst zurückgegeben (sichtbar, - * damit fehlende Texte auffallen statt leer zu bleiben). - */ -export function t(key: TranslationKey | string, params?: TParams): string { - const dict = DICTS[currentLanguage]; - const value = - (dict as Record)[key] ?? - (de as Record)[key] ?? - key; - return interpolate(value, params); -} - -// ── React-Hook ───────────────────────────────────────────────────────────── +export * from "./translate"; /** * Hook-Variante: liefert dieselbe `t`-Funktion, abonniert aber den - * Sprachzustand, sodass die Komponente beim Sprachwechsel neu rendert. In den - * meisten Komponenten reicht der direkte `t`-Import; useT() ist für den Fall - * gedacht, dass ein Live-Sprachumschalter existiert. + * Sprachzustand, sodass die Komponente beim Sprachwechsel neu rendert. */ export function useT(): typeof t { - useSyncExternalStore( - (cb) => { - listeners.add(cb); - return () => listeners.delete(cb); - }, - getLanguage, - getLanguage, - ); + useSyncExternalStore(subscribeLanguage, getLanguage, getLanguage); return t; } diff --git a/src/i18n/translate.ts b/src/i18n/translate.ts new file mode 100644 index 00000000..3d004700 --- /dev/null +++ b/src/i18n/translate.ts @@ -0,0 +1,80 @@ +// i18n-Kern (React-frei) — von Kern-Modulen importierbar. Der Hook `useT` liegt in index.ts. +// i18n-Schicht — eine einzige Übersetzungsfunktion `t(key, params?)` plus ein +// optionaler React-Hook `useT`. Default-Sprache ist Deutsch; das deutsche +// Wörterbuch (de.ts) hält die EXAKTEN bisherigen UI-Texte, sodass die Umstellung +// optisch nichts ändert. en.ts beweist die Übersetzbarkeit. +// +// Bewusst minimal gehalten: ein modulweiter „current language" + Wörterbuch- +// Lookup mit {param}-Interpolation. Kein Provider-Zwang — t(...) ist überall +// direkt aufrufbar; useT() liefert dieselbe Funktion und re-rendert Komponenten +// beim Sprachwechsel (subscribe), falls je ein Umschalter gebaut wird. +// +// Identifier/Keys bleiben englisch (DOSSIER-Namespacing); nur die Wörterbuch- +// Werte sind übersetzbarer Text. + +import { de } from "./de"; +import { en } from "./en"; +import type { TranslationKey } from "./de"; + +export type { TranslationKey } from "./de"; + +/** Unterstützte Sprachen. Default ist „de". */ +export type Language = "de" | "en"; + +/** Wörterbücher je Sprache. de ist die Quelle der Keys (Default-Sprache). */ +const DICTS: Record> = { de, en }; + +/** Werte für die Platzhalter-Interpolation (`{name}` → params.name). */ +export type TParams = Record; + +// ── Modulweiter Sprachzustand + Abonnenten (für useT) ────────────────────── + +let currentLanguage: Language = "de"; +const listeners = new Set<() => void>(); + +/** Aktuell gewählte Sprache. */ +export function getLanguage(): Language { + return currentLanguage; +} + +/** + * Sprache umschalten. Benachrichtigt abonnierte Komponenten (useT), damit sie + * mit den neuen Texten neu rendern. (Noch kein UI-Umschalter — die Naht ist + * aber vorhanden und verdrahtet.) + */ +export function setLanguage(lang: Language): void { + if (lang === currentLanguage) return; + currentLanguage = lang; + for (const l of listeners) l(); +} + +// ── Kern: Lookup + Interpolation ─────────────────────────────────────────── + +/** Ersetzt `{name}`-Platzhalter im Wert durch die übergebenen Parameter. */ +function interpolate(value: string, params?: TParams): string { + if (!params) return value; + return value.replace(/\{(\w+)\}/g, (match, name: string) => + name in params ? String(params[name]) : match, + ); +} + +/** + * Übersetzt einen Key in der aktuellen Sprache mit optionaler {param}- + * Interpolation. Fehlt der Key in der gewählten Sprache, greift Deutsch als + * Fallback; fehlt er auch dort, wird der Key selbst zurückgegeben (sichtbar, + * damit fehlende Texte auffallen statt leer zu bleiben). + */ +export function t(key: TranslationKey | string, params?: TParams): string { + const dict = DICTS[currentLanguage]; + const value = + (dict as Record)[key] ?? + (de as Record)[key] ?? + key; + return interpolate(value, params); +} + +/** Abo für den Sprachzustand (für `useT`). */ +export function subscribeLanguage(cb: () => void): () => void { + listeners.add(cb); + return () => listeners.delete(cb); +} diff --git a/src/main.tsx b/src/main.tsx index e14a105b..e9ae27ff 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -11,6 +11,7 @@ import { initCore } from "./core"; import { getLanguage, setLanguage } from "./i18n"; import type { Language } from "./i18n"; import { applyThemeMode, getStoredThemeMode } from "./theme/themeMode"; +import "material-symbols/outlined.css"; import "./styles.css"; import "./text/fonts.css"; diff --git a/src/native/projectFile.ts b/src/native/projectFile.ts index 03c2d837..fcb80bbc 100644 --- a/src/native/projectFile.ts +++ b/src/native/projectFile.ts @@ -118,6 +118,7 @@ export async function openProjectFileAtPath(path: string): Promise void, ): Promise { const filename = `${projectName || "projekt"}.${PROJECT_EXT}`; - return saveTextFile(json, filename, "application/json", PROJECT_DIALOG_FILTERS, onSavedPath); + return saveTextFile(json, filename, "application/json", PROJECT_DIALOG_FILTERS, onSavedPath, true); } // ── Lock gegen Doppelöffnung (nur Tauri) ──────────────────────────────────── diff --git a/src/native/saveFile.test.ts b/src/native/saveFile.test.ts index 73919347..69d6169c 100644 --- a/src/native/saveFile.test.ts +++ b/src/native/saveFile.test.ts @@ -49,3 +49,34 @@ describe("saveTextFile", () => { await expect(saveTextFile("x", "a.bin")).resolves.toBe(true); }); }); + +describe("saveTextFile atomar ([116])", () => { + async function withTauri(invoke: (cmd: string, args: unknown) => Promise) { + vi.resetModules(); + vi.stubGlobal("window", { __TAURI_INTERNALS__: {} }); + vi.doMock("@tauri-apps/plugin-dialog", () => ({ save: async () => "/tmp/x/a.obp" })); + vi.doMock("@tauri-apps/api/core", () => ({ invoke })); + return import("./saveFile"); + } + + it("ruft save_atomic mit Pfad und Inhalt und meldet den Pfad erst danach", async () => { + const calls: unknown[][] = []; + const m = await withTauri(async (cmd, args) => void calls.push([cmd, args])); + const saved: string[] = []; + const ok = await m.saveTextFile("{}", "a.obp", "application/json", undefined, (p) => saved.push(p), true); + expect(ok).toBe(true); + expect(calls).toEqual([["save_atomic", { path: "/tmp/x/a.obp", content: "{}" }]]); + expect(saved).toEqual(["/tmp/x/a.obp"]); + }); + + it("wirft SaveError bei Fehler, ohne Download-Fallback und ohne Pfad-Callback", async () => { + const m = await withTauri(async () => { + throw "Umbenennen: Permission denied"; + }); + const saved: string[] = []; + await expect( + m.saveTextFile("{}", "a.obp", "application/json", undefined, (p) => saved.push(p), true), + ).rejects.toBeInstanceOf(m.SaveError); + expect(saved).toEqual([]); + }); +}); diff --git a/src/native/saveFile.ts b/src/native/saveFile.ts index b9a97f28..302b569c 100644 --- a/src/native/saveFile.ts +++ b/src/native/saveFile.ts @@ -12,6 +12,26 @@ function isTauri(): boolean { let warnedFallback = false; +/** Schreiben in die Zieldatei ist gescheitert ([116]); die bisherige Datei ist unverändert. + * Wird NICHT auf den Browser-Download zurückgefallen — der Aufrufer meldet es dem Nutzer. */ +export class SaveError extends Error { + constructor(message: string) { + super(message); + this.name = "SaveError"; + } +} + +/** Atomar schreiben über den Rust-Befehl `save_atomic` (Temp-Datei + fsync + Umbenennen, + * Vorversion als `~`). Wirft {@link SaveError}. */ +export async function writeFileAtomic(path: string, content: string): Promise { + try { + const { invoke } = await import("@tauri-apps/api/core"); + await invoke("save_atomic", { path, content }); + } catch (err) { + throw new SaveError(err instanceof Error ? err.message : String(err)); + } +} + /** Datei-Endungsfilter fuer den nativen Speichern-/Oeffnen-Dialog (Tauri). */ export interface FileDialogFilter { name: string; @@ -29,6 +49,8 @@ export interface FileDialogFilter { * @param onSavedPath Optionaler Callback mit dem gewaehlten Pfad, NUR bei * erfolgreichem Tauri-Speichern (z. B. fuer die Zuletzt-geoeffnet-Liste, * s. state/recentProjects.ts) — additiv, aendert den Rueckgabewert nicht. + * @param atomic Absturzsicher schreiben ([116], `writeFileAtomic`): bei Fehler wird + * {@link SaveError} geworfen statt auf den Download zurückzufallen. * @returns `true` wenn geschrieben/geladen wurde, `false` bei Abbruch (Dialog * ohne Pfad). Bei einem Tauri-Fehler wird auf den Browser-Fallback * zurueckgefallen. @@ -39,17 +61,22 @@ export async function saveTextFile( mime = "application/octet-stream", filters?: FileDialogFilter[], onSavedPath?: (path: string) => void, + atomic = false, ): Promise { if (isTauri()) { try { const { save } = await import("@tauri-apps/plugin-dialog"); const path = await save({ defaultPath: defaultName, filters }); if (!path) return false; // Nutzer hat abgebrochen - const { writeTextFile } = await import("@tauri-apps/plugin-fs"); - await writeTextFile(path, content); + if (atomic) await writeFileAtomic(path, content); + else { + const { writeTextFile } = await import("@tauri-apps/plugin-fs"); + await writeTextFile(path, content); + } onSavedPath?.(path); return true; } catch (err) { + if (err instanceof SaveError) throw err; if (!warnedFallback) { warnedFallback = true; console.warn( diff --git a/src/net/csp.test.ts b/src/net/csp.test.ts new file mode 100644 index 00000000..1b083e04 --- /dev/null +++ b/src/net/csp.test.ts @@ -0,0 +1,27 @@ +// [117] Die CSP-Quelle (scripts/csp.cjs) deckt die netFetch-Hosts ab und steht wörtlich in tauri.conf.json. +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { describe, expect, it } from "vitest"; +import { ALLOWED_HOSTS } from "./net"; + +const { buildCsp, NET_HOSTS } = createRequire(import.meta.url)("../../scripts/csp.cjs") as { + buildCsp: () => string; + NET_HOSTS: string[]; +}; + +describe("CSP", () => { + it("connect-src enthält genau die Remote-Hosts von ALLOWED_HOSTS", () => { + const remote = ALLOWED_HOSTS.filter((h) => h !== "localhost" && h !== "127.0.0.1"); + expect([...NET_HOSTS].sort()).toEqual([...remote].sort()); + const connect = buildCsp().split("; ").find((d) => d.startsWith("connect-src "))!; + for (const h of remote) expect(connect).toContain(`https://${h}`); + }); + it("tauri.conf.json trägt dieselbe Richtlinie", () => { + const conf = JSON.parse(readFileSync("src-tauri/tauri.conf.json", "utf8")); + expect(conf.app.security.csp).toBe(buildCsp()); + }); + it("kein unsafe-eval, keine Inline-Skripte", () => { + const script = buildCsp().split("; ").find((d) => d.startsWith("script-src "))!; + expect(script).toBe("script-src 'self' 'wasm-unsafe-eval'"); + }); +}); diff --git a/src/plan/__golden__/komplex-ansicht-ansicht-sued.txt b/src/plan/__golden__/komplex-ansicht-ansicht-sued.txt new file mode 100644 index 00000000..42327abe --- /dev/null +++ b/src/plan/__golden__/komplex-ansicht-ansicht-sued.txt @@ -0,0 +1,9 @@ +viewBox -4.2 0 37.045 17.778 +bytes 344306 +circle 4 +line 1261 +polygon 1529 +rect 1 +svg 1 +text 4 +hash ac47902c2752e848 diff --git a/src/plan/__golden__/komplex-grundriss-dg-100.txt b/src/plan/__golden__/komplex-grundriss-dg-100.txt new file mode 100644 index 00000000..9ba222c5 --- /dev/null +++ b/src/plan/__golden__/komplex-grundriss-dg-100.txt @@ -0,0 +1,10 @@ +viewBox -16.5 0 49 35.22 +bytes 339680 +circle 14 +line 3498 +path 8 +polygon 91 +rect 1 +svg 1 +text 36 +hash 30888ca0d5cb84be diff --git a/src/plan/__golden__/komplex-grundriss-dg-50.txt b/src/plan/__golden__/komplex-grundriss-dg-50.txt new file mode 100644 index 00000000..c9504c2e --- /dev/null +++ b/src/plan/__golden__/komplex-grundriss-dg-50.txt @@ -0,0 +1,10 @@ +viewBox -16.5 0 49 35.22 +bytes 343059 +circle 14 +line 3498 +path 8 +polygon 91 +rect 1 +svg 1 +text 36 +hash f96ebde7ba7f7e74 diff --git a/src/plan/__golden__/komplex-grundriss-eg-100.txt b/src/plan/__golden__/komplex-grundriss-eg-100.txt new file mode 100644 index 00000000..48d39275 --- /dev/null +++ b/src/plan/__golden__/komplex-grundriss-eg-100.txt @@ -0,0 +1,10 @@ +viewBox -41.5 0 95 63.6 +bytes 148973 +circle 16 +line 861 +path 68 +polygon 260 +rect 1 +svg 1 +text 123 +hash aefdd0fe3c4658bd diff --git a/src/plan/__golden__/komplex-grundriss-eg-50.txt b/src/plan/__golden__/komplex-grundriss-eg-50.txt new file mode 100644 index 00000000..58242c95 --- /dev/null +++ b/src/plan/__golden__/komplex-grundriss-eg-50.txt @@ -0,0 +1,10 @@ +viewBox -41.5 0 95 63.6 +bytes 149368 +circle 16 +line 861 +path 68 +polygon 260 +rect 1 +svg 1 +text 123 +hash 65c62fa0ef5ee339 diff --git a/src/plan/__golden__/komplex-grundriss-og-100.txt b/src/plan/__golden__/komplex-grundriss-og-100.txt new file mode 100644 index 00000000..0b01a191 --- /dev/null +++ b/src/plan/__golden__/komplex-grundriss-og-100.txt @@ -0,0 +1,10 @@ +viewBox -16.5 0 49 35.22 +bytes 425217 +circle 14 +line 4040 +path 40 +polygon 236 +rect 1 +svg 1 +text 93 +hash 961473ba9c3e6937 diff --git a/src/plan/__golden__/komplex-grundriss-og-50.txt b/src/plan/__golden__/komplex-grundriss-og-50.txt new file mode 100644 index 00000000..81774b12 --- /dev/null +++ b/src/plan/__golden__/komplex-grundriss-og-50.txt @@ -0,0 +1,10 @@ +viewBox -16.5 0 49 35.22 +bytes 428731 +circle 14 +line 4040 +path 40 +polygon 236 +rect 1 +svg 1 +text 93 +hash 6f37dfa59b4e84a0 diff --git a/src/plan/__golden__/komplex-grundriss-ug-100.txt b/src/plan/__golden__/komplex-grundriss-ug-100.txt new file mode 100644 index 00000000..915f1b5b --- /dev/null +++ b/src/plan/__golden__/komplex-grundriss-ug-100.txt @@ -0,0 +1,10 @@ +viewBox -16.5 0 49 38.11 +bytes 86366 +circle 14 +line 501 +path 29 +polygon 113 +rect 1 +svg 1 +text 74 +hash cd3c20b2431eec2e diff --git a/src/plan/__golden__/komplex-grundriss-ug-50.txt b/src/plan/__golden__/komplex-grundriss-ug-50.txt new file mode 100644 index 00000000..d00f81f1 --- /dev/null +++ b/src/plan/__golden__/komplex-grundriss-ug-50.txt @@ -0,0 +1,10 @@ +viewBox -16.5 0 49 38.11 +bytes 86522 +circle 14 +line 501 +path 29 +polygon 113 +rect 1 +svg 1 +text 74 +hash 53435c6a8ca1a431 diff --git a/src/plan/__golden__/komplex-model3d.txt b/src/plan/__golden__/komplex-model3d.txt new file mode 100644 index 00000000..538d46ea --- /dev/null +++ b/src/plan/__golden__/komplex-model3d.txt @@ -0,0 +1,53 @@ +meshes [1849] +meshes[].color [3] x1849 +meshes[].indices [108] x6 +meshes[].indices [156648] +meshes[].indices [348] x6 +meshes[].indices [36] x1816 +meshes[].indices [372] +meshes[].indices [4032] +meshes[].indices [60] x9 +meshes[].indices [72] +meshes[].indices [84] x2 +meshes[].indices [96] x6 +meshes[].positions [1044] x6 +meshes[].positions [108] x30 +meshes[].positions [180] x9 +meshes[].positions [192] +meshes[].positions [216] +meshes[].positions [24] x1781 +meshes[].positions [252] x2 +meshes[].positions [2688] +meshes[].positions [288] x6 +meshes[].positions [324] x6 +meshes[].positions [72] x5 +meshes[].positions [78840] +roofLayers [59] +roofLayers[].color [3] x59 +roofLayers[].normal [3] x59 +roofLayers[].polygon [4] x53 +roofLayers[].polygon [5] x6 +roofLayers[].polygon[] [3] x242 +slabs [102] +slabs[].color [3] x102 +slabs[].outline [12] +slabs[].outline [14] x5 +slabs[].outline [21] x4 +slabs[].outline [24] +slabs[].outline [33] x5 +slabs[].outline [4] x81 +slabs[].outline [51] x5 +slabs[].outline[] [2] x934 +walls [1508] +walls[].color [3] x1508 +walls[].end [2] x1508 +walls[].endCut [4] x1139 +walls[].holes [1] x84 +walls[].holes [2] x25 +walls[].holes [3] x14 +walls[].layers [0] x1508 +walls[].start [2] x1508 +walls[].startCut [4] x1137 +walls[].topDrop [2] x112 +walls[].topPlane [3] x268 +hash cd9596786d4adacb diff --git a/src/plan/__golden__/komplex-schnitt-schnitt-a.txt b/src/plan/__golden__/komplex-schnitt-schnitt-a.txt new file mode 100644 index 00000000..455a3b6a --- /dev/null +++ b/src/plan/__golden__/komplex-schnitt-schnitt-a.txt @@ -0,0 +1,9 @@ +viewBox 4.457 0 21.343 17.778 +bytes 44167 +circle 3 +line 148 +polygon 169 +rect 1 +svg 1 +text 3 +hash 3310ddbc4a0ea666 diff --git a/src/plan/__golden__/muster-ansicht-ansicht-sued.txt b/src/plan/__golden__/muster-ansicht-ansicht-sued.txt new file mode 100644 index 00000000..78e8913b --- /dev/null +++ b/src/plan/__golden__/muster-ansicht-ansicht-sued.txt @@ -0,0 +1,7 @@ +viewBox 0.1 0 6.8 7.586 +bytes 8483 +line 31 +polygon 42 +rect 1 +svg 1 +hash c9caba6eee20fbd9 diff --git a/src/plan/__golden__/muster-grundriss-eg-100.txt b/src/plan/__golden__/muster-grundriss-eg-100.txt new file mode 100644 index 00000000..c334f7c9 --- /dev/null +++ b/src/plan/__golden__/muster-grundriss-eg-100.txt @@ -0,0 +1,9 @@ +viewBox -0.672 0 6.345 5.345 +bytes 15919 +line 67 +path 8 +polygon 61 +rect 1 +svg 1 +text 7 +hash 97bd11bea3bf9d08 diff --git a/src/plan/__golden__/muster-grundriss-eg-50.txt b/src/plan/__golden__/muster-grundriss-eg-50.txt new file mode 100644 index 00000000..decb859d --- /dev/null +++ b/src/plan/__golden__/muster-grundriss-eg-50.txt @@ -0,0 +1,9 @@ +viewBox -0.672 0 6.345 5.345 +bytes 15939 +line 67 +path 8 +polygon 61 +rect 1 +svg 1 +text 7 +hash 7dfca568eb0b0d41 diff --git a/src/plan/__golden__/muster-grundriss-og-100.txt b/src/plan/__golden__/muster-grundriss-og-100.txt new file mode 100644 index 00000000..0fd1ba0c --- /dev/null +++ b/src/plan/__golden__/muster-grundriss-og-100.txt @@ -0,0 +1,9 @@ +viewBox -0.9 0 6.8 5.8 +bytes 7180 +line 35 +path 4 +polygon 23 +rect 1 +svg 1 +text 4 +hash 5b480a1ff81665ec diff --git a/src/plan/__golden__/muster-grundriss-og-50.txt b/src/plan/__golden__/muster-grundriss-og-50.txt new file mode 100644 index 00000000..df7c84d1 --- /dev/null +++ b/src/plan/__golden__/muster-grundriss-og-50.txt @@ -0,0 +1,9 @@ +viewBox -0.9 0 6.8 5.8 +bytes 7202 +line 35 +path 4 +polygon 23 +rect 1 +svg 1 +text 4 +hash f1c8c391382719b8 diff --git a/src/plan/__golden__/muster-model3d.txt b/src/plan/__golden__/muster-model3d.txt new file mode 100644 index 00000000..ca0e1205 --- /dev/null +++ b/src/plan/__golden__/muster-model3d.txt @@ -0,0 +1,31 @@ +meshes [44] +meshes[].color [3] x44 +meshes[].indices [36] x42 +meshes[].indices [540] +meshes[].indices [60] +meshes[].positions [120] +meshes[].positions [24] x42 +meshes[].positions [360] +roofLayers [2] +roofLayers[].color [3] x2 +roofLayers[].normal [3] x2 +roofLayers[].polygon [4] x2 +roofLayers[].polygon[] [3] x8 +slabs [3] +slabs[].color [3] x3 +slabs[].cut.lineColor [3] +slabs[].outline [4] x3 +slabs[].outline[] [2] x12 +walls [47] +walls[].color [3] x47 +walls[].cut.lineColor [3] x11 +walls[].end [2] x47 +walls[].endCut [4] x47 +walls[].holes [1] x5 +walls[].holes [2] x5 +walls[].layers [0] x47 +walls[].start [2] x47 +walls[].startCut [4] x47 +walls[].topDrop [2] x6 +walls[].topPlane [3] x6 +hash 43431f51d1e44e8b diff --git a/src/plan/__golden__/muster-schnitt-schnitt-a.txt b/src/plan/__golden__/muster-schnitt-schnitt-a.txt new file mode 100644 index 00000000..08bf1a7e --- /dev/null +++ b/src/plan/__golden__/muster-schnitt-schnitt-a.txt @@ -0,0 +1,7 @@ +viewBox 0.1 0 6.8 7.586 +bytes 7242 +line 31 +polygon 31 +rect 1 +svg 1 +hash 64ff798e38d40dd0 diff --git a/src/plan/golden.test.ts b/src/plan/golden.test.ts new file mode 100644 index 00000000..ab4e6d9d --- /dev/null +++ b/src/plan/golden.test.ts @@ -0,0 +1,101 @@ +// [119] Referenz-Ausgaben: Plan (je Geschoss, 1:100 und 1:50), ein Schnitt, eine Ansicht und die +// 3D-Zusammenfassung beider Musterprojekte als lesbarer Digest (Zähler, Rahmen, Hash der gerundeten +// Zahlen) gegen eingecheckte Dateien in src/plan/__golden__. Gewollte Änderung übernehmen mit +// npx vitest run -u src/plan/golden.test.ts +// und den Diff der Dateien im Commit ansehen. Zahlen sind gerundet (Plan 1e-3 m, 3D 1e-4 m). +import { describe, expect, it } from "vitest"; +import { createHash } from "node:crypto"; +import { computeSection, generateElevationPlan, generatePlan, generateSectionPlan, planToSvgString, projectToModel3d } from "../core"; +import { sampleProject } from "../model/sampleProject"; +import { buildComplexSampleProject } from "../model/sampleProjectComplex"; +import type { Project } from "../model/types"; + +const roundNums = (s: string, dec: number): string => + s.replace(/-?\d+\.\d+(?:e-?\d+)?/g, (m) => { + const v = Number(Number(m).toFixed(dec)); + return String(Object.is(v, -0) ? 0 : v); + }); +const sha = (s: string): string => createHash("sha256").update(s).digest("hex").slice(0, 16); + +function svgDigest(svg: string): string { + const s = roundNums(svg, 3); + const tags = new Map(); + for (const m of s.matchAll(/<([a-z]+)\b/g)) tags.set(m[1], (tags.get(m[1]) ?? 0) + 1); + const viewBox = /viewBox="([^"]*)"/.exec(s)?.[1] ?? "-"; + const lines = [`viewBox ${viewBox}`, `bytes ${s.length}`]; + for (const [k, v] of [...tags].sort()) lines.push(`${k} ${v}`); + lines.push(`hash ${sha(s)}`); + return lines.join("\n") + "\n"; +} + +// Beliebige Struktur → Zähler je Feld (Länge von Listen/Puffern) + Hash der gerundeten Zahlen. +function structDigest(o: unknown): string { + const lines: string[] = []; + const h = createHash("sha256"); + const walk = (v: unknown, path: string): void => { + if (typeof v === "number") { + h.update(path + "=" + Number(v.toFixed(4)) + ";"); + } else if (ArrayBuffer.isView(v)) { + const a = Array.from(v as unknown as ArrayLike); + lines.push(`${path} [${a.length}]`); + h.update(path + ":" + a.map((x) => Number(x.toFixed(4))).join(",") + ";"); + } else if (Array.isArray(v)) { + lines.push(`${path} [${v.length}]`); + v.forEach((x, i) => walk(x, `${path}[${i}]`)); + } else if (v && typeof v === "object") { + for (const k of Object.keys(v).sort()) walk((v as Record)[k], path ? `${path}.${k}` : k); + } else { + h.update(path + "=" + String(v) + ";"); + } + }; + walk(o, ""); + // Elementweise Pfade (mit Index) nur im Hash, im Text nur die Feldzähler ohne Index + const counts = new Map(); + for (const l of lines) { + const key = l.replace(/\[\d+\](?=[. ])/g, "[]"); + counts.set(key, (counts.get(key) ?? 0) + 1); + } + return [...counts].sort().map(([k, n]) => `${k}${n > 1 ? ` x${n}` : ""}`).join("\n") + `\nhash ${h.digest("hex").slice(0, 16)}\n`; +} + +const projects: [string, () => Project][] = [ + ["muster", () => sampleProject], + ["komplex", buildComplexSampleProject], +]; + +for (const [name, make] of projects) { + describe(`Golden ${name}`, () => { + const p = make(); + const codes = new Set(p.layers.map((l) => l.code)); + + for (const lvl of p.drawingLevels.filter((l) => l.kind === "floor")) { + for (const scale of [100, 50]) { + it(`Grundriss ${lvl.id} 1:${scale}`, async () => { + const svg = planToSvgString(generatePlan(p, lvl.id, codes, undefined, "mittel", false, false, true, scale), { scaleDenominator: scale }); + await expect(svgDigest(svg)).toMatchFileSnapshot(`__golden__/${name}-grundriss-${lvl.id}-${scale}.txt`); + }); + } + } + + it("Schnitt", async () => { + const sec = p.drawingLevels.find((l) => l.kind === "section"); + if (!sec) return; + const out = await computeSection(p, sec); + expect(out).toBeTruthy(); + const svg = planToSvgString(generateSectionPlan(out!, false, { visibleCodes: codes, hiddenLines: sec.hiddenLines, openings: true, scaleDenominator: 100 }), { scaleDenominator: 100 }); + await expect(svgDigest(svg)).toMatchFileSnapshot(`__golden__/${name}-schnitt-${sec.id}.txt`); + }, 30_000); + + it("Ansicht", async () => { + const el = p.drawingLevels.find((l) => l.kind === "elevation"); + if (!el) return; + const plan = generateElevationPlan(p, el, { scaleDenominator: 100 }); + expect(plan).toBeTruthy(); + await expect(svgDigest(planToSvgString(plan!, { scaleDenominator: 100 }))).toMatchFileSnapshot(`__golden__/${name}-ansicht-${el.id}.txt`); + }); + + it("3D-Modell", async () => { + await expect(structDigest(projectToModel3d(p))).toMatchFileSnapshot(`__golden__/${name}-model3d.txt`); + }); + }); +} diff --git a/src/state/useProjectFileActions.ts b/src/state/useProjectFileActions.ts index cbe5951a..e58f490e 100644 --- a/src/state/useProjectFileActions.ts +++ b/src/state/useProjectFileActions.ts @@ -370,15 +370,22 @@ export function useProjectFileActions( const json = serializeProject(project); return saveProjectFile(json, project.name, (path) => addRecentProject(path, project.name || "modell"), - ).then((saved) => { - if (saved) { - lastSavedProjectRef.current = project; - void clearAutosave(openedProjectPathRef.current); - void clearAutosave(null); - autosaveTracker.cleared(); - } - return saved; - }); + ).then( + (saved) => { + if (saved) { + lastSavedProjectRef.current = project; + // Erst nach erfolgreichem Umbenennen ([116]) — bei Fehler bleibt die Kopie. + void clearAutosave(openedProjectPathRef.current); + void clearAutosave(null); + autosaveTracker.cleared(); + } + return saved; + }, + (e) => { + notify(`${t("project.save.failed")} ${e instanceof Error ? e.message : String(e)}`, "error"); + return false; + }, + ); }; // „Neu" (Datei-Menü): leeres Projekt, wie am Startbildschirm — löst dabei // einen evtl. gehaltenen Datei-Lock der bisherigen Projektdatei und vergisst diff --git a/src/text/renderHtml.test.ts b/src/text/renderHtml.test.ts index 18ca49f0..382b3373 100644 --- a/src/text/renderHtml.test.ts +++ b/src/text/renderHtml.test.ts @@ -119,3 +119,33 @@ describe("docToHtml — sizeUnit reicht bis in jeden Run-Span durch", () => { expect(html).toContain("font-size:1.5em"); }); }); + +describe("docToHtml: Bereinigung nicht vertrauenswürdiger Dateiinhalte ([117])", () => { + const evil = (over: Record, text = "x"): RichTextDoc => + ({ + version: 1, + paragraphs: [{ runs: [{ text, marks: { ...over } }] }], + }) as unknown as RichTextDoc; + + it("escapt Tags im Text", () => { + const html = docToHtml(evil({}, '')); + expect(html).not.toContain(" { + const html = docToHtml(evil({ font: 'a";onmouseover="alert(1)', color: "red;background:url(https://evil/x)" })); + expect(html).not.toContain("onmouseover"); + expect(html).not.toContain("url("); + expect(html).not.toContain("font-family"); + }); + it("behält harmlose Werte", () => { + const html = docToHtml(evil({ font: "Inter", color: "#aabbcc" })); + expect(html).toContain("font-family:Inter"); + expect(html).toContain("color:#aabbcc"); + }); + it("Absatz-Ausrichtung nur aus der Positivliste", () => { + const doc = { version: 1, paragraphs: [{ align: 'center;position:fixed', runs: [] }] } as unknown as RichTextDoc; + expect(docToHtml(doc)).not.toContain("position"); + }); +}); diff --git a/src/text/renderHtml.ts b/src/text/renderHtml.ts index d1f0e67c..5dbe3a19 100644 --- a/src/text/renderHtml.ts +++ b/src/text/renderHtml.ts @@ -27,6 +27,31 @@ function escapeAttr(s: string): string { // ── Gemeinsame Mark→Stil-Zuordnung ────────────────────────────────────────── +// ── CSS-Werte aus Dateien ([117]) ─────────────────────────────────────────── +// Rich-Text kommt auch aus importierten Projektdateien und landet per `innerHTML` im Editor. Der Text ist +// escaped; die Stil-Werte (Farbe, Schriftname, Ausrichtung, Zeilenhöhe) werden hier auf eine Positivliste +// beschränkt, damit keine CSS-Einschleusung (`;`, `url(…)`, `position:fixed` …) möglich ist. + +/** Farbe: `#rgb[a]`/`#rrggbb[aa]`, `rgb()/rgba()/hsl()` mit Zahlen, `var(--name)` oder ein Farbwort. */ +export function safeCssColor(v: unknown): string | undefined { + if (typeof v !== "string") return undefined; + const c = v.trim(); + if (/^#[0-9a-f]{3,8}$/i.test(c)) return c; + if (/^(rgb|rgba|hsl|hsla)\(\s*[0-9.%\s,/-]+\)$/i.test(c)) return c; + if (/^var\(--[a-z0-9-]+\)$/i.test(c)) return c; + if (/^[a-z]{3,20}$/i.test(c)) return c; + return undefined; +} + +/** Schriftname: Buchstaben, Ziffern, Leerzeichen, `-`, `,`, `_`, `.`, Anführungszeichen (kein `;(){}:/\\`). */ +export function safeFontFamily(v: unknown): string | undefined { + if (typeof v !== "string") return undefined; + const f = v.trim(); + return f.length > 0 && f.length <= 120 && /^[\p{L}\p{N} _.,'"-]+$/u.test(f) ? f : undefined; +} + +const SAFE_ALIGN = new Set(["left", "center", "right", "justify"]); + /** Kombiniert underline + strike zu einem CSS/SVG-text-decoration-Wert. */ function textDecoration(marks: Marks): string | undefined { const parts: string[] = []; @@ -67,11 +92,13 @@ export function runCssProps( if (marks.italic) css["font-style"] = "italic"; const deco = textDecoration(marks); if (deco) css["text-decoration"] = deco; - if (marks.font) css["font-family"] = marks.font; + const font = safeFontFamily(marks.font); + if (font) css["font-family"] = font; const sizePt = (marks.sizePt ?? basePt) * (marks.super || marks.sub ? SCRIPT_SCALE : 1); css["font-size"] = sizeUnit === "em" ? `${round(sizePt / basePt)}em` : `${round(sizePt)}pt`; - if (marks.color) css["color"] = marks.color; + const color = safeCssColor(marks.color); + if (color) css["color"] = color; if (marks.super) css["vertical-align"] = "super"; if (marks.sub) css["vertical-align"] = "sub"; return css; @@ -113,8 +140,8 @@ export function docToHtml(doc: RichTextDoc, opts: HtmlOptions = {}): string { function paragraphToHtml(p: Paragraph, basePt: number, sizeUnit: "pt" | "em", color?: string): string { const styles: string[] = []; - if (p.align && p.align !== "left") styles.push(`text-align:${p.align}`); - if (p.lineHeight != null) styles.push(`line-height:${p.lineHeight}`); + if (p.align && p.align !== "left" && SAFE_ALIGN.has(p.align)) styles.push(`text-align:${p.align}`); + if (typeof p.lineHeight === "number" && Number.isFinite(p.lineHeight)) styles.push(`line-height:${p.lineHeight}`); const style = styles.length ? ` style="${styles.join(";")}"` : ""; if (p.runs.length === 0) return `
`; const inner = p.runs.map((r) => runToHtmlSpan(r, basePt, sizeUnit, color)).join(""); diff --git a/vite.config.ts b/vite.config.ts index aff933aa..d46b0f4a 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,9 +1,21 @@ import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; +import { createRequire } from "node:module"; + +const { buildCsp } = createRequire(import.meta.url)("./scripts/csp.cjs") as { buildCsp: () => string }; + +// [117] CSP nur im Build (Meta-Tag): der Dev-Server braucht Inline-Skripte für HMR/React-Refresh. +const cspPlugin = { + name: "dossier-csp", + apply: "build" as const, + transformIndexHtml: () => [ + { tag: "meta", attrs: { "http-equiv": "Content-Security-Policy", content: buildCsp() }, injectTo: "head-prepend" as const }, + ], +}; // https://vitejs.dev/config/ export default defineConfig({ - plugins: [react()], + plugins: [react(), cspPlugin], // Tauri lädt die App über den Vite-Dev-Server; dessen Logs (cargo/tauri) // sollen nicht vom Bildschirm gewischt werden, und Tauri-eigene Env-Vars // müssen im Client sichtbar sein.