gavinsawyer / firebase-web-authn

A Firebase Extension for authentication with WebAuthn passkeys. Hire the developer: /in/gavinsawyer-dev.
https://extensions.dev/extensions/gavinsawyer/firebase-web-authn
Apache License 2.0
39 stars 2 forks source link
api authentication cloud-functions firebase monorepo nx serverless typescript web webauthn

FirebaseWebAuthn

A Firebase Extension for authentication with WebAuthn passkeys.

GitHub workflow status View in Extensions Hub

Demo: https://firebase-web-authn.dev

Summary

WebAuthn enables creating an account or signing in with as few as two clicks and doesn't ask the user to remember anything. This extension addresses a popular feature request for WebAuthn as an authentication provider in Firebase.

This is a monorepo with five packages including an easy-to-install Firebase Extension and small Browser SDK. The major version is tracking that of the Firebase JavaScript SDK and mirrors its implementation patterns.

Features include:

Latest version in NPM

Installation

Install

To install from the Extensions Hub, click the button above or run the following commands in your project root:

% firebase ext:install gavinsawyer/firebase-web-authn

To install from NPM, run the following commands in your project root:

% npm i @firebase-web-authn/extension --save-dev
% firebase ext:install ./node_modules/@firebase-web-authn/extension

Using NPM is recommended to receive updates to the extension alongside other FirebaseWebAuthn dependencies.

Prerequisites

Before installing this extension, you'll need to set up these services in your project. This must be done both in the Firebase Console and initialized in the application:

  1. As of July 2024, supported roles for Firebase Extensions do not include iam.serviceAccounts.signBlob or serviceusage.services.use which are needed for custom auth providers.
    • After deploying the extension, grant the Service Account Token Creator and Service Usage Consumer roles to the extension's service account in IAM under Firebase Extensions firebase-web-authn service account > Edit > Assign roles.
    • If the service account isn't appearing, click Grant Access and enter its address as ext-firebase-web-authn@${PROJECT_ID}.iam.gserviceaccount.com
  2. The browser must reach FirebaseWebAuthn from the same domain as your website. Modify your firebase.json to include a rewrite on each app where you'd like to use passkeys:

    {
      "hosting": [
        {
          "target":   "...",
          "rewrites": [
            {
              "source":   "/firebase-web-authn-api",
              "function": "ext-firebase-web-authn-api"
            }
          ]
        }
      ]
    }

    @firebase-web-authn/browser

    This package contains five tree-shakeable async methods for using FirebaseWebAuthn in components and a strongly-typed error object.

FirebaseWebAuthn version Firebase JS SDK version

Methods

createUserWithPasskey: (auth: Auth, functions: Functions, name: string) => Promise<UserCredential>;
    signInWithPasskey: (auth: Auth, functions: Functions)               => Promise<UserCredential>;
      linkWithPasskey: (auth: Auth, functions: Functions, name: string) => Promise<UserCredential>;
        unlinkPasskey: (auth: Auth, functions: Functions)               => Promise<void>;
verifyUserWithPasskey: (auth: Auth, functions: Functions)               => Promise<void>;

πŸŽ‰ 2FA passkeys are here in ^10.3.0!

All methods besides createUserWithPasskey accept an optional factor parameter of "first" or "second".

Default behaviors were designed to maintain backwards compatibility and are described below:

          signInWithPasskey(auth, functions) // Sign in and accept either credential.
 signInWithPasskey(auth, functions, "first") // Sign in and only accept a first (1FA) factor credential.
signInWithPasskey(auth, functions, "second") // Sign in and only accept a second (2FA) factor credential.
          linkWithPasskey(auth, functions, username) // Link a first (1FA) factor credential.
 linkWithPasskey(auth, functions, username, "first") // Link a first (1FA) factor credential.
linkWithPasskey(auth, functions, username, "second") // Link a second (2FA) factor credential.
          unlinkWithPasskey(auth, functions) // Unlink all credentials.
 unlinkWithPasskey(auth, functions, "first") // Unlink all credentials.
