From Supabase Auth
For: an operator and a developer who move an app from Supabase Auth to authtempo.
What it does: you export two tables of Supabase, import them into core’s tables, and change the app’s calls of supabase.auth to @authtempo/client.
Before you start
Section titled “Before you start”- An API with authtempo and
passwordset. Do a getting started tutorial first. - Access to the Supabase database with
psql. The Admin API returns no hash. The command reads the export. @authtempo/cliand@authtempo/legacy-hashesin the app’s workspace. authtempo import is a command of the first.
Export
Section titled “Export”- Export the users and the identities of Supabase as two CSV files.
psql "$SUPABASE_DB_URL" -c "\copy (select id, email, encrypted_password, email_confirmed_at, raw_user_meta_data, created_at, is_anonymous, deleted_at, banned_until, is_sso_user from auth.users) to 'users.csv' with csv header"psql "$SUPABASE_DB_URL" -c "\copy (select provider, provider_id, user_id from auth.identities) to 'identities.csv' with csv header"Carry the passwords
Section titled “Carry the passwords”- Chain the legacy seam before core’s PBKDF2 in the API. Pass
["bcrypt", "argon2id"]asformats.
// The API after the move of the guide "From Supabase Auth".import { createAuth, createPbkdf2PasswordHash, type MailPort, type StorageAdapter,} from "@authtempo/core";import { createLegacyPasswordHash, type LegacyFormat } from "@authtempo/legacy-hashes";
// Give `authtempo import supabase --formats` exactly this list.export const SUPABASE_FORMATS: readonly LegacyFormat[] = ["bcrypt", "argon2id"];
export function createSupabaseAuth(deps: { storage: StorageAdapter; mail: MailPort; secret: string;}) { 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: SUPABASE_FORMATS, // 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, and read the report.
- Check the
hashes:line against--formats. It counts the hash formats of the export, such ashashes: bcrypt 812, argon2id 4, 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 supabase --users users.csv --identities identities.csv --formats bcrypt,argon2id --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 supabase --users users.csv --identities identities.csv --formats bcrypt,argon2id --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 supabase --users users.csv --identities identities.csv --formats bcrypt,argon2id --target postgres --url-env COPY_URLauthtempo check https://api.example.comThe test below imports two Supabase users and signs each one in with the old password.
import { readFileSync } from "node:fs";import { importUsers, readSource } from "@authtempo/import";import { FIXTURE_EXPORTS } from "@authtempo/import/testing";import { VECTORS } from "@authtempo/legacy-hashes/testing";import { describe, expect, it } from "vitest";import { call, harness } from "../support/harness.ts";import { createSupabaseAuth, SUPABASE_FORMATS } from "./supabase.ts";
// The fixture export of the Supabase reader: Ada with the bcrypt2a vector, Bob with argon2id.const f = FIXTURE_EXPORTS.supabase;const GUIDE = new URL("../../src/content/docs/docs/migrate/supabase.mdx", import.meta.url);
describe("move users from Supabase 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: SUPABASE_FORMATS, }); expect({ passwords: report.created.password, refused: report.refusedHashes }).toEqual({ passwords: 2, refused: [], }); if (f.signIn === null) throw new Error("the fixture names no user that signs in"); const { email, password } = f.signIn;
const auth = createSupabaseAuth(h); const signIn = (p: string) => call(auth, "POST", "/auth/password/sign-in", { email, password: p }); expect((await signIn(VECTORS.bcrypt2a.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);
// Bob proves the argon2id half of the seam. const signInBob = (p: string) => call(auth, "POST", "/auth/password/sign-in", { email: "bob@example.com", password: p }); expect((await signInBob(VECTORS.argon2id.wrong)).status).toBe(401); const bob = await signInBob(VECTORS.argon2id.password); expect(bob.status).toBe(200); const { user: bobUser } = (await bob.json()) as { user: { id: string } }; const bobRow = await h.storage.findOne("password", [ { field: "userId", op: "eq", value: bobUser.id }, ]); expect(bobRow?.hash.startsWith("pbkdf2-sha256$")).toBe(true); });
it("uses the formats of the fixture", () => { expect(SUPABASE_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(SUPABASE_FORMATS.join(",")); const arrays = [...guide.matchAll(/`(\["[^`]*\])`/g)].map((m) => m[1]); for (const a of arrays) expect(a).toBe(JSON.stringify(SUPABASE_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”| Supabase | authtempo |
|---|---|
supabase.auth.signInWithOtp({ email }) |
client.magicLink.request({ email }) |
supabase.auth.signInWithPassword({ email, password }) |
client.password.signIn({ email, password }) |
supabase.auth.signUp({ email, password }) |
client.password.signUp({ email, password }) |
supabase.auth.signInWithOAuth({ provider: "google" }) |
Send the browser to /auth/social/google/start?next=/ on the API. |
supabase.auth.resetPasswordForEmail(email) |
client.password.requestReset({ email }) |
supabase.auth.updateUser({ password }) |
client.password.change({ newPassword }) |
supabase.auth.getSession(), supabase.auth.getUser() |
client.session() |
supabase.auth.signOut() |
client.signOut() |
supabase.auth.onAuthStateChange(callback) |
No event. Call client.session() after each sign-in and each sign-out. |
supabase.auth.getUser(jwt) on the server |
auth.session(request) |
A policy of row level security that reads auth.uid() does not move. Check the user in the API with auth.session, or mint a session JWT for the database.
How it behaves
Section titled “How it behaves”- A user with
email_confirmed_atset imports verified. Every other user imports unverified. - An SSO user is skipped as
sso_user, and a banned user asbanned. The command still exits 0 for them. - A phone-only user has no address and is skipped as
no_email. - The
githubprovider imports as GitHub, andlinkedin_oidcas LinkedIn. The olderlinkedinprovider is listed asidentity:linkedin_legacy. - A row with the tag
$fbscrypt$needs--firebase-signer-key-env,--firebase-salt-separator, andfirescryptin--formats. Give the same two values as the seam’sfirebaseoption. - Supabase passkeys do not move.
If it fails
Section titled “If it fails”- The command exits 1: a person must look at a refused hash, a refused record, a conflict, or a
partialrecord. The exit status lists each. - The command stops before any read: a column of the select is missing from the CSV header.
invalid_credentials: the hash format is not in the seam’sformats, or the password is wrong.