Foundation OAuth Implementation - Complete Guide
Overview
This guide details the Phase 3 Switchover implementation where aethex.dev becomes an OAuth client of aethex.foundation. aethex.foundation is the authoritative identity provider (the "issuer" of the Passport).
Status: ✅ Implementation complete with PKCE support
Architecture
User Flow:
┌─────────────────────────────────────────────────────────────┐
│ │
│ 1. User visits aethex.dev/login │
│ 2. Clicks "Login with Foundation" │
│ 3. Redirected to aethex.foundation /api/oauth/authorize │
│ 4. User authenticates on Foundation │
│ 5. Foundation redirects back to aethex.dev/auth/callback │
│ 6. Backend exchanges code for access token │
│ 7. User profile synced from Foundation to Corp DB │
│ 8. Session established on aethex.dev │
│ 9. Redirected to dashboard │
│ │
└─────────────────────────────────────────────────────────────┘Foundation OAuth Credentials
These credentials were obtained during Foundation Phase 1 setup:
Environment Variables (add to .env):
Foundation OAuth Endpoints
1. Authorization Endpoint
Redirect users here to initiate authentication.
Parameters:
client_id- aethex_corp (identifies this app)redirect_uri- Where Foundation redirects after authresponse_type- Always "code" (OAuth 2.0 authorization code flow)scope- Requested permissionsstate- CSRF token (generated by client, validated on callback)code_challenge- PKCE challenge (SHA256 hash of verifier)code_challenge_method- S256 (SHA256 PKCE method)
Implementation: See code/client/lib/foundation-oauth.ts → initiateFoundationLogin()
2. Token Exchange Endpoint
Backend exchanges authorization code for access token.
Response:
Implementation: See code/api/auth/callback.ts → performTokenExchange()
3. User Info Endpoint
Fetch authenticated user's profile.
Implementation: See code/api/auth/callback.ts → fetchUserInfoFromFoundation()
PKCE Implementation
PKCE (Proof Key for Code Exchange) adds extra security to OAuth flows.
How PKCE Works
Client generates code verifier:
Client generates code challenge:
Client sends challenge with authorization request:
Server stores challenge, validates with verifier on token exchange:
Server verifies:
Why PKCE?
Prevents authorization code interception attacks
Secure for mobile apps and single-page applications
Required by OAuth 2.1 best practices
Implementation: See code/client/lib/foundation-oauth.ts → generatePKCEParams()
Implementation Details
Frontend Components
1. Login Page (code/client/pages/Login.tsx)
code/client/pages/Login.tsx)Updated to show Foundation OAuth button:
Features:
Initiates Foundation OAuth flow
Generates PKCE parameters
Stores verifier and state in sessionStorage
Redirects to Foundation authorization endpoint
2. Foundation OAuth Library (code/client/lib/foundation-oauth.ts)
code/client/lib/foundation-oauth.ts)Core OAuth functionality:
3. useFoundationAuth Hook (code/client/hooks/use-foundation-auth.ts)
code/client/hooks/use-foundation-auth.ts)Handles OAuth callback:
Backend Endpoints
1. Callback Handler (code/api/auth/callback.ts)
code/api/auth/callback.ts)Route: GET /auth/callback?code=...&state=...
Flow:
Receive authorization code from Foundation
Validate state token (CSRF protection)
Exchange code for access token
Fetch user info from Foundation
Sync user to local database
Set session cookies
Redirect to dashboard
Code:
2. Token Exchange (POST /auth/callback/exchange)
POST /auth/callback/exchange)Called from frontend to exchange code for token safely:
Session Management
Session Cookies
After successful authentication:
Using Access Token
For authenticated API requests:
Clearing Session
On logout:
User Profile Sync
Sync Flow
Upsert Logic
Note: Existing user data is preserved, Foundation data is merged/updated.
Testing
Local Testing
Set up environment:
Test flow:
Visit
http://localhost:5173/loginClick "Login with Foundation"
Should redirect to Foundation auth page
After auth, should return to aethex.dev/auth/callback with code
Should exchange code and redirect to dashboard
Check cookies:
foundation_access_tokenandauth_user_id
Verify database:
Error Scenarios
Invalid code:
Invalid state:
Foundation down:
Files Modified/Created
New Files
Modified Files
Deprecated Files
These can be removed after testing completes:
Deployment Checklist
Monitoring
Key Metrics
Auth Success Rate
Target: >99%
Alert if: <95%
Token Exchange Time
Target: <500ms
Alert if: >2s
Error Categories
Track: invalid_code, state_mismatch, timeout, etc.
Foundation Connectivity
Monitor: /api/oauth/authorize, /api/oauth/token availability
Alert on: persistent errors from Foundation
Logging
Key points to log:
Troubleshooting
Problem: "No authorization code received"
Cause: Foundation didn't redirect back properly
Solutions:
Check
redirect_urimatches exactly (case-sensitive)Verify Foundation OAuth settings
Check browser console for JavaScript errors
Problem: "Invalid state token"
Cause: CSRF validation failed
Solutions:
Check that state is generated consistently
Verify sessionStorage isn't cleared between redirect
Check for multiple browser tabs (different state per tab)
Problem: "Token exchange failed"
Cause: Foundation token endpoint unavailable or code invalid
Solutions:
Check Foundation is running and
/api/oauth/tokenaccessibleVerify
client_idandclient_secretare correctCheck code hasn't expired (usually 10 minutes)
Review Foundation logs for errors
Problem: User not synced to database
Cause: Database error during sync
Solutions:
Check
user_profilestable exists and has proper schemaVerify Supabase connection and permissions
Check user_id isn't duplicated in database
Review application logs for sync errors
FAQ
Q: Why PKCE? A: OAuth 2.1 best practice. Prevents interception attacks on the authorization code.
Q: Can I use Foundation login on multiple apps? A: Yes! Any app with valid credentials can use Foundation for auth.
Q: What if Foundation is down? A: Users cannot login. Have a maintenance page ready.
Q: Do I need to handle token refresh? A: Foundation tokens are long-lived. Implement refresh if tokens are short-lived.
Q: Can users logout from Foundation and still access Corp? A: Yes, they have separate sessions. Eventually their Corp token will expire.
Q: What happens to existing Discord connections? A: They're managed by Foundation now, not Corp. Users reconnect on Foundation.
Summary
✅ aethex.dev is now an OAuth client of aethex.foundation
Foundation = Single source of truth for identity (Discord, email, etc.)
aethex.dev = OAuth client that redirects to Foundation for authentication
User experience = Seamless login with unified account across ecosystem
Security = PKCE prevents interception, secure cookie handling
Architecture = Axiom Model achieved - Foundation controls all identities
Status: ✅ Implementation complete, ready for testing and deployment
Last updated
