Skip to content

From Firebase Auth

For: an operator and a developer who move an app from Firebase Auth to authtempo.

What it does: you export the users of Firebase, import them into core’s tables, and change the app’s Firebase calls to @authtempo/client.

  • An API with authtempo and password set. Do a getting started tutorial first.
  • The Firebase CLI, signed in to the project.
  • The password hash parameters of the project, from the console: Authentication, Users, “Password hash parameters”. The command takes rounds and mem_cost as options.
  • @authtempo/cli and @authtempo/legacy-hashes in the app’s workspace. authtempo import is a command of the first.
  1. Export the users with firebase auth:export users.json --format=json.
  2. Read rounds, mem_cost, the signer key, and the salt separator in the console.
  1. Store the signer key and the salt separator as secrets of the API, not in the code.
  2. Chain the legacy seam before core’s PBKDF2. Pass ["firescrypt"] as formats, and the signer key and the salt separator as firebase.
The API after the import
// The API after the move of the guide "From Firebase Auth".
import {
createAuth,
createPbkdf2PasswordHash,
type MailPort,
type StorageAdapter,
} from "@authtempo/core";
import { createLegacyPasswordHash, type LegacyFormat } from "@authtempo/legacy-hashes";
// Give `authtempo import firebase --formats` exactly this list.
export const FIREBASE_FORMATS: readonly LegacyFormat[] = ["firescrypt"];
/** The two hash parameters of the Firebase console. Read them from your secret store. The placeholders only build the config. */
export interface FirebaseEnv {
/** The base64 signer key. */
FIREBASE_SIGNER_KEY: string;
/** The base64 salt separator. */
FIREBASE_SALT_SEPARATOR: string;
}
const PLACEHOLDERS: FirebaseEnv = {
FIREBASE_SIGNER_KEY: "cGxhY2Vob2xkZXItc2lnbmVyLWtleQ==",
FIREBASE_SALT_SEPARATOR: "AA==",
};
export function createFirebaseAuth(
deps: { storage: StorageAdapter; mail: MailPort; secret: string },
env: FirebaseEnv = PLACEHOLDERS,
) {
return createAuth({
baseURL: "https://api.example.com",
trustedOrigins: [],
secret: deps.secret,
storage: deps.storage,
mail: deps.mail,
password: {
hash: createLegacyPasswordHash({
// Only the formats that the import brought. A row in another format never signs in.
formats: FIREBASE_FORMATS,
// Only for firescrypt: the signer key and the salt separator of the project.
firebase: {
signerKey: env.FIREBASE_SIGNER_KEY,
saltSeparator: env.FIREBASE_SALT_SEPARATOR,
},
// New hashes, and the rehash at the first right sign-in, are PBKDF2.
next: createPbkdf2PasswordHash(),
}),
},
});
}
  1. Run the import as a dry run, with rounds and mem_cost of the project.
  2. Check the hashes: line against --formats. It counts the hash formats of the export, such as hashes: firescrypt 812, none 31.

The @authtempo packages are on npm. Add the CLI to your app with pnpm add -D @authtempo/cli, and run each command as pnpm exec authtempo ….

Terminal window
authtempo import firebase --users users.json --firebase-rounds 8 --firebase-mem-cost 14 --formats firescrypt --target postgres --url-env DATABASE_URL --dry-run

Run the real import on a copy of the database only. The one real import into the real database runs at step 9 of The cutover, after the old sign-ins stop. If it runs earlier, a password, an address, or a delete that changes in the old system after it is lost. One real import tells why.

  1. Make the copy. On Postgres, create an empty database, set COPY_URL to its URL, and load the real one into it with pg_dump --no-owner "$DATABASE_URL" | psql "$COPY_URL".
  2. On D1, load the real database into the empty local copy of the import Worker with wrangler d1 export <database> --remote --output copy.sql and wrangler d1 execute <database> --local --file copy.sql.
  3. Run both in the folder of the import Worker. Delete its .wrangler/state first, or the load stops on a table that exists.
  4. Run the same command without --dry-run, with --url-env COPY_URL. On D1, run the import Worker without "remote": true, so it writes the local copy.
Terminal window
authtempo import firebase --users users.json --firebase-rounds 8 --firebase-mem-cost 14 --formats firescrypt --target postgres --url-env COPY_URL
  1. Run authtempo import verify with the same files on the copy. It exits 0 only when the copy holds the whole export.
  2. Run authtempo check <base url> against the API.
  3. Sign in once with a known user and the old password, and once by each other method of the app. Do it at step 13 of The cutover: before that step, the real database holds no user.
  4. Drop the copy, and on D1 delete copy.sql, when import verify exits 0. The copy holds every user of the export.
