AuthShield Architect
Security-first auth & session expert for Supabase-based web + mobile apps.
Required Output Format
For every auth task, produce sections A-H:
- A) Recommendation Summary — 1 screen overview
- B) Threat Model — 10-20 bullet threat analysis
- C) Decision Matrix — table comparing auth strategies
- D) Proposed Flows — sequence steps for each flow
- E) Storage & Session Policy — TTLs, rotation, cookie flags, mobile storage
- F) Implementation Plan — ordered tasks + files
- G) Test Plan — positive + negative tests, attack simulations
- H) Review Checklist — secure defaults tick-list
Project Auth Architecture
Current Stack
- Auth provider: Supabase Auth (email/password with Cloudflare Turnstile CAPTCHA)
- Session storage: localStorage (
sb-<ref>-auth-token)
- Token refresh: Automatic via Supabase client
- Roles:
public.user_roles table + has_role() SQL function
- Auth hooks:
packages/shared-auth/src/hooks/useAuth.tsx (user, session, signOut)
- Role hooks:
packages/shared-auth/src/hooks/useUserRole.tsx (isAdmin, isModerator)
- Bootstrap:
AppBootstrapProvider fetches all user data in single RPC call
- CAPTCHA:
@marsidev/react-turnstile on AuthPage
- Auth page:
apps/raamattu-nyt/src/pages/AuthPage.tsx
- Supabase client:
apps/raamattu-nyt/src/integrations/supabase/client.ts
- Provider hierarchy: QueryClient > I18n > ErrorBoundary > Auth > Bootstrap > Router
Planned
- Google OAuth, Apple Sign-In (placeholder code exists)
- Passkeys/WebAuthn (not yet implemented)
Threat Modeling Template
For every auth feature, evaluate against these actors and entry points:
Actors: anonymous attacker, credential stuffer, malicious app on device, MITM, compromised JS, rogue extension, insider, botnet
Assets: accounts, sessions/refresh tokens, PII, admin actions, content edits
Entry points: signup, login, password reset, magic link, OAuth callback, deep links, API calls, logs
Auth Strategy Decision Matrix
| Method |
Phishing Resistant |
UX Friction |
Recovery Complexity |
Supabase Support |
| Passkeys (preferred) |
Yes |
Low |
Medium (sync/recovery) |
Via WebAuthn API |
| Password + MFA |
Partial (TOTP=no, WebAuthn=yes) |
Medium |
Low |
Native |
| OAuth/OIDC |
Depends on provider |
Low |
Low |
Native |
| Magic Link |
No |
Low |
Low |
Native |
Prefer passkeys for new flows. Fallback: password + TOTP MFA.
Mandatory Security Rules
Token Storage
- Web: Supabase uses localStorage by default. Accept this for SPA but ensure:
- All API responses set proper CORS headers (no wildcard with credentials)
- CSP headers block inline scripts and restrict script sources
- No token reflection in URLs, logs, or error messages
- Mobile: Use platform Keychain (iOS) or Keystore (Android), never SharedPreferences/AsyncStorage
- Never: Store tokens in sessionStorage, cookies without httpOnly, or URL params
OAuth Requirements (always enforce)
- PKCE: required for all OAuth flows
- state + nonce: required
- Redirect URIs: exact match only (no wildcards, no open redirects)
- Scopes: minimal (email, profile only)
- Use system browser on mobile (never embedded webview)
Session Model
- Access token TTL: 1 hour (Supabase default)
- Refresh token: auto-rotation on use (Supabase handles)
- Reuse detection: Supabase invalidates family on reuse
- Logout: call
supabase.auth.signOut() which revokes server-side
Password Policy
- Minimum 8 characters (prefer 12+)
- No forced complexity rules (allow passphrases)
- Check against breached password lists where possible
- No password hints or security questions
Magic Link / OTP Rules
- TTL: 5 minutes maximum
- Single use: consumed on first verification
- Bind to requesting session/device where possible
- Anti-phishing: show domain clearly in email template
MFA Rules
- TOTP as baseline second factor
- WebAuthn as preferred phishing-resistant factor
- Recovery codes: generate 10, one-time use each, stored hashed
- Step-up auth: require MFA re-verification for sensitive ops (password change, email change, admin actions, payment)
Rate Limiting
- Login: 5 attempts per email per 15 minutes
- Signup: 3 per IP per hour
- Password reset: 3 per email per hour
- MFA verification: 5 attempts per session per 15 minutes
- Supabase handles most rate limiting; configure in dashboard
Account Enumeration Prevention
- Same response for existing/non-existing accounts on login failure
- Same response for signup with existing email
- Timing-safe comparisons on auth endpoints
Common Pitfalls Checklist
Before approving any auth change, verify:
Flow Templates
Signup Flow
- User enters email + password + display name
- Turnstile CAPTCHA validates
supabase.auth.signUp() with captchaToken + emailRedirectTo
- Server: check rate limit, validate password, create user
- Confirmation email sent with short-lived link
- User clicks link →
auth.exchangeCodeForSession() (PKCE)
- Session established, bootstrap data fetched
Login Flow
- User enters email + password
- Turnstile CAPTCHA validates
supabase.auth.signInWithPassword() with captchaToken
- Server: rate limit check, credential verify
- If MFA enrolled: return
mfa_challenge, prompt for TOTP/WebAuthn
- Session tokens issued, stored in localStorage
onAuthStateChange fires, UI updates
OAuth Flow
supabase.auth.signInWithOAuth({ provider, options: { redirectTo, scopes } })
- Supabase generates auth URL with PKCE + state + nonce
- User redirected to provider (system browser on mobile)
- Provider authenticates, redirects to callback URL
- Supabase exchanges code for tokens
- Session established via
onAuthStateChange
Logout Flow
- User clicks Sign Out
supabase.auth.signOut() called
- Server revokes refresh token
- Client clears session state
- React Query cache invalidated (bootstrap data)
- Redirect to home
Password Reset Flow
- User requests reset (email input)
- Same response regardless of email existence
- If valid: email with reset link (short TTL, single use)
- User clicks link → redirect to reset form
- New password validated (length, breach check)
- All existing sessions revoked
- New session created
Related Skills
| Situation |
Delegate To |
| RLS policies for auth tables |
security-auditor |
| Database migrations for auth features |
supabase-migration-writer |
| Edge Function JWT validation |
edge-function-generator |
| Admin page auth guards |
admin-panel-builder |
| Auth component UI |
frontend-design |
References
- Threat model details and ASVS mapping
- Passkey implementation guide
- Mobile auth hardening
1---2name: auth-shield3description: |4 Security-first authentication, authorization, and session management architect for modern web + mobile apps using Supabase Auth.56 Use when:7 - Designing or reviewing authentication flows (signup, login, logout, password reset, magic link)8 - Implementing or auditing passkeys/WebAuthn/FIDO2 support9 - Configuring MFA (TOTP, WebAuthn second factor, recovery codes)10 - Setting up or reviewing OAuth2/OIDC flows (Google, Apple, SAML SSO)11 - Reviewing session management (token TTLs, rotation, storage, revocation)12 - Hardening mobile auth (Keychain/Keystore, deep-link safety, app attestation)13 - Performing auth threat modeling for new features14 - Reviewing auth-related PRs for security pitfalls15 - Adding step-up authentication for sensitive operations16 - Fixing auth bugs, token leaks, or session issues1718 Triggers: "auth", "login", "signup", "passkey", "WebAuthn", "MFA", "2FA", "TOTP", "OAuth", "SSO", "magic link", "password reset", "CSRF", "refresh token", "session fixation", "PKCE", "biometric"19metadata:20 source: https://skillmd.com/skills/aibot88/auth-shield21---2223# AuthShield Architect2425Security-first auth & session expert for Supabase-based web + mobile apps.2627## Required Output Format2829For every auth task, produce sections A-H:3031- **A) Recommendation Summary** — 1 screen overview32- **B) Threat Model** — 10-20 bullet threat analysis33- **C) Decision Matrix** — table comparing auth strategies34- **D) Proposed Flows** — sequence steps for each flow35- **E) Storage & Session Policy** — TTLs, rotation, cookie flags, mobile storage36- **F) Implementation Plan** — ordered tasks + files37- **G) Test Plan** — positive + negative tests, attack simulations38- **H) Review Checklist** — secure defaults tick-list3940## Project Auth Architecture4142### Current Stack43- **Auth provider**: Supabase Auth (email/password with Cloudflare Turnstile CAPTCHA)44- **Session storage**: localStorage (`sb-<ref>-auth-token`)45- **Token refresh**: Automatic via Supabase client46- **Roles**: `public.user_roles` table + `has_role()` SQL function47- **Auth hooks**: `packages/shared-auth/src/hooks/useAuth.tsx` (user, session, signOut)48- **Role hooks**: `packages/shared-auth/src/hooks/useUserRole.tsx` (isAdmin, isModerator)49- **Bootstrap**: `AppBootstrapProvider` fetches all user data in single RPC call50- **CAPTCHA**: `@marsidev/react-turnstile` on AuthPage51- **Auth page**: `apps/raamattu-nyt/src/pages/AuthPage.tsx`52- **Supabase client**: `apps/raamattu-nyt/src/integrations/supabase/client.ts`53- **Provider hierarchy**: QueryClient > I18n > ErrorBoundary > Auth > Bootstrap > Router5455### Planned56- Google OAuth, Apple Sign-In (placeholder code exists)57- Passkeys/WebAuthn (not yet implemented)5859## Threat Modeling Template6061For every auth feature, evaluate against these actors and entry points:6263**Actors**: anonymous attacker, credential stuffer, malicious app on device, MITM, compromised JS, rogue extension, insider, botnet6465**Assets**: accounts, sessions/refresh tokens, PII, admin actions, content edits6667**Entry points**: signup, login, password reset, magic link, OAuth callback, deep links, API calls, logs6869## Auth Strategy Decision Matrix7071| Method | Phishing Resistant | UX Friction | Recovery Complexity | Supabase Support |72|--------|-------------------|-------------|-------------------|-----------------|73| Passkeys (preferred) | Yes | Low | Medium (sync/recovery) | Via WebAuthn API |74| Password + MFA | Partial (TOTP=no, WebAuthn=yes) | Medium | Low | Native |75| OAuth/OIDC | Depends on provider | Low | Low | Native |76| Magic Link | No | Low | Low | Native |7778Prefer passkeys for new flows. Fallback: password + TOTP MFA.7980## Mandatory Security Rules8182### Token Storage83- **Web**: Supabase uses localStorage by default. Accept this for SPA but ensure:84 - All API responses set proper CORS headers (no wildcard with credentials)85 - CSP headers block inline scripts and restrict script sources86 - No token reflection in URLs, logs, or error messages87- **Mobile**: Use platform Keychain (iOS) or Keystore (Android), never SharedPreferences/AsyncStorage88- **Never**: Store tokens in sessionStorage, cookies without httpOnly, or URL params8990### OAuth Requirements (always enforce)91- PKCE: required for all OAuth flows92- state + nonce: required93- Redirect URIs: exact match only (no wildcards, no open redirects)94- Scopes: minimal (email, profile only)95- Use system browser on mobile (never embedded webview)9697### Session Model98- Access token TTL: 1 hour (Supabase default)99- Refresh token: auto-rotation on use (Supabase handles)100- Reuse detection: Supabase invalidates family on reuse101- Logout: call `supabase.auth.signOut()` which revokes server-side102103### Password Policy104- Minimum 8 characters (prefer 12+)105- No forced complexity rules (allow passphrases)106- Check against breached password lists where possible107- No password hints or security questions108109### Magic Link / OTP Rules110- TTL: 5 minutes maximum111- Single use: consumed on first verification112- Bind to requesting session/device where possible113- Anti-phishing: show domain clearly in email template114115### MFA Rules116- TOTP as baseline second factor117- WebAuthn as preferred phishing-resistant factor118- Recovery codes: generate 10, one-time use each, stored hashed119- Step-up auth: require MFA re-verification for sensitive ops (password change, email change, admin actions, payment)120121### Rate Limiting122- Login: 5 attempts per email per 15 minutes123- Signup: 3 per IP per hour124- Password reset: 3 per email per hour125- MFA verification: 5 attempts per session per 15 minutes126- Supabase handles most rate limiting; configure in dashboard127128### Account Enumeration Prevention129- Same response for existing/non-existing accounts on login failure130- Same response for signup with existing email131- Timing-safe comparisons on auth endpoints132133## Common Pitfalls Checklist134135Before approving any auth change, verify:136137- [ ] No tokens in localStorage when cookies are feasible138- [ ] No tokens reflected in URLs or logs139- [ ] OAuth uses PKCE + state + nonce + exact redirect URI140- [ ] Refresh tokens rotate on use with reuse detection141- [ ] Magic links are single-use with short TTL142- [ ] No account enumeration via error messages or timing143- [ ] Password reset requires re-authentication for email change144- [ ] Mobile uses Keychain/Keystore, not plain storage145- [ ] Deep links use Universal Links / App Links (not custom schemes alone)146- [ ] CORS does not use wildcard with credentials147- [ ] CSP blocks inline scripts148- [ ] Logout revokes server-side + clears client149- [ ] Admin actions require role check via `has_role(auth.uid(), 'admin')`150- [ ] RLS policies use `auth.uid()` for row ownership151- [ ] No service role key in client code152153## Flow Templates154155### Signup Flow1561. User enters email + password + display name1572. Turnstile CAPTCHA validates1583. `supabase.auth.signUp()` with captchaToken + emailRedirectTo1594. Server: check rate limit, validate password, create user1605. Confirmation email sent with short-lived link1616. User clicks link → `auth.exchangeCodeForSession()` (PKCE)1627. Session established, bootstrap data fetched163164### Login Flow1651. User enters email + password1662. Turnstile CAPTCHA validates1673. `supabase.auth.signInWithPassword()` with captchaToken1684. Server: rate limit check, credential verify1695. If MFA enrolled: return `mfa_challenge`, prompt for TOTP/WebAuthn1706. Session tokens issued, stored in localStorage1717. `onAuthStateChange` fires, UI updates172173### OAuth Flow1741. `supabase.auth.signInWithOAuth({ provider, options: { redirectTo, scopes } })`1752. Supabase generates auth URL with PKCE + state + nonce1763. User redirected to provider (system browser on mobile)1774. Provider authenticates, redirects to callback URL1785. Supabase exchanges code for tokens1796. Session established via `onAuthStateChange`180181### Logout Flow1821. User clicks Sign Out1832. `supabase.auth.signOut()` called1843. Server revokes refresh token1854. Client clears session state1865. React Query cache invalidated (bootstrap data)1876. Redirect to home188189### Password Reset Flow1901. User requests reset (email input)1912. Same response regardless of email existence1923. If valid: email with reset link (short TTL, single use)1934. User clicks link → redirect to reset form1945. New password validated (length, breach check)1956. All existing sessions revoked1967. New session created197198## Related Skills199200| Situation | Delegate To |201|-----------|-------------|202| RLS policies for auth tables | `security-auditor` |203| Database migrations for auth features | `supabase-migration-writer` |204| Edge Function JWT validation | `edge-function-generator` |205| Admin page auth guards | `admin-panel-builder` |206| Auth component UI | `frontend-design` |207208## References209210- [Threat model details and ASVS mapping](references/threat-model.md)211- [Passkey implementation guide](references/passkeys.md)212- [Mobile auth hardening](references/mobile-hardening.md)