From 61446b3edbde0006cd359f382e9c18d6bee1e07e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 17:37:56 +0000 Subject: [PATCH] =?UTF-8?q?[117]=20CSP:=20strikte=20Content-Security-Polic?= =?UTF-8?q?y=20f=C3=BCr=20Tauri,=20Electron=20und=20Web-Build;=20Rich-Text?= =?UTF-8?q?-Stilwerte=20bereinigt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Eine Quelle scripts/csp.cjs; tauri.conf.json (devCsp null), Electron-Header (nur gepackt), Meta-Tag im Vite-Build. Farbe/Schriftname/Ausrichtung/Zeilenhöhe aus Dateien per Positivliste. Tests: csp.test.ts, renderHtml.test.ts, e2e/csp.spec.ts. --- TODO.md | 10 +++++-- e2e/csp.spec.ts | 37 ++++++++++++++++++++++++ scripts/csp.cjs | 56 +++++++++++++++++++++++++++++++++++++ scripts/electron-main.cjs | 12 +++++++- src-tauri/tauri.conf.json | 3 +- src/net/csp.test.ts | 27 ++++++++++++++++++ src/text/renderHtml.test.ts | 30 ++++++++++++++++++++ src/text/renderHtml.ts | 35 ++++++++++++++++++++--- vite.config.ts | 14 +++++++++- 9 files changed, 215 insertions(+), 9 deletions(-) create mode 100644 e2e/csp.spec.ts create mode 100644 scripts/csp.cjs create mode 100644 src/net/csp.test.ts diff --git a/TODO.md b/TODO.md index afb89dbe..61ea7f7d 100644 --- a/TODO.md +++ b/TODO.md @@ -1043,8 +1043,14 @@ Prüfung des ganzen Programms (Rust-Kern, TS-Hülle, Build/Sicherheit), nur Code - ○ **[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 +- ✅ **[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 + fonts.googleapis.com, `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.** Dokument + Verlauf im selben WASM wie alle Geometrie (`web/document.rs`); TS hält Op-Log seit letztem Laden, baut Instanz nach Trap neu auf. · M - ○ **[119] Referenz-Ausgaben (golden).** Plan-Puffer/SVG/Schnitt/Ansicht der Musterprojekte als Snapshot; 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/scripts/csp.cjs b/scripts/csp.cjs new file mode 100644 index 00000000..c2f4a2cd --- /dev/null +++ b/scripts/csp.cjs @@ -0,0 +1,56 @@ +// Content-Security-Policy ([117]) — eine Quelle für Electron (Header), Vite-Build (Meta-Tag, damit +// `vite preview`/die e2e-Suite sie ausübt) und die Prüfung gegen `src-tauri/tauri.conf.json` +// (`src/net/csp.test.ts`; Tauri braucht den Text wörtlich in der JSON-Datei). +// Hosts = `ALLOWED_HOSTS` aus `src/net/net.ts` (der Test gleicht ab). + +const NET_HOSTS = [ + "ambientcg.com", + "api.ambientcg.com", + "geo.admin.ch", + "api3.geo.admin.ch", + "wms.geo.admin.ch", + "data.geo.admin.ch", + "overpass-api.de", + "nominatim.openstreetmap.org", +]; + +const https = NET_HOSTS.map((h) => `https://${h}`); +// Icon-Font (index.html): Stylesheet von fonts.googleapis.com, Schrift von fonts.gstatic.com. +const GOOGLE_FONTS_CSS = "https://fonts.googleapis.com"; +const GOOGLE_FONTS_FILES = "https://fonts.gstatic.com"; + +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'", GOOGLE_FONTS_CSS], + "font-src": ["'self'", "data:", GOOGLE_FONTS_FILES], + "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/tauri.conf.json b/src-tauri/tauri.conf.json index daeed467..55d26452 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' https://fonts.googleapis.com; font-src 'self' data: https://fonts.gstatic.com; 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/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/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.