{
  "id": "ai-rules-for-auth-and-security",
  "type": "rules",
  "category": "rules",
  "locale": "de",
  "url": "/de/rules/ai-rules-for-auth-and-security",
  "title": "KI-Codierungsregeln für Authentifizierung und Sicherheit",
  "description": "AGENTS.md-Regeln für Authentifizierung und Sicherheit, die verhindern, dass Agenten eigene Kryptografie implementieren, Geheimnisse preisgeben oder Autorisierungsprüfungen umgehen.",
  "tools": [
    "Cursor",
    "Claude Code",
    "Codex",
    "Windsurf"
  ],
  "stack": [
    "Next.js",
    "TypeScript",
    "PostgreSQL"
  ],
  "tags": [
    "agents-md",
    "auth",
    "security",
    "typescript",
    "conventions"
  ],
  "difficulty": null,
  "updated": "2026-06-08",
  "markdown": "Fügen Sie dies als `AGENTS.md` im Stammverzeichnis Ihres Repositorys ein. Sicherheitsregeln müssen `strict` sein – Agenten sind sehr gut in der Lage, Code zu schreiben, der funktional korrekt ist, aber kritische Authentifizierungs- oder Autorisierungslücken einführt.\n\n## AGENTS.md\n\n```md title=\"AGENTS.md\"\n# Project Rules — Auth and Security\n\n## Authentication — hard rules\n- NEVER implement custom password hashing. Use `bcrypt`, `argon2`, or the auth\n  library's built-in hashing (Better Auth, Auth.js, Clerk, Supabase Auth). Custom\n  hashing is almost always wrong and may be cryptographically broken.\n- NEVER store plaintext passwords, plaintext tokens, or plaintext secrets in the\n  database. Hash passwords; hash or encrypt tokens before persistence.\n- NEVER roll custom JWT signing or verification. Use a well-audited library\n  (`jose`, `jsonwebtoken`). Never use `alg: \"none\"` — reject tokens with no algorithm.\n- Session tokens must be at least 128 bits of cryptographic randomness. Use\n  `crypto.getRandomValues()` (Web) or `crypto.randomBytes(32)` (Node.js).\n  Do NOT use `Math.random()` for any security-relevant value.\n- NEVER store session tokens or JWTs in `localStorage`. Use `HttpOnly`, `Secure`,\n  `SameSite=Lax` cookies. `localStorage` is readable by any XSS payload on the page.\n\n## Authorization — hard rules\n- Every API route and server action MUST check the current user's session before\n  accessing data. Do not assume that reaching a route implies authorization.\n- Authorization checks must verify ownership or role, not just authentication.\n  \"Is logged in\" is authentication. \"Is allowed to read this resource\" is authorization.\n  Both are required.\n- Never pass a user-controlled ID directly into a database query without first\n  verifying that the authenticated user has permission to access that record.\n  This is an IDOR (Insecure Direct Object Reference) vulnerability.\n- In Next.js App Router: run auth checks in middleware OR at the top of every\n  Server Component and Server Action that touches user data. Do not rely on\n  client-side redirects for access control.\n\n## Secrets management\n- All secrets (API keys, database URLs, OAuth client secrets) live in environment\n  variables. Validate them with Zod at startup via `src/lib/env.ts`.\n- NEVER commit secrets to the repository. If a secret is accidentally committed,\n  treat it as compromised immediately — rotate it before doing anything else.\n- NEVER log secrets, tokens, or full request bodies that may contain credentials.\n  Scrub sensitive fields before logging.\n- Client-side code must never contain secrets. In Next.js, only variables prefixed\n  with `NEXT_PUBLIC_` are exposed to the client — and only non-sensitive values\n  should use that prefix.\n\n## Input validation and output encoding\n- Validate all user input at the server boundary with Zod before use. Never trust\n  client-provided data, including data in headers, cookies, or URL parameters.\n- Sanitize any HTML rendered from user input. Use a library (`DOMPurify`, `sanitize-html`)\n  — do NOT write a custom HTML sanitizer.\n- When constructing URLs from user input, use the `URL` constructor to parse and\n  validate. Never concatenate user input into a URL string that will be fetched\n  server-side — this is an SSRF vector.\n\n## CSRF and clickjacking\n- All state-mutating endpoints (POST, PUT, PATCH, DELETE) must be protected against\n  CSRF. In Next.js App Router, Server Actions are CSRF-protected by default; do not\n  disable this. For custom API routes, verify the `Origin` header or use a CSRF token.\n- Add `X-Frame-Options: DENY` or `Content-Security-Policy: frame-ancestors 'none'`\n  to pages that should not be embedded in iframes.\n\n## Definition of done\n- No `Math.random()` calls in authentication or token generation paths.\n- No `localStorage` for session/token storage (grep the codebase).\n- Every API route handler has an auth check at the top.\n- `NEXT_PUBLIC_` env vars contain no secrets (audit the list before shipping).\n- Zod validation runs on all form inputs before they touch the database.\n```\n\n## Warum diese Regeln\n\n- **Kein `localStorage` für Token** beseitigt den häufigsten Sicherheitsfehler in React/Next.js-Anwendungen. Agenten, die Authentifizierungsmuster aus älteren Tutorials (vor 2020) kopieren, speichern JWTs häufig in `localStorage`, das von jedem Drittanbieter-Skript auf der Seite problemlos gelesen werden kann. `HttpOnly`-Cookies sind überhaupt nicht von JavaScript aus zugänglich – sie sind der korrekte Speichermechanismus.\n- **Autorisierungsprüfungen überprüfen den Besitz, nicht nur die Authentifizierung** schließt die IDOR-Sicherheitslücke, die Agenten am häufigsten übersehen. Ein Agent, der gebeten wird, \"einen Endpunkt zum Abrufen der Bestellung eines Benutzers\" hinzuzufügen, wird normalerweise `if (!session)` prüfen, aber nicht `if (order.userId !== session.user.id)` – weil die zweite Prüfung ein Verständnis der Besitzsemantik des Datenmodells erfordert, die projektspezifisch sind und nicht aus der Aufgabenbeschreibung hervorgehen.\n\n## Geeignet für\n\n- Jede Anwendung mit Benutzerkonten, geschützten Ressourcen oder Zahlungsdaten – im Wesentlichen jede Produktions-Webanwendung.\n\n## Nicht geeignet\n\n- Interne Tools hinter einem Unternehmens-VPN oder netzwerkbasierten Zugriffskontrollen, wo das Bedrohungsmodell anders ist und einige dieser Kontrollen möglicherweise von der Infrastrukturschicht übernommen werden."
}