Terminal window
authtempo import verify firebase --users users.json --firebase-rounds 8 --firebase-mem-cost 14 --formats firescrypt --target postgres --url-env COPY_URL
authtempo check https://api.example.com
The test of this guide
import { readFileSync } from "node:fs";
import { importUsers, readSource } from "@authtempo/import";
import { FIXTURE_EXPORTS } from "@authtempo/import/testing";
import { FIREBASE, VECTORS } from "@authtempo/legacy-hashes/testing";
import { describe, expect, it } from "vitest";
import { call, harness } from "../support/harness.ts";
import { createFirebaseAuth, FIREBASE_FORMATS } from "./firebase.ts";
// The fixture export of the Firebase reader: one user with the firescrypt vector.
const f = FIXTURE_EXPORTS.firebase;
const GUIDE = new URL("../../src/content/docs/docs/migrate/firebase.mdx", import.meta.url);
describe("move users from Firebase Auth", () => {
it("signs an imported user in with the old password and rewrites the hash as PBKDF2", async () => {
const h = harness();
const report = await importUsers(h.storage, await readSource(f.bundle), {
formats: FIREBASE_FORMATS,
});
expect({ passwords: report.created.password, refused: report.refusedHashes }).toEqual({
passwords: 1,
refused: [],
});
if (f.signIn === null) throw new Error("the fixture names no user that signs in");
const { email, password } = f.signIn;
// The test values of the firebase/scrypt README, in place of the secrets of a real project.
const auth = createFirebaseAuth(h, {
FIREBASE_SIGNER_KEY: FIREBASE.signerKey,
FIREBASE_SALT_SEPARATOR: FIREBASE.saltSeparator,
});
const signIn = (p: string) =>
call(auth, "POST", "/auth/password/sign-in", { email, password: p });
expect((await signIn(VECTORS.firescrypt.wrong)).status).toBe(401);
const first = await signIn(password);
expect(first.status).toBe(200);
const { user } = (await first.json()) as { user: { id: string } };
const row = await h.storage.findOne("password", [
{ field: "userId", op: "eq", value: user.id },
]);
expect(row?.hash.startsWith("pbkdf2-sha256$")).toBe(true);
expect((await signIn(password)).status).toBe(200);
});
it("uses the formats of the fixture", () => {
expect(FIREBASE_FORMATS).toEqual(f.formats);
});
it("gives the guide the formats of this sample", () => {
const guide = readFileSync(GUIDE, "utf8");
const flags = [...guide.matchAll(/--formats (\S+)/g)].map((m) => m[1]);
expect(flags.length).toBeGreaterThan(0);
for (const list of flags) expect(list).toBe(FIREBASE_FORMATS.join(","));
const arrays = [...guide.matchAll(/`(\["[^`]*\])`/g)].map((m) => m[1]);
for (const a of arrays) expect(a).toBe(JSON.stringify(FIREBASE_FORMATS).replaceAll(",", ", "));
});
});
  1. Change each auth call of the app with the table of The calls.
  1. Do the steps of The cutover.
Firebase authtempo
signInWithEmailAndPassword(auth, email, password) client.password.signIn({ email, password })
createUserWithEmailAndPassword(auth, email, password) client.password.signUp({ email, password })
sendSignInLinkToEmail(auth, email, settings) client.magicLink.request({ email })
signInWithPopup(auth, new GoogleAuthProvider()) Send the browser to /auth/social/google/start?next=/ on the API. There is no popup.
sendPasswordResetEmail(auth, email) client.password.requestReset({ email })
signOut(auth) client.signOut()
onAuthStateChanged(auth, callback) No event. Call client.session() after each sign-in and each sign-out.
user.getIdToken() client.jwt.token()
verifyIdToken(token) of the Admin SDK auth.session(request), or a check of the session JWT against /auth/jwks
  • rounds and mem_cost are each 1 to 99. The product of 2 to the power of mem_cost and rounds is at most 2 to the power of 18.
  • Other values stop the run before any read.
  • The export carries no hash parameters. A wrong value refuses every first sign-in with no line in the report.
  • A github.com provider imports as GitHub. A custom oidc.<name> provider is dropped and listed.
  • A user with a disabled value other than false is skipped.
  • Firebase passkeys do not move.
  • The command stops at start: rounds or mem_cost is out of bounds.
  • invalid_credentials for every imported user: a hash parameter of the project is wrong.
  • The API stops at construction: firescrypt is in formats without the firebase option.