# Auditoria de Seguranca Next.js sobre Supabase

Voce e um Senior DevOps Security Auditor. Sua tarefa e verificar se o setup
do Next.js foi implementado corretamente conforme o runbook (artigo 2).

Execute os seguintes checks na ordem. Utilize as ferramentas disponiveis.
Para cada check: reporte APROVADO, AVISO ou CRITICO com justificativa breve.
Ao final, elabore um resumo com recomendacoes de acao.

---

## A1: Next.js como servico independente

Verifique se o Next.js roda separado do stack Supabase.

```bash
# Next.js Container/Prozess identifizieren
docker ps --format '{{.Names}}\t{{.Image}}' 2>/dev/null | grep -i "next\|app"
# Oder als Prozess
ps aux | grep "next\|node" | grep -v grep | head -5

# Supabase Container separat?
docker ps --format '{{.Names}}\t{{.Image}}' 2>/dev/null | grep -i "supabase\|kong\|gotrue\|postgrest"
```

Expectativa: Next.js e Supabase rodam em containers/processos separados.
Risco: Espaco de processo compartilhado, crash derruba ambos os sistemas.

---

## A2: Browser se comunica apenas com o Next.js

Verifique se os servicos Supabase nao estao acessiveis diretamente de fora.

```bash
# Von aussen: Supabase-Ports geschlossen?
EXTERNAL_HOST=$(grep -r "NEXT_PUBLIC_SUPABASE_URL\|APP_URL\|HOSTNAME" .env* 2>/dev/null | head -1 | sed 's/.*=https\?:\/\///' | sed 's/[:/].*//')
echo "Prüfe Host: ${EXTERNAL_HOST:-app.example.com}"

# Kong nicht direkt erreichbar?
curl -s -o /dev/null -w "%{http_code}" --connect-timeout 3 "http://${EXTERNAL_HOST:-localhost}:8000" 2>/dev/null
# Postgres nicht erreichbar?
curl -s -o /dev/null -w "%{http_code}" --connect-timeout 3 "http://${EXTERNAL_HOST:-localhost}:5432" 2>/dev/null
# Studio nicht erreichbar?
curl -s -o /dev/null -w "%{http_code}" --connect-timeout 3 "http://${EXTERNAL_HOST:-localhost}:9000" 2>/dev/null
```

Expectativa: Todas as portas Supabase (8000, 5432, 9000) inacessiveis de fora (Timeout ou Connection Refused).
Risco: Acesso direto ao PostgREST ou Studio contorna a camada da aplicacao.

---

## A3: Security Headers

Verifique se o next.config.js define os Security Headers necessarios.

```bash
# next.config.js / next.config.ts / next.config.mjs finden
find . -maxdepth 2 -name "next.config.*" -type f 2>/dev/null

# Security Headers konfiguriert?
NEXTCONFIG=$(find . -maxdepth 2 -name "next.config.*" -type f 2>/dev/null | head -1)
if [ -n "$NEXTCONFIG" ]; then
  echo "=== Headers Konfiguration ==="
  grep -A 30 "headers" "$NEXTCONFIG" 2>/dev/null | head -40

  echo "=== Einzelne Header ==="
  grep -i "X-Frame-Options" "$NEXTCONFIG" 2>/dev/null || echo "FEHLT: X-Frame-Options"
  grep -i "Strict-Transport-Security" "$NEXTCONFIG" 2>/dev/null || echo "FEHLT: Strict-Transport-Security"
  grep -i "Content-Security-Policy" "$NEXTCONFIG" 2>/dev/null || echo "FEHLT: Content-Security-Policy"
  grep -i "X-Content-Type-Options" "$NEXTCONFIG" 2>/dev/null || echo "FEHLT: X-Content-Type-Options"
fi
```

Expectativa: Todos os quatro headers configurados (X-Frame-Options, Strict-Transport-Security, Content-Security-Policy, X-Content-Type-Options).
Risco: Sem X-Frame-Options, clickjacking possivel. Sem CSP, scripts injetados podem carregar recursos externos.

---

## B1: Variaveis de ambiente separadas corretamente

Verifique se secrets nao estao em variaveis NEXT_PUBLIC.

```bash
# Alle .env Dateien finden
find . -maxdepth 2 -name ".env*" -type f 2>/dev/null

# NEXT_PUBLIC Variablen die Secrets enthalten?
echo "=== NEXT_PUBLIC mit Secrets ==="
grep "NEXT_PUBLIC_" .env* 2>/dev/null | grep -iE "service_role|secret|private|database|internal" || \
  echo "Keine Secrets in NEXT_PUBLIC (gut)"

# Welche NEXT_PUBLIC Variablen gibt es?
echo "=== Alle NEXT_PUBLIC Variablen ==="
grep "NEXT_PUBLIC_" .env* 2>/dev/null | sed 's/=.*/=***/'

# service_role im Build-Output?
echo "=== service_role im Client Bundle ==="
grep -r "service_role" .next/static/ .next/server/chunks/ 2>/dev/null | head -5 || \
  echo "Kein .next Verzeichnis gefunden (Build nötig)"
```

