Compare commits

...

2 Commits

Author SHA1 Message Date
duffyduck 4e91d96b5b Security-Hardening Runde 6: Customer-Liste-Leak + XFF-Bypass + Vollmacht-Validation
Tiefer Live-Pentest deckte 3 weitere Schwachstellen:

🚨 CRITICAL: GET /api/customers leakte komplette Kundendatenbank
- Stage-4 hatte canAccessCustomer auf den Single-Endpoint angewendet,
  der List-Endpoint hatte nur den Daten-Sanitizer (filtert Passwort-Hashes)
  aber keinen Portal-Filter. Folge: Portal-Kunde sah ALLE Kunden mit Namen,
  E-Mails, customerNumber etc. – DSGVO-relevant.
- Fix: getCustomers filtert für Portal-User auf eigene + vertretene IDs.

🚨 HIGH: Rate-Limit-Bypass via X-Forwarded-For
- `trust proxy = 1` hat jedem XFF-Wert vertraut. 12+ Logins mit
  rotierender XFF-IP gingen ohne 429 durch.
- Fix: `trust proxy = 'loopback'` – XFF nur noch von 127.0.0.1 / ::1
  akzeptiert (= lokaler Reverse-Proxy).
- Plus: LISTEN_ADDR-Default 127.0.0.1 in Production, damit das Backend
  nicht von außen direkt ansprechbar ist.

🛡 MEDIUM: Self-Grant + Existence-Disclosure in toggleMyAuthorization
- Portal-User konnte:
  a) sich selbst Vollmacht erteilen (customerId=representativeId=1)
  b) Authorization-Records für nicht-existierende customerIds anlegen
     (scheitert erst am DB-Constraint mit vollem Prisma-Stack-Leak)
  c) Customer-IDs durch 404-vs-403-Differenzen enumerieren.
- Fix: Self-Grant 400. Existenz + aktive CustomerRepresentative-Beziehung
  in einem Query – Non-Existent / Non-Related geben identisch 403.
  Prisma-Error-Stacks generisch ersetzt.

Live-verifiziert: Customer-Liste filtert, Self-Grant 400, Existence-Probing
dicht.

Geprüft + sauber (Runde 6, kein Bug):
- Prototype Pollution Login-Body
- HTTP-Method-Override-Header
- Path-Traversal Backup-Name (Regex blockt)
- Developer-Routes existieren nicht
- Email-Endpoints mit fremder StressfreiEmail-ID → 403
- /api/customers/:id GET liefert 403 statt 404 (kein Leak)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 20:14:20 +02:00
duffyduck 8be9baee84 Security-Hardening Runde 5: Hack-Das-Ding (DSGVO-GAU + Timing + XSS)
Live-Pentest gegen Dev-Server + 3 parallele Audit-Agents.

