From 03cf2b00c4ae98acaa7eb44ce09270fbdb670ed3 Mon Sep 17 00:00:00 2001 From: "Claude (KI)" Date: Tue, 6 Oct 2026 13:32:19 +0200 Subject: [PATCH] =?UTF-8?q?=C3=96ffentliche=20Statusseite=20mit=20Wartungs?= =?UTF-8?q?-=20und=20Vorfallverwaltung=20(#23)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Modul status (Migration 044): Störungen und Wartungen mit Zustand, Auswirkung, Bereich, Zeitraum und Meldungsverlauf. Öffentlich (/v1/public/status, Seite /status) nur, was das Personal veröffentlicht – nur dessen Texte, keine Kunden-/Ressourcen-/Anbieterdaten, nicht aus den internen Betriebsalarmen gespeist. Gesamtzustand aus aktiven Einträgen; angekündigte Wartungen zählen erst ab Beginn. - Verwaltung /admin/status (Support/Admin/Superadmin; Buchhaltung und Kunden nicht), Navigation. - Tests: API (Rechte, Veröffentlichung, Zustände, Abschluss, Felder) und Browser (Status- und Registrierungsseite barrierefrei, 12/12 grün). Passkeys und Berichte bleiben eigene offene Teilaufgaben. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/modules/index.ts | 3 +- apps/api/src/modules/status/index.ts | 78 ++++++++++++++++++++ apps/api/test/status.test.ts | 34 +++++++++ apps/e2e/tests/abnahme.spec.ts | 14 ++++ apps/web/src/app/(app)/admin/status/page.tsx | 53 +++++++++++++ apps/web/src/app/(app)/layout.tsx | 2 +- apps/web/src/app/status/page.tsx | 37 ++++++++++ docs/design/sitemap.md | 3 +- docs/sicherheit-und-bedrohungsmodell.md | 1 + migrations/044_status_page.sql | 26 +++++++ 10 files changed, 248 insertions(+), 3 deletions(-) create mode 100644 apps/api/src/modules/status/index.ts create mode 100644 apps/api/test/status.test.ts create mode 100644 apps/web/src/app/(app)/admin/status/page.tsx create mode 100644 apps/web/src/app/status/page.tsx create mode 100644 migrations/044_status_page.sql diff --git a/apps/api/src/modules/index.ts b/apps/api/src/modules/index.ts index f0f59d6..d91a556 100644 --- a/apps/api/src/modules/index.ts +++ b/apps/api/src/modules/index.ts @@ -15,6 +15,7 @@ import { mailModule } from './mail/index.js'; import { discordModule } from './discord/index.js'; import { licenseModule } from './license/index.js'; import { licensingModule } from './licensing/index.js'; +import { statusModule } from './status/index.js'; /** Aktive Module. Neue Module (Produkte, Verträge, Connectoren, Tickets, Rechnungen) werden hier eingetragen. */ -export const modules: KcModule[] = [systemModule, identityModule, customersModule, auditModule, connectorsModule, resourcesModule, catalogModule, domainsModule, ordersModule, ticketsModule, invoicesModule, backupModule, mailModule, discordModule, licenseModule, licensingModule]; +export const modules: KcModule[] = [systemModule, identityModule, customersModule, auditModule, connectorsModule, resourcesModule, catalogModule, domainsModule, ordersModule, ticketsModule, invoicesModule, backupModule, mailModule, discordModule, licenseModule, licensingModule, statusModule]; diff --git a/apps/api/src/modules/status/index.ts b/apps/api/src/modules/status/index.ts new file mode 100644 index 0000000..027efa7 --- /dev/null +++ b/apps/api/src/modules/status/index.ts @@ -0,0 +1,78 @@ +import type { FastifyInstance } from 'fastify'; +import { z } from 'zod'; +import { randomUUID } from 'node:crypto'; +import { one, query, run, tx } from '../../core/db.js'; +import { audit } from '../../core/audit.js'; +import { clientIp, requirePermission } from '../../core/auth.js'; +import { badRequest, notFound } from '../../core/errors.js'; +import { rl } from '../../core/config.js'; +import type { KcModule } from '../../core/module.js'; + +/** + * Öffentliche Statusseite (#23). Wartungen und Vorfälle werden vom Personal angelegt und erst mit „veröffentlichen“ + * öffentlich sichtbar. Die öffentliche Ausgabe enthält nur die vom Personal geschriebenen Texte (Titel, Bereich, + * Meldungen) – nie Kunden-, Ressourcen- oder Anbieterdaten und nichts aus den internen Betriebsalarmen. + */ +const OPEN_STATES = ['planned', 'investigating', 'identified', 'monitoring', 'in_progress']; +const STATE = { incident: ['investigating', 'identified', 'monitoring', 'resolved'], maintenance: ['planned', 'in_progress', 'completed'] } as const; +const view = (e: any, updates: any[], admin = false) => ({ + ...(admin ? { published: !!e.published } : {}), + id: e.id, kind: e.kind, title: e.title, component: e.component, impact: e.impact, state: e.state, startsAt: e.starts_at, endsAt: e.ends_at, + updates: updates.filter((u) => u.event_id === e.id).map((u) => ({ state: u.state, body: u.body, at: u.created_at })), +}); +async function withUpdates(events: any[], admin = false) { + if (!events.length) return []; + const ups = await query(`SELECT event_id, state, body, created_at FROM status_updates WHERE event_id IN (${events.map(() => '?').join(',')}) ORDER BY created_at DESC`, events.map((e) => e.id)); + return events.map((e) => view(e, ups, admin)); +} + +export const statusModule: KcModule = { + name: 'status', + permissions: { staff: { support: ['status.read', 'status.write'], admin: ['status.read', 'status.write'], superadmin: ['status.read', 'status.write'] } }, + register(app: FastifyInstance) { + /** Öffentlich, ohne Anmeldung. */ + app.get('/public/status', { config: rl(60, '1 minute') }, async () => { + const current = await query(`SELECT * FROM status_events WHERE published = 1 AND state IN (${OPEN_STATES.map(() => '?').join(',')}) ORDER BY starts_at`, OPEN_STATES); + const recent = await query("SELECT * FROM status_events WHERE published = 1 AND state IN ('resolved','completed') AND COALESCE(ends_at, updated_at) > DATE_SUB(UTC_TIMESTAMP(3), INTERVAL 14 DAY) ORDER BY COALESCE(ends_at, updated_at) DESC LIMIT 20"); + const now = Date.now(); + const active = current.filter((e) => e.kind === 'incident' || new Date(e.starts_at).getTime() <= now); + const overall = active.some((e) => e.impact === 'major') ? 'major' : active.some((e) => e.impact === 'minor') ? 'minor' : active.length ? 'maintenance' : 'ok'; + return { overall, current: await withUpdates(current), recent: await withUpdates(recent), generatedAt: new Date().toISOString() }; + }); + + app.get('/admin/status-events', async (req) => { + requirePermission(req, 'status.read'); + return withUpdates(await query('SELECT * FROM status_events ORDER BY starts_at DESC LIMIT 100'), true); + }); + app.post('/admin/status-events', async (req) => { + const a = requirePermission(req, 'status.write'); + const b = z.object({ kind: z.enum(['incident', 'maintenance']), title: z.string().trim().min(3).max(200), component: z.string().trim().max(100).optional(), + impact: z.enum(['none', 'minor', 'major']).default('minor'), startsAt: z.coerce.date().optional(), endsAt: z.coerce.date().optional(), body: z.string().trim().min(3).max(2000), published: z.boolean().default(false) }).parse(req.body); + if (b.endsAt && b.startsAt && b.endsAt < b.startsAt) throw badRequest('Das Ende liegt vor dem Beginn', 'BAD_RANGE'); + const id = randomUUID(); const state = b.kind === 'incident' ? 'investigating' : 'planned'; + await tx(async (c) => { + await run('INSERT INTO status_events (id, kind, title, component, impact, state, starts_at, ends_at, published, created_by) VALUES (?,?,?,?,?,?,?,?,?,?)', + [id, b.kind, b.title, b.component ?? null, b.impact, state, b.startsAt ?? new Date(), b.endsAt ?? null, b.published ? 1 : 0, a.user.id], c); + await run('INSERT INTO status_updates (id, event_id, state, body, created_by) VALUES (?,?,?,?,?)', [randomUUID(), id, state, b.body, a.user.id], c); + }); + await audit({ actorType: 'user', actorId: a.user.id, action: 'status.create', resourceType: 'status_event', resourceId: id, correlationId: req.correlationId, ip: clientIp(req), after: { kind: b.kind, published: b.published } }); + return { id }; + }); + /** Neuer Stand (Meldung) und/oder Veröffentlichung ändern. */ + app.post('/admin/status-events/:id/update', async (req) => { + const a = requirePermission(req, 'status.write'); + const { id } = z.object({ id: z.string().uuid() }).parse(req.params); + const b = z.object({ state: z.string().max(30).optional(), body: z.string().trim().min(3).max(2000).optional(), published: z.boolean().optional(), impact: z.enum(['none', 'minor', 'major']).optional(), endsAt: z.coerce.date().optional() }).parse(req.body); + const e = await one('SELECT * FROM status_events WHERE id = ?', [id]); if (!e) throw notFound(); + if (b.state && !(STATE[e.kind as 'incident' | 'maintenance'] as readonly string[]).includes(b.state)) throw badRequest('Dieser Zustand passt nicht zur Art des Eintrags', 'BAD_STATE'); + const closing = b.state === 'resolved' || b.state === 'completed'; + await tx(async (c) => { + await run('UPDATE status_events SET state = COALESCE(?, state), published = COALESCE(?, published), impact = COALESCE(?, impact), ends_at = COALESCE(?, IF(?, UTC_TIMESTAMP(3), ends_at)) WHERE id = ?', + [b.state ?? null, b.published === undefined ? null : b.published ? 1 : 0, b.impact ?? null, b.endsAt ?? null, closing ? 1 : 0, id], c); + if (b.body) await run('INSERT INTO status_updates (id, event_id, state, body, created_by) VALUES (?,?,?,?,?)', [randomUUID(), id, b.state ?? e.state, b.body, a.user.id], c); + }); + await audit({ actorType: 'user', actorId: a.user.id, action: 'status.update', resourceType: 'status_event', resourceId: id, correlationId: req.correlationId, ip: clientIp(req), after: { state: b.state, published: b.published } }); + return { ok: true }; + }); + }, +}; diff --git a/apps/api/test/status.test.ts b/apps/api/test/status.test.ts new file mode 100644 index 0000000..a9430aa --- /dev/null +++ b/apps/api/test/status.test.ts @@ -0,0 +1,34 @@ +import { beforeAll, describe, expect, it } from 'vitest'; +import type { FastifyInstance } from 'fastify'; +import { buildApp } from '../src/server.js'; +import { call, code, login, makeUser } from './helpers.js'; + +let app: FastifyInstance; +beforeAll(async () => { app = await buildApp(); await app.ready(); }); +const pub = async () => (await app.inject({ method: 'GET', url: '/v1/public/status' })).json(); +async function staff(email: string, role: string) { + await makeUser({ email, kind: 'staff', staffRole: role }); const { client } = await login(app, email); + const s = (await call(app, client, 'POST', '/auth/mfa/setup')).json(); await call(app, client, 'POST', '/auth/mfa/confirm', { code: code(s.secret) }); return client; +} + +describe('Öffentliche Statusseite (#23)', () => { + it('nur Veröffentlichtes ist öffentlich, ohne interne Felder; Gesamtzustand und Abschluss', async () => { + const sup = await staff('status-support@example.com', 'support'); const acc = await staff('status-buha@example.com', 'accounting'); + await makeUser({ email: 'status-kunde@example.com' }); const cust = (await login(app, 'status-kunde@example.com')).client; + expect((await pub()).overall).toBe('ok'); + expect((await call(app, cust, 'POST', '/admin/status-events', { kind: 'incident', title: 'X', body: 'xxx' })).statusCode).toBe(403); + expect((await call(app, acc, 'POST', '/admin/status-events', { kind: 'incident', title: 'X', body: 'xxx' })).statusCode).toBe(403); + const ev = (await call(app, sup, 'POST', '/admin/status-events', { kind: 'incident', title: 'E-Mail verzögert', component: 'E-Mail', impact: 'major', body: 'Wir untersuchen das.' })).json(); + expect((await pub()).current).toHaveLength(0); // nicht veröffentlicht + await call(app, sup, 'POST', `/admin/status-events/${ev.id}/update`, { published: true, state: 'identified', body: 'Ursache gefunden.' }); + let p = await pub(); expect(p.overall).toBe('major'); expect(p.current[0].title).toBe('E-Mail verzögert'); + expect(p.current[0].updates.map((u: any) => u.state)).toEqual(['identified', 'investigating']); + const keys = Object.keys(p.current[0]); for (const k of ['published', 'created_by', 'createdBy']) expect(keys).not.toContain(k); + expect((await call(app, sup, 'POST', `/admin/status-events/${ev.id}/update`, { state: 'completed' })).statusCode).toBe(400); // passt nicht zu Störung + await call(app, sup, 'POST', `/admin/status-events/${ev.id}/update`, { state: 'resolved', body: 'Behoben.' }); + p = await pub(); expect(p.overall).toBe('ok'); expect(p.recent[0].state).toBe('resolved'); expect(p.recent[0].endsAt).toBeTruthy(); + // geplante Wartung in der Zukunft: angekündigt, beeinflusst den Gesamtzustand noch nicht + await call(app, sup, 'POST', '/admin/status-events', { kind: 'maintenance', title: 'Wartung Webserver', impact: 'minor', startsAt: new Date(Date.now() + 86400000).toISOString(), body: 'Kurze Unterbrechung möglich.', published: true }); + p = await pub(); expect(p.overall).toBe('ok'); expect(p.current.map((e: any) => e.kind)).toContain('maintenance'); + }); +}); diff --git a/apps/e2e/tests/abnahme.spec.ts b/apps/e2e/tests/abnahme.spec.ts index be32e7f..c1d8f45 100644 --- a/apps/e2e/tests/abnahme.spec.ts +++ b/apps/e2e/tests/abnahme.spec.ts @@ -87,3 +87,17 @@ test('2FA-Code kann nicht wiederverwendet werden (Replay)', async ({ page }) => await page.getByRole('button', { name: 'Bestätigen' }).click(); await expect(page).not.toHaveURL(/\/dashboard/); }); + +test('Öffentliche Statusseite: ohne Anmeldung erreichbar und barrierefrei', async ({ page }) => { + await page.goto('/status'); + await expect(page.getByRole('heading', { name: 'Systemstatus' })).toBeVisible(); + await expect(page.getByText('Alle Systeme laufen normal')).toBeVisible(); + await expectAccessible(page, 'Statusseite'); +}); + +test('Registrierungsseite: bei ausgeschalteter Registrierung nur Hinweis, barrierefrei', async ({ page }) => { + await page.goto('/registrieren'); + await expect(page.getByText('Eine Selbstregistrierung ist derzeit nicht möglich')).toBeVisible(); + await expectAccessible(page, 'Registrierung'); +}); + diff --git a/apps/web/src/app/(app)/admin/status/page.tsx b/apps/web/src/app/(app)/admin/status/page.tsx new file mode 100644 index 0000000..1a2e9aa --- /dev/null +++ b/apps/web/src/app/(app)/admin/status/page.tsx @@ -0,0 +1,53 @@ +'use client'; +import { useCallback, useEffect, useState, type FormEvent } from 'react'; +import Link from 'next/link'; +import { api, errMsg } from '@/lib/api'; +import { useSession } from '@/lib/session'; +import { Alert, Empty, Field, fmt } from '@/components/ui'; + +interface Ev { id: string; kind: 'incident' | 'maintenance'; title: string; component: string | null; impact: string; state: string; startsAt: string; endsAt: string | null; published?: boolean; updates: { state: string; body: string; at: string }[] } +const STATES = { incident: [['investigating', 'Wird untersucht'], ['identified', 'Ursache gefunden'], ['monitoring', 'Wird beobachtet'], ['resolved', 'Behoben']], maintenance: [['planned', 'Geplant'], ['in_progress', 'Läuft'], ['completed', 'Abgeschlossen']] } as const; + +function Row({ e, onDone }: { e: Ev; onDone: (m: { k: 'ok' | 'err'; t: string }) => void }) { + const [busy, setBusy] = useState(false); + async function update(ev: FormEvent) { + ev.preventDefault(); setBusy(true); const f = new FormData(ev.currentTarget); + try { await api('POST', `/admin/status-events/${e.id}/update`, { state: f.get('state'), body: String(f.get('body') ?? '').trim() || undefined, published: f.get('published') === 'on' }); onDone({ k: 'ok', t: 'Gespeichert.' }); (ev.target as HTMLFormElement).reset(); } + catch (x) { onDone({ k: 'err', t: errMsg(x) }); } finally { setBusy(false); } + } + return (
+ {e.title} ({e.kind === 'incident' ? 'Störung' : 'Wartung'}{e.component ? `, ${e.component}` : ''}, Auswirkung {e.impact}, seit {fmt(e.startsAt)}) +
    {e.updates.map((u, i) =>
  • {u.state} ({fmt(u.at)}): {u.body}
  • )}
+
+
+ + +
); +} +/** Verwaltung der öffentlichen Statusseite (#23). Nur eigene Texte, keine Kunden- oder Anbieterdetails eintragen. */ +export default function StatusAdmin() { + const { can } = useSession(); + const [list, setList] = useState(null); const [msg, setMsg] = useState<{ k: 'ok' | 'err'; t: string } | null>(null); const [kind, setKind] = useState<'incident' | 'maintenance'>('incident'); + const load = useCallback(() => api('GET', '/admin/status-events').then(setList).catch((e) => setMsg({ k: 'err', t: errMsg(e) })), []); + useEffect(() => { void load(); }, [load]); + async function create(ev: FormEvent) { + ev.preventDefault(); const f = new FormData(ev.currentTarget); const v = (k: string) => String(f.get(k) ?? '').trim() || undefined; + try { await api('POST', '/admin/status-events', { kind, title: v('title'), component: v('component'), impact: f.get('impact'), startsAt: v('startsAt'), endsAt: v('endsAt'), body: v('body'), published: f.get('published') === 'on' }); setMsg({ k: 'ok', t: 'Angelegt.' }); (ev.target as HTMLFormElement).reset(); void load(); } + catch (x) { setMsg({ k: 'err', t: errMsg(x) }); } + } + const w = can('status.write'); + return (<> +

Statusseite

Öffentliche Ansicht
+

Öffentlich sichtbar ist nur, was hier veröffentlicht wird. Bitte keine Kundennamen, Ressourcen oder internen Details eintragen.

+ {msg && {msg.t}} + {w &&

Neuer Eintrag

+
{([['incident', 'Störung'], ['maintenance', 'Wartung']] as const).map(([k, l]) => )}
+
+
+ {kind === 'maintenance' &&
} + + +
} + {list === null ?

Wird geladen …

: list.length === 0 ?
: list.map((e) => { setMsg(m); void load(); }} />)} + ); +} diff --git a/apps/web/src/app/(app)/layout.tsx b/apps/web/src/app/(app)/layout.tsx index 1cbda19..a5b1a39 100644 --- a/apps/web/src/app/(app)/layout.tsx +++ b/apps/web/src/app/(app)/layout.tsx @@ -33,7 +33,7 @@ export default function AppLayout({ children }: { children: ReactNode }) { async function logout() { await api('POST', '/auth/logout'); await reload(); r.replace('/login'); } async function stopImpersonation() { const orgId = me!.impersonating!.orgId; await api('POST', '/auth/impersonate/stop'); await reload(); r.replace(`/admin/kunden/${orgId}`); } const produkte = [(me.kind === 'customer' || can('licenses.read')) && ['/lizenzen', me.kind === 'customer' ? 'Meine Lizenzen' : 'Lizenzen'], (me.kind === 'customer' || can('resources.read')) && ['/ressourcen', 'Ressourcen'], (me.kind === 'customer' || can('contracts.read')) && ['/vertraege', 'Verträge'], (me.kind === 'customer' || can('orders.read')) && ['/bestellungen', 'Bestellungen']].filter(Boolean) as [string, string][]; - const verwaltung = [can('customers.read') && ['/admin/kunden', 'Kunden'], can('products.read') && ['/admin/produkte', 'Produkte'], can('domains.read') && ['/admin/domains', 'Domain-Aufstellung'], can('users.read') && ['/admin/benutzer', 'Benutzer'], can('jobs.read') && ['/admin/auftraege', 'Aufträge'], can('audit.read') && ['/admin/audit', 'Audit-Protokoll'], (can('connectors.read') || can('backup.read')) && ['/einstellungen', 'Einstellungen']].filter(Boolean) as [string, string][]; + const verwaltung = [can('customers.read') && ['/admin/kunden', 'Kunden'], can('products.read') && ['/admin/produkte', 'Produkte'], can('domains.read') && ['/admin/domains', 'Domain-Aufstellung'], can('users.read') && ['/admin/benutzer', 'Benutzer'], can('jobs.read') && ['/admin/auftraege', 'Aufträge'], can('audit.read') && ['/admin/audit', 'Audit-Protokoll'], can('status.read') && ['/admin/status', 'Statusseite'], (can('connectors.read') || can('backup.read')) && ['/einstellungen', 'Einstellungen']].filter(Boolean) as [string, string][]; const nav = (