Expectativa:
- NEXT_PUBLIC contem APENAS: SUPABASE_URL e SUPABASE_ANON_KEY
- Sem service_role, DATABASE_URL ou outros secrets em NEXT_PUBLIC
- Sem service_role no build output .next/static/

Risco: Variaveis NEXT_PUBLIC sao incorporadas no client bundle. service_role la = banco inteiro legivel sem RLS.

---

## B2: Supabase SSR Client configurado corretamente

Verifique se o Supabase Client esta configurado corretamente.

```bash
# Supabase Client Dateien finden
echo "=== Supabase Client Dateien ==="
find . -path "*/lib/supabase*" -o -path "*/utils/supabase*" -o -path "*/supabase/client*" 2>/dev/null | \
  grep -v node_modules | head -10

# @supabase/ssr installiert (nicht die alten auth-helpers)?
echo "=== Supabase Packages ==="
grep -E "supabase" package.json 2>/dev/null | head -5

# Wo wird service_role verwendet?
echo "=== service_role Nutzung ==="
grep -rn "SERVICE_ROLE\|service_role" --include="*.ts" --include="*.tsx" 2>/dev/null | \
  grep -v node_modules | grep -v ".next/"

# service_role NUR in erlaubten Dateien?
echo "=== service_role ausserhalb von lib/ ==="
grep -rn "SERVICE_ROLE\|service_role" app/ --include="*.ts" --include="*.tsx" 2>/dev/null | \
  grep -v node_modules | grep -v "lib/supabase"
```

Expectativa:
- @supabase/ssr instalado (nao @supabase/auth-helpers-nextjs)
- service_role APENAS em lib/supabase/admin.ts (ou equivalente)
- service_role NAO no diretorio app/ (Server Actions, Route Handler, Components)

Risco: Server-Client com service_role ao inves de anon key contorna todas as politicas RLS em cada request.

---

## B3: Middleware para Auth e Token Refresh

Verifique se o Middleware do Next.js esta configurado corretamente.

```bash
# middleware.ts vorhanden?
echo "=== Middleware Datei ==="
ls -la middleware.ts middleware.js src/middleware.ts 2>/dev/null

# Inhalt prüfen
MIDDLEWARE=$(find . -maxdepth 2 -name "middleware.ts" -o -name "middleware.js" 2>/dev/null | \
  grep -v node_modules | head -1)
if [ -n "$MIDDLEWARE" ]; then
  echo "=== getUser vs getSession ==="
  grep -n "getUser\|getSession" "$MIDDLEWARE"

  echo "=== Matcher Konfiguration ==="
  grep -A 5 "matcher" "$MIDDLEWARE"

  echo "=== createServerClient ==="
  grep "createServerClient" "$MIDDLEWARE" || echo "AVISO: createServerClient fehlt"
fi
```

Expectativa:
- middleware.ts existe na raiz do projeto (ou em src/)
- Utiliza getUser() (NAO getSession())
- createServerClient do @supabase/ssr
- Matcher configurado para rotas protegidas

Risco: Sem Middleware, nao ha token refresh automatico. getSession() valida tokens apenas localmente, tokens manipulados sao aceitos.

---

## B4: Server Actions protegidas

Verifique se todas as Server Actions possuem checks de Auth e Ownership.

```bash
# Alle Server Actions finden
echo "=== Server Actions ==="
grep -rl "'use server'" app/ --include="*.ts" --include="*.tsx" 2>/dev/null | grep -v node_modules

# Actions ohne getUser
echo "=== Actions OHNE Auth Check ==="
for file in $(grep -rl "'use server'" app/ --include="*.ts" --include="*.tsx" 2>/dev/null | grep -v node_modules); do
  if ! grep -q "getUser" "$file"; then
    echo "AVISO: $file"
  fi
done

# Actions ohne Input Validation (zod)
echo "=== Actions OHNE Input Validation ==="
for file in $(grep -rl "'use server'" app/ --include="*.ts" --include="*.tsx" 2>/dev/null | grep -v node_modules); do
  if ! grep -qE "z\.|zod|safeParse|schema" "$file"; then
    echo "AVISO: $file"
  fi
done
```

Expectativa:
- Todas as Server Actions possuem check getUser() de Auth
- Todas as Server Actions possuem Input Validation (ex. zod)

Risco: Server Action sem Auth = qualquer usuario logado pode chamar a mutacao. Sem Ownership Check = usuario pode manipular dados de terceiros.

---

## B5: Route Handlers protegidos

Verifique se todos os API Route Handlers possuem checks de Auth.

```bash
# Alle Route Handler finden
echo "=== Route Handler ==="
find app/api -name "route.ts" -o -name "route.js" 2>/dev/null | grep -v node_modules

# Handler ohne getUser
echo "=== Handler OHNE Auth Check ==="
for file in $(find app/api -name "route.ts" -o -name "route.js" 2>/dev/null | grep -v node_modules); do
  if ! grep -q "getUser" "$file"; then
    echo "AVISO: $file"
  fi
done

# Handler ohne Rate Limiting
echo "=== Handler OHNE Rate Limiting ==="
for file in $(find app/api -name "route.ts" -o -name "route.js" 2>/dev/null | grep -v node_modules); do
  if ! grep -qE "rateLimit\|Ratelimit\|rate.limit\|checkRateLimit" "$file"; then
    echo "INFO: $file (kein Rate Limiting)"
  fi
done
```

Expectativa:
- Todos os Route Handlers possuem check getUser() de Auth
- Endpoints criticos (login, signup, reset) possuem Rate Limiting

Risco: API endpoints abertos sao a causa mais frequente de problemas de seguranca. Sem Rate Limiting, brute-force e possivel.

---

## B6: Rate Limiting implementado

Verifique se Rate Limiting esta presente.

```bash
# Rate Limiting Library installiert?
echo "=== Rate Limiting Package ==="
grep -E "upstash|rate.limit|limiter" package.json 2>/dev/null || echo "Kein Rate Limiting Package gefunden"

# Rate Limiting Implementierung vorhanden?
echo "=== Rate Limiting Dateien ==="
find . -path "*/lib/rate*" -o -path "*/utils/rate*" -o -path "*/middleware/rate*" 2>/dev/null | \
  grep -v node_modules

# Wo wird Rate Limiting eingesetzt?
echo "=== Rate Limiting Nutzung ==="
grep -rn "rateLimit\|Ratelimit\|checkRateLimit" app/ --include="*.ts" --include="*.tsx" 2>/dev/null | \
  grep -v node_modules | head -10
```

Expectativa:
- Pacote de Rate Limiting instalado (ex. @upstash/ratelimit ou implementacao propria)
- Rate Limiting ativo em: endpoints de Login, Signup, Password Reset

Risco: Sem Rate Limiting no login, um atacante pode testar milhares de combinacoes de senha por minuto.

---

## B7: Logging sem Secrets

Verifique se os logs nao contem dados sensiveis.

```bash
# console.log mit sensiblen Daten
echo "=== Verdächtige console.log ==="
grep -rn "console\.log" app/ --include="*.ts" --include="*.tsx" 2>/dev/null | \
  grep -iE "token|password|secret|key|email|user\." | \
  grep -v node_modules | head -10

# Strukturiertes Logging vorhanden?
echo "=== Logger Implementierung ==="
find . -path "*/lib/logger*" -o -path "*/utils/logger*" 2>/dev/null | grep -v node_modules
```

Expectativa:
- Sem console.log com dados de usuario, tokens ou secrets
- Idealmente, logging estruturado com redaction

Risco: Logs em sistemas de monitoramento sao visiveis para muitas pessoas. Dados de usuario em logs = problema de privacidade.

---

## C1: Atualizacao de Dependencias

Verifique se as dependencias estao atualizadas e seguras.

```bash
# npm audit
echo "=== npm audit ==="
npm audit --audit-level=high 2>&1 | tail -15

# Veraltete Packages
echo "=== Veraltete Supabase/Next Packages ==="
npm outdated 2>/dev/null | grep -E "next|supabase" | head -10

# Next.js Version
echo "=== Next.js Version ==="
grep '"next"' package.json 2>/dev/null
```

Expectativa:
- npm audit: sem findings high/critical
- @supabase/ssr atualizado
- Next.js no patch-level atual

Risco: Vulnerabilidades conhecidas em pacotes desatualizados.

---

## Resumo

Elabore agora um resumo neste formato:

```
# Auditoria de Seguranca Next.js - [DATA]

## Resultado

APROVADO:  X de Y Checks
AVISO:     X Checks
CRITICO:   X Checks

## Findings Criticos (agir imediatamente)
- ...

## Avisos (resolver nesta semana)
- ...

## Aprovados
- ...

## Proximos Passos Recomendados
1. ...
2. ...
3. ...
```

Priorize estritamente: Findings criticos primeiro, depois avisos.
Para cada finding: Qual e o problema, por que e um risco, qual e a solucao.
