### Install `firebase-auth-cloudflare-workers` via npm Source: https://github.com/code-hex/firebase-auth-cloudflare-workers/blob/main/README.md This command installs the `firebase-auth-cloudflare-workers` package from the npm registry. This package provides the necessary tools and functions to integrate Firebase authentication into Cloudflare Workers, enabling JWT and session cookie verification. ```bash $ npm i firebase-auth-cloudflare-workers ``` -------------------------------- ### Get Firebase Auth Emulator Host Source: https://github.com/code-hex/firebase-auth-cloudflare-workers/blob/main/README.md Retrieves the host and port of the Firebase Auth Emulator. This is useful for testing authentication flows locally. The emulator host is typically configured via environment variables (e.g., `FIREBASE_AUTH_EMULATOR_HOST`). ```typescript import { emulatorHost } from "firebase-auth-cloudflare-workers"; // Assuming env contains environment variables // const emulator = emulatorHost(env); // if (emulator) { // console.log(`Using Firebase Auth Emulator at: ${emulator}`); // } ``` -------------------------------- ### Get Firebase User Data Source: https://github.com/code-hex/firebase-auth-cloudflare-workers/blob/main/README.md Retrieves user data for a given Firebase User ID (UID). This function is useful for fetching user profiles and associated information. ```typescript import { Auth } from "firebase-auth-cloudflare-workers"; // Assuming authObj is initialized with credentials and projectId // const authObj = AdminAuthApiClient.getOrInitialize(projectId, credential); async function getUserData(authObj, uid) { try { const userRecord = await authObj.getUser(uid); return userRecord; } catch (error) { console.error(`Error getting user data for UID ${uid}:`, error); throw error; } } ``` -------------------------------- ### Cloudflare Service Worker Fetch Handler (TypeScript) Source: https://github.com/code-hex/firebase-auth-cloudflare-workers/blob/main/README.md This TypeScript code demonstrates setting up a Service Worker for Cloudflare that handles incoming fetch events. It defines global bindings for Firebase configuration and creates an `EmulatorEnv` object to pass to the `verifyJWT` function, ensuring the worker can authenticate requests using Firebase. ```typescript declare global { const PROJECT_ID: string const PUBLIC_JWK_CACHE_KEY: string const PUBLIC_JWK_CACHE_KV: KVNamespace const FIREBASE_AUTH_EMULATOR_HOST: string } addEventListener('fetch', (event: FetchEvent) => { // Create env object for verifyIdToken API. const bindings: EmulatorEnv = { PROJECT_ID, PUBLIC_JWK_CACHE_KEY, PUBLIC_JWK_CACHE_KV, FIREBASE_AUTH_EMULATOR_HOST, } event.respondWith(verifyJWT(event.request, bindings)) }) ``` -------------------------------- ### WorkersKVStoreSingle.getOrInitialize Source: https://github.com/code-hex/firebase-auth-cloudflare-workers/blob/main/README.md Initializes or retrieves a singleton instance of WorkersKVStoreSingle, used for caching public keys for Firebase ID token verification in Cloudflare Workers KV. ```APIDOC ## POST /kv-store/getOrInitialize ### Description Initializes or retrieves a singleton object for WorkersKVStoreSingle. This is used to cache the public key for verifying Firebase ID tokens in Cloudflare Workers KV. ### Method POST ### Endpoint /kv-store/getOrInitialize ### Parameters #### Request Body - **cacheKey** (string) - Required - The key to use for caching the public key in KV. - **cfKVNamespace** (KVNamespace) - Required - The Cloudflare KV namespace bound to your worker. ### Response #### Success Response (200) - **instance** (WorkersKVStoreSingle) - The singleton instance of WorkersKVStoreSingle. #### Response Example ```json { "instance": "" } ``` ``` -------------------------------- ### Cloudflare Worker `wrangler.toml` Configuration Source: https://github.com/code-hex/firebase-auth-cloudflare-workers/blob/main/README.md This is a sample `wrangler.toml` configuration file for a Cloudflare Worker project. It sets the worker name, compatibility date, and enables the development server. It also defines environment variables for Firebase project ID, emulator host, and KV namespace bindings, including a specific key for caching public JWKs. ```toml name = "firebase-auth-example" compatibility_date = "2022-07-05" workers_dev = true [vars] FIREBASE_AUTH_EMULATOR_HOST = "127.0.0.1:9099" PROJECT_ID = "example-project12345" # Specify cache key to store and get public jwk. PUBLIC_JWK_CACHE_KEY = "public-jwk-cache-key" [[kv_namespaces]] binding = "PUBLIC_JWK_CACHE_KV" id = "" preview_id = "testingId" ``` -------------------------------- ### Define EmulatorEnv Interface for Firebase Emulator Host Source: https://github.com/code-hex/firebase-auth-cloudflare-workers/blob/main/README.md The `EmulatorEnv` interface specifies the expected environment variable for the Firebase authentication emulator host. This is crucial for directing authentication requests to the local emulator during development. ```typescript interface EmulatorEnv { FIREBASE_AUTH_EMULATOR_HOST: string | undefined } ``` -------------------------------- ### Auth Initialization API Source: https://github.com/code-hex/firebase-auth-cloudflare-workers/blob/main/README.md Initializes the Auth singleton object. This is necessary because Module Workers only access environment variables at request time. ```APIDOC ## Auth.getOrInitialize(projectId: string, keyStore: KeyStorer, credential?: Credential): Auth ### Description Auth is created as a singleton object. This is because the Module Worker syntax only use environment variables at the time of request. - `projectId` specifies the ID of the project for which firebase auth is used. - `keyStore` is used to cache the public key used to validate the Firebase ID token (JWT). - `credential` is an optional. This is used to utilize Admin APIs such as `createSessionCookie`. Currently, you can specify `ServiceAccountCredential` class, which allows you to use a service account. See official document for project ID: https://firebase.google.com/docs/projects/learn-more#project-identifiers ### Method Static method ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ts const auth = Auth.getOrInitialize( env.PROJECT_ID, WorkersKVStoreSingle.getOrInitialize(env.PUBLIC_JWK_CACHE_KEY, env.PUBLIC_JWK_CACHE_KV) ); ``` ### Response #### Success Response (200) Returns an instance of the Auth object. #### Response Example ```json { "message": "Auth object initialized" } ``` ``` -------------------------------- ### Initialize Admin Auth API Client Source: https://github.com/code-hex/firebase-auth-cloudflare-workers/blob/main/README.md Initializes a singleton AdminAuthApiClient for interacting with the Firebase Admin Auth API. Requires a project ID and credential object (e.g., ServiceAccountCredential). The service account must have the 'roles/firebaseauth.admin' role. ```typescript import { AdminAuthApiClient, ServiceAccountCredential, Credential } from "firebase-auth-cloudflare-workers"; // Assuming projectId is your Firebase project ID // const projectId = "your-project-id"; // Assuming serviceAccountJson is the content of your service account JSON file // const serviceAccountJson = { ... }; function initializeAdminAuthClient(projectId, serviceAccountJson) { const credential = new ServiceAccountCredential(serviceAccountJson); const authApiClient = AdminAuthApiClient.getOrInitialize(projectId, credential); return authApiClient; } ``` -------------------------------- ### AdminAuthApiClient.getOrInitialize Source: https://github.com/code-hex/firebase-auth-cloudflare-workers/blob/main/README.md Initializes or retrieves a singleton instance of AdminAuthApiClient. This client is used to interact with the Admin Auth API for Firebase project authentication. ```APIDOC ## POST /admin-auth/getOrInitialize ### Description Initializes or retrieves a singleton object for AdminAuthApiClient. This client allows interaction with the Admin Auth API, often used for generating access tokens from credentials like Service Accounts. ### Method POST ### Endpoint /admin-auth/getOrInitialize ### Parameters #### Request Body - **projectId** (string) - Required - The Firebase project ID. - **credential** (Credential) - Required - The credential used for authentication (e.g., ServiceAccountCredential). - **retryConfig** (RetryConfig) - Optional - Configuration for retry attempts. ### Response #### Success Response (200) - **client** (AdminAuthApiClient) - The singleton instance of AdminAuthApiClient. #### Response Example ```json { "client": "" } ``` ``` -------------------------------- ### Initialize Workers KV Store for Caching Source: https://github.com/code-hex/firebase-auth-cloudflare-workers/blob/main/README.md Initializes a singleton WorkersKVStoreSingle object to cache public keys used for verifying Firebase ID tokens. This utilizes Cloudflare Workers KV for persistent storage. Requires a cache key and a KV namespace binding. ```typescript import { WorkersKVStoreSingle } from "firebase-auth-cloudflare-workers"; // Assuming cfKVNamespace is a bound KVNamespace in your Cloudflare Worker // const cfKVNamespace = env.YOUR_KV_NAMESPACE; function initializeKVStore(cacheKey, cfKVNamespace) { const kvStore = WorkersKVStoreSingle.getOrInitialize(cacheKey, cfKVNamespace); return kvStore; } ``` -------------------------------- ### useEmulator Source: https://github.com/code-hex/firebase-auth-cloudflare-workers/blob/main/README.md Checks if the SDK should use the Firebase Auth Emulator for API calls. ```APIDOC ## GET /emulator/use ### Description This is a wrapper function for `emulatorHost`. When true, the SDK communicates with the Auth Emulator for all API calls and produces unsigned tokens. ### Method GET ### Endpoint /emulator/use ### Parameters #### Query Parameters - **env** (EmulatorEnv) - Optional - Environment configuration. ### Response #### Success Response (200) - **useEmulator** (boolean) - True if the emulator should be used, false otherwise. #### Response Example ```json { "useEmulator": true } ``` ``` -------------------------------- ### emulatorHost Source: https://github.com/code-hex/firebase-auth-cloudflare-workers/blob/main/README.md Retrieves the host address of the Firebase Auth Emulator if configured. ```APIDOC ## GET /emulator/host ### Description Returns the host of your Firebase Auth Emulator. For example, this case returns `"127.0.0.1:9099"` if you configured like below in `wrangler.toml`: ```toml [vars] FIREBASE_AUTH_EMULATOR_HOST = "127.0.0.1:9099" ``` ### Method GET ### Endpoint /emulator/host ### Parameters #### Query Parameters - **env** (EmulatorEnv) - Optional - Environment configuration. ### Response #### Success Response (200) - **host** (string | undefined) - The emulator host address or undefined if not configured. #### Response Example ```json { "host": "127.0.0.1:9099" } ``` ``` -------------------------------- ### Cloudflare Module Worker Fetch Handler (TypeScript) Source: https://github.com/code-hex/firebase-auth-cloudflare-workers/blob/main/README.md This TypeScript code snippet shows how to define a Module Worker's `fetch` handler in Cloudflare. It imports the `verifyJWT` function (presumably defined elsewhere) and exports it as the main fetch handler, allowing the worker to process incoming requests and respond using the JWT verification logic. ```typescript export async function fetch(req: Request, env: Bindings) { return await verifyJWT(req, env) } export default { fetch }; ``` -------------------------------- ### Check if Using Firebase Auth Emulator Source: https://github.com/code-hex/firebase-auth-cloudflare-workers/blob/main/README.md A boolean function that indicates whether the SDK should communicate with the Firebase Auth Emulator for all API calls. Returns true if the emulator is configured and active. ```typescript import { useEmulator } from "firebase-auth-cloudflare-workers"; // Assuming env contains environment variables // const isUsingEmulator = useEmulator(env); // if (isUsingEmulator) { // console.log("Firebase Auth Emulator is enabled."); // } ``` -------------------------------- ### Verify JWT in Cloudflare Worker (TypeScript) Source: https://github.com/code-hex/firebase-auth-cloudflare-workers/blob/main/README.md This snippet demonstrates how to verify a Firebase JWT within a Cloudflare Worker. It extracts the JWT from the Authorization header, initializes the Auth library with project ID and a KeyValue store for JWK caching, and then verifies the token. It returns the decoded token claims or an error response. Dependencies include the 'firebase-auth-cloudflare-workers' library. ```typescript import type { EmulatorEnv } from "firebase-auth-cloudflare-workers"; import { Auth, WorkersKVStoreSingle } from "firebase-auth-cloudflare-workers"; interface Bindings extends EmulatorEnv { PROJECT_ID: string PUBLIC_JWK_CACHE_KEY: string PUBLIC_JWK_CACHE_KV: KVNamespace FIREBASE_AUTH_EMULATOR_HOST: string } const verifyJWT = async (req: Request, env: Bindings): Promise => { const authorization = req.headers.get('Authorization') if (authorization === null) { return new Response(null, { status: 400, }) } const jwt = authorization.replace(/Bearer\s+/i, "") const auth = Auth.getOrInitialize( env.PROJECT_ID, WorkersKVStoreSingle.getOrInitialize(env.PUBLIC_JWK_CACHE_KEY, env.PUBLIC_JWK_CACHE_KV) ) const firebaseToken = await auth.verifyIdToken(jwt, false, env) return new Response(JSON.stringify(firebaseToken), { headers: { "Content-Type": "application/json" } }) } ``` -------------------------------- ### Define KeyStorer Interface for Caching Public Keys Source: https://github.com/code-hex/firebase-auth-cloudflare-workers/blob/main/README.md The `KeyStorer` interface defines a contract for caching Firebase ID token public keys. Implementations can use any storage mechanism. It includes methods to retrieve cached values and store new ones with an expiration. ```typescript interface KeyStorer { get(): Promise; put(value: string, expirationTtl: number): Promise; } ``` -------------------------------- ### authObj.getUser Source: https://github.com/code-hex/firebase-auth-cloudflare-workers/blob/main/README.md Retrieves user data for a given user ID (uid). This is useful for fetching user profiles and associated information. ```APIDOC ## GET /auth/getUser ### Description Gets the user data for the user corresponding to a given `uid`. ### Method GET ### Endpoint /auth/getUser ### Parameters #### Query Parameters - **uid** (string) - Required - The `uid` of the user whose data to fetch. - **env** (EmulatorEnv) - Optional - Used to detect if the emulator should be used. ### Response #### Success Response (200) - **userRecord** (UserRecord) - An object containing the user's data. #### Response Example ```json { "userRecord": { "uid": "some-uid", "email": "user@example.com", "displayName": "John Doe", "emailVerified": true, "photoURL": "https://example.com/photo.jpg", "phoneNumber": "+11234567890", "disabled": false, "metadata": { "creationTime": "2023-01-01T12:00:00Z", "lastSignInTime": "2023-01-01T12:00:00Z" }, "customClaims": {} } } ``` ``` -------------------------------- ### Create Firebase Session Cookie Source: https://github.com/code-hex/firebase-auth-cloudflare-workers/blob/main/README.md Creates a Firebase session cookie from an ID token. The JWT can be used for server-side session management and contains the same claims as the ID token. Requires service account credentials. ```typescript import { Auth } from "firebase-auth-cloudflare-workers"; // Assuming authObj is initialized with credentials and projectId // const authObj = AdminAuthApiClient.getOrInitialize(projectId, credential); async function createSessionCookie(authObj, idToken, sessionCookieOptions) { try { const sessionCookie = await authObj.createSessionCookie(idToken, sessionCookieOptions); return sessionCookie; } catch (error) { console.error("Error creating session cookie:", error); throw error; } } ``` -------------------------------- ### authObj.setCustomUserClaims Source: https://github.com/code-hex/firebase-auth-cloudflare-workers/blob/main/README.md Sets or updates custom claims for a user, which can be used for role-based access control. These claims are propagated to the user's ID token. ```APIDOC ## PUT /auth/setCustomUserClaims ### Description Sets additional developer claims on an existing user identified by the provided `uid`, typically used to define user roles and levels of access. These claims should propagate to all devices where the user is already signed in (after token expiration or when token refresh is forced) and the next time the user signs in. If a reserved OIDC claim name is used (sub, iat, iss, etc), an error is thrown. They are set on the authenticated user's ID token JWT. ### Method PUT ### Endpoint /auth/setCustomUserClaims ### Parameters #### Request Body - **uid** (string) - Required - The `uid` of the user to edit. - **customUserClaims** (object | null) - Required - The developer claims to set. If null is passed, existing custom claims are deleted. Passing a custom claims payload larger than 1000 bytes will throw an error. Custom claims are added to the user's ID token which is transmitted on every authenticated request. For profile non-access related user attributes, use database or other separate storage systems. - **env** (EmulatorEnv) - Optional - Used to detect if the emulator should be used. ### Request Example ```json { "uid": "some-uid", "customUserClaims": { "admin": true, "level": 10 } } ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful update of custom claims. #### Response Example ```json { "message": "Custom user claims updated successfully for user: some-uid" } ``` ``` -------------------------------- ### Define FirebaseIdToken Interface for Decoded Tokens Source: https://github.com/code-hex/firebase-auth-cloudflare-workers/blob/main/README.md The `FirebaseIdToken` interface represents the structure of a decoded Firebase ID token. This interface is returned by the `authObj.verifyIdToken` method and contains claims and metadata from the token. ```typescript interface FirebaseIdToken { // Interface representing a decoded Firebase ID token, returned from the `authObj.verifyIdToken` method. } ``` -------------------------------- ### Verify ID Token API Source: https://github.com/code-hex/firebase-auth-cloudflare-workers/blob/main/README.md Verifies a Firebase ID token (JWT). If the token is valid, it returns the decoded claims; otherwise, it rejects the promise. ```APIDOC ## authObj.verifyIdToken(idToken: string, checkRevoked?: boolean, env?: EmulatorEnv): Promise ### Description Verifies a Firebase ID token (JWT). If the token is valid, the promise is fulfilled with the token's decoded claims; otherwise, the promise is rejected. See the [ID Token section of the OpenID Connect spec](http://openid.net/specs/openid-connect-core-1_0.html#IDToken) for more information about the specific properties below. ### Method Instance method ### Endpoint N/A (Method within an object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **idToken** (string) - Required - The ID token to verify. - **checkRevoked** (boolean) - Optional - Whether to check if the session cookie was revoked. This requires an extra request to the Firebase Auth backend to check the `tokensValidAfterTime` time for the corresponding user. When not specified, this additional check is not performed. - **env** (EmulatorEnv) - Optional - Used to detect whether to use the emulator. ### Request Example ```ts const firebaseToken = await auth.verifyIdToken(jwt, false, env); ``` ### Response #### Success Response (200) - **FirebaseIdToken** - The decoded claims of the ID token. #### Response Example ```json { "iss": "https://securetoken.google.com/your-project-id", "aud": "your-project-id", "auth_time": 1678886400, "user_id": "some-user-id", "sub": "some-user-id", "iat": 1678886400, "exp": 1678890000, "email": "user@example.com", "email_verified": true, "firebase": { "identities": {}, "sign_in_provider": "password" } } ``` ``` -------------------------------- ### authObj.createSessionCookie Source: https://github.com/code-hex/firebase-auth-cloudflare-workers/blob/main/README.md Creates a new Firebase session cookie JWT with specified options. This JWT can be used for server-side session management and has the same claims as the provided ID token. ```APIDOC ## POST /auth/createSessionCookie ### Description Creates a new Firebase session cookie with the specified options. The created JWT string can be set as a server-side session cookie with a custom cookie policy, and be used for session management. The session cookie JWT will have the same payload claims as the provided ID token. ### Method POST ### Endpoint /auth/createSessionCookie ### Parameters #### Request Body - **idToken** (string) - Required - The Firebase ID token to exchange for a session cookie. - **sessionCookieOptions** (SessionCookieOptions) - Required - The session cookie options which includes custom session duration. - **env** (EmulatorEnv) - Optional - Used to detect if the emulator should be used. ### Request Example ```json { "idToken": "", "sessionCookieOptions": { "expiresIn": "1h", "httpOnly": true, "secure": true } } ``` ### Response #### Success Response (200) - **sessionCookie** (string) - The generated Firebase session cookie JWT. #### Response Example ```json { "sessionCookie": "" } ``` ``` -------------------------------- ### Set Custom User Claims in Firebase Source: https://github.com/code-hex/firebase-auth-cloudflare-workers/blob/main/README.md Sets or updates custom claims for a Firebase user, identified by their UID. These claims can be used for authorization and role management. Custom claims are added to the user's ID token. Maximum payload size is 1000 bytes. ```typescript import { Auth } from "firebase-auth-cloudflare-workers"; // Assuming authObj is initialized with credentials and projectId // const authObj = AdminAuthApiClient.getOrInitialize(projectId, credential); async function setCustomClaims(authObj, uid, customClaims) { try { await authObj.setCustomUserClaims(uid, customClaims); console.log(`Successfully set custom claims for UID: ${uid}`); } catch (error) { console.error(`Error setting custom claims for UID ${uid}:`, error); throw error; } } ``` -------------------------------- ### Verify Session Cookie API Source: https://github.com/code-hex/firebase-auth-cloudflare-workers/blob/main/README.md Verifies a Firebase session cookie. Returns a Promise with the cookie claims or rejects if the cookie could not be verified. ```APIDOC ## authObj.verifySessionCookie(sessionCookie: string, checkRevoked?: boolean, env?: EmulatorEnv): Promise ### Description Verifies a Firebase session cookie. Returns a Promise with the cookie claims. Rejects the promise if the cookie could not be verified. See [Verify Session Cookies](https://firebase.google.com/docs/auth/admin/manage-cookies#verify_session_cookie_and_check_permissions) for code samples and detailed documentation. ### Method Instance method ### Endpoint N/A (Method within an object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **sessionCookie** (string) - Required - The session cookie to verify. - **checkRevoked** (boolean) - Optional - Whether to check if the session cookie was revoked. This requires an extra request to the Firebase Auth backend to check the `tokensValidAfterTime` time for the corresponding user. When not specified, this additional check is not performed. - **env** (EmulatorEnv) - Optional - Used to detect whether to use the emulator. ### Request Example ```ts const sessionClaims = await auth.verifySessionCookie(cookie, true, env); ``` ### Response #### Success Response (200) - **FirebaseIdToken** - The claims of the session cookie. #### Response Example ```json { "iss": "https://session.firebase.google.com/your-project-id", "aud": "your-project-id", "auth_time": 1678886400, "user_id": "some-user-id", "sub": "some-user-id", "iat": 1678886400, "exp": 1678890000, "firebase": { "identities": {}, "sign_in_provider": "password" } } ``` ``` -------------------------------- ### authObj.revokeRefreshTokens Source: https://github.com/code-hex/firebase-auth-cloudflare-workers/blob/main/README.md Revokes all refresh tokens for a specified user, forcing them to re-authenticate. ```APIDOC ## POST /auth/revokeRefreshTokens ### Description Revokes all refresh tokens for an existing user. ### Method POST ### Endpoint /auth/revokeRefreshTokens ### Parameters #### Request Body - **uid** (string) - Required - The `uid` of the user whose refresh tokens are to be revoked. - **env** (EmulatorEnv) - Optional - Used to detect if the emulator should be used. ### Response #### Success Response (200) - **message** (string) - Indicates successful revocation. #### Response Example ```json { "message": "Refresh tokens revoked successfully for user: some-uid" } ``` ``` -------------------------------- ### Revoke Firebase User Refresh Tokens Source: https://github.com/code-hex/firebase-auth-cloudflare-workers/blob/main/README.md Revokes all refresh tokens for a specified Firebase user, effectively logging them out from all active sessions. Requires the user's UID. ```typescript import { Auth } from "firebase-auth-cloudflare-workers"; // Assuming authObj is initialized with credentials and projectId // const authObj = AdminAuthApiClient.getOrInitialize(projectId, credential); async function revokeRefreshTokens(authObj, uid) { try { await authObj.revokeRefreshTokens(uid); console.log(`Successfully revoked refresh tokens for UID: ${uid}`); } catch (error) { console.error(`Error revoking refresh tokens for UID ${uid}:`, error); throw error; } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.