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.
Before you start
Section titled “Before you start”- An API with authtempo and
passwordset. 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
roundsandmem_costas options. @authtempo/cliand@authtempo/legacy-hashesin the app’s workspace. authtempo import is a command of the first.
Export
Section titled “Export”- Export the users with
firebase auth:export users.json --format=json. - Read
rounds,mem_cost, the signer key, and the salt separator in the console.
Carry the passwords
Section titled “Carry the passwords”- Store the signer key and the salt separator as secrets of the API, not in the code.
- Chain the legacy seam before core’s PBKDF2. Pass
["firescrypt"]asformats, and the signer key and the salt separator asfirebase.
// 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(), }), }, });}Dry run
Section titled “Dry run”- Run the import as a dry run, with
roundsandmem_costof the project. - Check the
hashes:line against--formats. It counts the hash formats of the export, such ashashes: 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 ….
authtempo import firebase --users users.json --firebase-rounds 8 --firebase-mem-cost 14 --formats firescrypt --target postgres --url-env DATABASE_URL --dry-runRun 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.
- Make the copy. On Postgres, create an empty database, set
COPY_URLto its URL, and load the real one into it withpg_dump --no-owner "$DATABASE_URL" | psql "$COPY_URL". - On D1, load the real database into the empty local copy of the import Worker with
wrangler d1 export <database> --remote --output copy.sqlandwrangler d1 execute <database> --local --file copy.sql. - Run both in the folder of the import Worker. Delete its
.wrangler/statefirst, or the load stops on a table that exists. - 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.
authtempo import firebase --users users.json --firebase-rounds 8 --firebase-mem-cost 14 --formats firescrypt --target postgres --url-env COPY_URLVerify
Section titled “Verify”- Run
authtempo import verifywith the same files on the copy. It exits 0 only when the copy holds the whole export. - Run
authtempo check <base url>against the API. - 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.
- Drop the copy, and on D1 delete
copy.sql, whenimport verifyexits 0. The copy holds every user of the export.
authtempo import verify firebase --users users.json --firebase-rounds 8 --firebase-mem-cost 14 --formats firescrypt --target postgres --url-env COPY_URLauthtempo check https://api.example.comimport { 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(",", ", ")); });});Change the calls
Section titled “Change the calls”- Change each auth call of the app with the table of The calls.
Cut over
Section titled “Cut over”- Do the steps of The cutover.
The calls
Section titled “The calls”| 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 |
How it behaves
Section titled “How it behaves”roundsandmem_costare each 1 to 99. The product of 2 to the power ofmem_costandroundsis 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.comprovider imports as GitHub. A customoidc.<name>provider is dropped and listed. - A user with a
disabledvalue other thanfalseis skipped. - Firebase passkeys do not move.
If it fails
Section titled “If it fails”- The command stops at start:
roundsormem_costis out of bounds. invalid_credentialsfor every imported user: a hash parameter of the project is wrong.- The API stops at construction:
firescryptis informatswithout thefirebaseoption.