🚨 CRITICAL: /api/uploads/* war ohne Auth erreichbar
- express.static('/api/uploads', ...) → jeder konnte mit ratbarer URL
  sensible PDFs (Kündigungsbestätigungen, Ausweise, Bankkarten,
  Vollmachten) ziehen. Live-verifiziert: 23-KB-PDF eines echten Kunden
  ohne Login geladen.
- Fix: authenticate-Middleware vor static-Handler (req.query.token
  unterstützung war schon da, jetzt aktiv genutzt).
- Frontend: utils/fileUrl.ts hängt JWT als ?token=... an. 24 direkte
  /api${...Path}-URLs in 5 Dateien per Skript migriert (CustomerDetail,
  ContractDetail, InvoicesSection, PdfTemplates, GDPRDashboard).

🚨 HIGH: Login-Timing User-Enumeration
- bcrypt.compare wurde nur bei existierenden Usern ausgeführt → 110ms
  vs 10ms Differenz, Email-Enumeration trivial messbar.
- Fix: Dummy-bcrypt-compare bei invalid user (Cost 12). Plus Lazy-
  Rehash bei erfolgreichem Login: alte Cost-10-Hashes (z.B. admin aus
  Installation) werden auf BCRYPT_COST upgraded, damit Dummy- und
  Echt-Hash-Cost zusammenpassen.
- Live-verifiziert nach Admin-Rehash: 422ms (invalid) vs 423ms (valid)
  – Side-Channel dicht.

🚨 HIGH: XSS via Privacy-Policy/Imprint-HTML
- 4 Frontend-Seiten renderten Backend-HTML ohne DOMPurify
  (PortalPrivacy, ConsentPage, PortalWebsitePrivacy, PortalImprint).
  Admin-eingegebene <script>-Tags wären bei jedem Portal-Kunden-
  Besuch ausgeführt worden – auch auf der öffentlichen Consent-Seite.
- Fix: DOMPurify.sanitize mit strikter FORBID_TAGS/ATTR Config.

🛡 HIGH: IDOR-Härtung an Upload-/Document-Endpoints
- canAccessContract jetzt in: uploadContractDocument,
  deleteContractDocument, handleContractDocumentUpload (Kündigungs-
  Letter+Confirmation), handleContractDocumentDelete,
  saveAttachmentAsContractDocument.
- Defense-in-Depth: aktuell durch requirePermission abgesichert,
  schützt auch gegen künftige Staff-Scoping-Rollen.

Offen für v1.1:
- Per-File-Ownership-Check für /api/uploads (Kontroll-Lookup
  welche Ressource zur Datei gehört)
- TipTap-Link-Tool javascript:-Protokoll blockieren
- Prisma-Error-Messages in Admin-Endpoints generisch sanitisieren

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 00:21:37 +02:00
18 changed files with 264 additions and 48 deletions

View File

@ -1926,6 +1926,9 @@ export async function saveAttachmentAsContractDocument(req: Request, res: Respon
return;
}
// Ownership-Check (Portal-Kunde darf nur auf eigenen/vertretenen Vertrag)
if (!(await canAccessContract(req as AuthRequest, res, contract.id))) return;
// Für gesendete E-Mails: Prüfen ob UID vorhanden
if (email.folder === 'SENT' && email.uid === 0) {
res.status(400).json({

View File

@ -462,6 +462,7 @@ export async function getContractDocuments(req: AuthRequest, res: Response): Pro
export async function uploadContractDocument(req: AuthRequest, res: Response): Promise<void> {
try {
const contractId = parseInt(req.params.id);
if (!(await canAccessContract(req, res, contractId))) return;
const { documentType, notes, deliveryDate } = req.body;
if (!req.file) {
@ -511,6 +512,7 @@ export async function deleteContractDocument(req: AuthRequest, res: Response): P
try {
const documentId = parseInt(req.params.documentId);
const contractId = parseInt(req.params.id);
if (!(await canAccessContract(req, res, contractId))) return;
const doc = await prisma.contractDocument.findUnique({ where: { id: documentId } });
if (!doc || doc.contractId !== contractId) {

View File

@ -29,11 +29,24 @@ export async function getCustomers(req: AuthRequest, res: Response): Promise<voi
page: page ? parseInt(page as string) : undefined,
limit: limit ? parseInt(limit as string) : undefined,
});
let customers = result.customers as any[];
// Portal-Kunden: Liste auf eigenen + vertretene Kunden einschränken.
// Ohne diesen Filter würde der List-Endpoint die komplette Kundendatenbank
// an einen einzelnen Portal-Account preisgeben.
if (req.user?.isCustomerPortal) {
const allowedIds = new Set<number>();
if (req.user.customerId) allowedIds.add(req.user.customerId);
const represented = (req.user as any).representedCustomerIds || [];
for (const id of represented) allowedIds.add(id);
customers = customers.filter((c) => allowedIds.has(c.id));
}
// Portal-Kunden oder andere Rollen sehen kein portalPasswordEncrypted
const canSeePasswords = req.user?.permissions?.includes('customers:update') ?? false;
const sanitized = canSeePasswords
? sanitizeCustomers(result.customers as any)
: (result.customers as any[]).map((c) => sanitizeCustomerStrict(c)).filter(Boolean);
? sanitizeCustomers(customers)
: customers.map((c) => sanitizeCustomerStrict(c)).filter(Boolean);
res.json({ success: true, data: sanitized, pagination: result.pagination } as ApiResponse);
} catch (error) {
res.status(500).json({

View File

@ -970,12 +970,27 @@ export async function toggleMyAuthorization(req: AuthRequest, res: Response) {
const representativeId = parseInt(req.params.representativeId);
const { grant } = req.body;
// Vertreter-Name laden
const representative = await prisma.customer.findUnique({
where: { id: representativeId },
select: { firstName: true, lastName: true },
// Validierungen:
// 1) Self-Grant verhindern (sinnlos und schafft Datenmüll).
if (representativeId === user.customerId) {
return res.status(400).json({ success: false, error: 'Kein Self-Grant möglich' });
}
// 2) Existenz + aktives Vertreter-Verhältnis in EINEM Lookup prüfen.
// Beide Fälle (representative existiert nicht / keine aktive Beziehung)
// geben identisch 403, damit ein Angreifer keine Customer-IDs aus der
// DB enumerieren kann (kein 404-vs-403-Disclosure).
const relation = await prisma.customerRepresentative.findFirst({
where: { customerId: user.customerId, representativeId, isActive: true },
include: { representative: { select: { firstName: true, lastName: true } } },
});
const repName = representative ? `${representative.firstName} ${representative.lastName}` : `#${representativeId}`;
if (!relation) {
return res.status(403).json({
success: false,
error: 'Kein Vertreter-Verhältnis Vollmacht nicht erlaubt',
});
}
const repName = `${relation.representative.firstName} ${relation.representative.lastName}`;
let auth;
if (grant) {
@ -991,10 +1006,9 @@ export async function toggleMyAuthorization(req: AuthRequest, res: Response) {
res.json({ success: true, data: auth });
} catch (error) {
console.error('Fehler beim Ändern der Vollmacht:', error);
res.status(400).json({
success: false,
error: error instanceof Error ? error.message : 'Fehler beim Ändern',
});
// Generische Fehlermeldung Prisma-Errors enthalten Pfad/Schema und
// sollten nicht an Endkunden geleakt werden.
res.status(400).json({ success: false, error: 'Vollmacht konnte nicht aktualisiert werden' });
}
}

View File

@ -38,6 +38,7 @@ import { startBirthdayScheduler } from './services/birthdayScheduler.service.js'
import { startContractStatusScheduler } from './services/contractStatusScheduler.service.js';
import { auditContextMiddleware } from './middleware/auditContext.js';
import { auditMiddleware } from './middleware/audit.js';
import { authenticate } from './middleware/auth.js';
dotenv.config();
@ -57,10 +58,15 @@ const app = express();
const PORT = process.env.PORT || 3001;
// Hinter einem Reverse-Proxy (Nginx/Plesk) läuft der Server typisch auf localhost.
// `trust proxy = 1` = dem ersten Hop X-Forwarded-For vertrauen (damit req.ip
// die echte Client-IP ist). Wichtig für express-rate-limit, sonst teilen sich
// alle Requests dieselbe Proxy-IP und das Rate-Limit ist unwirksam.
app.set('trust proxy', 1);
// `trust proxy = 'loopback'` vertraut nur Connections von 127.0.0.1 / ::1
// (= lokaler Reverse-Proxy). Damit kann ein Angreifer mit DIREKTEM Zugriff
// auf das Backend nicht via X-Forwarded-For den Rate-Limiter umgehen,
// während gleichzeitig der lokale Reverse-Proxy die echte Client-IP liefern darf.
//
// WICHTIG für Production: Backend nur auf 127.0.0.1 lauschen lassen
// (LISTEN_ADDR=127.0.0.1) sonst kann ein direkter Connect von außen
// trotzdem als loopback gelten, falls das Routing das so durchstellt.
app.set('trust proxy', 'loopback');
// ==================== SECURITY MIDDLEWARE ====================
@ -95,8 +101,12 @@ app.use(express.json({ limit: '5mb' }));
app.use(auditContextMiddleware);
app.use(auditMiddleware);
// Statische Dateien für Uploads
app.use('/api/uploads', express.static(path.join(process.cwd(), 'uploads')));
// Statische Dateien für Uploads NUR für authentifizierte User.
// authenticate-Middleware unterstützt ?token=... Query-Parameter für direkte
// <a href>-Downloads, bei denen der Browser keinen Authorization-Header sendet.
// Ohne diesen Schutz könnte jeder per Datei-Name-Enumeration sensible PDFs
// (Ausweise, Kündigungsbestätigungen, Bankkarten) abrufen DSGVO-GAU.
app.use('/api/uploads', authenticate as any, express.static(path.join(process.cwd(), 'uploads')));
// Öffentliche Routes (OHNE Authentifizierung)
app.use('/api/public/consent', consentPublicRoutes);
@ -169,8 +179,13 @@ app.use((err: Error & { status?: number; type?: string }, req: express.Request,
res.status(status).json({ success: false, error: message });
});
app.listen(PORT, () => {
console.log(`Server läuft auf Port ${PORT}`);
// Listen-Adresse: in Production typischerweise 127.0.0.1 (nur lokaler
// Reverse-Proxy soll connecten dürfen). LISTEN_ADDR per Env überschreibbar.
const LISTEN_ADDR = process.env.LISTEN_ADDR
|| (process.env.NODE_ENV === 'production' ? '127.0.0.1' : '0.0.0.0');
app.listen(PORT as number, LISTEN_ADDR, () => {
console.log(`Server läuft auf ${LISTEN_ADDR}:${PORT}`);
// Hintergrund-Scheduler (Geburtstagsgrüße etc.) starten
startBirthdayScheduler();
startContractStatusScheduler();

View File

@ -6,6 +6,7 @@ import prisma from '../lib/prisma.js';
import { authenticate, requirePermission } from '../middleware/auth.js';
import { AuthRequest } from '../types/index.js';
import { logChange } from '../services/audit.service.js';
import { canAccessContract } from '../utils/accessControl.js';
const router = Router();
@ -546,6 +547,7 @@ async function handleContractDocumentUpload(
}
const contractId = parseInt(req.params.id);
if (!(await canAccessContract(req, res, contractId))) return;
const relativePath = `/uploads/${subDir}/${req.file.filename}`;
// Alte Datei löschen falls vorhanden
@ -631,6 +633,7 @@ async function handleContractDocumentDelete(
) {
try {
const contractId = parseInt(req.params.id);
if (!(await canAccessContract(req, res, contractId))) return;
const contract = await prisma.contract.findUnique({ where: { id: contractId } });
if (!contract) {

View File

@ -11,6 +11,40 @@ import { getSystemEmailCredentials } from './emailProvider/emailProviderService.
// Bestehende Hashes mit Faktor 10 bleiben gültig (bcrypt kodiert den Faktor im Hash).
const BCRYPT_COST = 12;
// Dummy-Hash mit Cost 12 für Timing-Attack-Schutz: bei nicht-existierendem User
// führen wir trotzdem ein bcrypt.compare() durch, damit die Antwortzeit nicht
// verrät, ob die E-Mail existiert. Konstanter Hash hat keine Bedeutung außer
// dem Timing-Angleich.
const DUMMY_BCRYPT_HASH = '$2a$12$CwTycUXWue0Thq9StjUM0uJ8gQKwqKjq8lZ3TZ9qg8aJ0A9hPn4Wy';
/**
* Upgrade eines bestehenden Passwort-Hashes auf aktuellen BCRYPT_COST.
* Wird nach erfolgreichem Login aufgerufen. Alte User (z.B. admin mit Cost 10
* aus der Installation) werden so lazy auf Cost 12 migriert damit sich die
* Antwortzeit beim Login der Dummy-Zeit bei ungültigen Usern angleicht.
*/
async function maybeUpgradePasswordHash(
table: 'user' | 'customer',
id: number,
plaintextPassword: string,
currentHash: string,
): Promise<void> {
const match = currentHash.match(/^\$2[aby]\$(\d+)\$/);
const currentCost = match ? parseInt(match[1], 10) : 0;
if (currentCost === BCRYPT_COST) return;
try {
const newHash = await bcrypt.hash(plaintextPassword, BCRYPT_COST);
if (table === 'user') {
await prisma.user.update({ where: { id }, data: { password: newHash } });
} else {
await prisma.customer.update({ where: { id }, data: { portalPasswordHash: newHash } });
}
} catch (err) {
// Nicht kritisch Login war erfolgreich, Rehash kann beim nächsten Login nachgeholt werden
console.warn('[maybeUpgradePasswordHash] Fehler beim Rehash:', err);
}
}
// Mitarbeiter-Login
export async function login(email: string, password: string) {
const user = await prisma.user.findUnique({
@ -33,6 +67,9 @@ export async function login(email: string, password: string) {
});
if (!user || !user.isActive) {
// Timing-Attack-Schutz: Dummy-bcrypt-compare damit die Antwortzeit bei
// nicht-existierendem/deaktiviertem User der eines gültigen Users entspricht.
await bcrypt.compare(password, DUMMY_BCRYPT_HASH);
throw new Error('Ungültige Anmeldedaten');
}
@ -41,6 +78,10 @@ export async function login(email: string, password: string) {
throw new Error('Ungültige Anmeldedaten');
}
// Lazy-Upgrade: ältere Cost-10-Hashes auf aktuellen BCRYPT_COST rehashen.
// Async, nicht blockierend für die Response.
maybeUpgradePasswordHash('user', user.id, password, user.password).catch(() => {});
// Collect all permissions from all roles
const permissions = new Set<string>();
for (const userRole of user.roles) {
@ -107,6 +148,8 @@ export async function customerLogin(email: string, password: string) {
if (!customer || !customer.portalEnabled || !customer.portalPasswordHash) {
console.log('[CustomerLogin] Abbruch: Kunde nicht gefunden oder Portal nicht aktiviert');
// Timing-Attack-Schutz (siehe login())
await bcrypt.compare(password, DUMMY_BCRYPT_HASH);
throw new Error('Ungültige Anmeldedaten');
}
@ -117,6 +160,9 @@ export async function customerLogin(email: string, password: string) {
throw new Error('Ungültige Anmeldedaten');
}
// Lazy-Upgrade analog zu Mitarbeiter-Login
maybeUpgradePasswordHash('customer', customer.id, password, customer.portalPasswordHash).catch(() => {});
// Letzte Anmeldung aktualisieren
await prisma.customer.update({
where: { id: customer.id },

View File

@ -141,6 +141,77 @@ isolierte Instanz (keine Multi-Tenancy im Code), Provisioning + Abrechnung
- Provider/Tariff-GETs: `requirePermission('providers:read')` (Portal-Kunden sehen Provider-Liste nicht mehr)
- SMTP-Header-Injection: zentrale CRLF-Validierung in `smtpService.sendEmail` (schützt alle Caller)
- bcrypt cost 10 → 12 (OWASP 2026)
- **Runde 6 Tiefer Live-Pentest (auf Wunsch des Users, „bevor andere es tun"):**
- 🚨 **`GET /api/customers` leakte als Portal-User die komplette
Kundendatenbank** (alle Namen, E-Mails, customerNumber etc.). Der
Single-Endpoint war Stage 4 mit `canAccessCustomer` gefixt, der List-
Endpoint nicht. Jetzt: Portal-User bekommt nur eigene + vertretene
Kunden (Filter im Controller).
- 🚨 **Rate-Limit-Bypass via `X-Forwarded-For`**: 12+ Login-Versuche
mit rotierenden XFF-Werten gingen alle durch ohne 429. `trust proxy = 1`
hat naiv jedem XFF-Wert vertraut. Jetzt: `trust proxy = 'loopback'`
XFF wird nur akzeptiert wenn die Connection von 127.0.0.1 / ::1 kommt
(= lokaler Reverse-Proxy). Plus: `LISTEN_ADDR=127.0.0.1` in Production-
Default, damit das Backend nicht direkt von außen ansprechbar ist.
- **Self-Grant + Existence-Disclosure in `toggleMyAuthorization`**:
- Portal-User konnte sich selbst Vollmacht erteilen (1→1) und
Datensätze für beliebige `representativeId`s anlegen (auch nicht-
existierende, scheiterte erst auf DB-Constraint mit Prisma-Stack-Leak).
- 404 vs 403 erlaubte Existence-Probing der gesamten customer-ID-Range.
- Fix: Self-Grant 400er. Existenz + aktives `CustomerRepresentative`-
Verhältnis in einem Query, beide Fehlfälle identisch 403.
- **Prisma-Error-Leak generisch in `toggleMyAuthorization`**: keine
Prisma-Stacks mehr im Response.
- Live-verifiziert: Customer-Liste 3 statt 3000 (jetzt nur erlaubte),
Self-Grant 400, Existence-Disclosure dicht (alle 403 uniform), Auth
auf `/api/customers/:id` 200/403 (kein 404-Leak).
**Geprüft + sauber (Runde 6):**
- Prototype Pollution beim Login → kein Effekt
- HTTP-Method-Override via Header → ignoriert
- Path-Traversal in Backup-Name → durch Regex blockiert
- Developer-Routes existieren nicht (404)
- Email-Endpoints (Send/Sync/Read mit fremder StressfreiEmail-ID) → 403
- Self-grant Vollmacht via `customers/X/representatives` → 403 (perm)
- `/api/customers/:id` GET: 200 für eigene, 403 sonst (kein 404-Leak)
**Offen für v1.1:**
- `/api/contracts/:id` GET liefert 404 für nicht-existente IDs (Existence-
Probing). Da contractIds aber nicht direkt mit personenbezogenen Daten
korrelieren, niedrig-Prio. Vereinheitlichung auf 403 wäre sauberer.
- Prisma-Error-Leaks in anderen Admin-Endpoints (z.B. `addInvoice` bei
Validation-Fehler) Defense-in-Depth-Kandidat.
- **Runde 5 Hack-Das-Ding-Audit (Live-Pentest + 3 parallele Audit-Agents):**
- 🚨 **`/api/uploads/*` war OHNE AUTH erreichbar** (DSGVO-GAU!) jetzt hinter
`authenticate`. Direkte <a href>-Links nutzen `?token=...` Query-Parameter,
unterstützt von auth-Middleware. Frontend-Helper `fileUrl(path)` hängt
Token automatisch an, 24 URLs migriert (CustomerDetail, ContractDetail,
InvoicesSection, PdfTemplates, GDPRDashboard).
- **Login-Timing-Side-Channel**: Bei ungültigem User fehlte `bcrypt.compare`
→ 110ms vs 10ms, User-Enumeration trivial. Jetzt Dummy-bcrypt-compare
(Cost 12) bei invalid user + Lazy-Rehash alter Cost-10-Hashes beim Login.
Live-verifiziert: 422ms vs 425ms Timing-Angriff dicht.
- **XSS via Privacy Policy / Imprint**: 4 Frontend-Seiten renderten
Backend-HTML ohne DOMPurify (`PortalPrivacy`, `ConsentPage`,
`PortalWebsitePrivacy`, `PortalImprint`). Admin-eingegebene
`<script>`-Tags wären bei jedem Portal-Kunden-Besuch ausgeführt worden.
Jetzt mit strikter Sanitize-Config (FORBID_TAGS/ATTR).
- **IDOR-Härtung Upload/Delete/SaveAttachment**: `canAccessContract` jetzt
in `uploadContractDocument`, `deleteContractDocument`, im generischen
`handleContractDocumentUpload` (Kündigungsschreiben + -bestätigungen)
und in `saveAttachmentAsContractDocument`. Defense-in-Depth, blockt
auch bei künftigen Staff-Scoping-Rollen.
- Global Error-Handler: `err.status` wird respektiert (413/400 statt 500).
**Offen für v1.1**:
- Per-File-Ownership-Check bei `/api/uploads/*` (aktuell reicht
Authentifizierung, kein Datei-spezifischer Owner-Check). Implementierung
bräuchte dedizierten `GET /api/files/download?path=...`-Endpoint mit
DB-Lookup, welche Ressource zur Datei gehört.
- TipTap-Link-Tool: `javascript:`-Protokoll blockieren (Admin-only erreichbar,
niedrig-Prio).
- **Runde 4 Live-Tests gegen Dev-Server deckten 9 weitere IDORs auf:**
- `getCustomer` + `getAddresses`/`getBankCards`/`getDocuments`/`getMeters`/`getRepresentatives`/`getPortalSettings` hatten NUR Daten-Sanitizer aber KEINEN `canAccessCustomer`-Check
- `gdpr.getCustomerConsents` + `getAuthorizations` + `checkConsentStatus` ebenso ungeschützt

View File

@ -9,6 +9,7 @@ import Select from '../ui/Select';
import Badge from '../ui/Badge';
import { invoiceApi } from '../../services/api';
import type { Invoice, InvoiceType } from '../../types';
import { fileUrl } from '../../utils/fileUrl';
const invoiceTypeLabels: Record<InvoiceType, string> = {
INTERIM: 'Zwischenrechnung',
@ -120,7 +121,7 @@ export default function InvoicesSection({
{invoice.documentPath && (
<div className="flex items-center gap-2">
<a
href={`/api${invoice.documentPath}`}
href={fileUrl(invoice.documentPath)}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-1 text-blue-600 hover:text-blue-800 text-sm"
@ -129,7 +130,7 @@ export default function InvoicesSection({
<Eye className="w-4 h-4" />
</a>
<a
href={`/api${invoice.documentPath}`}
href={fileUrl(invoice.documentPath)}
download
className="flex items-center gap-1 text-blue-600 hover:text-blue-800 text-sm"
title="Download"

View File

@ -19,6 +19,7 @@ import CopyButton, { CopyableBlock } from '../../components/ui/CopyButton';
import { formatDate } from '../../utils/dateFormat';
import { useProviderSettings } from '../../hooks/useProviderSettings';
import type { ContractType, ContractStatus, SimCard, MeterReading, ContractTask, ContractTaskSubtask, ContractMeter, ContractDocument } from '../../types';
import { fileUrl } from '../../utils/fileUrl';
const typeLabels: Record<ContractType, string> = {
ELECTRICITY: 'Strom',
@ -2034,7 +2035,7 @@ export default function ContractDetail() {
{c.cancellationLetterPath ? (
<div className="flex items-center gap-3 flex-wrap">
<a
href={`/api${c.cancellationLetterPath}`}
href={fileUrl(c.cancellationLetterPath)}
target="_blank"
rel="noopener noreferrer"
className="text-blue-600 hover:underline text-sm flex items-center gap-1"
@ -2043,7 +2044,7 @@ export default function ContractDetail() {
Anzeigen
</a>
<a
href={`/api${c.cancellationLetterPath}`}
href={fileUrl(c.cancellationLetterPath)}
download
className="text-blue-600 hover:underline text-sm flex items-center gap-1"
>
@ -2091,7 +2092,7 @@ export default function ContractDetail() {
<>
<div className="flex items-center gap-3 flex-wrap">
<a
href={`/api${c.cancellationConfirmationPath}`}
href={fileUrl(c.cancellationConfirmationPath)}
target="_blank"
rel="noopener noreferrer"
className="text-blue-600 hover:underline text-sm flex items-center gap-1"
@ -2100,7 +2101,7 @@ export default function ContractDetail() {
Anzeigen
</a>
<a
href={`/api${c.cancellationConfirmationPath}`}
href={fileUrl(c.cancellationConfirmationPath)}
download
className="text-blue-600 hover:underline text-sm flex items-center gap-1"
>
@ -2177,7 +2178,7 @@ export default function ContractDetail() {
{c.cancellationLetterOptionsPath ? (
<div className="flex items-center gap-3 flex-wrap">
<a
href={`/api${c.cancellationLetterOptionsPath}`}
href={fileUrl(c.cancellationLetterOptionsPath)}
target="_blank"
rel="noopener noreferrer"
className="text-blue-600 hover:underline text-sm flex items-center gap-1"
@ -2186,7 +2187,7 @@ export default function ContractDetail() {
Anzeigen
</a>
<a
href={`/api${c.cancellationLetterOptionsPath}`}
href={fileUrl(c.cancellationLetterOptionsPath)}
download
className="text-blue-600 hover:underline text-sm flex items-center gap-1"
>
@ -2234,7 +2235,7 @@ export default function ContractDetail() {
<>
<div className="flex items-center gap-3 flex-wrap">
<a
href={`/api${c.cancellationConfirmationOptionsPath}`}
href={fileUrl(c.cancellationConfirmationOptionsPath)}
target="_blank"
rel="noopener noreferrer"
className="text-blue-600 hover:underline text-sm flex items-center gap-1"
@ -2243,7 +2244,7 @@ export default function ContractDetail() {
Anzeigen
</a>
<a
href={`/api${c.cancellationConfirmationOptionsPath}`}
href={fileUrl(c.cancellationConfirmationOptionsPath)}
download
className="text-blue-600 hover:underline text-sm flex items-center gap-1"
>
@ -3310,7 +3311,7 @@ function ContractDocumentsSection({
{doc.documentType}
</span>
<a
href={`/api${doc.documentPath}`}
href={fileUrl(doc.documentPath)}
target="_blank"
rel="noopener noreferrer"
className="text-sm text-blue-600 hover:underline"
@ -3327,7 +3328,7 @@ function ContractDocumentsSection({
</div>
<div className="flex items-center gap-2">
<a
href={`/api${doc.documentPath}`}
href={fileUrl(doc.documentPath)}
download
className="text-gray-400 hover:text-blue-600"
title="Herunterladen"

View File

@ -20,6 +20,7 @@ import { formatDate } from '../../utils/dateFormat';
import { getContractTypeInfo } from '../../utils/contractInfo';
import { useProviderSettings } from '../../hooks/useProviderSettings';
import type { Address, BankCard, IdentityDocument, Meter, Customer, CustomerRepresentative, CustomerSummary, CustomerConsent, ConsentType, ConsentStatus, RepresentativeAuthorization } from '../../types';
import { fileUrl } from '../../utils/fileUrl';
export default function CustomerDetail({ portalCustomerId }: { portalCustomerId?: number } = {}) {
const { id } = useParams();
@ -564,7 +565,7 @@ function BusinessDataCard({
{customer.businessRegistrationPath ? (
<div className="flex items-center gap-2 flex-wrap">
<a
href={`/api${customer.businessRegistrationPath}`}
href={fileUrl(customer.businessRegistrationPath)}
target="_blank"
rel="noopener noreferrer"
className="text-blue-600 hover:underline text-sm flex items-center gap-1"
@ -573,7 +574,7 @@ function BusinessDataCard({
Anzeigen
</a>
<a
href={`/api${customer.businessRegistrationPath}`}
href={fileUrl(customer.businessRegistrationPath)}
download
className="text-blue-600 hover:underline text-sm flex items-center gap-1"
>
@ -615,7 +616,7 @@ function BusinessDataCard({
{customer.commercialRegisterPath ? (
<div className="flex items-center gap-2 flex-wrap">
<a
href={`/api${customer.commercialRegisterPath}`}
href={fileUrl(customer.commercialRegisterPath)}
target="_blank"
rel="noopener noreferrer"
className="text-blue-600 hover:underline text-sm flex items-center gap-1"
@ -624,7 +625,7 @@ function BusinessDataCard({
Anzeigen
</a>
<a
href={`/api${customer.commercialRegisterPath}`}
href={fileUrl(customer.commercialRegisterPath)}
download
className="text-blue-600 hover:underline text-sm flex items-center gap-1"
>
@ -935,7 +936,7 @@ function BankCardsTab({
{card.documentPath ? (
<div className="flex items-center gap-2 flex-wrap">
<a
href={`/api${card.documentPath}`}
href={fileUrl(card.documentPath)}
target="_blank"
rel="noopener noreferrer"
className="text-blue-600 hover:underline text-sm flex items-center gap-1"
@ -944,7 +945,7 @@ function BankCardsTab({
Anzeigen
</a>
<a
href={`/api${card.documentPath}`}
href={fileUrl(card.documentPath)}
download
className="text-blue-600 hover:underline text-sm flex items-center gap-1"
>
@ -1171,7 +1172,7 @@ function DocumentsTab({
{doc.documentPath ? (
<div className="flex items-center gap-2 flex-wrap">
<a
href={`/api${doc.documentPath}`}
href={fileUrl(doc.documentPath)}
target="_blank"
rel="noopener noreferrer"
className="text-blue-600 hover:underline text-sm flex items-center gap-1"
@ -1180,7 +1181,7 @@ function DocumentsTab({
Anzeigen
</a>
<a
href={`/api${doc.documentPath}`}
href={fileUrl(doc.documentPath)}
download
className="text-blue-600 hover:underline text-sm flex items-center gap-1"
>
@ -3925,7 +3926,7 @@ function ConsentTab({
{customer.privacyPolicyPath ? (
<div className="flex items-center gap-3 flex-wrap">
<a
href={`/api${customer.privacyPolicyPath}`}
href={fileUrl(customer.privacyPolicyPath)}
target="_blank"
rel="noopener noreferrer"
className="text-blue-600 hover:underline text-sm flex items-center gap-1"
@ -3934,7 +3935,7 @@ function ConsentTab({
Anzeigen
</a>
<a
href={`/api${customer.privacyPolicyPath}`}
href={fileUrl(customer.privacyPolicyPath)}
download
className="text-blue-600 hover:underline text-sm flex items-center gap-1"
>
@ -4231,7 +4232,7 @@ function AuthorizationsSection({ customerId, customerEmail }: { customerId: numb
{auth.documentPath ? (
<>
<a
href={`/api${auth.documentPath}`}
href={fileUrl(auth.documentPath)}
target="_blank"
rel="noopener noreferrer"
className="text-blue-600 hover:underline text-xs flex items-center gap-1"

View File

@ -2,6 +2,12 @@ import { useQuery } from '@tanstack/react-query';
import { gdprApi } from '../../services/api';
import Card from '../../components/ui/Card';
import { Building } from 'lucide-react';
import DOMPurify from 'dompurify';
const SANITIZE_OPTIONS = {
FORBID_TAGS: ['script', 'style', 'iframe', 'object', 'embed', 'form', 'input', 'button'],
FORBID_ATTR: ['onerror', 'onload', 'onclick', 'onmouseover', 'onfocus', 'onblur', 'formaction'],
};
export default function PortalImprint() {
const { data, isLoading, isError } = useQuery({
@ -22,7 +28,7 @@ export default function PortalImprint() {
<h1 className="text-2xl font-bold">Impressum</h1>
</div>
<Card>
<div className="prose prose-sm max-w-none" dangerouslySetInnerHTML={{ __html: html }} />
<div className="prose prose-sm max-w-none" dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(html, SANITIZE_OPTIONS) }} />
</Card>
</div>
);

View File

@ -11,6 +11,12 @@ import {
CheckCircle2,
} from 'lucide-react';
import Card from '../../components/ui/Card';
import DOMPurify from 'dompurify';
const SANITIZE_OPTIONS = {
FORBID_TAGS: ['script', 'style', 'iframe', 'object', 'embed', 'form', 'input', 'button'],
FORBID_ATTR: ['onerror', 'onload', 'onclick', 'onmouseover', 'onfocus', 'onblur', 'formaction'],
};
const CONSENT_TYPE_LABELS: Record<ConsentType, { label: string; description: string }> = {
DATA_PROCESSING: {
@ -178,7 +184,7 @@ export default function PortalPrivacy() {
</div>
<div
className="prose prose-sm max-w-none"
dangerouslySetInnerHTML={{ __html: privacyPolicyHtml }}
dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(privacyPolicyHtml, SANITIZE_OPTIONS) }}
/>
</Card>

View File

@ -2,6 +2,12 @@ import { useQuery } from '@tanstack/react-query';
import { gdprApi } from '../../services/api';
import Card from '../../components/ui/Card';
import { Shield } from 'lucide-react';
import DOMPurify from 'dompurify';
const SANITIZE_OPTIONS = {
FORBID_TAGS: ['script', 'style', 'iframe', 'object', 'embed', 'form', 'input', 'button'],
FORBID_ATTR: ['onerror', 'onload', 'onclick', 'onmouseover', 'onfocus', 'onblur', 'formaction'],
};
export default function PortalWebsitePrivacy() {
const { data, isLoading, isError } = useQuery({
@ -22,7 +28,7 @@ export default function PortalWebsitePrivacy() {
<h1 className="text-2xl font-bold">Datenschutzerklärung</h1>
</div>
<Card>
<div className="prose prose-sm max-w-none" dangerouslySetInnerHTML={{ __html: html }} />
<div className="prose prose-sm max-w-none" dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(html, SANITIZE_OPTIONS) }} />
</Card>
</div>
);

View File

@ -4,6 +4,12 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { publicApi } from '../../services/api';
import { formatDate } from '../../utils/dateFormat';
import { Shield, CheckCircle2, FileDown, Loader2 } from 'lucide-react';
import DOMPurify from 'dompurify';
const SANITIZE_OPTIONS = {
FORBID_TAGS: ['script', 'style', 'iframe', 'object', 'embed', 'form', 'input', 'button'],
FORBID_ATTR: ['onerror', 'onload', 'onclick', 'onmouseover', 'onfocus', 'onblur', 'formaction'],
};
export default function ConsentPage() {
const { hash } = useParams<{ hash: string }>();
@ -150,7 +156,7 @@ export default function ConsentPage() {
</div>
<div
className="p-6 prose prose-sm max-w-none"
dangerouslySetInnerHTML={{ __html: privacyPolicyHtml }}
dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(privacyPolicyHtml, SANITIZE_OPTIONS) }}
/>
</div>

View File

@ -7,6 +7,7 @@ import Card from '../../components/ui/Card';
import Button from '../../components/ui/Button';
import Select from '../../components/ui/Select';
import { ArrowLeft, FileText, Users, CheckCircle, Clock, XCircle, AlertTriangle, Download, X, ChevronRight } from 'lucide-react';
import { fileUrl } from '../../utils/fileUrl';
const STATUS_OPTIONS = [
{ value: '', label: 'Alle Status' },
@ -362,7 +363,7 @@ export default function GDPRDashboard() {
<Button
variant="ghost"
size="sm"
onClick={() => window.open(`/api/uploads/${request.proofDocument}`, '_blank')}
onClick={() => window.open(fileUrl(`/uploads/${request.proofDocument}`), '_blank')}
title="Löschnachweis anzeigen"
>
<FileText className="w-4 h-4 text-blue-500" />

View File

@ -9,6 +9,7 @@ import Input from '../../components/ui/Input';
import Badge from '../../components/ui/Badge';
import Modal from '../../components/ui/Modal';
import { ArrowLeft, Plus, Edit, Trash2, FileText, Upload, Link2, Eye, Play } from 'lucide-react';
import { fileUrl } from '../../utils/fileUrl';
export default function PdfTemplates() {
const navigate = useNavigate();
@ -95,7 +96,7 @@ export default function PdfTemplates() {
<Button variant="ghost" size="sm" onClick={() => setTestTemplate(t)} title="Testvorschau mit Vertragsdaten">
<Play className="w-4 h-4 text-green-500" />
</Button>
<a href={`/api${t.templatePath}`} target="_blank" rel="noopener noreferrer">
<a href={fileUrl(t.templatePath)} target="_blank" rel="noopener noreferrer">
<Button variant="ghost" size="sm" title="Leere Vorlage anzeigen">
<Eye className="w-4 h-4" />
</Button>

View File

@ -0,0 +1,20 @@
/**
* Baut eine Download-URL für ein im Backend gespeichertes Upload-File.
*
* `/api/uploads/*` läuft hinter authenticate-Middleware, aber <a href> und
* window.open senden keinen Authorization-Header. Darum hängen wir das JWT
* als Query-Parameter an. Die authenticate-Middleware akzeptiert
* `?token=<jwt>` neben dem Header.
*
* Trade-off: Tokens in URLs landen potenziell in Logs/Referrer. Für eine
* saubere Lösung (kurzlebige Download-Tokens) wäre ein separater Endpoint
* nötig TODO für v1.1.
*/
export function fileUrl(path: string | null | undefined): string {
if (!path) return '';
const token = localStorage.getItem('token');
const base = `/api${path.startsWith('/') ? path : '/' + path}`;
if (!token) return base;
const separator = base.includes('?') ? '&' : '?';
return `${base}${separator}token=${encodeURIComponent(token)}`;
}