npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

firebase-app-check-cloudflare-workers

v1.0.5

Published

Zero-dependencies firebase app check library for Cloudflare Workers.

Downloads

1

Readme

firebase-auth-cloudflare-workers

Zero-dependencies firebase App Check library for Cloudflare Workers.

  • Implemented by only Web Standard API.
  • Supported UTF-8.
  • Supported Firebase Auth Emulator.

Synopsis

import type { EmulatorEnv } from "firebase-app-check-cloudflare-workers";
import { Auth, WorkersKVStoreSingle } from "firebase-app-check-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<Response> => {
  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, env)

  return new Response(JSON.stringify(firebaseToken), {
    headers: {
      "Content-Type": "application/json"
    }
  })
}

wrangler.toml

name = "firebase-app-check-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"

Module Worker syntax

export async function fetch(req: Request, env: Bindings) {
  return await verifyJWT(req, env)
}

export default { fetch };

Service Worker syntax

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))
})

Install

You can install from npm registry.

$ npm i firebase-auth-cloudflare-workers

Docs

API

Auth.getOrInitialize(projectId: string, keyStore: KeyStorer): Auth

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

See official document for project ID: https://firebase.google.com/docs/projects/learn-more#project-identifiers

authObj.verifyIdToken(idToken: string, env?: EmulatorEnv): Promise<FirebaseIdToken>

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 for more information about the specific properties below.

  • env is an optional parameter. but this is using to detect should use emulator or not.

WorkersKVStoreSingle.getOrInitialize(cacheKey: string, cfKVNamespace: KVNamespace): WorkersKVStoreSingle

WorkersKVStoreSingle is created as a singleton object. This is because the Module Worker syntax only use environment variables at the time of request.

This caches the public key used to verify the Firebase ID token in the Workers KV.

This is implemented KeyStorer interface.

  • cacheKey specifies the key of the public key cache.
  • cfKVNamespace specifies the KV namespace which is bound your workers.

emulatorHost(env?: EmulatorEnv): string | undefined

Returns the host of your Firebase Auth Emulator. For example, this case returns "127.0.0.1:9099" if you configured like below.

wrangler.toml

[vars]
FIREBASE_AUTH_EMULATOR_HOST = "127.0.0.1:9099"

useEmulator(env?: EmulatorEnv): boolean

This is a wrapper emulatorHost function.

When true the SDK should communicate with the Auth Emulator for all API calls and also produce unsigned tokens.

Type

KeyStorer

This is an interface to cache the public key used to verify the Firebase ID token. By creating a class that implemented this interface, you can cache it in any storage of your choice.

interface KeyStorer {
  get<ExpectedValue = unknown>(): Promise<ExpectedValue | null>;
  put(value: string, expirationTtl: number): Promise<void>;
}

EmulatorEnv

interface EmulatorEnv {
  FIREBASE_AUTH_EMULATOR_HOST: string | undefined
}

FirebaseIdToken

Interface representing a decoded Firebase ID token, returned from the authObj.verifyIdToken method.

Run example code

I put an example directory as Module Worker Syntax. this is explanation how to run the code.

  1. Clone this repository and change your directory to it.
  2. Install dev dependencies as yarn command.
  3. Run firebase auth emulator by $ yarn start-firebase-emulator
  4. Access to Emulator UI in your favorite browser.
  5. Create a new user on Emulator UI. (email: [email protected] password: test1234)
  6. Run example code on local (may serve as localhost:8787) by $ yarn start-example
  7. Get jwt for created user by $ curl -s http://localhost:8787/get-jwt | jq .idToken -r
  8. Try authorization with user jwt $ curl http://localhost:8787/ -H 'Authorization: Bearer PASTE-JWT-HERE'

Todo

Non-required service account key.

  • [x] IDToken verification

Required service account key.

  • [ ] Check authorized user is deleted (revoked)