unlinkWithPasskey(auth, functions, "second") // Unlink a second (2FA) factor credential.
          verifyUserWithPasskey(auth, functions) // Verify the user and allow either credential.
 verifyUserWithPasskey(auth, functions, "first") // Verify the user and allow only a first (1FA) factor credential.
verifyUserWithPasskey(auth, functions, "second") // Verify the user and allow only a second (2FA) factor credential.

Designed to be used like the Firebase JavaScript SDK:

import { createUserWithEmailAndPassword } from "firebase/auth";
import { createUserWithPasskey }          from "@firebase-web-authn/browser";
class SignUpComponent {

  constructor(
    private readonly auth: Auth,
    private readonly functions: Functions,
  ) {
    // Firebase JavaScript SDK usage
    this
      .createUserWithEmailAndPassword = (email: string, password: string) => createUserWithEmailAndPassword(auth, email, password)
      .then(() => void(0));

    // FirebaseWebAuthn usage
    this
      .createUserWithPasskey = (name: string) => createUserWithPasskey(auth, functions, name)
      .then(() => void(0));

  }

  public readonly createUserWithEmailAndPassword: (email: string, password: string) => Promise<void>;
  public readonly createUserWithPasskey: (name: string) => Promise<void>;

}

Add .catch((err: FirebaseWebAuthnError): void => console.error(err)) to these for a detailed error object with a code, message, method, and/or operation. method is present for Firebase errors, and operation is present on all errors except Firebase errors from Auth methods:

import { FirebaseWebAuthnError } from "@firebase-web-authn/browser";
class FirebaseWebAuthnError extends Error {
  code: `firebaseWebAuthn/${FirebaseError["code"] | "missing-auth" | "missing-user-doc" | "no-op" | "not-verified" | "user-doc-missing-challenge-field" | "user-doc-missing-passkey-fields" | "cancelled" | "invalid"}`;
  message: FirebaseError["message"] | "No user is signed in." | "No user document was found in Firestore." | "No operation is needed." | "User not verified." | "User doc is missing challenge field from prior operation." | "User doc is missing passkey fields from prior operation.";
  method?: "httpsCallableFromURL" | "signInAnonymously" | "signInWithCustomToken";
  operation?: "clear challenge" | "clear credential" | "create authentication challenge" | "create reauthentication challenge" | "create registration challenge" | "verify authentication" | "verify reauthentication" | "verify registration";
}

Caveats

FirebaseWebAuthn version Firebase Admin SDK version

Methods

         credentials: (uid: string, app?: App) => Promise<{ [key in WebAuthnUserCredentialFactor]: WebAuthnUserCredential | null }>;
  lastCredentialUsed: (uid: string, app?: App) => Promise<WebAuthnUserCredentialFactor | null>;
         lastPresent: (uid: string, app?: App) => Promise<Timestamp | null>;
        lastVerified: (uid: string, app?: App) => Promise<Timestamp | null>;
 lastWebAuthnProcess: (uid: string, app?: App) => Promise<WebAuthnProcess | null>;
webAuthnUserDocument: (uid: string, app?: App) => Promise<WebAuthnUserDocument | null>;

Designed to be used within Firebase Functions or another secure context with access to Firestore to check users' status with FirebaseWebAuthn:

import { getApps, initializeApp } from "firebase-admin/app";
import { lastVerified }           from "@firebase-web-authn/server";
getApps().length === 0 && initializeApp();

// If the user was verified within the past 30 seconds, proceed. Otherwise, ask for reverification:
(await lastVerified(uid))?.seconds > (Date.now() / 1000) - 30 ?
  proceed() :
  askForReverification();

If your check involves multiple pieces of data from WebAuthnUserDocument, use the webAuthnUserDocument method to reduce Firestore calls:

// If the user was verified with their first-factor credential within the past 30 seconds, proceed. Otherwise, ask for reverification:
(await webAuthnUserDocument(user.uid).then<boolean>(
  (webAuthnUserDocument: WebAuthnUserDocument): boolean => webAuthnUserDocument.lastVerified?.seconds > (Date.now() / 1000) - 30 && webAuthnUserDocument.lastCredentialUsed === "first",
)) ?
  proceed() :
  askForReverification();

Other packages