CSV-Export: Formelanfänge auch in der Domain-Aufstellung neutralisieren (#77)
Der Browser-Export der Domain-Aufstellung quotierte nur Anführungszeichen; Kundennamen/Notizen mit führendem =,+,-,@ wurden in Excel als Formel ausgeführt. Gemeinsame Regel in @kc/platform/csv (auch CR), von Audit- und Rechnungsexport genutzt; Web nutzt dieselbe Regel für Textzellen, Beträge bleiben Zahlen. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
2af4beb8e2
commit
ce71058b4d
6 changed files with 37 additions and 7 deletions
|
|
@ -5,13 +5,12 @@ import { audit, verifyAuditChain, purgeAuditRetention } from '../../core/audit.j
|
|||
import { clientIp, requirePermission } from '../../core/auth.js';
|
||||
import { badRequest } from '../../core/errors.js';
|
||||
import type { KcModule } from '../../core/module.js';
|
||||
import { csvCell } from '@kc/platform/csv';
|
||||
|
||||
const AUDIT_SQL = 'SELECT id, ts, actor_type, actor_id, org_id, action, resource_type, resource_id, result, error_class, correlation_id, ip, before_json, after_json FROM audit_events';
|
||||
const listQuery = z.object({ action: z.string().max(100).optional(), actor: z.string().uuid().optional(), org: z.string().uuid().optional(), from: z.string().date().optional(), to: z.string().date().optional() });
|
||||
// Formel-Injection-Schutz wie im Rechnungs-CSV-Export (apps/api/src/modules/invoices/index.ts) - hier lokal
|
||||
// dupliziert statt importiert, damit Module weiterhin ohne Querverweise aufeinander auskommen.
|
||||
const csvSafe = (s: string) => (/^[=+\-@\t]/.test(s) ? `'${s}` : s);
|
||||
const csvCell = (s: string) => { const v = csvSafe(s); return /[;"\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v; };
|
||||
|
||||
export const auditModule: KcModule = {
|
||||
name: 'audit',
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ import { can, canInOrg } from '../../core/policy.js';
|
|||
import type { KcModule } from '../../core/module.js';
|
||||
import { config } from '../../core/config.js';
|
||||
import { renderInvoicePdf, type CompanySettings, type InvoiceForPdf } from './pdf.js';
|
||||
import { csvSafe, csvCell } from '@kc/platform/csv';
|
||||
|
||||
/** Kaufmännisches Runden (halb auf), wie in @kc/platform/pricing – hier lokal, weil Rechnungspositionen
|
||||
* (Freitext, Dezimalmenge) sich nicht in das Produkt-Preisschema von calculatePrice pressen lassen. */
|
||||
|
|
@ -96,8 +97,6 @@ function exportFilter(q: z.infer<typeof exportQuery>): { sql: string; params: un
|
|||
const csvNum = (cents: number) => (cents / 100).toFixed(2).replace('.', ',');
|
||||
// Formel-Injection-Schutz (CSV): Zellen, die mit =, +, -, @ oder Tab beginnen, werden von Excel/Sheets sonst als Formel
|
||||
// ausgeführt. Firmenname/Notiz stammen aus vom Kunden bzw. Personal eingegebenen Feldern – daher immer entschärfen.
|
||||
const csvSafe = (s: string): string => (/^[=+\-@\t]/.test(s) ? `'${s}` : s);
|
||||
const csvCell = (s: string): string => { const v = csvSafe(s); return /[;"\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v; };
|
||||
const csvDate = (d: unknown) => (d ? new Date(d as string).toISOString().slice(0, 10) : '');
|
||||
const STATUS_LABEL: Record<string, string> = { open: 'Offen', paid: 'Bezahlt', cancelled: 'Storniert' };
|
||||
|
||||
|
|
|
|||
|
|
@ -5,18 +5,19 @@ import { useSearchParams } from 'next/navigation';
|
|||
import { api, errMsg } from '@/lib/api';
|
||||
import { useSession } from '@/lib/session';
|
||||
import { Alert, Empty, Field, eur } from '@/components/ui';
|
||||
import { csvText, csvValue } from '@/lib/csv';
|
||||
|
||||
interface Rec { id: string; domain: string; tld: string; orgId: string | null; customer: string | null; customerNumber: string | null; source: string; termMonths: number | null; costNetCents: number | null; costGrossCents: number | null; setupCostCents: number; sellNetCents: number | null; taxBp: number; sellGrossCents: number | null; profitNetCents: number | null; procurement: 'open' | 'ordered' | 'external'; orderedAt: string | null; note: string | null }
|
||||
interface Res { id: string; name: string; type: string; orgId: string | null }
|
||||
const PROC = { open: 'Bei KCS zu bestellen', ordered: 'Bei KCS bestellt', external: 'Anderer Anbieter' } as const;
|
||||
const money = (c: number | null) => c === null ? '–' : eur(c);
|
||||
const csvNum = (c: number | null) => c === null ? '' : (c / 100).toFixed(2).replace('.', ',');
|
||||
const csvCell = (v: string | number | null) => `"${String(v ?? '').replace(/"/g, '""')}"`;
|
||||
/** CSV für Excel (Semikolon, UTF-8 mit BOM): Bestellliste bzw. Gesamtaufstellung. */
|
||||
function download(rows: Rec[], name: string) {
|
||||
const head = ['Domain', 'Endung', 'Laufzeit (Monate)', 'Kunde', 'Kundennr.', 'EK brutto', 'EK netto', 'Setup EK brutto', 'VK brutto', 'VK netto', 'USt %', 'Gewinn netto', 'Status', 'bestellt am', 'Notiz'];
|
||||
const lines = rows.map((r) => [r.domain, r.tld, r.termMonths, r.customer, r.customerNumber, csvNum(r.costGrossCents), csvNum(r.costNetCents), csvNum(r.setupCostCents), csvNum(r.sellGrossCents), csvNum(r.sellNetCents), r.taxBp / 100, csvNum(r.profitNetCents), PROC[r.procurement], r.orderedAt ? new Date(r.orderedAt).toLocaleDateString('de-DE') : '', r.note].map(csvCell).join(';'));
|
||||
const url = URL.createObjectURL(new Blob(['' + [head.map(csvCell).join(';'), ...lines].join('\r\n')], { type: 'text/csv;charset=utf-8' }));
|
||||
// Texte (Domain, Kunde, Notiz …) neutralisiert, Beträge/Zahlen als Werte.
|
||||
const lines = rows.map((r) => [csvText(r.domain), csvText(r.tld), csvValue(r.termMonths), csvText(r.customer), csvText(r.customerNumber), csvValue(csvNum(r.costGrossCents)), csvValue(csvNum(r.costNetCents)), csvValue(csvNum(r.setupCostCents)), csvValue(csvNum(r.sellGrossCents)), csvValue(csvNum(r.sellNetCents)), csvValue(r.taxBp / 100), csvValue(csvNum(r.profitNetCents)), csvText(PROC[r.procurement]), csvText(r.orderedAt ? new Date(r.orderedAt).toLocaleDateString('de-DE') : ''), csvText(r.note)].join(';'));
|
||||
const url = URL.createObjectURL(new Blob(['' + [head.map(csvText).join(';'), ...lines].join('\r\n')], { type: 'text/csv;charset=utf-8' }));
|
||||
const a = document.createElement('a'); a.href = url; a.download = name; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url);
|
||||
}
|
||||
export function DomainRecords({ orgId }: { orgId?: string }) {
|
||||
|
|
|
|||
8
apps/web/src/lib/csv.ts
Normal file
8
apps/web/src/lib/csv.ts
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
/**
|
||||
* CSV-Zellen für den Excel-Export im Browser. Gleiche Regel wie @kc/platform/csv (dort getestet): Textzellen, die mit
|
||||
* = + - @ Tab oder CR beginnen, bekommen ein führendes Apostroph, damit Excel sie nicht als Formel ausführt.
|
||||
* Zahlenzellen (Beträge) nur quotieren, nicht neutralisieren – sonst würde aus "-1,50" Text.
|
||||
*/
|
||||
const quote = (s: string) => `"${s.replace(/"/g, '""')}"`;
|
||||
export const csvText = (v: string | null | undefined): string => { const s = v ?? ''; return quote(/^[=+\-@\t\r]/.test(s) ? `'${s}` : s); };
|
||||
export const csvValue = (v: string | number | null | undefined): string => quote(String(v ?? ''));
|
||||
9
packages/platform/src/csv.ts
Normal file
9
packages/platform/src/csv.ts
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
/**
|
||||
* CSV-Zellen für Excel/LibreOffice (Semikolon-getrennt). Textzellen aus Nutzereingaben (Kundennamen, Notizen,
|
||||
* Audit-Aktionen …) dürfen beim Öffnen nie als Formel ausgewertet werden: Zellen, die mit = + - @ Tab oder CR
|
||||
* beginnen, bekommen ein führendes Apostroph (OWASP „CSV Injection“). Zahlen bewusst NICHT durch csvSafe schicken –
|
||||
* ein negativer Betrag wie "-1,50" soll eine Zahl bleiben.
|
||||
*/
|
||||
export const csvSafe = (s: string): string => (/^[=+\-@\t\r]/.test(s) ? `'${s}` : s);
|
||||
/** Textzelle: neutralisiert und nur bei Bedarf in Anführungszeichen. */
|
||||
export const csvCell = (s: string): string => { const v = csvSafe(s); return /[;"\r\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v; };
|
||||
14
packages/platform/test/csv.test.ts
Normal file
14
packages/platform/test/csv.test.ts
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { csvCell, csvSafe } from '../src/csv.js';
|
||||
|
||||
describe('CSV-Zellen (Formel-Injection)', () => {
|
||||
it('neutralisiert Formelanfänge in Textzellen', () => {
|
||||
for (const s of ['=1+1', '+49 123', '-2+3', '@SUM(A1)', '\t=1', '\r=1']) expect(csvSafe(s).startsWith("'")).toBe(true);
|
||||
expect(csvCell('=HYPERLINK("http://x")')).toBe(`"'=HYPERLINK(""http://x"")"`);
|
||||
expect(csvCell('Kunde A; GmbH')).toBe('"Kunde A; GmbH"');
|
||||
});
|
||||
it('lässt normale Texte unverändert', () => {
|
||||
expect(csvCell('Musterfirma GmbH')).toBe('Musterfirma GmbH');
|
||||
expect(csvCell('')).toBe('');
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue