Tpl dominio autenticacao enterprise

From artubss/SKILLS-CLAUDE-CODE · View interactive version

Tpl dominio autenticacao enterprise is an AI agent skill from the GitHub repository artubss/SKILLS-CLAUDE-CODE. Template do pack (dominio/04-autenticacao-enterprise.md). Orienta o agente em regras de negocio e requisitos de produto alinhado a esse contexto.

How to use this skill

Skill file

DOMAIN: Autenticação Enterprise (OAuth2, SSO, MFA)

Skill gerado a partir do pack templates-claude-code. Arquivo de origem: dominio/04-autenticacao-enterprise.md. Use como baseline e adapte ao projeto antes de mudancas grandes.

Conteudo do template

CONTEXT

Auth enterprise vai muito além de username/password com bcrypt. SAML SSO para clientes

corporativos, WebAuthn para segurança alta, TOTP como segundo fator — cada um tem fluxo

específico com armadilhas próprias. A maioria dos bugs de segurança em auth não é

sofisticada: é token não expirado, state CSRF não validado, session não invalidada no logout.

STACK ASSUMPTIONS

CORE CONCEPTS

ARCHITECTURE RULES

JWT Strategy

OAuth2 / SAML SSO

MFA Flow

Session Management

Account Security

ROUTING TABLE

| Trigger | Action |

|---------|--------|

| POST /auth/login | Verificar credenciais → checar lockout → emitir tokens → criar session |

| POST /auth/refresh | Validar refresh token → rotacionar → emitir novo access token |

| POST /auth/logout | Invalidar session → revogar refresh token → limpar cookies |

| GET /auth/oauth/:provider | Gerar state + PKCE verifier → redirect ao IdP |

| GET /auth/oauth/:provider/callback | Validar state → trocar code por tokens → mapear user → emitir JWT |

| POST /auth/mfa/totp/setup | Gerar secret → retornar QR URL (não ativar ainda) |

| POST /auth/mfa/totp/verify-setup | Verificar TOTP de confirmação → ativar MFA → gerar recovery codes |

| POST /auth/mfa/totp/challenge | Verificar TOTP no login step-up → emitir token com MFA claim |

| POST /auth/mfa/webauthn/register | Gerar challenge → retornar PublicKeyCredentialCreationOptions |

| POST /auth/mfa/webauthn/verify-register | Verificar credential → armazenar publicKey + counter |

| POST /auth/mfa/webauthn/challenge | Gerar assertion challenge para login |

| POST /auth/password/reset-request | Rate limit → enviar magic link (não expor se email existe) |

| GET /sessions | Listar devices ativos do usuário com last_seen |

| DELETE /sessions/:id | Revogar session específica (logout remoto) |

CRITICAL RULES

  1. Nunca logar passwords, tokens ou secrets — nem em debug
  2. state OAuth2 obrigatório e verificado no callback (CSRF protection)
  3. Refresh token rotacionado a cada uso — detectar reuse → invalidar toda família
  4. Respostas de auth não devem diferenciar "usuário não existe" de "senha incorreta"
  5. Lockout por IP E por userId — não apenas um deles
  6. TOTP não ativar sem verificação confirmada pelo usuário
  7. WebAuthn counter: rejeitar se counter novo ≤ counter armazenado (clone detection)
  8. RS256 para JWT em vez de HS256 (chave assimétrica — serviços validam sem ter signing key)
  9. Session invalidada no backend ao logout — JWT expirado não é logout
  10. Recovery codes: hash com bcrypt, marcar como usados, nunca exibir após setup

COMMON PITFALLS

❌ State OAuth2 ignorado

// ERRADO: vulnerável a CSRF
app.get('/oauth/callback', async (req) => {
  const { code } = req.query; // ignora state
  const tokens = await exchangeCode(code);
});

// CORRETO
app.get('/oauth/callback', async (req) => {
  const { code, state } = req.query;
  const storedState = await redis.get(`oauth_state:${req.session.id}`);
  if (state !== storedState) throw new Error('CSRF detected');
  const tokens = await exchangeCode(code);
});

❌ JWT stateless sem revogação

// ERRADO: logout apenas no client — token ainda válido por 8h
res.clearCookie('token'); // no servidor, token ainda aceito

// CORRETO: session + JWT de vida curta
await redis.del(`session:${sessionId}`); // logout real
// Access token expira em 15min (dano limitado)

❌ Diferenciar erros de auth

// ERRADO: user enumeration vulnerability
if (!user) return res.status(404).json({ error: 'User not found' });
if (!validPassword) return res.status(401).json({ error: 'Wrong password' });

// CORRETO: mensagem genérica + timing constante
await bcrypt.compare(password, user?.hash ?? '$2b$10$invalidhashtopreventtiming');
return res.status(401).json({ error: 'Invalid credentials' });

QUALITY GATES

FORBIDDEN

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.