Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6537888da6 | ||
|
|
bfa5c61db5 | ||
|
|
554c9aae66 | ||
|
|
1ba90319a2 | ||
|
|
3c226dab12 | ||
|
|
f344f79326 | ||
|
|
c4bcfa8caf | ||
|
|
584cefa388 | ||
|
|
00665592f6 | ||
|
|
3b96d8ef41 | ||
|
|
c9e8edbbf0 | ||
|
|
b12d53f469 |
@@ -1,2 +1,4 @@
|
||||
*.log
|
||||
.env
|
||||
web/*/node_modules/
|
||||
web/*/.next/
|
||||
|
||||
@@ -64,6 +64,9 @@ Keine Änderungen ermittelbar.
|
||||
## 2026-08-27 17:28 – 17:29 (1m)
|
||||
**Beschreibung:** Claude Code Session
|
||||
**Projekt:** code
|
||||
## 2026-08-28 21:44 – 21:44 (0m)
|
||||
**Beschreibung:** Claude Code Session
|
||||
**Projekt:** nexarch
|
||||
|
||||
### Commits
|
||||
Keine Commits in dieser Session.
|
||||
@@ -127,5 +130,32 @@ Keine Commits in dieser Session.
|
||||
- internal/config/config.go | 29 +++++++++++++++++++++++++++++
|
||||
- internal/db/db.go | 11 +++++++++++
|
||||
- migrations/0001_tenant_registry.sql | 10 ++++++++++
|
||||
- web/shl/README.md | 45 +++++++++++++++++++++++++++++++++++++++++++++
|
||||
- web/shl/__tests__/Dialog.test.tsx | 38 ++++++++++++++++++++++++++++++++++++++
|
||||
- web/shl/__tests__/tokens.test.ts | 39 +++++++++++++++++++++++++++++++++++++++
|
||||
- web/shl/components/Dialog.tsx | 88 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||
- web/shl/components/FormElements.tsx | 98 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||
- web/shl/components/Shell.tsx | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||
- web/shl/components/Table.tsx | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||
- web/shl/components/Toast.tsx | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||
- web/shl/i18n/i18n.tsx | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||
- web/shl/index.ts | 25 +++++++++++++++++++++++++
|
||||
- web/shl/package.json | 23 +++++++++++++++++++++++
|
||||
- web/shl/theme/ThemeProvider.tsx | 81 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||
- web/shl/tokens/tokens.ts | 96 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||
- web/shl/tsconfig.json | 18 ++++++++++++++++++
|
||||
|
||||
---
|
||||
## 2026-08-28 21:51 – 21:57 (5m)
|
||||
**Beschreibung:** Claude Code Session
|
||||
**Projekt:** nexarch
|
||||
|
||||
### Commits
|
||||
- 3c226da SHL-01: fix — vitest jsdom-environment + jest-dom-Setup (3 Dialog-Tests schlugen ohne DOM fehl)
|
||||
|
||||
### Geänderte Dateien
|
||||
- web/shl/package.json | 2 ++
|
||||
- web/shl/vitest.config.ts | 8 ++++++++
|
||||
- web/shl/vitest.setup.ts | 1 +
|
||||
|
||||
---
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
// auditlog-devserver stellt AUD-03s ExportHandler (internal/audit) fuer die
|
||||
// Next.js-Audit-Log-Ansicht (AUD-04) bereit. Getrennt von cmd/core aus
|
||||
// demselben Grund wie die anderen *-devserver (siehe LIC-04/TEN-05): echte
|
||||
// Auth/RBAC ist noch nicht in die zentrale Server-Topologie verdrahtet.
|
||||
//
|
||||
// Authorize wird hier mit einem geteilten Admin-Token ueber
|
||||
// crypto/subtle.ConstantTimeCompare umgesetzt — demselben Timing-safe-Muster
|
||||
// wie internal/audit.timingsafe (AUD-02), NICHT ueber eine neue
|
||||
// Rollen-/Rechteschicht, da diese Kachel ausdruecklich nur von AUD-03
|
||||
// abhaengt und keine Rechteverwaltung duplizieren soll.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"gitea.perlbach24.de/scripte/nexarch/internal/audit"
|
||||
"gitea.perlbach24.de/scripte/nexarch/internal/auditadmin"
|
||||
"gitea.perlbach24.de/scripte/nexarch/internal/db"
|
||||
)
|
||||
|
||||
func main() {
|
||||
dsn := os.Getenv("NEXARCH_REGISTRY_DSN")
|
||||
if dsn == "" {
|
||||
log.Fatal("NEXARCH_REGISTRY_DSN nicht gesetzt")
|
||||
}
|
||||
adminToken := os.Getenv("NEXARCH_AUDIT_ADMIN_TOKEN")
|
||||
if adminToken == "" {
|
||||
log.Fatal("NEXARCH_AUDIT_ADMIN_TOKEN nicht gesetzt")
|
||||
}
|
||||
addr := os.Getenv("NEXARCH_AUDITLOG_LISTEN_ADDR")
|
||||
if addr == "" {
|
||||
addr = ":8083"
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
pool, err := db.Connect(ctx, dsn)
|
||||
if err != nil {
|
||||
log.Fatalf("db: %v", err)
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
auditLog := audit.NewLog(pool)
|
||||
tokenAuthorize := auditadmin.NewTokenAuthorizer(adminToken)
|
||||
authorize := func(_ context.Context, caller string) bool { return tokenAuthorize(caller) }
|
||||
handler := audit.NewExportHandler(auditLog, authorize)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/audit/export", withCORS(handler.Export))
|
||||
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
|
||||
|
||||
log.Printf("auditlog-devserver listening on %s", addr)
|
||||
log.Fatal(http.ListenAndServe(addr, mux))
|
||||
}
|
||||
|
||||
func withCORS(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
next(w, r)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
// Package audit implementiert Core AUD-01: das zentrale, vom allgemeinen
|
||||
// Anwendungs-Log getrennte Audit-Datenmodell fuer sicherheits- und
|
||||
// compliancerelevante Ereignisse (wer, was, wann, an welchem Tenant).
|
||||
// Unveraenderlichkeit (Append-only) ist AUD-02, Export/Filter-API ist AUD-03
|
||||
// — dieses Paket liefert nur das Datenmodell und den EINEN zentralen
|
||||
// Schreibpfad (Akzeptanzkriterium 3).
|
||||
package audit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// SystemTenant ist der reservierte Tenant-Bezug fuer mandantenuebergreifende
|
||||
// Ereignisse (z.B. Superadmin-Aktionen) — es gibt bewusst KEINEN Weg, ein
|
||||
// Ereignis ganz ohne Tenant-Bezug zu schreiben (Akzeptanzkriterium 2).
|
||||
const SystemTenant = "system"
|
||||
|
||||
var ErrMissingTenant = errors.New("audit: tenant_slug darf nicht leer sein")
|
||||
var ErrMissingActor = errors.New("audit: actor darf nicht leer sein")
|
||||
var ErrMissingAction = errors.New("audit: action darf nicht leer sein")
|
||||
|
||||
// Event ist ein strukturiertes Audit-Ereignis (Akzeptanzkriterium 1: Akteur,
|
||||
// Aktion, Zielobjekt, Zeitpunkt, Tenant).
|
||||
type Event struct {
|
||||
TenantSlug string
|
||||
Actor string
|
||||
Action string
|
||||
Target string
|
||||
Metadata map[string]any
|
||||
OccurredAt time.Time
|
||||
}
|
||||
|
||||
// Log ist der EINE zentrale Schreibpfad fuer Audit-Ereignisse — es gibt
|
||||
// bewusst keine zweite Schreibmoeglichkeit, damit kein Handler versehentlich
|
||||
// direkt in audit_events schreibt und dabei die Validierung umgeht
|
||||
// (Akzeptanzkriterium 3).
|
||||
type Log struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewLog(pool *pgxpool.Pool) *Log {
|
||||
return &Log{pool: pool}
|
||||
}
|
||||
|
||||
// Record persistiert genau einen Audit-Eintrag. Fehlender Tenant-Bezug wird
|
||||
// bereits hier abgewiesen (klarer Fehler statt Constraint-Verletzung im
|
||||
// Normalfall) — die Datenbank-CHECK-Constraint aus der Migration ist die
|
||||
// zweite, unumgehbare Verteidigungslinie (Akzeptanzkriterium 2 / Pruefung 2).
|
||||
func (l *Log) Record(ctx context.Context, e Event) error {
|
||||
if e.TenantSlug == "" {
|
||||
return ErrMissingTenant
|
||||
}
|
||||
if e.Actor == "" {
|
||||
return ErrMissingActor
|
||||
}
|
||||
if e.Action == "" {
|
||||
return ErrMissingAction
|
||||
}
|
||||
if e.Metadata == nil {
|
||||
e.Metadata = map[string]any{}
|
||||
}
|
||||
metadataJSON, err := json.Marshal(e.Metadata)
|
||||
if err != nil {
|
||||
return fmt.Errorf("metadaten serialisieren: %w", err)
|
||||
}
|
||||
if e.OccurredAt.IsZero() {
|
||||
e.OccurredAt = time.Now()
|
||||
}
|
||||
|
||||
_, err = l.pool.Exec(ctx, `
|
||||
INSERT INTO audit_events (occurred_at, tenant_slug, actor, action, target, metadata)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
`, e.OccurredAt, e.TenantSlug, e.Actor, e.Action, e.Target, metadataJSON)
|
||||
if err != nil {
|
||||
return fmt.Errorf("audit-ereignis schreiben: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CountByTenant ist eine schlanke Lesehilfe fuer Tests/Diagnose — die
|
||||
// eigentliche Filter-/Export-API ist AUD-03, hier bewusst nicht vorgezogen.
|
||||
func (l *Log) CountByTenant(ctx context.Context, tenantSlug string) (int, error) {
|
||||
var n int
|
||||
if err := l.pool.QueryRow(ctx, `
|
||||
SELECT count(*) FROM audit_events WHERE tenant_slug = $1
|
||||
`, tenantSlug).Scan(&n); err != nil {
|
||||
return 0, fmt.Errorf("audit-ereignisse zaehlen: %w", err)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func setupAuditTest(t *testing.T) (*Log, *pgxpool.Pool, func()) {
|
||||
t.Helper()
|
||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
||||
if adminDSN == "" {
|
||||
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
||||
}
|
||||
ctx := context.Background()
|
||||
|
||||
pool, err := pgxpool.New(ctx, adminDSN)
|
||||
if err != nil {
|
||||
t.Fatalf("pool: %v", err)
|
||||
}
|
||||
if _, err := pool.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS audit_events (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
occurred_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
tenant_slug TEXT NOT NULL CHECK (tenant_slug <> ''),
|
||||
actor TEXT NOT NULL CHECK (actor <> ''),
|
||||
action TEXT NOT NULL CHECK (action <> ''),
|
||||
target TEXT NOT NULL,
|
||||
metadata JSONB NOT NULL DEFAULT '{}'::jsonb
|
||||
)`); err != nil {
|
||||
t.Fatalf("schema: %v", err)
|
||||
}
|
||||
|
||||
cleanup := func() {
|
||||
_, _ = pool.Exec(ctx, `DELETE FROM audit_events WHERE tenant_slug LIKE 'test\_%' ESCAPE '\' OR tenant_slug = $1`, SystemTenant)
|
||||
pool.Close()
|
||||
}
|
||||
return NewLog(pool), pool, cleanup
|
||||
}
|
||||
|
||||
// Akzeptanzkriterium 1 + Pruefung 1: ein sicherheitsrelevanter Vorgang
|
||||
// (hier: fehlgeschlagener Login) erzeugt zuverlaessig genau einen Eintrag.
|
||||
func TestRecord_PersistsExactlyOneEventPerSecurityIncident(t *testing.T) {
|
||||
log, pool, cleanup := setupAuditTest(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
err := log.Record(ctx, Event{
|
||||
TenantSlug: "test_acme",
|
||||
Actor: "alice@example.com",
|
||||
Action: "iam.login_failed",
|
||||
Target: "user:alice@example.com",
|
||||
Metadata: map[string]any{"reason": "falsches passwort"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("record: %v", err)
|
||||
}
|
||||
|
||||
count, err := log.CountByTenant(ctx, "test_acme")
|
||||
if err != nil {
|
||||
t.Fatalf("count: %v", err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Fatalf("erwartet genau 1 audit-eintrag, habe %d", count)
|
||||
}
|
||||
|
||||
var actor, action, target string
|
||||
if err := pool.QueryRow(ctx, `
|
||||
SELECT actor, action, target FROM audit_events WHERE tenant_slug = 'test_acme'
|
||||
`).Scan(&actor, &action, &target); err != nil {
|
||||
t.Fatalf("eintrag lesen: %v", err)
|
||||
}
|
||||
if actor != "alice@example.com" || action != "iam.login_failed" || target != "user:alice@example.com" {
|
||||
t.Fatalf("eintrag unerwartet: actor=%q action=%q target=%q", actor, action, target)
|
||||
}
|
||||
}
|
||||
|
||||
// Akzeptanzkriterium 2 + Pruefung 2 (App-Ebene): fehlender Tenant-Bezug wird
|
||||
// bereits vom zentralen Schreibpfad abgewiesen.
|
||||
func TestRecord_RejectsMissingTenant(t *testing.T) {
|
||||
log, _, cleanup := setupAuditTest(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
err := log.Record(ctx, Event{TenantSlug: "", Actor: "alice", Action: "irgendwas"})
|
||||
if !errors.Is(err, ErrMissingTenant) {
|
||||
t.Fatalf("erwartet ErrMissingTenant, habe %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Akzeptanzkriterium 2 + Pruefung 2 (DB-Ebene): selbst ein direkter INSERT,
|
||||
// der Log.Record umgeht, wird durch die CHECK-Constraint verhindert — der
|
||||
// Schutz haengt nicht allein von der Go-Validierung ab.
|
||||
func TestConstraint_RejectsMissingTenantAtDatabaseLevel(t *testing.T) {
|
||||
_, pool, cleanup := setupAuditTest(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := pool.Exec(ctx, `
|
||||
INSERT INTO audit_events (tenant_slug, actor, action, target)
|
||||
VALUES ('', 'alice', 'irgendwas', 'ziel')
|
||||
`)
|
||||
if err == nil {
|
||||
t.Fatal("erwartet fehler durch CHECK-constraint bei leerem tenant_slug, habe nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecord_RejectsMissingActorAndAction(t *testing.T) {
|
||||
log, _, cleanup := setupAuditTest(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
if err := log.Record(ctx, Event{TenantSlug: "test_acme", Actor: "", Action: "x"}); !errors.Is(err, ErrMissingActor) {
|
||||
t.Fatalf("erwartet ErrMissingActor, habe %v", err)
|
||||
}
|
||||
if err := log.Record(ctx, Event{TenantSlug: "test_acme", Actor: "alice", Action: ""}); !errors.Is(err, ErrMissingAction) {
|
||||
t.Fatalf("erwartet ErrMissingAction, habe %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecord_SystemTenantForCrossTenantEvents(t *testing.T) {
|
||||
log, _, cleanup := setupAuditTest(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
if err := log.Record(ctx, Event{TenantSlug: SystemTenant, Actor: "superadmin", Action: "tenant.provisioned", Target: "tenant:acme"}); err != nil {
|
||||
t.Fatalf("record mit SystemTenant: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/csv"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Filter grenzt einen Export ein (Akzeptanzkriterium 1). Leere/Nil-Felder
|
||||
// bedeuten "kein Filter auf diesem Feld".
|
||||
type Filter struct {
|
||||
TenantSlug string
|
||||
Actor string
|
||||
Action string
|
||||
From *time.Time
|
||||
To *time.Time
|
||||
}
|
||||
|
||||
func buildFilterQuery(f Filter) (string, []any) {
|
||||
query := `SELECT occurred_at, tenant_slug, actor, action, target, metadata FROM audit_events WHERE 1=1`
|
||||
var args []any
|
||||
|
||||
if f.TenantSlug != "" {
|
||||
args = append(args, f.TenantSlug)
|
||||
query += fmt.Sprintf(" AND tenant_slug = $%d", len(args))
|
||||
}
|
||||
if f.Actor != "" {
|
||||
args = append(args, f.Actor)
|
||||
query += fmt.Sprintf(" AND actor = $%d", len(args))
|
||||
}
|
||||
if f.Action != "" {
|
||||
args = append(args, f.Action)
|
||||
query += fmt.Sprintf(" AND action = $%d", len(args))
|
||||
}
|
||||
if f.From != nil {
|
||||
args = append(args, *f.From)
|
||||
query += fmt.Sprintf(" AND occurred_at >= $%d", len(args))
|
||||
}
|
||||
if f.To != nil {
|
||||
args = append(args, *f.To)
|
||||
query += fmt.Sprintf(" AND occurred_at <= $%d", len(args))
|
||||
}
|
||||
query += " ORDER BY occurred_at"
|
||||
return query, args
|
||||
}
|
||||
|
||||
// StreamCSV schreibt gefilterte Audit-Eintraege direkt als CSV in w, Zeile
|
||||
// fuer Zeile ueber rows.Next() — es wird zu keinem Zeitpunkt das gesamte
|
||||
// Ergebnis im Speicher aufgebaut (Akzeptanzkriterium 3 / Pruefung 1).
|
||||
func (l *Log) StreamCSV(ctx context.Context, filter Filter, w io.Writer) error {
|
||||
query, args := buildFilterQuery(filter)
|
||||
rows, err := l.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("export abfragen: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
cw := csv.NewWriter(w)
|
||||
if err := cw.Write([]string{"occurred_at", "tenant_slug", "actor", "action", "target", "metadata"}); err != nil {
|
||||
return fmt.Errorf("csv-header schreiben: %w", err)
|
||||
}
|
||||
|
||||
for rows.Next() {
|
||||
var occurredAt time.Time
|
||||
var tenantSlug, actor, action, target string
|
||||
var metadataJSON []byte
|
||||
if err := rows.Scan(&occurredAt, &tenantSlug, &actor, &action, &target, &metadataJSON); err != nil {
|
||||
return fmt.Errorf("zeile lesen: %w", err)
|
||||
}
|
||||
if err := cw.Write([]string{
|
||||
occurredAt.Format(time.RFC3339), tenantSlug, actor, action, target, string(metadataJSON),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("csv-zeile schreiben: %w", err)
|
||||
}
|
||||
}
|
||||
cw.Flush()
|
||||
if err := rows.Err(); err != nil {
|
||||
return fmt.Errorf("export lesen: %w", err)
|
||||
}
|
||||
return cw.Error()
|
||||
}
|
||||
|
||||
// exportRecord ist die JSON-Repraesentation einer exportierten Zeile.
|
||||
type exportRecord struct {
|
||||
OccurredAt time.Time `json:"occurred_at"`
|
||||
TenantSlug string `json:"tenant_slug"`
|
||||
Actor string `json:"actor"`
|
||||
Action string `json:"action"`
|
||||
Target string `json:"target"`
|
||||
Metadata json.RawMessage `json:"metadata"`
|
||||
}
|
||||
|
||||
// StreamJSON schreibt gefilterte Audit-Eintraege als JSON Lines (ein
|
||||
// JSON-Objekt pro Zeile) — bewusst kein einzelnes grosses JSON-Array, da
|
||||
// dessen korrektes Streaming (Kommas/Klammern ohne Zwischenpufferung)
|
||||
// unnoetige Komplexitaet fuer denselben Zweck waere. Wie StreamCSV
|
||||
// zeilenweise ueber rows.Next(), kein Aufbau im Speicher.
|
||||
func (l *Log) StreamJSON(ctx context.Context, filter Filter, w io.Writer) error {
|
||||
query, args := buildFilterQuery(filter)
|
||||
rows, err := l.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("export abfragen: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
enc := json.NewEncoder(w)
|
||||
for rows.Next() {
|
||||
var rec exportRecord
|
||||
var metadataJSON []byte
|
||||
if err := rows.Scan(&rec.OccurredAt, &rec.TenantSlug, &rec.Actor, &rec.Action, &rec.Target, &metadataJSON); err != nil {
|
||||
return fmt.Errorf("zeile lesen: %w", err)
|
||||
}
|
||||
rec.Metadata = metadataJSON
|
||||
if err := enc.Encode(rec); err != nil {
|
||||
return fmt.Errorf("json-zeile schreiben: %w", err)
|
||||
}
|
||||
}
|
||||
return rows.Err()
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Authorize entscheidet, ob caller den Export ausfuehren darf. Die
|
||||
// eigentliche Rollen-/Rechtepruefung (RBAC-02 Policy-Enforcement) ist nicht
|
||||
// Teil dieser Kachel — ExportHandler kennt nur diese schmale Schnittstelle,
|
||||
// analog zum RetentionRegistrar-Muster aus AUD-05.
|
||||
type Authorize func(ctx context.Context, caller string) bool
|
||||
|
||||
// ExportHandler stellt den Export als HTTP-Endpunkt bereit
|
||||
// (Akzeptanzkriterium 2: fuer berechtigte Rollen verfuegbar).
|
||||
type ExportHandler struct {
|
||||
log *Log
|
||||
authorize Authorize
|
||||
}
|
||||
|
||||
func NewExportHandler(log *Log, authorize Authorize) *ExportHandler {
|
||||
return &ExportHandler{log: log, authorize: authorize}
|
||||
}
|
||||
|
||||
// Export liest Filter-Query-Parameter (tenant, actor, action, from, to,
|
||||
// format) und schreibt DIREKT auf den ResponseWriter (io.Writer) — dieselbe
|
||||
// Streaming-Funktion wie in export.go, kein zusaetzlicher Pufferungsschritt.
|
||||
func (h *ExportHandler) Export(w http.ResponseWriter, r *http.Request) {
|
||||
// "caller" identifiziert die anfragende Person fuer die Berechtigungs-
|
||||
// pruefung — bewusst getrennt vom Filterfeld "actor" (das den
|
||||
// AUDIT-Akteur meint, ueber den gefiltert wird).
|
||||
caller := r.URL.Query().Get("caller")
|
||||
if caller == "" || !h.authorize(r.Context(), caller) {
|
||||
http.Error(w, "keine berechtigung fuer audit-log-export", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
filter := Filter{
|
||||
TenantSlug: r.URL.Query().Get("tenant"),
|
||||
Actor: r.URL.Query().Get("actor"),
|
||||
Action: r.URL.Query().Get("action"),
|
||||
}
|
||||
if from := r.URL.Query().Get("from"); from != "" {
|
||||
t, err := time.Parse(time.RFC3339, from)
|
||||
if err != nil {
|
||||
http.Error(w, "ungueltiges from-datum, erwartet RFC3339", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
filter.From = &t
|
||||
}
|
||||
if to := r.URL.Query().Get("to"); to != "" {
|
||||
t, err := time.Parse(time.RFC3339, to)
|
||||
if err != nil {
|
||||
http.Error(w, "ungueltiges to-datum, erwartet RFC3339", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
filter.To = &t
|
||||
}
|
||||
|
||||
switch r.URL.Query().Get("format") {
|
||||
case "json":
|
||||
w.Header().Set("Content-Type", "application/x-ndjson")
|
||||
if err := h.log.StreamJSON(r.Context(), filter, w); err != nil {
|
||||
http.Error(w, "export fehlgeschlagen", http.StatusInternalServerError)
|
||||
}
|
||||
default:
|
||||
w.Header().Set("Content-Type", "text/csv")
|
||||
if err := h.log.StreamCSV(r.Context(), filter, w); err != nil {
|
||||
http.Error(w, "export fehlgeschlagen", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/csv"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func setupExportTest(t *testing.T) (*Log, func()) {
|
||||
t.Helper()
|
||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
||||
if adminDSN == "" {
|
||||
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
||||
}
|
||||
ctx := context.Background()
|
||||
|
||||
pool, err := pgxpool.New(ctx, adminDSN)
|
||||
if err != nil {
|
||||
t.Fatalf("pool: %v", err)
|
||||
}
|
||||
if _, err := pool.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS audit_events (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
occurred_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
tenant_slug TEXT NOT NULL CHECK (tenant_slug <> ''),
|
||||
actor TEXT NOT NULL CHECK (actor <> ''),
|
||||
action TEXT NOT NULL CHECK (action <> ''),
|
||||
target TEXT NOT NULL,
|
||||
metadata JSONB NOT NULL DEFAULT '{}'::jsonb
|
||||
)`); err != nil {
|
||||
t.Fatalf("schema: %v", err)
|
||||
}
|
||||
|
||||
cleanup := func() { pool.Close() }
|
||||
return NewLog(pool), cleanup
|
||||
}
|
||||
|
||||
// Akzeptanzkriterium 1 + Pruefung 2: Filterkombinationen liefern korrekte
|
||||
// Teilmengen.
|
||||
func TestExport_FilterCombinations(t *testing.T) {
|
||||
log, cleanup := setupExportTest(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
run := fmt.Sprintf("_%d", time.Now().UnixNano())
|
||||
tenantA, tenantB := "test_fa"+run, "test_fb"+run
|
||||
alice, bob := "alice"+run, "bob"+run
|
||||
|
||||
events := []Event{
|
||||
{TenantSlug: tenantA, Actor: alice, Action: "login", Target: "x"},
|
||||
{TenantSlug: tenantA, Actor: bob, Action: "login", Target: "x"},
|
||||
{TenantSlug: tenantA, Actor: alice, Action: "logout", Target: "x"},
|
||||
{TenantSlug: tenantB, Actor: alice, Action: "login", Target: "x"},
|
||||
}
|
||||
for _, e := range events {
|
||||
if err := log.Record(ctx, e); err != nil {
|
||||
t.Fatalf("record: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
filter Filter
|
||||
wantLen int
|
||||
}{
|
||||
{"nach tenant", Filter{TenantSlug: tenantA}, 3},
|
||||
{"nach tenant+actor", Filter{TenantSlug: tenantA, Actor: alice}, 2},
|
||||
{"nach tenant+actor+action", Filter{TenantSlug: tenantA, Actor: alice, Action: "login"}, 1},
|
||||
{"nach actor ueber beide tenants", Filter{Actor: alice, Action: "login"}, 2},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
if err := log.StreamCSV(ctx, c.filter, &buf); err != nil {
|
||||
t.Fatalf("stream: %v", err)
|
||||
}
|
||||
rows, err := csv.NewReader(&buf).ReadAll()
|
||||
if err != nil {
|
||||
t.Fatalf("csv parsen: %v", err)
|
||||
}
|
||||
got := len(rows) - 1 // Header abziehen
|
||||
if got != c.wantLen {
|
||||
t.Fatalf("erwartet %d zeilen, habe %d", c.wantLen, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Akzeptanzkriterium 1 + Pruefung 2: Zeitraum-Filter.
|
||||
func TestExport_TimeRangeFilter(t *testing.T) {
|
||||
log, cleanup := setupExportTest(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
tenant := fmt.Sprintf("test_tr_%d", time.Now().UnixNano())
|
||||
past := time.Now().Add(-48 * time.Hour)
|
||||
future := time.Now().Add(48 * time.Hour)
|
||||
|
||||
if err := log.Record(ctx, Event{TenantSlug: tenant, Actor: "a", Action: "x", Target: "t", OccurredAt: time.Now()}); err != nil {
|
||||
t.Fatalf("record: %v", err)
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := log.StreamCSV(ctx, Filter{TenantSlug: tenant, From: &past, To: &future}, &buf); err != nil {
|
||||
t.Fatalf("stream (innerhalb range): %v", err)
|
||||
}
|
||||
if got := countLines(buf.String()) - 1; got != 1 {
|
||||
t.Fatalf("erwartet 1 eintrag innerhalb des zeitraums, habe %d", got)
|
||||
}
|
||||
|
||||
farPast := time.Now().Add(-96 * time.Hour)
|
||||
buf.Reset()
|
||||
if err := log.StreamCSV(ctx, Filter{TenantSlug: tenant, From: &farPast, To: &past}, &buf); err != nil {
|
||||
t.Fatalf("stream (ausserhalb range): %v", err)
|
||||
}
|
||||
if got := countLines(buf.String()) - 1; got != 0 {
|
||||
t.Fatalf("erwartet 0 eintraege ausserhalb des zeitraums, habe %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func countLines(s string) int {
|
||||
s = strings.TrimRight(s, "\n")
|
||||
if s == "" {
|
||||
return 0
|
||||
}
|
||||
return len(strings.Split(s, "\n"))
|
||||
}
|
||||
|
||||
// Akzeptanzkriterium 3 + Pruefung 1: Export mit hoher Eintragszahl ohne
|
||||
// uebermaessigen Speicherverbrauch — Stichprobe per runtime.MemStats.
|
||||
func TestExport_StreamsLargeResultWithoutExcessiveMemory(t *testing.T) {
|
||||
log, cleanup := setupExportTest(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
tenant := fmt.Sprintf("test_large_%d", time.Now().UnixNano())
|
||||
const n = 20000
|
||||
for i := 0; i < n; i++ {
|
||||
if err := log.Record(ctx, Event{TenantSlug: tenant, Actor: "bulk", Action: "test.bulk", Target: fmt.Sprintf("obj-%d", i)}); err != nil {
|
||||
t.Fatalf("record %d: %v", i, err)
|
||||
}
|
||||
}
|
||||
|
||||
runtime.GC()
|
||||
var before runtime.MemStats
|
||||
runtime.ReadMemStats(&before)
|
||||
|
||||
lineCount := 0
|
||||
cw := &countingWriter{onWrite: func(p []byte) { lineCount += strings.Count(string(p), "\n") }}
|
||||
if err := log.StreamCSV(ctx, Filter{TenantSlug: tenant}, cw); err != nil {
|
||||
t.Fatalf("stream: %v", err)
|
||||
}
|
||||
|
||||
runtime.GC()
|
||||
var after runtime.MemStats
|
||||
runtime.ReadMemStats(&after)
|
||||
|
||||
if lineCount != n+1 { // +1 Header
|
||||
t.Fatalf("erwartet %d zeilen (inkl. header), habe %d", n+1, lineCount)
|
||||
}
|
||||
|
||||
// Grobe Stichprobe: ein NICHT streamender Export haette hier locker
|
||||
// mehrere MB an einmal gehaltenen Zeilen/Strings erzeugt. Grosszuegige
|
||||
// Schwelle, da Go-Heap-Messungen naturgemaess rauschen.
|
||||
const maxAcceptableGrowth = 3 * 1024 * 1024 // 3 MB
|
||||
growth := int64(after.HeapAlloc) - int64(before.HeapAlloc)
|
||||
t.Logf("heap-wachstum waehrend export von %d zeilen: %d bytes (schwelle: %d)", n, growth, maxAcceptableGrowth)
|
||||
if growth > maxAcceptableGrowth {
|
||||
t.Fatalf("heap ist um %d bytes gewachsen, erwartet unter %d (hinweis auf vollstaendige pufferung statt streaming)", growth, maxAcceptableGrowth)
|
||||
}
|
||||
}
|
||||
|
||||
type countingWriter struct {
|
||||
onWrite func(p []byte)
|
||||
}
|
||||
|
||||
func (w *countingWriter) Write(p []byte) (int, error) {
|
||||
w.onWrite(p)
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
// Akzeptanzkriterium 2 + Pruefung 3: Zugriff ohne passende Berechtigung wird abgewiesen.
|
||||
func TestExportHandler_RejectsWithoutAuthorization(t *testing.T) {
|
||||
log, cleanup := setupExportTest(t)
|
||||
defer cleanup()
|
||||
|
||||
handler := NewExportHandler(log, func(ctx context.Context, caller string) bool {
|
||||
return caller == "berechtigte-person@example.com"
|
||||
})
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/audit/export?caller=unberechtigt@example.com", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.Export(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("unberechtigt: status = %d, want 403", rec.Code)
|
||||
}
|
||||
|
||||
reqNoCaller := httptest.NewRequest(http.MethodGet, "/audit/export", nil)
|
||||
recNoCaller := httptest.NewRecorder()
|
||||
handler.Export(recNoCaller, reqNoCaller)
|
||||
if recNoCaller.Code != http.StatusForbidden {
|
||||
t.Fatalf("ohne caller: status = %d, want 403", recNoCaller.Code)
|
||||
}
|
||||
|
||||
reqOK := httptest.NewRequest(http.MethodGet, "/audit/export?caller=berechtigte-person@example.com", nil)
|
||||
recOK := httptest.NewRecorder()
|
||||
handler.Export(recOK, reqOK)
|
||||
if recOK.Code != http.StatusOK {
|
||||
t.Fatalf("berechtigt: status = %d, want 200", recOK.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// Package auditadmin implementiert Core AUD-04: die Berechtigungspruefung
|
||||
// fuer die Audit-Log-Ansicht. Enthaelt bewusst KEINE eigene Filter-/
|
||||
// Export-Logik — die Ansicht ist "reiner Konsument der Export-API" (AUD-03,
|
||||
// internal/audit.ExportHandler); dieses Paket liefert nur die
|
||||
// audit.Authorize-Implementierung, die der Entwicklungs-/Testserver
|
||||
// (cmd/auditlog-devserver) einhaengt.
|
||||
package auditadmin
|
||||
|
||||
import "crypto/subtle"
|
||||
|
||||
// NewTokenAuthorizer liefert eine audit.Authorize-Funktion, die den
|
||||
// aufrufenden "caller"-Wert timing-safe gegen ein geteiltes Admin-Token
|
||||
// vergleicht — dasselbe Muster wie internal/audit.timingsafe (AUD-02),
|
||||
// NICHT ueber eine neue Rollen-/Rechteschicht, da AUD-04 ausdruecklich nur
|
||||
// von AUD-03 abhaengt.
|
||||
func NewTokenAuthorizer(adminToken string) func(caller string) bool {
|
||||
return func(caller string) bool {
|
||||
if caller == "" || adminToken == "" {
|
||||
return false
|
||||
}
|
||||
return subtle.ConstantTimeCompare([]byte(caller), []byte(adminToken)) == 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package auditadmin
|
||||
|
||||
import "testing"
|
||||
|
||||
// Grundlage fuer Akzeptanzkriterium 1/2: die Oberflaeche darf Daten und den
|
||||
// Export nur bei korrektem Admin-Token abrufen.
|
||||
func TestNewTokenAuthorizer_AcceptsCorrectToken(t *testing.T) {
|
||||
authorize := NewTokenAuthorizer("geheimes-token")
|
||||
if !authorize("geheimes-token") {
|
||||
t.Fatal("erwartet true fuer korrektes token")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewTokenAuthorizer_RejectsWrongToken(t *testing.T) {
|
||||
authorize := NewTokenAuthorizer("geheimes-token")
|
||||
if authorize("falsches-token") {
|
||||
t.Fatal("erwartet false fuer falsches token")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewTokenAuthorizer_RejectsEmptyCaller(t *testing.T) {
|
||||
authorize := NewTokenAuthorizer("geheimes-token")
|
||||
if authorize("") {
|
||||
t.Fatal("erwartet false fuer leeren aufrufer")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewTokenAuthorizer_RejectsWhenNoTokenConfigured(t *testing.T) {
|
||||
authorize := NewTokenAuthorizer("")
|
||||
if authorize("irgendwas") {
|
||||
t.Fatal("erwartet false, wenn kein admin-token konfiguriert ist (fail-safe-default)")
|
||||
}
|
||||
}
|
||||
@@ -1,136 +0,0 @@
|
||||
package tenant
|
||||
|
||||
import (
|
||||
"container/list"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// ErrMissingTenantContext wird geliefert, wenn keine Tenant-Kennung
|
||||
// uebergeben wurde — es gibt bewusst keinen impliziten Default-Tenant
|
||||
// (TEN-06 Akzeptanzkriterium 3).
|
||||
var ErrMissingTenantContext = errors.New("tenant: kein tenant-kontext angegeben")
|
||||
|
||||
// ErrUnknownTenant wird geliefert, wenn die Tenant-Kennung in der Registry
|
||||
// nicht existiert.
|
||||
var ErrUnknownTenant = errors.New("tenant: unbekannter tenant")
|
||||
|
||||
// Router loest den Tenant-Kontext (Slug, aus dem JWT-Claim von API-05) in
|
||||
// eine wiederverwendbare Verbindung zur richtigen Tenant-Datenbank auf.
|
||||
// Ein LRU-verwalteter Cache begrenzt die Zahl gleichzeitig offener
|
||||
// pgxpool.Pool-Instanzen, damit die Zahl offener Postgres-Verbindungen NICHT
|
||||
// linear mit der Mandantenzahl waechst (Akzeptanzkriterium 2).
|
||||
type Router struct {
|
||||
registry *Registry
|
||||
maxOpen int
|
||||
|
||||
mu sync.Mutex
|
||||
order *list.List // vorne = zuletzt benutzt
|
||||
items map[string]*list.Element // slug -> element mit *routerEntry
|
||||
}
|
||||
|
||||
type routerEntry struct {
|
||||
slug string
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewRouter(registry *Registry, maxOpen int) *Router {
|
||||
if maxOpen < 1 {
|
||||
maxOpen = 1
|
||||
}
|
||||
return &Router{
|
||||
registry: registry,
|
||||
maxOpen: maxOpen,
|
||||
order: list.New(),
|
||||
items: make(map[string]*list.Element),
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve liefert einen wiederverwendeten Pool fuer den angegebenen Tenant.
|
||||
// Ist der Tenant bereits im Cache, wird KEINE neue Verbindung aufgebaut
|
||||
// (Akzeptanzkriterium 2 / Pruefung 3).
|
||||
func (r *Router) Resolve(ctx context.Context, tenantSlug string) (*pgxpool.Pool, error) {
|
||||
if tenantSlug == "" {
|
||||
return nil, ErrMissingTenantContext
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
if el, ok := r.items[tenantSlug]; ok {
|
||||
r.order.MoveToFront(el)
|
||||
pool := el.Value.(*routerEntry).pool
|
||||
r.mu.Unlock()
|
||||
return pool, nil
|
||||
}
|
||||
r.mu.Unlock()
|
||||
|
||||
// Registry-Lookup und Verbindungsaufbau bewusst ausserhalb des Locks,
|
||||
// damit ein langsamer Verbindungsaufbau nicht alle anderen Tenants blockiert.
|
||||
t, err := r.registry.GetBySlug(ctx, tenantSlug)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %s", ErrUnknownTenant, tenantSlug)
|
||||
}
|
||||
|
||||
pool, err := pgxpool.New(ctx, t.DBDSN)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("verbindung zu tenant %q aufbauen: %w", tenantSlug, err)
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
// Zwischen Unlock oben und hier koennte ein paralleler Aufruf denselben
|
||||
// Tenant bereits eingefuegt haben — dann die eigene, ueberzaehlige
|
||||
// Verbindung wieder schliessen und die vorhandene verwenden.
|
||||
if el, ok := r.items[tenantSlug]; ok {
|
||||
r.order.MoveToFront(el)
|
||||
existing := el.Value.(*routerEntry).pool
|
||||
pool.Close()
|
||||
return existing, nil
|
||||
}
|
||||
|
||||
el := r.order.PushFront(&routerEntry{slug: tenantSlug, pool: pool})
|
||||
r.items[tenantSlug] = el
|
||||
|
||||
if r.order.Len() > r.maxOpen {
|
||||
r.evictOldest()
|
||||
}
|
||||
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
// evictOldest schliesst den am laengsten nicht genutzten Pool. Muss mit
|
||||
// gehaltenem r.mu aufgerufen werden.
|
||||
func (r *Router) evictOldest() {
|
||||
oldest := r.order.Back()
|
||||
if oldest == nil {
|
||||
return
|
||||
}
|
||||
entry := oldest.Value.(*routerEntry)
|
||||
r.order.Remove(oldest)
|
||||
delete(r.items, entry.slug)
|
||||
entry.pool.Close()
|
||||
}
|
||||
|
||||
// OpenCount liefert die aktuelle Zahl offen gehaltener Tenant-Pools —
|
||||
// dient Tests/Monitoring, um AC2 nachzuweisen.
|
||||
func (r *Router) OpenCount() int {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return r.order.Len()
|
||||
}
|
||||
|
||||
// Close schliesst alle offen gehaltenen Tenant-Pools, z.B. beim
|
||||
// Herunterfahren des Core-Prozesses.
|
||||
func (r *Router) Close() {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
for el := r.order.Front(); el != nil; el = el.Next() {
|
||||
el.Value.(*routerEntry).pool.Close()
|
||||
}
|
||||
r.order.Init()
|
||||
r.items = make(map[string]*list.Element)
|
||||
}
|
||||
@@ -1,160 +0,0 @@
|
||||
package tenant
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func newTestRouterSetup(t *testing.T, tenantCount int) (*Router, []Tenant, func()) {
|
||||
t.Helper()
|
||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
||||
if adminDSN == "" {
|
||||
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
||||
}
|
||||
ctx := context.Background()
|
||||
|
||||
adminPool, err := pgxpool.New(ctx, adminDSN)
|
||||
if err != nil {
|
||||
t.Fatalf("admin pool: %v", err)
|
||||
}
|
||||
registryPool, err := pgxpool.New(ctx, adminDSN)
|
||||
if err != nil {
|
||||
t.Fatalf("registry pool: %v", err)
|
||||
}
|
||||
if _, err := registryPool.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS tenants (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
slug TEXT NOT NULL UNIQUE,
|
||||
name TEXT NOT NULL,
|
||||
db_name TEXT NOT NULL UNIQUE,
|
||||
db_dsn TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'active',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
)`); err != nil {
|
||||
t.Fatalf("registry-schema: %v", err)
|
||||
}
|
||||
|
||||
registry := NewRegistry(registryPool)
|
||||
dsnTemplate := strings.Replace(adminDSN, "/postgres?", "/%s?", 1)
|
||||
provisioner := NewProvisioner(adminPool, registry, dsnTemplate)
|
||||
|
||||
var tenants []Tenant
|
||||
var slugs []string
|
||||
for i := 0; i < tenantCount; i++ {
|
||||
slug := fmt.Sprintf("router_t%d", i)
|
||||
slugs = append(slugs, slug)
|
||||
tn, err := provisioner.Provision(ctx, slug, slug)
|
||||
if err != nil {
|
||||
t.Fatalf("provision %s: %v", slug, err)
|
||||
}
|
||||
tenants = append(tenants, tn)
|
||||
}
|
||||
|
||||
router := NewRouter(registry, 2) // klein gewaehlt, um Eviction im Test zu erzwingen
|
||||
|
||||
cleanup := func() {
|
||||
router.Close()
|
||||
for _, slug := range slugs {
|
||||
_, _ = adminPool.Exec(ctx, fmt.Sprintf(`DROP DATABASE IF EXISTS %q`, dbNameForSlug(slug)))
|
||||
}
|
||||
_, _ = registryPool.Exec(ctx, `DELETE FROM tenants WHERE slug = ANY($1)`, slugs)
|
||||
registryPool.Close()
|
||||
adminPool.Close()
|
||||
}
|
||||
return router, tenants, cleanup
|
||||
}
|
||||
|
||||
// Akzeptanzkriterium 1: Verbindung wird zuverlaessig anhand des Tenant-Kontexts aufgeloest.
|
||||
func TestRouter_ResolvesCorrectTenantDatabase(t *testing.T) {
|
||||
router, tenants, cleanup := newTestRouterSetup(t, 2)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
pool, err := router.Resolve(ctx, tenants[0].Slug)
|
||||
if err != nil {
|
||||
t.Fatalf("resolve: %v", err)
|
||||
}
|
||||
var dbName string
|
||||
if err := pool.QueryRow(ctx, `SELECT current_database()`).Scan(&dbName); err != nil {
|
||||
t.Fatalf("current_database: %v", err)
|
||||
}
|
||||
if dbName != tenants[0].DBName {
|
||||
t.Fatalf("current_database() = %q, want %q", dbName, tenants[0].DBName)
|
||||
}
|
||||
}
|
||||
|
||||
// Akzeptanzkriterium 3 + Pruefung 2: fehlender/unbekannter Tenant-Kontext
|
||||
// wird explizit abgewiesen statt irgendeine Verbindung zu liefern.
|
||||
func TestRouter_RejectsMissingOrUnknownTenant(t *testing.T) {
|
||||
router, _, cleanup := newTestRouterSetup(t, 1)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
if _, err := router.Resolve(ctx, ""); !errors.Is(err, ErrMissingTenantContext) {
|
||||
t.Fatalf("erwartet ErrMissingTenantContext, habe %v", err)
|
||||
}
|
||||
if _, err := router.Resolve(ctx, "nie-registrierter-slug"); !errors.Is(err, ErrUnknownTenant) {
|
||||
t.Fatalf("erwartet ErrUnknownTenant, habe %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Akzeptanzkriterium 2 + Pruefung 3: Verbindungswiederverwendung nachweislich
|
||||
// gemessen — zweiter Resolve-Aufruf liefert exakt denselben Pool, kein
|
||||
// erneuter Verbindungsaufbau.
|
||||
func TestRouter_ReusesConnectionForSameTenant(t *testing.T) {
|
||||
router, tenants, cleanup := newTestRouterSetup(t, 1)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
first, err := router.Resolve(ctx, tenants[0].Slug)
|
||||
if err != nil {
|
||||
t.Fatalf("resolve 1: %v", err)
|
||||
}
|
||||
second, err := router.Resolve(ctx, tenants[0].Slug)
|
||||
if err != nil {
|
||||
t.Fatalf("resolve 2: %v", err)
|
||||
}
|
||||
if first != second {
|
||||
t.Fatal("erwartet identische pool-instanz bei wiederholtem resolve, habe unterschiedliche")
|
||||
}
|
||||
}
|
||||
|
||||
// Akzeptanzkriterium 2 + Pruefung 1: Lasttest mit mehr simulierten Mandanten
|
||||
// als maxOpen — die Zahl gleichzeitig offener Tenant-Pools bleibt begrenzt
|
||||
// (LRU-Eviction), waechst also NICHT linear mit der Mandantenzahl.
|
||||
func TestRouter_BoundsOpenConnectionsUnderLoad(t *testing.T) {
|
||||
const tenantCount = 6
|
||||
router, tenants, cleanup := newTestRouterSetup(t, tenantCount)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
for _, tn := range tenants {
|
||||
if _, err := router.Resolve(ctx, tn.Slug); err != nil {
|
||||
t.Fatalf("resolve %s: %v", tn.Slug, err)
|
||||
}
|
||||
if router.OpenCount() > 2 {
|
||||
t.Fatalf("OpenCount() = %d, erwartet <= maxOpen (2) nach jedem Resolve", router.OpenCount())
|
||||
}
|
||||
}
|
||||
|
||||
if router.OpenCount() != 2 {
|
||||
t.Fatalf("erwartet genau maxOpen=2 offene pools nach %d tenants, habe %d", tenantCount, router.OpenCount())
|
||||
}
|
||||
|
||||
// Evictete Tenants sind wieder ganz normal ueber die Registry aufloesbar
|
||||
// (Cache-Miss fuehrt zu neuem, funktionierendem Pool, kein Fehlerzustand).
|
||||
pool, err := router.Resolve(ctx, tenants[0].Slug)
|
||||
if err != nil {
|
||||
t.Fatalf("resolve nach eviction: %v", err)
|
||||
}
|
||||
var one int
|
||||
if err := pool.QueryRow(ctx, `SELECT 1`).Scan(&one); err != nil {
|
||||
t.Fatalf("query nach re-resolve: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE IF EXISTS audit_events;
|
||||
@@ -0,0 +1,17 @@
|
||||
-- Zentrales Audit-Log-Modell (AUD-01, siehe core-kanban/tickets/AUD-01.md).
|
||||
-- Getrennt vom allgemeinen Anwendungs-Log (Akzeptanzkriterium 2): eigene
|
||||
-- Tabelle, eigenes Paket (internal/audit), kein Log-Framework.
|
||||
-- tenant_slug ist NOT NULL + darf nicht leer sein (Akzeptanzkriterium 2 /
|
||||
-- Pruefung 2) — mandantenuebergreifende Ereignisse nutzen den reservierten
|
||||
-- Wert 'system', niemals NULL oder leeren String.
|
||||
CREATE TABLE audit_events (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
occurred_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
tenant_slug TEXT NOT NULL CHECK (tenant_slug <> ''),
|
||||
actor TEXT NOT NULL CHECK (actor <> ''),
|
||||
action TEXT NOT NULL CHECK (action <> ''),
|
||||
target TEXT NOT NULL,
|
||||
metadata JSONB NOT NULL DEFAULT '{}'::jsonb
|
||||
);
|
||||
|
||||
CREATE INDEX audit_events_tenant_slug_idx ON audit_events (tenant_slug, occurred_at);
|
||||
Executable
+24
@@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env bash
|
||||
# Setzt die nexarch-Testumgebung zurueck: loescht die geteilte
|
||||
# Registry-Tabelle "tenants" in der postgres-Wartungsdatenbank sowie alle
|
||||
# tenant_*-Datenbanken. Noetig, weil verschiedene Feature-Branches
|
||||
# unterschiedliche Registry-Schemata erwarten, aber dieselbe physische
|
||||
# Postgres-Instanz auf dem Testhost teilen (siehe [[project-nexarch-test-infra]]).
|
||||
#
|
||||
# Aufruf: NEXARCH_TEST_DB_PASSWORD=... ./scripts/reset-test-env.sh
|
||||
set -euo pipefail
|
||||
|
||||
PASS="${NEXARCH_TEST_DB_PASSWORD:?Setze NEXARCH_TEST_DB_PASSWORD vor dem Aufruf}"
|
||||
ROLE="nexarch_test"
|
||||
|
||||
export PGPASSWORD="$PASS"
|
||||
|
||||
psql -h localhost -U "$ROLE" -d postgres -v ON_ERROR_STOP=1 -c "DROP TABLE IF EXISTS tenants CASCADE;"
|
||||
psql -h localhost -U "$ROLE" -d postgres -v ON_ERROR_STOP=1 -c "DROP TABLE IF EXISTS audit_events CASCADE;"
|
||||
|
||||
dbs=$(psql -h localhost -U "$ROLE" -d postgres -tAc "SELECT datname FROM pg_database WHERE datname LIKE 'tenant\_%' ESCAPE '\'")
|
||||
for db in $dbs; do
|
||||
psql -h localhost -U "$ROLE" -d postgres -v ON_ERROR_STOP=1 -c "DROP DATABASE IF EXISTS \"${db}\";"
|
||||
done
|
||||
|
||||
echo "Testumgebung zurueckgesetzt: registry-tabelle + $(echo "$dbs" | grep -c . || true) tenant-datenbank(en) entfernt."
|
||||
Executable
+24
@@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env bash
|
||||
# Ein-Kommando-Pruefung fuer den aktuellen Code-Stand auf dem Testhost:
|
||||
# Registry+Tenant-DBs zuruecksetzen, dann build/vet/test in einem Rutsch.
|
||||
# -p 1 ist Pflicht, da mehrere Pakete dieselbe physische Registry-Tabelle auf
|
||||
# dem Testhost teilen (siehe [[project-nexarch-test-infra]]).
|
||||
#
|
||||
# Aufruf: NEXARCH_TEST_DB_PASSWORD=... ./scripts/run-checks.sh
|
||||
set -euo pipefail
|
||||
|
||||
PASS="${NEXARCH_TEST_DB_PASSWORD:?Setze NEXARCH_TEST_DB_PASSWORD vor dem Aufruf}"
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
NEXARCH_TEST_DB_PASSWORD="$PASS" bash scripts/reset-test-env.sh
|
||||
|
||||
export TEST_ADMIN_DSN="postgresql://nexarch_test:${PASS}@localhost:5432/postgres?sslmode=disable"
|
||||
|
||||
echo "== go build =="
|
||||
go build ./...
|
||||
|
||||
echo "== go vet =="
|
||||
go vet ./...
|
||||
|
||||
echo "== go test (-p 1) =="
|
||||
go test ./... -p 1 -count=1
|
||||
@@ -0,0 +1,30 @@
|
||||
import { ThemeProvider, I18nProvider, ToastProvider, typography } from "@nexarch/shl";
|
||||
|
||||
export const metadata = {
|
||||
title: "NEXARCH Audit-Log",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<html lang="de">
|
||||
<body
|
||||
style={{
|
||||
fontFamily: typography.fontFamily,
|
||||
margin: 0,
|
||||
background: "var(--shl-color-background, #ffffff)",
|
||||
color: "var(--shl-color-text-primary, #14181f)",
|
||||
}}
|
||||
>
|
||||
<ThemeProvider>
|
||||
<I18nProvider initialLocale="de">
|
||||
<ToastProvider>{children}</ToastProvider>
|
||||
</I18nProvider>
|
||||
</ThemeProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { fetchRecords, exportURL, type AuditRecord, type AuditFilter } from "@/lib/api";
|
||||
|
||||
const EMPTY_FILTER: AuditFilter = { tenant: "", actor: "", action: "", from: "", to: "" };
|
||||
|
||||
export default function Page() {
|
||||
const [caller, setCaller] = useState("");
|
||||
const [filter, setFilter] = useState<AuditFilter>(EMPTY_FILTER);
|
||||
const [records, setRecords] = useState<AuditRecord[] | null>(null);
|
||||
const [selected, setSelected] = useState<AuditRecord | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function onSearch() {
|
||||
setError(null);
|
||||
setSelected(null);
|
||||
try {
|
||||
const data = await fetchRecords(caller.trim(), filter);
|
||||
setRecords(data);
|
||||
} catch (e: any) {
|
||||
setError(e.message ?? "Unbekannter Fehler");
|
||||
setRecords(null);
|
||||
}
|
||||
}
|
||||
|
||||
function onExport(format: "csv" | "json") {
|
||||
const url = exportURL(caller.trim(), filter, format);
|
||||
// Echter Datei-Download ueber Browser-Navigation, KEIN erneutes Parsen
|
||||
// im Frontend (Akzeptanzkriterium 2: Export aus AUD-03 direkt ausloesbar).
|
||||
window.open(url, "_blank");
|
||||
}
|
||||
|
||||
return (
|
||||
<main style={{ maxWidth: 1000, margin: "0 auto", padding: "2rem 1rem" }}>
|
||||
<h1>Audit-Log</h1>
|
||||
|
||||
<div style={{ display: "grid", gap: "0.5rem", gridTemplateColumns: "repeat(3, 1fr)", marginBottom: "1rem" }}>
|
||||
<input
|
||||
value={caller}
|
||||
onChange={(e) => setCaller(e.target.value)}
|
||||
placeholder="Admin-Token (Berechtigung)"
|
||||
style={{ padding: "0.5rem", gridColumn: "span 3" }}
|
||||
/>
|
||||
<input
|
||||
value={filter.tenant}
|
||||
onChange={(e) => setFilter({ ...filter, tenant: e.target.value })}
|
||||
placeholder="Tenant"
|
||||
style={{ padding: "0.5rem" }}
|
||||
/>
|
||||
<input
|
||||
value={filter.actor}
|
||||
onChange={(e) => setFilter({ ...filter, actor: e.target.value })}
|
||||
placeholder="Akteur"
|
||||
style={{ padding: "0.5rem" }}
|
||||
/>
|
||||
<input
|
||||
value={filter.action}
|
||||
onChange={(e) => setFilter({ ...filter, action: e.target.value })}
|
||||
placeholder="Aktion"
|
||||
style={{ padding: "0.5rem" }}
|
||||
/>
|
||||
<label>
|
||||
Von
|
||||
<input
|
||||
type="datetime-local"
|
||||
value={filter.from}
|
||||
onChange={(e) =>
|
||||
setFilter({ ...filter, from: e.target.value ? new Date(e.target.value).toISOString() : "" })
|
||||
}
|
||||
style={{ width: "100%", padding: "0.4rem" }}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Bis
|
||||
<input
|
||||
type="datetime-local"
|
||||
value={filter.to}
|
||||
onChange={(e) =>
|
||||
setFilter({ ...filter, to: e.target.value ? new Date(e.target.value).toISOString() : "" })
|
||||
}
|
||||
style={{ width: "100%", padding: "0.4rem" }}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div style={{ display: "flex", gap: "0.5rem", marginBottom: "1rem" }}>
|
||||
<button onClick={onSearch}>Suchen</button>
|
||||
<button onClick={() => onExport("csv")}>Export als CSV</button>
|
||||
<button onClick={() => onExport("json")}>Export als JSON</button>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p style={{ color: "#c62828" }} role="alert">
|
||||
Fehler: {error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{records && (
|
||||
<table style={{ width: "100%", borderCollapse: "collapse", background: "white" }}>
|
||||
<thead>
|
||||
<tr style={{ textAlign: "left", borderBottom: "2px solid #ddd" }}>
|
||||
<th style={{ padding: "0.5rem" }}>Zeitpunkt</th>
|
||||
<th style={{ padding: "0.5rem" }}>Tenant</th>
|
||||
<th style={{ padding: "0.5rem" }}>Akteur</th>
|
||||
<th style={{ padding: "0.5rem" }}>Aktion</th>
|
||||
<th style={{ padding: "0.5rem" }}></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{records.map((r, i) => (
|
||||
<tr key={i} style={{ borderBottom: "1px solid #eee" }}>
|
||||
<td style={{ padding: "0.5rem" }}>{new Date(r.occurred_at).toLocaleString("de-DE")}</td>
|
||||
<td style={{ padding: "0.5rem" }}>{r.tenant_slug}</td>
|
||||
<td style={{ padding: "0.5rem" }}>{r.actor}</td>
|
||||
<td style={{ padding: "0.5rem" }}>{r.action}</td>
|
||||
<td style={{ padding: "0.5rem" }}>
|
||||
<button onClick={() => setSelected(r)}>Details</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{records.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={5} style={{ padding: "0.5rem" }}>
|
||||
Keine Einträge gefunden.
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
|
||||
{selected && (
|
||||
<section style={{ background: "white", padding: "1rem", borderRadius: 8, marginTop: "1.5rem" }}>
|
||||
<h2>Eintrag-Details</h2>
|
||||
<dl>
|
||||
<dt>Zeitpunkt</dt>
|
||||
<dd>{new Date(selected.occurred_at).toLocaleString("de-DE")}</dd>
|
||||
<dt>Tenant</dt>
|
||||
<dd>{selected.tenant_slug}</dd>
|
||||
<dt>Akteur</dt>
|
||||
<dd>{selected.actor}</dd>
|
||||
<dt>Aktion</dt>
|
||||
<dd>{selected.action}</dd>
|
||||
<dt>Ziel</dt>
|
||||
<dd>{selected.target}</dd>
|
||||
<dt>Metadaten</dt>
|
||||
<dd>
|
||||
<pre style={{ whiteSpace: "pre-wrap", background: "#f5f6f8", padding: "0.5rem" }}>
|
||||
{JSON.stringify(selected.metadata, null, 2)}
|
||||
</pre>
|
||||
</dd>
|
||||
</dl>
|
||||
<button onClick={() => setSelected(null)}>Schließen</button>
|
||||
</section>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// Duenner Client der AUD-03-Export-API (internal/audit.ExportHandler) —
|
||||
// keine eigene Aggregations-/Filterlogik im Frontend (Ticket-Vorgabe:
|
||||
// "reiner Konsument der Export-API"). Die JSON-Lines-Antwort wird nur
|
||||
// dekodiert, nicht neu berechnet oder gefiltert.
|
||||
export type AuditRecord = {
|
||||
occurred_at: string;
|
||||
tenant_slug: string;
|
||||
actor: string;
|
||||
action: string;
|
||||
target: string;
|
||||
metadata: unknown;
|
||||
};
|
||||
|
||||
export type AuditFilter = {
|
||||
tenant: string;
|
||||
actor: string;
|
||||
action: string;
|
||||
from: string; // RFC3339, leer = kein Filter
|
||||
to: string;
|
||||
};
|
||||
|
||||
function apiBase(): string {
|
||||
const base = process.env.NEXT_PUBLIC_AUDITLOG_API_URL;
|
||||
if (!base) {
|
||||
throw new Error(
|
||||
"NEXT_PUBLIC_AUDITLOG_API_URL ist nicht gesetzt (Umgebungsvariable erforderlich)"
|
||||
);
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
function buildParams(caller: string, filter: AuditFilter, format: "json" | "csv"): URLSearchParams {
|
||||
const params = new URLSearchParams({ caller, format });
|
||||
if (filter.tenant) params.set("tenant", filter.tenant);
|
||||
if (filter.actor) params.set("actor", filter.actor);
|
||||
if (filter.action) params.set("action", filter.action);
|
||||
if (filter.from) params.set("from", filter.from);
|
||||
if (filter.to) params.set("to", filter.to);
|
||||
return params;
|
||||
}
|
||||
|
||||
// exportURL liefert die Adresse desselben Endpunkts, den auch die
|
||||
// Export-Datei-Funktion (Akzeptanzkriterium 2) verwendet — Liste und Export
|
||||
// sind bewusst DERSELBE API-Aufruf mit unterschiedlichem "format".
|
||||
export function exportURL(caller: string, filter: AuditFilter, format: "json" | "csv"): string {
|
||||
return `${apiBase()}/audit/export?${buildParams(caller, filter, format)}`;
|
||||
}
|
||||
|
||||
// fetchRecords laedt die Liste als JSON-Lines und dekodiert Zeile fuer
|
||||
// Zeile — dieselben Filterparameter wie ein direkter API-Aufruf
|
||||
// (Akzeptanzkriterium 1 / Pruefung 1).
|
||||
export async function fetchRecords(caller: string, filter: AuditFilter): Promise<AuditRecord[]> {
|
||||
const res = await fetch(exportURL(caller, filter, "json"), { cache: "no-store" });
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => "");
|
||||
throw new Error(text || `Anfrage fehlgeschlagen (${res.status})`);
|
||||
}
|
||||
const text = await res.text();
|
||||
return text
|
||||
.split("\n")
|
||||
.filter((line) => line.trim() !== "")
|
||||
.map((line) => JSON.parse(line) as AuditRecord);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
// @nexarch/shl liegt als file:-Dependency mit TS-Quellen in node_modules —
|
||||
// Next.js transpiliert node_modules standardmäßig nicht, siehe web/shl/README.md.
|
||||
transpilePackages: ["@nexarch/shl"],
|
||||
};
|
||||
export default nextConfig;
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "nexarch-audit-log",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "next lint"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nexarch/shl": "file:../shl",
|
||||
"next": "14.2.35",
|
||||
"react": "18.3.1",
|
||||
"react-dom": "18.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "20.14.9",
|
||||
"@types/react": "18.3.3",
|
||||
"@types/react-dom": "18.3.0",
|
||||
"typescript": "5.5.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es2017",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "preserve",
|
||||
"incremental": true,
|
||||
"plugins": [{ "name": "next" }],
|
||||
"paths": { "@/*": ["./*"] }
|
||||
},
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
# @nexarch/shl — UI-Shell & Design-System (Core SHL-01)
|
||||
|
||||
Gemeinsames Paket für alle NEXARCH-Modul-Frontends (Core, DMS, Mail, Archive, Workflow, AI, Connect).
|
||||
Ein Modul-Frontend importiert ausschließlich über `index.ts`, kopiert keine Komponenten oder Tokens lokal.
|
||||
|
||||
## Enthält
|
||||
|
||||
- **Design-Tokens** (`tokens/tokens.ts`) — Farbe (Hell/Dunkel), Abstand, Typografie. Kontrastwerte gegen WCAG 2.1 AA geprüft (siehe `__tests__/tokens.test.ts`).
|
||||
- **Theming** (`theme/ThemeProvider.tsx`) — zentrale Hell/Dunkel-Umschaltung, respektiert `prefers-color-scheme`, persistiert in `localStorage`.
|
||||
- **i18n-Rahmen** (`i18n/i18n.tsx`) — Umschaltmechanismus Deutsch/Englisch. Modul-Frontends registrieren ihre fachlichen Textbausteine über `registerMessages()`, statt einen eigenen Mechanismus zu bauen.
|
||||
- **Basis-Komponenten** (`components/`) — `Shell` (Layout + Navigation), `Table`, `Dialog`, `TextField`/`SelectField`/`CheckboxField`, `Toast`. Alle mit WCAG-2.1-AA-Grundlage (Tastaturbedienung, ARIA-Attribute, Fokus-Management).
|
||||
|
||||
## Verwendung in einem Modul-Frontend
|
||||
|
||||
```tsx
|
||||
import { ThemeProvider, I18nProvider, ToastProvider, Shell } from "@nexarch/shl";
|
||||
|
||||
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<ThemeProvider>
|
||||
<I18nProvider initialLocale="de">
|
||||
<ToastProvider>
|
||||
<Shell modules={[]} tenantLabel="Mandant XY">
|
||||
{children}
|
||||
</Shell>
|
||||
</ToastProvider>
|
||||
</I18nProvider>
|
||||
</ThemeProvider>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Bekannter offener Punkt
|
||||
|
||||
Die vier bereits gebauten Core-Frontends (`TEN-05`, `LIC-04`, `AUD-04`, `OPS-02`) sind vor diesem Paket entstanden und binden es noch nicht ein — Retrofit ist der nächste Schritt, siehe `nexarch-state.json`.
|
||||
|
||||
## Tests
|
||||
|
||||
Ausführung auf dem Test-Host (nicht lokal, siehe Projekt-Testinfrastruktur):
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm test
|
||||
npm run typecheck
|
||||
```
|
||||
@@ -0,0 +1,38 @@
|
||||
// Prüfung: Tastaturbedienung der Basis-Komponenten funktioniert (SHL-01 Prüfung 2).
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { Dialog } from "../components/Dialog";
|
||||
import { I18nProvider } from "../i18n/i18n";
|
||||
|
||||
function renderDialog(onClose: () => void) {
|
||||
return render(
|
||||
<I18nProvider>
|
||||
<Dialog open titleId="test-title" title="Test-Dialog" onClose={onClose}>
|
||||
<button type="button">Erste Aktion</button>
|
||||
<button type="button">Zweite Aktion</button>
|
||||
</Dialog>
|
||||
</I18nProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("Dialog: Tastaturbedienung", () => {
|
||||
it("schließt sich bei ESC", () => {
|
||||
const onClose = vi.fn();
|
||||
renderDialog(onClose);
|
||||
fireEvent.keyDown(document, { key: "Escape" });
|
||||
expect(onClose).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("setzt den Fokus beim Öffnen auf das erste fokussierbare Element", () => {
|
||||
renderDialog(vi.fn());
|
||||
const closeButton = screen.getByRole("button", { name: /schließen/i });
|
||||
expect(document.activeElement).toBe(closeButton);
|
||||
});
|
||||
|
||||
it("ist als modaler Dialog mit Titel-Referenz ausgezeichnet", () => {
|
||||
renderDialog(vi.fn());
|
||||
const dialog = screen.getByRole("dialog");
|
||||
expect(dialog).toHaveAttribute("aria-modal", "true");
|
||||
expect(dialog).toHaveAttribute("aria-labelledby", "test-title");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
// Prüfung: Kontrastwerte erfüllen mindestens AA (SHL-01 Prüfung 3 / Akzeptanzkriterium 4).
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { colorTokens } from "../tokens/tokens";
|
||||
|
||||
// WCAG-2.1-AA-Kontrastberechnung (relative Luminanz, sRGB) — keine externe Abhängigkeit nötig.
|
||||
function relLuminance(hex: string): number {
|
||||
const rgb = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255);
|
||||
const [r, g, b] = rgb.map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));
|
||||
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
||||
}
|
||||
|
||||
function contrastRatio(a: string, b: string): number {
|
||||
const l1 = relLuminance(a);
|
||||
const l2 = relLuminance(b);
|
||||
const [lighter, darker] = l1 > l2 ? [l1, l2] : [l2, l1];
|
||||
return (lighter + 0.05) / (darker + 0.05);
|
||||
}
|
||||
|
||||
describe("Design-Tokens: WCAG 2.1 AA Kontrast", () => {
|
||||
for (const scheme of ["light", "dark"] as const) {
|
||||
const c = colorTokens[scheme];
|
||||
|
||||
it(`${scheme}: textPrimary auf background erfüllt AA (>= 4.5:1)`, () => {
|
||||
expect(contrastRatio(c.textPrimary, c.background)).toBeGreaterThanOrEqual(4.5);
|
||||
});
|
||||
|
||||
it(`${scheme}: textSecondary auf surface erfüllt AA (>= 4.5:1)`, () => {
|
||||
expect(contrastRatio(c.textSecondary, c.surface)).toBeGreaterThanOrEqual(4.5);
|
||||
});
|
||||
|
||||
it(`${scheme}: accentContrast auf accent erfüllt AA (>= 4.5:1)`, () => {
|
||||
expect(contrastRatio(c.accentContrast, c.accent)).toBeGreaterThanOrEqual(4.5);
|
||||
});
|
||||
|
||||
it(`${scheme}: dangerContrast auf danger erfüllt AA (>= 4.5:1)`, () => {
|
||||
expect(contrastRatio(c.dangerContrast, c.danger)).toBeGreaterThanOrEqual(4.5);
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
"use client";
|
||||
|
||||
// Dialog-Basis-Komponente — SHL-01. WCAG 2.1 AA: Fokus-Falle, ESC schließt, Tastaturbedienung vollständig.
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
import { useI18n } from "../i18n/i18n";
|
||||
|
||||
const FOCUSABLE_SELECTOR =
|
||||
'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])';
|
||||
|
||||
export interface DialogProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
titleId: string;
|
||||
title: string;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function Dialog({ open, onClose, titleId, title, children }: DialogProps) {
|
||||
const { t } = useI18n();
|
||||
const dialogRef = useRef<HTMLDivElement>(null);
|
||||
const previouslyFocused = useRef<HTMLElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
previouslyFocused.current = document.activeElement as HTMLElement | null;
|
||||
|
||||
const node = dialogRef.current;
|
||||
const focusables = node?.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR);
|
||||
focusables?.[0]?.focus();
|
||||
|
||||
function handleKeyDown(event: KeyboardEvent) {
|
||||
if (event.key === "Escape") {
|
||||
onClose();
|
||||
return;
|
||||
}
|
||||
if (event.key !== "Tab" || !node) return;
|
||||
|
||||
const items = Array.from(node.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR));
|
||||
if (items.length === 0) return;
|
||||
const first = items[0];
|
||||
const last = items[items.length - 1];
|
||||
|
||||
if (event.shiftKey && document.activeElement === first) {
|
||||
event.preventDefault();
|
||||
last.focus();
|
||||
} else if (!event.shiftKey && document.activeElement === last) {
|
||||
event.preventDefault();
|
||||
first.focus();
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener("keydown", handleKeyDown);
|
||||
return () => {
|
||||
document.removeEventListener("keydown", handleKeyDown);
|
||||
previouslyFocused.current?.focus();
|
||||
};
|
||||
}, [open, onClose]);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="shl-dialog-backdrop"
|
||||
role="presentation"
|
||||
onMouseDown={(event) => {
|
||||
if (event.target === event.currentTarget) onClose();
|
||||
}}
|
||||
>
|
||||
<div
|
||||
ref={dialogRef}
|
||||
className="shl-dialog"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby={titleId}
|
||||
>
|
||||
<div className="shl-dialog-header">
|
||||
<h2 id={titleId}>{title}</h2>
|
||||
<button type="button" onClick={onClose} aria-label={t("shl.dialog.close")}>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
<div className="shl-dialog-body">{children}</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// Formularelemente-Basis-Komponenten — SHL-01. WCAG: jedes Feld hat verknüpftes <label>,
|
||||
// Fehler werden per aria-describedby + aria-invalid angebunden, nicht nur farblich markiert.
|
||||
|
||||
import { useId } from "react";
|
||||
import type { InputHTMLAttributes, ReactNode, SelectHTMLAttributes } from "react";
|
||||
|
||||
interface FieldWrapperProps {
|
||||
label: string;
|
||||
error?: string;
|
||||
hint?: string;
|
||||
children: (ids: { inputId: string; describedBy: string | undefined }) => ReactNode;
|
||||
}
|
||||
|
||||
function FieldWrapper({ label, error, hint, children }: FieldWrapperProps) {
|
||||
const inputId = useId();
|
||||
const hintId = hint ? `${inputId}-hint` : undefined;
|
||||
const errorId = error ? `${inputId}-error` : undefined;
|
||||
const describedBy = [hintId, errorId].filter(Boolean).join(" ") || undefined;
|
||||
|
||||
return (
|
||||
<div className="shl-field">
|
||||
<label htmlFor={inputId}>{label}</label>
|
||||
{children({ inputId, describedBy })}
|
||||
{hint && (
|
||||
<p id={hintId} className="shl-field-hint">
|
||||
{hint}
|
||||
</p>
|
||||
)}
|
||||
{error && (
|
||||
<p id={errorId} className="shl-field-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export interface TextFieldProps
|
||||
extends Omit<InputHTMLAttributes<HTMLInputElement>, "id" | "aria-describedby"> {
|
||||
label: string;
|
||||
error?: string;
|
||||
hint?: string;
|
||||
}
|
||||
|
||||
export function TextField({ label, error, hint, ...inputProps }: TextFieldProps) {
|
||||
return (
|
||||
<FieldWrapper label={label} error={error} hint={hint}>
|
||||
{({ inputId, describedBy }) => (
|
||||
<input
|
||||
id={inputId}
|
||||
aria-describedby={describedBy}
|
||||
aria-invalid={error ? true : undefined}
|
||||
{...inputProps}
|
||||
/>
|
||||
)}
|
||||
</FieldWrapper>
|
||||
);
|
||||
}
|
||||
|
||||
export interface SelectFieldProps
|
||||
extends Omit<SelectHTMLAttributes<HTMLSelectElement>, "id" | "aria-describedby"> {
|
||||
label: string;
|
||||
error?: string;
|
||||
hint?: string;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function SelectField({ label, error, hint, children, ...selectProps }: SelectFieldProps) {
|
||||
return (
|
||||
<FieldWrapper label={label} error={error} hint={hint}>
|
||||
{({ inputId, describedBy }) => (
|
||||
<select
|
||||
id={inputId}
|
||||
aria-describedby={describedBy}
|
||||
aria-invalid={error ? true : undefined}
|
||||
{...selectProps}
|
||||
>
|
||||
{children}
|
||||
</select>
|
||||
)}
|
||||
</FieldWrapper>
|
||||
);
|
||||
}
|
||||
|
||||
export interface CheckboxFieldProps
|
||||
extends Omit<InputHTMLAttributes<HTMLInputElement>, "id" | "type"> {
|
||||
label: string;
|
||||
}
|
||||
|
||||
export function CheckboxField({ label, ...inputProps }: CheckboxFieldProps) {
|
||||
const inputId = useId();
|
||||
return (
|
||||
<div className="shl-field shl-field-checkbox">
|
||||
<input id={inputId} type="checkbox" {...inputProps} />
|
||||
<label htmlFor={inputId}>{label}</label>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
"use client";
|
||||
|
||||
// Layout-Shell mit Navigation — SHL-01 Akzeptanzkriterium 1.
|
||||
// Globale Navigation zeigt nur Module, die Core für Tenant/Benutzer freigibt (Backend entscheidet, UI blendet nur aus).
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { useI18n } from "../i18n/i18n";
|
||||
import { useTheme } from "../theme/ThemeProvider";
|
||||
|
||||
export interface ModuleLink {
|
||||
key: string;
|
||||
label: string;
|
||||
href: string;
|
||||
active?: boolean;
|
||||
}
|
||||
|
||||
export interface ShellProps {
|
||||
modules: ModuleLink[];
|
||||
tenantLabel: string;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function Shell({ modules, tenantLabel, children }: ShellProps) {
|
||||
const { scheme, toggle } = useTheme();
|
||||
const { t } = useI18n();
|
||||
|
||||
return (
|
||||
<div className="shl-shell">
|
||||
<a className="shl-skip-link" href="#shl-main-content">
|
||||
{t("shl.shell.skipToContent", "Zum Inhalt springen")}
|
||||
</a>
|
||||
<header className="shl-shell-header">
|
||||
<nav aria-label={t("shl.shell.moduleNav", "Modul-Navigation")}>
|
||||
<ul>
|
||||
{modules.map((mod) => (
|
||||
<li key={mod.key}>
|
||||
<a href={mod.href} aria-current={mod.active ? "page" : undefined}>
|
||||
{mod.label}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</nav>
|
||||
<div className="shl-shell-context">
|
||||
<span className="shl-tenant-context">{tenantLabel}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggle}
|
||||
aria-label={
|
||||
scheme === "light" ? t("shl.theme.toggleToDark") : t("shl.theme.toggleToLight")
|
||||
}
|
||||
>
|
||||
{scheme === "light" ? "🌙" : "☀️"}
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
<main id="shl-main-content" className="shl-shell-content" tabIndex={-1}>
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
// Table-Basis-Komponente — SHL-01. WCAG: semantische <table>, scope auf Kopfzellen, sortierbare Spalten per Tastatur.
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { useI18n } from "../i18n/i18n";
|
||||
|
||||
export interface TableColumn<Row> {
|
||||
key: string;
|
||||
header: string;
|
||||
render: (row: Row) => ReactNode;
|
||||
sortable?: boolean;
|
||||
}
|
||||
|
||||
export interface TableProps<Row> {
|
||||
columns: TableColumn<Row>[];
|
||||
rows: Row[];
|
||||
rowKey: (row: Row) => string;
|
||||
sortKey?: string;
|
||||
sortDirection?: "asc" | "desc";
|
||||
onSort?: (key: string) => void;
|
||||
caption?: string;
|
||||
}
|
||||
|
||||
export function Table<Row>({
|
||||
columns,
|
||||
rows,
|
||||
rowKey,
|
||||
sortKey,
|
||||
sortDirection,
|
||||
onSort,
|
||||
caption,
|
||||
}: TableProps<Row>) {
|
||||
const { t } = useI18n();
|
||||
|
||||
return (
|
||||
<table className="shl-table">
|
||||
{caption && <caption>{caption}</caption>}
|
||||
<thead>
|
||||
<tr>
|
||||
{columns.map((column) => {
|
||||
const isSorted = column.key === sortKey;
|
||||
const ariaSort = column.sortable
|
||||
? isSorted
|
||||
? sortDirection === "asc"
|
||||
? "ascending"
|
||||
: "descending"
|
||||
: "none"
|
||||
: undefined;
|
||||
return (
|
||||
<th key={column.key} scope="col" aria-sort={ariaSort}>
|
||||
{column.sortable ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onSort?.(column.key)}
|
||||
className="shl-table-sort-button"
|
||||
>
|
||||
{column.header}
|
||||
</button>
|
||||
) : (
|
||||
column.header
|
||||
)}
|
||||
</th>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={columns.length}>{t("shl.table.noRows")}</td>
|
||||
</tr>
|
||||
) : (
|
||||
rows.map((row) => (
|
||||
<tr key={rowKey(row)}>
|
||||
{columns.map((column) => (
|
||||
<td key={column.key}>{column.render(row)}</td>
|
||||
))}
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
"use client";
|
||||
|
||||
// Toast-Basis-Komponente — SHL-01. WCAG: aria-live sorgt dafür, dass Screenreader Meldungen ansagen.
|
||||
|
||||
import { createContext, useCallback, useContext, useMemo, useState } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
import { useI18n } from "../i18n/i18n";
|
||||
|
||||
export type ToastVariant = "info" | "success" | "danger" | "warning";
|
||||
|
||||
export interface ToastMessage {
|
||||
id: string;
|
||||
text: string;
|
||||
variant: ToastVariant;
|
||||
}
|
||||
|
||||
interface ToastContextValue {
|
||||
toasts: ToastMessage[];
|
||||
push: (text: string, variant?: ToastVariant) => void;
|
||||
dismiss: (id: string) => void;
|
||||
}
|
||||
|
||||
const ToastContext = createContext<ToastContextValue | null>(null);
|
||||
|
||||
export function ToastProvider({ children }: { children: ReactNode }) {
|
||||
const [toasts, setToasts] = useState<ToastMessage[]>([]);
|
||||
const { t } = useI18n();
|
||||
|
||||
const dismiss = useCallback((id: string) => {
|
||||
setToasts((current) => current.filter((toast) => toast.id !== id));
|
||||
}, []);
|
||||
|
||||
const push = useCallback((text: string, variant: ToastVariant = "info") => {
|
||||
const id = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
setToasts((current) => [...current, { id, text, variant }]);
|
||||
}, []);
|
||||
|
||||
const value = useMemo(() => ({ toasts, push, dismiss }), [toasts, push, dismiss]);
|
||||
|
||||
return (
|
||||
<ToastContext.Provider value={value}>
|
||||
{children}
|
||||
<div className="shl-toast-region" role="status" aria-live="polite" aria-atomic="false">
|
||||
{toasts.map((toast) => (
|
||||
<div key={toast.id} className={`shl-toast shl-toast-${toast.variant}`}>
|
||||
<span>{toast.text}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => dismiss(toast.id)}
|
||||
aria-label={t("shl.toast.dismiss")}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ToastContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useToast(): ToastContextValue {
|
||||
const ctx = useContext(ToastContext);
|
||||
if (!ctx) {
|
||||
throw new Error("useToast muss innerhalb von <ToastProvider> aufgerufen werden");
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
"use client";
|
||||
|
||||
// i18n-Rahmen (mind. Deutsch/Englisch) — SHL-01 Akzeptanzkriterium 5.
|
||||
// Liefert nur den Umschaltmechanismus + Basis-Komponenten-Texte.
|
||||
// Modul-Frontends liefern ihre eigenen fachlichen Textbausteine über registerMessages(),
|
||||
// statt einen eigenen i18n-Mechanismus zu bauen (siehe UI-UX-KONZEPT.md Abschnitt 4).
|
||||
|
||||
import { createContext, useContext, useMemo, useState } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
export type Locale = "de" | "en";
|
||||
|
||||
type MessageDict = Record<string, string>;
|
||||
type MessageBundle = Record<Locale, MessageDict>;
|
||||
|
||||
const baseMessages: MessageBundle = {
|
||||
de: {
|
||||
"shl.dialog.close": "Schließen",
|
||||
"shl.toast.dismiss": "Meldung schließen",
|
||||
"shl.table.noRows": "Keine Einträge vorhanden",
|
||||
"shl.theme.toggleToLight": "Helles Erscheinungsbild",
|
||||
"shl.theme.toggleToDark": "Dunkles Erscheinungsbild",
|
||||
},
|
||||
en: {
|
||||
"shl.dialog.close": "Close",
|
||||
"shl.toast.dismiss": "Dismiss message",
|
||||
"shl.table.noRows": "No entries",
|
||||
"shl.theme.toggleToLight": "Switch to light theme",
|
||||
"shl.theme.toggleToDark": "Switch to dark theme",
|
||||
},
|
||||
};
|
||||
|
||||
// Registry, in die Modul-Frontends ihre eigenen Textbausteine einhängen.
|
||||
const registry: MessageBundle = { de: { ...baseMessages.de }, en: { ...baseMessages.en } };
|
||||
|
||||
export function registerMessages(locale: Locale, messages: MessageDict): void {
|
||||
registry[locale] = { ...registry[locale], ...messages };
|
||||
}
|
||||
|
||||
interface I18nContextValue {
|
||||
locale: Locale;
|
||||
setLocale: (locale: Locale) => void;
|
||||
t: (key: string, fallback?: string) => string;
|
||||
}
|
||||
|
||||
const I18nContext = createContext<I18nContextValue | null>(null);
|
||||
|
||||
export function I18nProvider({
|
||||
initialLocale = "de",
|
||||
children,
|
||||
}: {
|
||||
initialLocale?: Locale;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const [locale, setLocale] = useState<Locale>(initialLocale);
|
||||
|
||||
const value = useMemo<I18nContextValue>(
|
||||
() => ({
|
||||
locale,
|
||||
setLocale,
|
||||
t: (key: string, fallback?: string) => registry[locale][key] ?? fallback ?? key,
|
||||
}),
|
||||
[locale],
|
||||
);
|
||||
|
||||
return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;
|
||||
}
|
||||
|
||||
export function useI18n(): I18nContextValue {
|
||||
const ctx = useContext(I18nContext);
|
||||
if (!ctx) {
|
||||
throw new Error("useI18n muss innerhalb von <I18nProvider> aufgerufen werden");
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// Öffentliche Schnittstelle des Pakets @nexarch/shl — Modul-Frontends importieren ausschließlich hierüber,
|
||||
// nicht aus internen Unterpfaden (SHL-01 Akzeptanzkriterium 2: dokumentiert, versioniert, importierbar statt kopiert).
|
||||
|
||||
export { colorTokens, spacing, breakpoints, typography, cssVariables } from "./tokens/tokens";
|
||||
export type { ColorScheme, ColorTokens } from "./tokens/tokens";
|
||||
|
||||
export { ThemeProvider, useTheme, currentColors } from "./theme/ThemeProvider";
|
||||
|
||||
export { I18nProvider, useI18n, registerMessages } from "./i18n/i18n";
|
||||
export type { Locale } from "./i18n/i18n";
|
||||
|
||||
export { Shell } from "./components/Shell";
|
||||
export type { ShellProps, ModuleLink } from "./components/Shell";
|
||||
|
||||
export { Dialog } from "./components/Dialog";
|
||||
export type { DialogProps } from "./components/Dialog";
|
||||
|
||||
export { Table } from "./components/Table";
|
||||
export type { TableProps, TableColumn } from "./components/Table";
|
||||
|
||||
export { TextField, SelectField, CheckboxField } from "./components/FormElements";
|
||||
export type { TextFieldProps, SelectFieldProps, CheckboxFieldProps } from "./components/FormElements";
|
||||
|
||||
export { ToastProvider, useToast } from "./components/Toast";
|
||||
export type { ToastMessage, ToastVariant } from "./components/Toast";
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"name": "@nexarch/shl",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "NEXARCH UI-Shell & Design-System (Core SHL-01) — gemeinsames Paket für alle Modul-Frontends.",
|
||||
"main": "index.ts",
|
||||
"types": "index.ts",
|
||||
"scripts": {
|
||||
"test": "vitest run",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@testing-library/jest-dom": "^6.4.8",
|
||||
"@testing-library/react": "^16.0.0",
|
||||
"@types/react": "18.3.3",
|
||||
"@types/react-dom": "18.3.0",
|
||||
"jsdom": "^24.1.1",
|
||||
"typescript": "5.5.3",
|
||||
"vitest": "^2.0.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
"use client";
|
||||
|
||||
// Zentrales Theming (Hell/Dunkel) — SHL-01 Akzeptanzkriterium 6.
|
||||
// Einzige Quelle für Hell/Dunkel-Werte; Modul-Frontends schalten nur um, bauen kein eigenes Theming.
|
||||
|
||||
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
import { colorTokens, cssVariables, type ColorScheme } from "../tokens/tokens";
|
||||
|
||||
const STORAGE_KEY = "nexarch-shl-theme";
|
||||
|
||||
interface ThemeContextValue {
|
||||
scheme: ColorScheme;
|
||||
setScheme: (scheme: ColorScheme) => void;
|
||||
toggle: () => void;
|
||||
}
|
||||
|
||||
const ThemeContext = createContext<ThemeContextValue | null>(null);
|
||||
|
||||
function readStoredScheme(): ColorScheme | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
try {
|
||||
const stored = window.localStorage.getItem(STORAGE_KEY);
|
||||
return stored === "light" || stored === "dark" ? stored : null;
|
||||
} catch {
|
||||
// localStorage kann in privaten Fenstern/eingeschränkten Kontexten fehlschlagen — kein Absturz, nur kein persistierter Zustand.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function systemPrefersDark(): boolean {
|
||||
if (typeof window === "undefined" || !window.matchMedia) return false;
|
||||
return window.matchMedia("(prefers-color-scheme: dark)").matches;
|
||||
}
|
||||
|
||||
export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
const [scheme, setSchemeState] = useState<ColorScheme>("light");
|
||||
|
||||
useEffect(() => {
|
||||
const stored = readStoredScheme();
|
||||
setSchemeState(stored ?? (systemPrefersDark() ? "dark" : "light"));
|
||||
}, []);
|
||||
|
||||
const setScheme = useCallback((next: ColorScheme) => {
|
||||
setSchemeState(next);
|
||||
try {
|
||||
window.localStorage.setItem(STORAGE_KEY, next);
|
||||
} catch {
|
||||
// Speichern optional — Umschaltung funktioniert auch ohne Persistenz.
|
||||
}
|
||||
}, []);
|
||||
|
||||
const toggle = useCallback(() => {
|
||||
setScheme(scheme === "light" ? "dark" : "light");
|
||||
}, [scheme, setScheme]);
|
||||
|
||||
useEffect(() => {
|
||||
const vars = cssVariables(scheme);
|
||||
const root = document.documentElement;
|
||||
for (const [key, value] of Object.entries(vars)) {
|
||||
root.style.setProperty(key, value);
|
||||
}
|
||||
root.dataset.shlTheme = scheme;
|
||||
}, [scheme]);
|
||||
|
||||
const value = useMemo(() => ({ scheme, setScheme, toggle }), [scheme, setScheme, toggle]);
|
||||
|
||||
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
|
||||
}
|
||||
|
||||
export function useTheme(): ThemeContextValue {
|
||||
const ctx = useContext(ThemeContext);
|
||||
if (!ctx) {
|
||||
throw new Error("useTheme muss innerhalb von <ThemeProvider> aufgerufen werden");
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
|
||||
export function currentColors(scheme: ColorScheme) {
|
||||
return colorTokens[scheme];
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
// Design-Tokens: einzige Quelle für Farbe, Abstand, Typografie im gesamten Frontend-Verbund.
|
||||
// Modul-Frontends importieren diese Tokens, überschreiben sie nicht lokal (SHL-01 Akzeptanzkriterium 3).
|
||||
// Kontrastwerte sind gegen WCAG 2.1 AA geprüft (Akzeptanzkriterium 1/4): mindestens 4.5:1 für Fließtext.
|
||||
|
||||
export type ColorScheme = "light" | "dark";
|
||||
|
||||
export interface ColorTokens {
|
||||
background: string;
|
||||
surface: string;
|
||||
surfaceRaised: string;
|
||||
border: string;
|
||||
textPrimary: string;
|
||||
textSecondary: string;
|
||||
accent: string;
|
||||
accentContrast: string;
|
||||
danger: string;
|
||||
dangerContrast: string;
|
||||
success: string;
|
||||
warning: string;
|
||||
focusRing: string;
|
||||
}
|
||||
|
||||
// Kontrastwerte geprüft: textPrimary auf background/surface >= 7:1, textSecondary >= 4.5:1,
|
||||
// accentContrast auf accent >= 4.5:1 (WCAG AA, siehe SHL-01 Prüfung 3).
|
||||
export const colorTokens: Record<ColorScheme, ColorTokens> = {
|
||||
light: {
|
||||
background: "#FFFFFF",
|
||||
surface: "#F5F6F8",
|
||||
surfaceRaised: "#FFFFFF",
|
||||
border: "#D7DBE0",
|
||||
textPrimary: "#14181F",
|
||||
textSecondary: "#4B5563",
|
||||
accent: "#1D4ED8",
|
||||
accentContrast: "#FFFFFF",
|
||||
danger: "#B91C1C",
|
||||
dangerContrast: "#FFFFFF",
|
||||
success: "#15803D",
|
||||
warning: "#B45309",
|
||||
focusRing: "#1D4ED8",
|
||||
},
|
||||
dark: {
|
||||
background: "#0F1115",
|
||||
surface: "#181B21",
|
||||
surfaceRaised: "#20242C",
|
||||
border: "#333944",
|
||||
textPrimary: "#F2F4F7",
|
||||
textSecondary: "#B4BAC4",
|
||||
accent: "#5B8DEF",
|
||||
accentContrast: "#0F1115",
|
||||
danger: "#F87171",
|
||||
dangerContrast: "#0F1115",
|
||||
success: "#4ADE80",
|
||||
warning: "#FBBF24",
|
||||
focusRing: "#5B8DEF",
|
||||
},
|
||||
};
|
||||
|
||||
export const spacing = {
|
||||
xs: "4px",
|
||||
sm: "8px",
|
||||
md: "16px",
|
||||
lg: "24px",
|
||||
xl: "32px",
|
||||
xxl: "48px",
|
||||
} as const;
|
||||
|
||||
export const breakpoints = {
|
||||
mobile: "0px",
|
||||
tablet: "768px",
|
||||
desktop: "1200px",
|
||||
} as const;
|
||||
|
||||
export const typography = {
|
||||
fontFamily: "'Inter', 'Segoe UI', system-ui, sans-serif",
|
||||
fontFamilyMono: "'JetBrains Mono', ui-monospace, monospace",
|
||||
sizeSm: "13px",
|
||||
sizeMd: "15px",
|
||||
sizeLg: "18px",
|
||||
sizeXl: "24px",
|
||||
lineHeight: 1.5,
|
||||
weightRegular: 400,
|
||||
weightMedium: 500,
|
||||
weightBold: 600,
|
||||
} as const;
|
||||
|
||||
export function cssVariables(scheme: ColorScheme): Record<string, string> {
|
||||
const c = colorTokens[scheme];
|
||||
const vars: Record<string, string> = {};
|
||||
for (const [key, value] of Object.entries(c)) {
|
||||
vars[`--shl-color-${key.replace(/([A-Z])/g, "-$1").toLowerCase()}`] = value;
|
||||
}
|
||||
for (const [key, value] of Object.entries(spacing)) {
|
||||
vars[`--shl-spacing-${key}`] = value;
|
||||
}
|
||||
return vars;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"jsx": "react-jsx",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"strict": true,
|
||||
"declaration": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true
|
||||
},
|
||||
"include": ["**/*.ts", "**/*.tsx"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
environment: "jsdom",
|
||||
setupFiles: ["./vitest.setup.ts"],
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { afterEach } from "vitest";
|
||||
import { cleanup } from "@testing-library/react";
|
||||
|
||||
// Ohne explizites Cleanup bleiben zwischen den it()-Blöcken gerenderte Dialoge im DOM stehen
|
||||
// (mehrere <html>/<body>-Bäume stapeln sich), wodurch getByRole() mehrere Treffer statt einen findet.
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
Reference in New Issue
Block a user