firebase-auth-cloudflare-workers

repository·main·Indexed 41 days ago

https://github.com/code-hex/firebase-auth-cloudflare-workers

A zero-dependency Firebase Authentication library for Cloudflare Workers (v2.0.6). It enables verifying ID tokens and session cookies, managing custom user claims, and performing administrative tasks using Web Standard APIs. Includes built-in support for Cloudflare KV caching of public JWKs via WorkersKVStoreSingle and integration with the Firebase Auth Emulator.

Tokens
7.9K
Snippets
29
Records
34
Agent score
51%

What's inside firebase-auth-cloudflare-workers

  1. Manage Multi-Factor Authentication (MFA) settings

    main

    If a user has enrolled in second-factor authentication, the UserRecord.multiFactor property will contain a MultiFactorSettings object. This object contains an array of enrolledFactors.

    if (user.multiFactor) {
      user.multiFactor.enrolledFactors.forEach(factor => {
        console.log(`Factor ID: ${factor.factorId}`); // 'phone' or 'totp'
        console.log(`UID: ${factor.uid}`);
        
        if (factor instanceof PhoneMultiFactorInfo) {
          console.log(`Phone: ${factor.phoneNumber}`);
        } else if (factor instanceof TotpMultiFactorInfo) {
          console.log(`TOTP Info:`, factor.totpInfo);
        }
      });
    }
  2. Configure Firebase Auth Emulator

    main

    To use the Firebase Auth Emulator, ensure your wrangler.toml includes the FIREBASE_AUTH_EMULATOR_HOST variable. The SDK will automatically detect the emulator if the env object passed to API calls contains this host.

    Example wrangler.toml configuration:

    [vars]
    FIREBASE_AUTH_EMULATOR_HOST = "127.0.0.1:9099"
  3. Cache Public JWKs using WorkersKVStoreSingle

    main

    To avoid fetching the public key for every request, use WorkersKVStoreSingle.getOrInitialize() to implement the KeyStorer interface using Cloudflare KV. This caches the public key used to validate Firebase ID tokens.

    • cacheKey: The key used to store/retrieve the public key in KV.
    • cfKVNamespace: The KVNamespace binding from your Cloudflare environment.
    const keyStore = WorkersKVStoreSingle.getOrInitialize(
      env.PUBLIC_JWK_CACHE_KEY, 
      env.PUBLIC_JWK_CACHE_KV
    );
  4. Verify a Firebase ID Token

    main

    Use authObj.verifyIdToken() to validate a Firebase JWT. If valid, it returns a promise that resolves with the decoded FirebaseIdToken claims.

    • idToken: The JWT string to verify.
    • checkRevoked: (Optional) If true, performs an extra request to the Firebase backend to check if the session was revoked.
    • env: (Optional) Used to detect if the Firebase Auth Emulator should be used.
    const firebaseToken = await auth.verifyIdToken(jwt, false, env);
  5. Verify a Firebase Session Cookie

    main

    Use authObj.verifySessionCookie() to validate a Firebase session cookie. It returns a promise with the cookie claims or rejects if the cookie is invalid.

    • sessionCookie: The cookie string to verify.
    • checkRevoked: (Optional) If true, checks if the session was revoked via an extra backend request.
    • env: (Optional) Used to detect if the Firebase Auth Emulator should be used.
    const firebaseToken = await auth.verifySessionCookie(sessionCookie, true, env);
  6. Manage User Data and Claims

    main

    The Auth object provides several administrative methods:

    • getUser(uid, env): Fetches the UserRecord for a specific UID.
    • revokeRefreshTokens(uid, env): Revokes all refresh tokens for a user.
    • setCustomUserClaims(uid, customUserClaims, env): Sets custom claims on a user. Passing null deletes existing claims. Claims are added to the user's ID token. Note that claims larger than 1000 bytes will throw an error.
    // Set custom claims
    await auth.setCustomUserClaims(uid, { role: 'admin' }, env);
    
    // Get user
    const user = await auth.getUser(uid, env);
  7. Initialize Auth with Auth.getOrInitialize()

    main

    The Auth object is created as a singleton. This pattern is used because Cloudflare Module Workers only access environment variables during the request lifecycle.

    To initialize the Auth instance, provide the projectId, a keyStore for caching public JWKs, and an optional credential (e.g., ServiceAccountCredential) if you need to perform Admin tasks like creating session cookies.

    import { Auth, WorkersKVStoreSingle } from "firebase-auth-cloudflare-workers";
    
    // Inside your fetch handler:
    const auth = Auth.getOrInitialize(
      env.PROJECT_ID,
      WorkersKVStoreSingle.getOrInitialize(env.PUBLIC_JWK_CACHE_KEY, env.PUBLIC_JWK_CACHE_KV)
    );
  8. Create a Firebase Session Cookie

    main

    Use authObj.createSessionCookie() to exchange an ID token for a session cookie. This is useful for server-side session management.

    Note: This requires a service account credential to be provided during Auth.getOrInitialize().

    • idToken: The Firebase ID token to exchange.
    • sessionCookieOptions: Options including custom session duration.
    • env: (Optional) Used to detect if the Firebase Auth Emulator should be used.
    const sessionCookie = await auth.createSessionCookie(idToken, sessionCookieOptions, env);
  9. Configure HTTP retry behavior with RetryConfig

    main

    You can customize how the client handles failing HTTP requests using the RetryConfig interface. This allows you to control retries for specific HTTP status codes or low-level I/O errors, and define an exponential backoff strategy.

    Key properties:

    • maxRetries: Maximum number of retry attempts.
    • statusCodes: Array of HTTP status codes that trigger a retry (e.g., [503]).
    • ioErrorCodes: Array of low-level I/O error codes to retry (e.g., ['ECONNRESET', 'ETIMEDOUT']).
    • backOffFactor: Multiplier for exponential backoff. Delay is calculated as (2^n) * backOffFactor, where n is the number of retries. A factor of 0 means no delay; 1 means the duration doubles each iteration.
    • maxDelayInMillis: The maximum time to wait before initiating a retry.
    export interface RetryConfig {
      maxRetries: number;
      statusCodes?: number[];
      ioErrorCodes?: string[];
      backOffFactor?: number;
      maxDelayInMillis: number;
    }
  10. Use the default retry configuration

    main

    The defaultRetryConfig() function provides a sensible default for HTTP requests. It is configured to retry up to 4 times on connection resets, timeouts, and HTTP 503 errors, using an exponential backoff factor of 0.5 and a maximum delay of 60 seconds.

    const retryConfig = defaultRetryConfig();
    // Returns:
    // {
    //   maxRetries: 4,
    //   statusCodes: [503],
    //   ioErrorCodes: ['ECONNRESET', 'ETIMEDOUT'],
    //   backOffFactor: 0.5,
    //   maxDelayInMillis: 60000
    // }
  11. Initialize the Auth instance with getOrInitialize()

    main

    The Auth class is a singleton used to verify Firebase ID tokens and session cookies. Use Auth.getOrInitialize() to obtain an instance. You must provide a projectId and a KeyStorer (such as WorkersKVStoreSingle). Optionally, you can provide a Credential (like ServiceAccountCredential) if you need to perform administrative tasks or if the library requires it for specific verification flows.

    import { Auth, WorkersKVStoreSingle } from 'firebase-auth-cloudflare-workers';
    
    // Assuming 'env.MY_KV' is a KVNamespace from Cloudflare
    const keyStore = WorkersKVStoreSingle.getOrInitialize('firebase-jwks-cache', env.MY_KV);
    
    const auth = Auth.getOrInitialize('your-firebase-project-id', keyStore);
    
    // Example usage (method signatures from documentation):
    // const decodedToken = await auth.verifyIdToken(idToken);