OAuth client for handling OAuth2 Authorization Code flow with PKCE

This class implements the OAuth2 Authorization Code flow with PKCE (Proof Key for Code Exchange) for secure authentication. It provides a complete OAuth2 implementation including:

  • Authorization URL generation with PKCE
  • Token exchange with code verifier
  • Token refresh
  • State parameter support for CSRF protection

The implementation follows RFC 7636 for PKCE, ensuring secure authentication even for public clients.

The class uses cryptographically secure random values for code verifiers and implements the S256 challenge method as specified in RFC 7636. All code verifiers are 128 characters long and properly base64url encoded.

Basic OAuth flow:

// Initialize OAuth client
const oauth = new OAuth({
clientId: 'your-client-id',
redirectUri: 'https://your-app.com/callback',
appURL: 'https://mosaia.ai',
scopes: ['read', 'write']
});

// Step 1: Get authorization URL and code verifier
const { url, codeVerifier } = oauth.getAuthorizationUrlAndCodeVerifier();

// Store code verifier securely (e.g., session storage)
sessionStorage.setItem('code_verifier', codeVerifier);

// Step 2: Redirect user to authorization URL
window.location.href = url;

// Step 3: Handle OAuth callback
const code = new URLSearchParams(window.location.search).get('code');
const storedVerifier = sessionStorage.getItem('code_verifier');

if (code && storedVerifier) {
const config = await oauth.authenticateWithCodeAndVerifier(
code,
storedVerifier
);

// Use the config with the SDK
const mosaia = new MosaiaClient(config);
}

With state parameter for CSRF protection:

const state = crypto.randomBytes(32).toString('hex');
sessionStorage.setItem('oauth_state', state);

const oauth = new OAuth({
clientId: 'your-client-id',
redirectUri: 'https://your-app.com/callback',
scopes: ['read', 'write'],
state: state
});

Constructors

  • Creates a new OAuth instance

    Initializes an OAuth client with the provided configuration. If certain configuration values are missing, it attempts to use values from the ConfigurationManager.

    Parameters

    • Optionalconfig: OAuthConfig

      OAuth configuration object

      OAuth configuration interface

      Configuration object for OAuth2 Authorization Code flow with PKCE. Used when initializing OAuth instances for secure authentication. This interface defines all the parameters needed to configure OAuth authentication flows.

      • OptionalredirectUri?: string

        Redirect URI for the OAuth flow (optional)

      • OptionalappURL?: string

        App URL for authorization endpoints (optional defaults to https://mosaia.ai)

      • Optionalscopes?: string[]

        Array of scopes to request (optional)

      • OptionalclientId?: string

        OAuth client ID (required only if not using default)

      • OptionalapiURL?: string

        API URL for API endpoints (required only if not using default)

      • OptionalapiVersion?: string

        API version (required only if not using default)

      • Optionalstate?: string

        State parameter for CSRF protection (optional)

    Returns OAuth

    When required configuration values (clientId, apiURL, apiVersion) are missing

    // Basic initialization
    const oauth = new OAuth({
    clientId: 'your-client-id',
    redirectUri: 'https://your-app.com/callback',
    scopes: ['read', 'write']
    });

    // Full configuration
    const oauth = new OAuth({
    clientId: 'your-client-id',
    redirectUri: 'https://your-app.com/callback',
    appURL: 'https://mosaia.ai',
    scopes: ['read', 'write'],
    state: 'random-state-string',
    apiURL: 'https://api.mosaia.ai',
    apiVersion: '1'
    });

Properties

config: OAuthConfig

OAuth configuration object containing all settings for the OAuth flow

This configuration object is initialized in the constructor and used throughout the OAuth flow. It includes all necessary parameters for authorization, token exchange, and API access.

Methods

  • Generates the authorization URL and PKCE code verifier for the OAuth flow

    This method prepares everything needed to start the OAuth authorization flow:

    1. Generates a PKCE code verifier and challenge
    2. Constructs the authorization URL with all required parameters
    3. Returns both the URL and verifier for the next steps

    The authorization URL includes:

    • client_id
    • redirect_uri
    • response_type=code
    • code_challenge (PKCE)
    • code_challenge_method=S256
    • scopes (if provided)
    • state (if provided)

    Returns { url: string; codeVerifier: string }

    Authorization data for the OAuth flow

    When required configuration (scopes, redirectUri) is missing

    Basic usage:

    const { url, codeVerifier } = oauth.getAuthorizationUrlAndCodeVerifier();

    // Store verifier securely
    sessionStorage.setItem('code_verifier', codeVerifier);

    // Redirect to authorization URL
    window.location.href = url;

    With error handling:

    try {
    const { url, codeVerifier } = oauth.getAuthorizationUrlAndCodeVerifier();

    // Store both verifier and current URL for later
    sessionStorage.setItem('code_verifier', codeVerifier);
    sessionStorage.setItem('return_to', window.location.href);

    // Redirect to authorization
    window.location.href = url;
    } catch (error) {
    console.error('Failed to start OAuth flow:', error.message);
    }

    authenticateWithCodeAndVerifier for handling the callback

  • Exchanges an authorization code for access and refresh tokens

    This method completes the OAuth flow by exchanging the authorization code for access and refresh tokens. It includes the PKCE code verifier in the token request for additional security.

    The method:

    1. Validates required parameters
    2. Constructs the token request with PKCE verification
    3. Exchanges the code for tokens
    4. Returns a complete MosaiaConfig with the new tokens

    Parameters

    Returns Promise<MosaiaConfig>

    Promise resolving to a complete MosaiaConfig

    When required configuration (redirectUri) is missing

    When token exchange fails

    When code is invalid or expired

    When code verifier doesn't match challenge

    Basic OAuth callback handling:

    // In your OAuth callback route/page
    const code = new URLSearchParams(window.location.search).get('code');
    const verifier = sessionStorage.getItem('code_verifier');

    if (code && verifier) {
    try {
    const config = await oauth.authenticateWithCodeAndVerifier(code, verifier);

    // Initialize SDK with the new config
    const mosaia = new MosaiaClient(config);

    // Clean up stored values
    sessionStorage.removeItem('code_verifier');

    // Return to original page
    const returnTo = sessionStorage.getItem('return_to') || '/';
    window.location.href = returnTo;
    } catch (error) {
    console.error('Token exchange failed:', error);
    // Handle error (e.g., redirect to login)
    }
    }

    With state verification:

    const params = new URLSearchParams(window.location.search);
    const code = params.get('code');
    const state = params.get('state');
    const verifier = sessionStorage.getItem('code_verifier');
    const savedState = sessionStorage.getItem('oauth_state');

    // Verify state to prevent CSRF
    if (state !== savedState) {
    throw new Error('OAuth state mismatch');
    }

    if (code && verifier) {
    const config = await oauth.authenticateWithCodeAndVerifier(code, verifier);
    // Use the config...
    }

    getAuthorizationUrlAndCodeVerifier for starting the OAuth flow