[117] Merge: strikte CSP (Tauri, Electron, Vite-Build), Rich-Text-Stile per Positivliste

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-11-03 17:43:10 +00:00
commit 012fe94126
9 files changed
+215 -9

No files matched your search

+8 -2
View File
@@ -1047,8 +1047,14 @@ Prüfung des ganzen Programms (Rust-Kern, TS-Hülle, Build/Sicherheit), nur Code
(`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.** `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).** 3.11.: `src/plan/golden.test.ts` — beide Musterprojekte: Grundriss je Geschoss
+37
View File
@@ -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([]);
});
+56
View File
@@ -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 };
+11 -1
View File
@@ -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();
+2 -1
View File
@@ -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": {
+27
View File
@@ -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'");
});
});
+30
View File
@@ -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<string, unknown>, text = "x"): RichTextDoc =>
({
version: 1,
paragraphs: [{ runs: [{ text, marks: { ...over } }] }],
}) as unknown as RichTextDoc;
it("escapt Tags im Text", () => {
const html = docToHtml(evil({}, '<img src=x onerror=alert(1)><script>1</script>'));
expect(html).not.toContain("<img");
expect(html).not.toContain("<script");
expect(html).toContain("&lt;img");
});
it("verwirft Schrift und Farbe mit CSS-/Attribut-Einschleusung", () => {
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");
});
});
+31 -4
View File
@@ -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 `<div${style}><br></div>`;
const inner = p.runs.map((r) => runToHtmlSpan(r, basePt, sizeUnit, color)).join("");
+13 -1
View File
@@ -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.