From 93f1c095e02cd05c53148c695827a0842d651e90 Mon Sep 17 00:00:00 2001 From: Gerald Fruhmann Date: Mon, 8 Jun 2026 14:27:20 +0200 Subject: [PATCH] =?UTF-8?q?feat:=20v3.0.0=20=E2=80=94=20full=20English=20t?= =?UTF-8?q?ranslation=20of=20all=20skills=20and=20documentation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Translated all 95 files from German to English: - 24 SKILL.md files (frontmatter description/triggers, workflow steps, output templates) - 50+ references/*.md files (curriculum mappings, pattern references, checklists) - 25 commands/*.md files (description, argument-hint, body instructions) - claude/*.md rule files + reference/*.md docs + CLAUDE.md + docs/ - plugins/dev/rules/*.md mirror updated Also applied dev: prefix to all SKILL.md name: fields (e.g. name: tool-perf -> name: dev:tool-perf). Preserved: URLs, tool/library names, university names, author names, book titles, code block contents, technical acronyms (OWASP, WCAG, DORA, SLO, CDC, etc.). Added language note in design-secure and design-iac for German/Norwegian sources. Co-Authored-By: Claude Sonnet 4.6 --- CLAUDE.md | 164 +-- claude/app-rules.md | 190 +-- claude/architecture-rules.md | 212 +-- claude/essential-rules.md | 104 +- claude/github-rules.md | 200 +-- docs/skill-research-basis.md | 94 +- plugins/dev/commands/design-api.md | 12 +- plugins/dev/commands/design-app.md | 14 +- plugins/dev/commands/design-cicd.md | 10 +- plugins/dev/commands/design-data.md | 12 +- plugins/dev/commands/design-iac.md | 10 +- plugins/dev/commands/design-llm.md | 10 +- plugins/dev/commands/design-migration.md | 10 +- plugins/dev/commands/design-observability.md | 10 +- plugins/dev/commands/design-secure.md | 14 +- plugins/dev/commands/design-ux.md | 10 +- plugins/dev/commands/meta-create-skill.md | 10 +- plugins/dev/commands/meta-drift.md | 14 +- plugins/dev/commands/meta-help.md | 10 +- plugins/dev/commands/meta-install.md | 10 +- plugins/dev/commands/meta-sync.md | 10 +- plugins/dev/commands/review-app.md | 10 +- plugins/dev/commands/review-arch.md | 12 +- plugins/dev/commands/review-llm.md | 10 +- plugins/dev/commands/review-secure.md | 14 +- plugins/dev/commands/review-ux.md | 10 +- plugins/dev/commands/tool-a11y.md | 10 +- plugins/dev/commands/tool-debug.md | 16 +- plugins/dev/commands/tool-perf.md | 10 +- plugins/dev/commands/tool-style.md | 16 +- plugins/dev/commands/tool-test.md | 16 +- plugins/dev/rules/app-rules.md | 190 +-- plugins/dev/rules/architecture-rules.md | 212 +-- plugins/dev/rules/essential-rules.md | 104 +- plugins/dev/rules/github-rules.md | 200 +-- plugins/dev/skills/design-api/SKILL.md | 28 +- plugins/dev/skills/design-app/SKILL.md | 55 +- plugins/dev/skills/design-cicd/SKILL.md | 216 ++-- .../references/curriculum-mapping.md | 32 +- .../references/deployment-strategies.md | 72 +- .../design-cicd/references/dora-metrics.md | 44 +- plugins/dev/skills/design-data/SKILL.md | 26 +- plugins/dev/skills/design-iac/SKILL.md | 201 +-- .../references/curriculum-mapping.md | 32 +- .../design-iac/references/iac-patterns.md | 58 +- .../design-iac/references/state-management.md | 64 +- plugins/dev/skills/design-llm/SKILL.md | 194 +-- .../references/curriculum-mapping.md | 32 +- .../references/evaluation-framework.md | 78 +- .../references/integration-patterns.md | 56 +- .../design-llm/references/rag-architecture.md | 82 +- plugins/dev/skills/design-migration/SKILL.md | 50 +- .../references/curriculum-mapping.md | 10 +- .../references/schema-evolution.md | 142 +-- .../dev/skills/design-observability/SKILL.md | 244 ++-- .../references/alert-runbook.md | 92 +- .../references/curriculum-mapping.md | 34 +- .../references/golden-signals.md | 54 +- .../references/slo-patterns.md | 50 +- plugins/dev/skills/design-secure/SKILL.md | 35 +- .../references/curriculum-mapping.md | 2 +- .../references/design-principles.md | 4 +- plugins/dev/skills/design-ux/SKILL.md | 358 +++--- .../design-ux/references/framework-mapping.md | 86 +- plugins/dev/skills/meta-create-skill/SKILL.md | 264 ++-- plugins/dev/skills/meta-drift/SKILL.md | 114 +- plugins/dev/skills/meta-help/SKILL.md | 84 +- plugins/dev/skills/meta-install/SKILL.md | 140 +- plugins/dev/skills/meta-sync/SKILL.md | 110 +- plugins/dev/skills/review-app/SKILL.md | 208 +-- plugins/dev/skills/review-arch/SKILL.md | 36 +- plugins/dev/skills/review-llm/SKILL.md | 146 +-- .../references/curriculum-mapping.md | 6 +- .../review-llm/references/failure-patterns.md | 56 +- .../review-llm/references/security-checks.md | 80 +- plugins/dev/skills/review-secure/SKILL.md | 28 +- plugins/dev/skills/review-ux/SKILL.md | 252 ++-- .../review-ux/references/dark-patterns.md | 36 +- .../skills/review-ux/references/frameworks.md | 52 +- plugins/dev/skills/tool-a11y/SKILL.md | 206 +-- .../references/curriculum-mapping.md | 24 +- .../tool-a11y/references/testing-tools.md | 72 +- .../tool-a11y/references/wcag-checks.md | 98 +- plugins/dev/skills/tool-debug/SKILL.md | 146 +-- plugins/dev/skills/tool-perf/SKILL.md | 198 +-- .../tool-perf/references/bentley-rules.md | 74 +- .../references/curriculum-mapping.md | 28 +- .../skills/tool-perf/references/use-method.md | 72 +- plugins/dev/skills/tool-style/SKILL.md | 168 +-- .../tool-style/references/design-tokens.md | 50 +- .../tool-style/references/visual-patterns.md | 36 +- plugins/dev/skills/tool-test/SKILL.md | 150 +-- reference/app-best-practices.md | 1134 ++++++++--------- reference/architecture-best-practices.md | 926 +++++++------- reference/github-best-practices.md | 522 ++++---- 95 files changed, 4953 insertions(+), 4954 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 1190816..29dd957 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,39 +1,39 @@ # Dev Best Practices -Dieses Repo enthaelt Best-Practice-Regeln fuer Software-Projekte (RAG-Systeme, AI Agents, Data Pipelines, Full-Stack Web Apps) und ein **Claude Code Plugin** mit 24 Skills. +This repo contains best-practice rules for software projects (RAG systems, AI agents, data pipelines, full-stack web apps) and a **Claude Code Plugin** with 24 skills. -## Repo-Struktur +## Repo Structure ```text .claude-plugin/ - marketplace.json # Macht dieses Repo als Marketplace installierbar + marketplace.json # Makes this repo installable as a marketplace plugin plugins/dev/ .claude-plugin/ - plugin.json # Plugin-Metadaten (name: "dev", version: "2.0.0") - commands/ # Slash-Command-Definitionen (eine Datei pro Skill) - skills/ # Skill-Workflow-Definitionen (auto-triggered) - rules/ # Mirror von claude/*.md (wird von Skills als Referenz genutzt) - -claude/ # Kondensierte Regeln fuer Claude Code - essential-rules.md # ~80 Zeilen -- in Projekt-CLAUDE.md einfuegen - app-rules.md # App-Regeln im Detail - github-rules.md # GitHub / CI-Regeln im Detail - architecture-rules.md # Architektur-Regeln im Detail - -reference/ # Detaillierte Dokumentation zum Nachschlagen + plugin.json # Plugin metadata (name: "dev", version: "2.0.0") + commands/ # Slash command definitions (one file per skill) + skills/ # Skill workflow definitions (auto-triggered) + rules/ # Mirror of claude/*.md (used by skills as reference) + +claude/ # Condensed rules for Claude Code + essential-rules.md # ~80 lines -- insert into project CLAUDE.md + app-rules.md # App rules in detail + github-rules.md # GitHub / CI rules in detail + architecture-rules.md # Architecture rules in detail + +reference/ # Detailed documentation for reference app-best-practices.md # Security, Auth, API, DB, Monitoring, OWASP github-best-practices.md # CI/CD, Linting, Testing, Docker, Code Review - architecture-best-practices.md # Schichten, Patterns, Infra, 12-Factor + architecture-best-practices.md # Layers, Patterns, Infra, 12-Factor docs/ - skill-research-basis.md # Akademische & Industrie-Quellen pro Skill + skill-research-basis.md # Academic & industry sources per skill scripts/ - validate-skills.sh # Plugin-Struktur-Validator (CI + pre-commit) + validate-skills.sh # Plugin structure validator (CI + pre-commit) ``` -## Plugin-Skills (24) +## Plugin Skills (24) ```text DESIGN: design-app, design-secure, design-api, design-data, design-migration, @@ -43,100 +43,100 @@ TOOLS: tool-debug, tool-test, tool-style, tool-a11y, tool-perf META: meta-help, meta-install, meta-drift, meta-sync, meta-create-skill ``` -Navigationsmenue: `/dev:meta-help` +Navigation menu: `/dev:meta-help` -## Verwendung in Projekten +## Usage in Projects -**Plugin installieren:** `claude plugin install dev@gerald-dev-best-practices` +**Install plugin:** `claude plugin install dev@gerald-dev-best-practices` -**Nur Regeln (ohne Plugin):** `claude/essential-rules.md` in Projekt-CLAUDE.md kopieren, oder `/dev:meta-install` verwenden. +**Rules only (without plugin):** Copy `claude/essential-rules.md` into project CLAUDE.md, or use `/dev:meta-install`. -**Mehr Detail:** Sections aus `claude/app-rules.md`, `claude/github-rules.md`, `claude/architecture-rules.md` selektiv ergaenzen. +**More detail:** Selectively add sections from `claude/app-rules.md`, `claude/github-rules.md`, `claude/architecture-rules.md`. -## Pflege +## Maintenance -- `reference/` aktualisieren wenn sich Best Practices aendern -- `claude/` synchron halten (nur Regeln, keine Erklaerungen) -- Mirror aktualisieren nach Regel-Aenderungen: `cp claude/*.md plugins/dev/rules/` -- Neuen Skill hinzufuegen: `/dev:meta-create-skill` -- Quellen und akademische Basis: `docs/skill-research-basis.md` +- Update `reference/` when best practices change +- Keep `claude/` in sync (rules only, no explanations) +- Update mirror after rule changes: `cp claude/*.md plugins/dev/rules/` +- Add new skill: `/dev:meta-create-skill` +- Sources and academic basis: `docs/skill-research-basis.md` - - + + ## Dev Best Practices ### Security -- Security Headers setzen: CSP (`default-src 'self'`), HSTS, X-Content-Type-Options, X-Frame-Options, Referrer-Policy, Permissions-Policy -- CSP-Strategie: Nonce-basiert mit `'strict-dynamic'`. `'unsafe-inline'` nur fuer `style-src` -- Auth an 3 Schichten: Middleware → Route → **Data Access Layer** (wichtigste!) -- Passwort: bcrypt (cost ≥ 12) / Argon2id, nie Plaintext. Rate Limiting auf Login +- Set security headers: CSP (`default-src 'self'`), HSTS, X-Content-Type-Options, X-Frame-Options, Referrer-Policy, Permissions-Policy +- CSP strategy: Nonce-based with `'strict-dynamic'`. `'unsafe-inline'` only for `style-src` +- Auth at 3 layers: Middleware → Route → **Data Access Layer** (most important!) +- Password: bcrypt (cost ≥ 12) / Argon2id, never plaintext. Rate limiting on login - Sessions: httpOnly, secure, sameSite=Lax -- Input validieren an System-Grenze: TS → Zod, Python → Pydantic -- SQL: Immer Prepared Statements. Shell: Nie User-Input in Commands -- DOM XSS: Kein `innerHTML` mit User-Daten. Trusted Types + DOMPurify bei dynamischem HTML -- Keine Secrets in Error-Responses. Keine Secrets loggen -- `.env` nie committen, `.env.example` committen. Env-Validierung beim App-Start (crasht sofort wenn Variable fehlt) -- Security Assessment: `ruff-S`+`semgrep` (SAST), `pip-audit` (SCA), ASVS 5.0 als Pruefrahmen - -### API & Datenbank - -- Einheitliches Error-Format: `{ error: { code, message, details } }` -- Rate Limiting auf Middleware/Gateway-Level. Pagination fuer alle Listen -- API-Typ: Intern → tRPC. Extern → REST -- DB: Immer Migrations-Tool (nie manuell SQL auf Prod). Prepared Statements, Least Privilege User, TLS zum DB-Server -- ORM-Wahl: Query Builder (Drizzle, SQLAlchemy Core) als Sweet Spot -- Connection Pooling Pflicht. Serverless → externer Pooler +- Validate input at system boundary: TS → Zod, Python → Pydantic +- SQL: Always prepared statements. Shell: Never user input in commands +- DOM XSS: No `innerHTML` with user data. Trusted Types + DOMPurify for dynamic HTML +- No secrets in error responses. Never log secrets +- Never commit `.env`, do commit `.env.example`. Validate env vars at app start (crashes immediately if variable is missing) +- Security assessment: `ruff-S`+`semgrep` (SAST), `pip-audit` (SCA), ASVS 5.0 as verification framework + +### API & Database + +- Uniform error format: `{ error: { code, message, details } }` +- Rate limiting at middleware/gateway level. Pagination for all lists +- API type: Internal → tRPC. External → REST +- DB: Always use a migration tool (never manual SQL on prod). Prepared statements, least privilege user, TLS to DB server +- ORM choice: Query builder (Drizzle, SQLAlchemy Core) as sweet spot +- Connection pooling required. Serverless → external pooler ### Architecture -- **Feature-basierte** Ordnerstruktur (nicht technisch) -- Schichtung: Routes → Services → Data Access (2-3 Schichten reichen fuer Solo) -- **Starte mit Monolith.** Microservices nur bei konkretem Grund -- Monorepo fuer Full-Stack (Turborepo / pnpm Workspaces / uv Workspaces) -- 12-Factor: Config in Env, Stateless Processes, Logs auf Stdout, Port Binding -- Server Components als Default (React/Next.js). `"use client"` nur bei Interaktivitaet -- Server State (TanStack Query) und Client State (useState/Zustand) nie mischen +- **Feature-based** folder structure (not technical) +- Layering: Routes → Services → Data Access (2-3 layers are enough for solo) +- **Start with a monolith.** Microservices only for a concrete reason +- Monorepo for full-stack (Turborepo / pnpm Workspaces / uv Workspaces) +- 12-Factor: Config in env, stateless processes, logs to stdout, port binding +- Server components as default (React/Next.js). `"use client"` only for interactivity +- Never mix server state (TanStack Query) with client state (useState/Zustand) ### GitHub & CI/CD -- Pre-commit Hooks Pflicht: gitleaks → ruff (Lint+Fix inkl. S-Regeln) → Format → Type Check +- Pre-commit hooks required: gitleaks → ruff (lint+fix incl. S-rules) → format → type check - TS: ESLint Flat Config + Prettier + Husky. Python: Ruff + mypy + pre-commit -- TS Package Manager: pnpm. Python: uv. Lockfiles immer committen -- CI: Jeder PR durch Pipeline (Install → Lint → Type Check → Build/Test → gitleaks) -- Branch Protection auf main: Require PR, Status Checks, No Force Push -- Renovate (nicht Dependabot). devDeps patch Automerge, Major manuell. Dependabot Alerts aktivieren (Security-Meldungen) -- PR-Groesse: < 400 LOC, darueber aufteilen +- TS package manager: pnpm. Python: uv. Always commit lockfiles +- CI: Every PR through pipeline (install → lint → type check → build/test → gitleaks) +- Branch protection on main: Require PR, status checks, no force push +- Renovate (not Dependabot). devDeps patch automerge, major manual. Enable Dependabot alerts (security notifications) +- PR size: < 400 LOC, split above that ### Testing -- TS: Vitest + Testing Library + MSW (API-Mocking) + Playwright (E2E). Python: pytest + Playwright -- Prioritaet: 1) API Endpoints 2) Data Transformationen 3) E2E Smoke Test -- Tests testen Verhalten, nicht Implementierung. Mocke nur an Systemgrenzen -- Coverage: 70-80% Lines. Kritische Pfade (Auth, Payment) ~100%. 100% gesamt ist kein Ziel +- TS: Vitest + Testing Library + MSW (API mocking) + Playwright (E2E). Python: pytest + Playwright +- Priority: 1) API endpoints 2) data transformations 3) E2E smoke test +- Tests test behavior, not implementation. Mock only at system boundaries +- Coverage: 70-80% lines. Critical paths (auth, payment) ~100%. 100% overall is not the goal ### Docker & Deployment -- Multi-Stage Build (Builder + Runner). Base Images mit Digest pinnen -- Non-root User. HEALTHCHECK. `.dockerignore` pflegen -- Ports nur auf `127.0.0.1` binden. Named Volumes fuer Prod -- Reverse Proxy vor der App (Caddy / Nginx). Automatisches HTTPS -- Health Checks: `/health` (Liveness) + `/ready` (Readiness) -- Container-Scanning: Trivy (CRITICAL, HIGH, exit-code 1) -- Feature Flags fuer Zero-Downtime: neues Verhalten hinter Flag → ausrollen → Flag entfernen. Kill Switch fuer sofortiges Rollback +- Multi-stage build (builder + runner). Pin base images with digest +- Non-root user. HEALTHCHECK. Maintain `.dockerignore` +- Bind ports only to `127.0.0.1`. Named volumes for prod +- Reverse proxy in front of the app (Caddy / Nginx). Automatic HTTPS +- Health checks: `/health` (liveness) + `/ready` (readiness) +- Container scanning: Trivy (CRITICAL, HIGH, exit-code 1) +- Feature flags for zero-downtime: new behavior behind flag → roll out → remove flag. Kill switch for immediate rollback ### Monitoring & Logging -- Structured Logging (JSON): TS → Pino, Python → structlog. Timestamps UTC -- Error Tracking: Sentry. Uptime: UptimeRobot. Logs: Better Stack / Axiom -- Alert-Schwellen: Error Rate > 1%, p95 > 2s, CPU/Memory > 80% -- OpenTelemetry als Standard. Metrics/Traces erst bei Bedarf +- Structured logging (JSON): TS → Pino, Python → structlog. Timestamps UTC +- Error tracking: Sentry. Uptime: UptimeRobot. Logs: Better Stack / Axiom +- Alert thresholds: error rate > 1%, p95 > 2s, CPU/memory > 80% +- OpenTelemetry as standard. Metrics/traces only when needed ### Accessibility -- Gesetzlich Pflicht (EU Accessibility Act, BFSG) -- Semantisches HTML, Heading-Hierarchie, alt auf Bildern, Fokus-Styles nicht entfernen -- Testen: axe-core + Lighthouse (automatisch), Tastatur + Screen Reader (manuell) +- Legally required (EU Accessibility Act, BFSG) +- Semantic HTML, heading hierarchy, alt on images, don't remove focus styles +- Testing: axe-core + Lighthouse (automated), keyboard + screen reader (manual) diff --git a/claude/app-rules.md b/claude/app-rules.md index 7829dae..484b427 100644 --- a/claude/app-rules.md +++ b/claude/app-rules.md @@ -1,13 +1,13 @@ # App Rules -Verbindliche Regeln fuer Web-Applikationen. Keine Theorie -- nur Entscheidungen. -Detaillierte Erklaerungen: `../reference/app-best-practices.md` +Binding rules for web applications. No theory -- decisions only. +Detailed explanations: `../reference/app-best-practices.md` --- ## Security Headers -Jede App MUSS diese Response-Headers setzen: +Every app MUST set these response headers: - `Strict-Transport-Security`: `max-age=31536000; includeSubDomains` - `X-Content-Type-Options`: `nosniff` @@ -15,185 +15,185 @@ Jede App MUSS diese Response-Headers setzen: - `Referrer-Policy`: `strict-origin-when-cross-origin` - `Permissions-Policy`: `camera=(), microphone=(), geolocation=(), payment=()` -**CSP-Strategie:** Nonce-basiert mit `'strict-dynamic'` (Gold-Standard): +**CSP strategy:** Nonce-based with `'strict-dynamic'` (gold standard): `Content-Security-Policy: default-src 'self'; script-src 'nonce-{RANDOM}' 'strict-dynamic'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'` -> Einfachere Variante (ohne Nonce, nur fuer Apps ohne dynamisch geladene Scripts): +> Simpler variant (without nonce, only for apps without dynamically loaded scripts): > `script-src 'self'` -CSP zuerst im `Report-Only` Modus testen. +Test CSP in `Report-Only` mode first. --- ## Authentication & Authorization -- **Defense in Depth:** Auth an 3 Schichten: Middleware → Route/Controller → Data Access Layer (wichtigste!) -- **Fail Closed:** Bei Fehler Zugang verweigern -- **Passwort:** bcrypt (cost ≥ 12) / scrypt / Argon2id, nie Plaintext, Timing-safe Vergleiche, Rate Limiting auf Login -- **Sessions:** Session Cookies mit `httpOnly=true`, `secure=true`, `sameSite=Lax` (Standard-Empfehlung) -- **JWT:** Nur wenn Statelessness wirklich noetig. Algorithm pinnen (`HS256`/`RS256`, `alg:none` ablehnen), Secret ≥ 256 bit, Refresh Token + Rotation bei Logout -- **MFA:** TOTP oder WebAuthn (ASVS L2). Account Lockout nach ≥ 5 Fehlversuchen. Password-Reset: Einmal-Token, max. 15 min -- **Kein eigenes Crypto** -- immer etablierte Libraries +- **Defense in Depth:** Auth at 3 layers: Middleware → Route/Controller → Data Access Layer (most important!) +- **Fail Closed:** Deny access on error +- **Password:** bcrypt (cost ≥ 12) / scrypt / Argon2id, never plaintext, timing-safe comparisons, rate limiting on login +- **Sessions:** Session cookies with `httpOnly=true`, `secure=true`, `sameSite=Lax` (standard recommendation) +- **JWT:** Only when statelessness is truly needed. Pin algorithm (`HS256`/`RS256`, reject `alg:none`), secret ≥ 256 bit, refresh token + rotation on logout +- **MFA:** TOTP or WebAuthn (ASVS L2). Account lockout after ≥ 5 failed attempts. Password reset: one-time token, max. 15 min +- **No custom crypto** -- always use established libraries --- -## Input-Validierung & Output-Encoding +## Input Validation & Output Encoding -- **Validiere an der System-Grenze** (API-Eingang): Typ, Format, Laenge, Wertebereich -- **Schema-Validierung:** TypeScript → Zod, Python → Pydantic -- **Output-Encoding:** Framework-Defaults nutzen. Kein `dangerouslySetInnerHTML` (React), kein `| safe` (Django) -- **SQL:** Immer Prepared Statements / Parameterized Queries -- **Shell:** Nie User-Input in Shell-Commands -- **DOM XSS:** Kein `innerHTML`/`outerHTML` mit User-Daten. Trusted Types + DOMPurify bei dynamischem HTML-Rendering +- **Validate at system boundary** (API entry): type, format, length, value range +- **Schema validation:** TypeScript → Zod, Python → Pydantic +- **Output encoding:** Use framework defaults. No `dangerouslySetInnerHTML` (React), no `| safe` (Django) +- **SQL:** Always prepared statements / parameterized queries +- **Shell:** Never user input in shell commands +- **DOM XSS:** No `innerHTML`/`outerHTML` with user data. Trusted Types + DOMPurify for dynamic HTML rendering --- ## API Design -- **Response-Format:** Einheitlich mit `{ error: { code, message, details } }` bei Fehlern -- **Versionierung:** URL Path (`/api/v1/`) -- **Rate Limiting:** Middleware/Gateway-Level (Fixed Window oder Token Bucket) -- **Pagination:** Nie unbegrenzte Listen -- **Idempotenz:** PUT/DELETE muessen wiederholbar sein -- **API-Typ:** Internes API → tRPC. Externes/Public API → REST. Komplexe Datenmodelle → GraphQL +- **Response format:** Uniform with `{ error: { code, message, details } }` on errors +- **Versioning:** URL path (`/api/v1/`) +- **Rate limiting:** Middleware/gateway level (fixed window or token bucket) +- **Pagination:** Never unbounded lists +- **Idempotency:** PUT/DELETE must be repeatable +- **API type:** Internal API → tRPC. External/public API → REST. Complex data models → GraphQL --- -## Datenbank +## Database -- **Migrationen:** Immer Migration-Tool (nie manuell SQL auf Prod). TS → Drizzle Kit / Prisma Migrate. Python → Alembic -- **Migrations-Regeln:** Immer vorwaerts, idempotent (`IF NOT EXISTS`), kleine Schritte, in Staging testen -- **ORM-Wahl:** Query Builder (Drizzle, SQLAlchemy Core) als Sweet Spot. ORM fuer Prototypen. Raw SQL nur fuer komplexe Queries -- **Connection Pooling:** Pflicht. Serverless → externer Pooler (PgBouncer, Neon Pooler) -- **Sicherheit:** Prepared Statements, Least Privilege DB User, TLS zum DB-Server, Credentials in Env Vars, Backups testen -- **PostgreSQL:** `SCRAM-SHA-256` in `pg_hba.conf` (kein `md5`). pgAudit fuer Audit-Trails +- **Migrations:** Always use a migration tool (never manual SQL on prod). TS → Drizzle Kit / Prisma Migrate. Python → Alembic +- **Migration rules:** Always forward, idempotent (`IF NOT EXISTS`), small steps, test in staging +- **ORM choice:** Query builder (Drizzle, SQLAlchemy Core) as sweet spot. ORM for prototypes. Raw SQL only for complex queries +- **Connection pooling:** Required. Serverless → external pooler (PgBouncer, Neon Pooler) +- **Security:** Prepared statements, least privilege DB user, TLS to DB server, credentials in env vars, test backups +- **PostgreSQL:** `SCRAM-SHA-256` in `pg_hba.conf` (not `md5`). pgAudit for audit trails --- ## Error Handling & Monitoring -- **Fail Fast:** Fehler sofort melden, nicht verschlucken -- **Keine Secrets in Errors:** Stack Traces, DB-Queries, Pfade nie an Client -- **Retry:** Exponentielles Backoff fuer transiente Fehler -- **Monitoring-Minimum:** Sentry (Error Tracking), Better Stack/UptimeRobot (Uptime), Structured Logging -- **Alert-Schwellen:** Error Rate > 1%, Response Time p95 > 2s, CPU/Memory > 80% +- **Fail Fast:** Report errors immediately, don't swallow them +- **No secrets in errors:** Never leak stack traces, DB queries, paths to client +- **Retry:** Exponential backoff for transient errors +- **Monitoring minimum:** Sentry (error tracking), Better Stack/UptimeRobot (uptime), structured logging +- **Alert thresholds:** Error rate > 1%, response time p95 > 2s, CPU/memory > 80% --- ## Logging -- **Strukturiert (JSON)**, Correlation ID pro Request, Timestamps in UTC -- **Keine Secrets loggen** (API-Keys, Passwort, Tokens, PII) +- **Structured (JSON)**, correlation ID per request, timestamps in UTC +- **Never log secrets** (API keys, passwords, tokens, PII) - **Tools:** Node.js → Pino, Python → structlog -- **Log Levels:** error (kaputt), warn (unerwartet), info (normaler Betrieb), debug (Entwicklung) -- **Aggregation:** Better Stack (1GB/mo free) oder Axiom (500GB/mo free) +- **Log levels:** error (broken), warn (unexpected), info (normal operation), debug (development) +- **Aggregation:** Better Stack (1GB/mo free) or Axiom (500GB/mo free) --- ## Environment & Secrets -- `.env` nie committen, `.env.example` committen -- **Env-Validierung beim App-Start:** App crasht sofort wenn Variable fehlt (Zod / Pydantic) -- **Secrets:** Lokal → `.env`. CI/CD → GitHub Secrets. Production → Vault / Secrets Manager -- Secrets regelmaessig rotieren (alle 90 Tage oder bei Verdacht auf Kompromittierung sofort) +- Never commit `.env`, do commit `.env.example` +- **Validate env vars at app start:** App crashes immediately if variable is missing (Zod / Pydantic) +- **Secrets:** Local → `.env`. CI/CD → GitHub Secrets. Production → Vault / Secrets Manager +- Rotate secrets regularly (every 90 days or immediately upon suspected compromise) --- ## Caching -- **HTTP:** Statische Assets → `Cache-Control: public, max-age=31536000, immutable`. API → `max-age=60, stale-while-revalidate=300`. Personalisiert → `private, no-cache`. Login/Mutations → `no-store` -- **App-Level:** Redis fuer Key-Value. In-Memory (`lru-cache` / `cachetools`) fuer Hot Data -- **Strategie:** Cache-Aside fuer Lese-lastige Apps. TTL-based als einfachster Ansatz +- **HTTP:** Static assets → `Cache-Control: public, max-age=31536000, immutable`. API → `max-age=60, stale-while-revalidate=300`. Personalized → `private, no-cache`. Login/mutations → `no-store` +- **App-level:** Redis for key-value. In-memory (`lru-cache` / `cachetools`) for hot data +- **Strategy:** Cache-aside for read-heavy apps. TTL-based as simplest approach --- ## CORS -- `Access-Control-Allow-Origin`: Explizite Domain(s), **nie `*` mit Credentials** -- Preflight (OPTIONS) immer handeln -- `Access-Control-Max-Age: 86400` (Preflight cachen) +- `Access-Control-Allow-Origin`: Explicit domain(s), **never `*` with credentials** +- Always handle preflight (OPTIONS) +- `Access-Control-Max-Age: 86400` (cache preflight) --- ## File Uploads -- Dateigroesse limitieren (z.B. max 10MB) -- Dateityp via Magic Bytes validieren (nicht Extension) -- Nie im Web-Root speichern, zufaelligen Dateinamen generieren -- Separater Storage (S3/GCS statt lokales Filesystem) +- Limit file size (e.g. max 10MB) +- Validate file type via magic bytes (not extension) +- Never store in web root, generate random filename +- Separate storage (S3/GCS instead of local filesystem) --- ## Accessibility -- **Gesetzlich Pflicht** (EU Accessibility Act seit Juni 2025, BFSG) -- Semantisches HTML (`