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 auth

  • response_type - Always "code" (OAuth 2.0 authorization code flow)

  • scope - Requested permissions

  • state - 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.tsinitiateFoundationLogin()

2. Token Exchange Endpoint

Backend exchanges authorization code for access token.

Response:

Implementation: See code/api/auth/callback.tsperformTokenExchange()

3. User Info Endpoint

Fetch authenticated user's profile.

Implementation: See code/api/auth/callback.tsfetchUserInfoFromFoundation()


PKCE Implementation

PKCE (Proof Key for Code Exchange) adds extra security to OAuth flows.

How PKCE Works

  1. Client generates code verifier:

  2. Client generates code challenge:

  3. Client sends challenge with authorization request:

  4. Server stores challenge, validates with verifier on token exchange:

  5. 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.tsgeneratePKCEParams()


Implementation Details

Frontend Components

1. Login Page (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)

Core OAuth functionality:

3. useFoundationAuth Hook (code/client/hooks/use-foundation-auth.ts)

Handles OAuth callback:

Backend Endpoints

1. Callback Handler (code/api/auth/callback.ts)

Route: GET /auth/callback?code=...&state=...

Flow:

  1. Receive authorization code from Foundation

  2. Validate state token (CSRF protection)

  3. Exchange code for access token

  4. Fetch user info from Foundation

  5. Sync user to local database

  6. Set session cookies

  7. Redirect to dashboard

Code:

2. Token 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

  1. Set up environment:

  2. Test flow:

    • Visit http://localhost:5173/login

    • Click "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_token and auth_user_id

  3. 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

  1. Auth Success Rate

    • Target: >99%

    • Alert if: <95%

  2. Token Exchange Time

    • Target: <500ms

    • Alert if: >2s

  3. Error Categories

    • Track: invalid_code, state_mismatch, timeout, etc.

  4. 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:

  1. Check redirect_uri matches exactly (case-sensitive)

  2. Verify Foundation OAuth settings

  3. Check browser console for JavaScript errors

Problem: "Invalid state token"

Cause: CSRF validation failed

Solutions:

  1. Check that state is generated consistently

  2. Verify sessionStorage isn't cleared between redirect

  3. Check for multiple browser tabs (different state per tab)

Problem: "Token exchange failed"

Cause: Foundation token endpoint unavailable or code invalid

Solutions:

  1. Check Foundation is running and /api/oauth/token accessible

  2. Verify client_id and client_secret are correct

  3. Check code hasn't expired (usually 10 minutes)

  4. Review Foundation logs for errors

Problem: User not synced to database

Cause: Database error during sync

Solutions:

  1. Check user_profiles table exists and has proper schema

  2. Verify Supabase connection and permissions

  3. Check user_id isn't duplicated in database

  4. 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