From Auth.js
For: an operator and a developer who move an app from Auth.js to authtempo.
What it does: you read the tables of Auth.js into one JSON file, and import it into core’s tables. Then you change the app’s calls to @authtempo/client.
Before you start
Section titled “Before you start”- An API with authtempo. Set
passwordwhen the old app has a password column of its own. Do a getting started tutorial first. - The Auth.js tables on Postgres, with the Prisma names
User,Account, andAuthenticator. The command reads their export. @authtempo/cliand@authtempo/legacy-hashesin the app’s workspace. authtempo import is a command of the first.
Export
Section titled “Export”- Read the three tables into
tables.json, and keep the file private.
(umask 077; psql -At "$DATABASE_URL_OLD" -c "select json_build_object('users', (select coalesce(json_agg(json_build_object('id', u.id, 'email', u.email, 'emailVerified', u.\"emailVerified\" at time zone 'UTC', 'name', u.name, 'image', u.image, 'passwordHash', u.\"passwordHash\")), '[]') from \"User\" u), 'accounts', (select coalesce(json_agg(json_build_object('userId', a.\"userId\", 'type', a.type, 'provider', a.provider, 'providerAccountId', a.\"providerAccountId\")), '[]') from \"Account\" a), 'authenticators', (select coalesce(json_agg(json_build_object('credentialID', x.\"credentialID\", 'userId', x.\"userId\", 'credentialPublicKey', x.\"credentialPublicKey\", 'counter', x.counter, 'credentialDeviceType', x.\"credentialDeviceType\", 'credentialBackedUp', x.\"credentialBackedUp\", 'transports', x.transports)), '[]') from \"Authenticator\" x))" > tables.json)- Put the app’s own password column in the select in place of
passwordHash. - Remove that pair from the select when the app has no password column.
- When the
emailVerifiedcolumn is alreadytimestamptz, removeat time zone 'UTC'from the select.
Carry the passwords
Section titled “Carry the passwords”- Chain the legacy seam before core’s PBKDF2 in the API. Pass the format of the app’s hashes as
formats, such as["bcrypt"]. - With no password column, the seam has nothing to carry. Skip this phase.
// The API after the move of the guide "From Auth.js".import { createAuth, createPbkdf2PasswordHash, type MailPort, type StorageAdapter,} from "@authtempo/core";import { createLegacyPasswordHash, type LegacyFormat } from "@authtempo/legacy-hashes";
// Give `authtempo import authjs --formats` exactly this list.export const AUTHJS_FORMATS: readonly LegacyFormat[] = ["bcrypt"];
export function createAuthjsAuth(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: AUTHJS_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. Add
--same-passkey-rp-idonly when the new API keeps the old relying party id. - Check the
hashes:line against--formats. It counts the hash formats of the export, such ashashes: bcrypt 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 authjs --authjs-tables tables.json --formats bcrypt --password-column passwordHash --same-passkey-rp-id --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 authjs --authjs-tables tables.json --formats bcrypt --password-column passwordHash --same-passkey-rp-id --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 authjs --authjs-tables tables.json --formats bcrypt --password-column passwordHash --same-passkey-rp-id --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 { VECTORS } from "@authtempo/legacy-hashes/testing";import { describe, expect, it } from "vitest";import { call, harness } from "../support/harness.ts";import { AUTHJS_FORMATS, createAuthjsAuth } from "./authjs.ts";
// The fixture export of the Auth.js reader: Ida with the bcrypt2a vector in the app's password column.const f = FIXTURE_EXPORTS.authjs;const GUIDE = new URL("../../src/content/docs/docs/migrate/authjs.mdx", import.meta.url);
describe("move users from Auth.js", () => { 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: AUTHJS_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;
const auth = createAuthjsAuth(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); });
it("uses the formats of the fixture", () => { expect(AUTHJS_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(AUTHJS_FORMATS.join(",")); const arrays = [...guide.matchAll(/`(\["[^`]*\])`/g)].map((m) => m[1]); for (const a of arrays) expect(a).toBe(JSON.stringify(AUTHJS_FORMATS).replaceAll(",", ", ")); });
it("moves the passkey only with --same-passkey-rp-id", async () => { // The fixture has no authenticator row. This test adds one for Ida, in the columns of the guide's select. const tables = JSON.parse(f.bundle.files.tables ?? "{}") as { users: { id: string }[]; authenticators: unknown[]; }; const ida = tables.users[0]?.id ?? ""; tables.authenticators = [ { credentialID: "AQID", userId: ida, credentialPublicKey: "pQECAyYgASFYIPv/", counter: 7, credentialDeviceType: "multiDevice", credentialBackedUp: true, transports: "internal", }, ]; const files = { ...f.bundle.files, tables: JSON.stringify(tables) }; const passkeyRow = (storage: ReturnType<typeof harness>["storage"]) => storage.findOne("passkey", [{ field: "credentialId", op: "eq", value: "AQID" }]);
const h = harness(); const same = await importUsers( h.storage, await readSource({ ...f.bundle, files, samePasskeyRpId: true }), { formats: AUTHJS_FORMATS }, ); expect({ passkeys: same.created.passkey, dropped: same.dropped }).toEqual({ passkeys: 1, dropped: [], }); expect(await passkeyRow(h.storage)).not.toBeNull();
const other = harness(); // The same bundle with no samePasskeyRpId field, as a run without --same-passkey-rp-id writes it. const dropped = await importUsers(other.storage, await readSource({ ...f.bundle, files }), { formats: AUTHJS_FORMATS, }); expect({ passkeys: dropped.created.passkey, dropped: dropped.dropped }).toEqual({ passkeys: 0, dropped: [{ sourceId: ida, item: "passkey:rp_id_not_confirmed" }], }); expect(await passkeyRow(other.storage)).toBeNull(); });});- Delete
tables.jsonwithrm tables.json.
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.
- Delete the
tables.jsonof the new export after step 14 of the cutover. It holds the password hashes.
The calls
Section titled “The calls”| Auth.js | authtempo |
|---|---|
signIn("google") |
Send the browser to /auth/social/google/start?next=/ on the API. |
signIn("resend", { email }) |
client.magicLink.request({ email }) |
signIn("credentials", { email, password }) |
client.password.signIn({ email, password }) |
signOut() |
client.signOut() |
useSession(), getSession() |
client.session() |
auth(), getServerSession() on the server |
auth.session(request) |
How it behaves
Section titled “How it behaves”- The select leaves out the OAuth tokens of
Account. A refresh token gives access to the person’s account at the provider. - Without the time zone, every user imports unverified, and the report lists
email_verified:unreadable. - A passkey with a key, a counter, or a device field that core could not write is refused and listed.
- A credential id on two users imports on neither.
- Account rows other than
oauthandoidcare dropped and listed. - A
linkedinaccount of typeoidcimports as LinkedIn. One of typeoauthis listed asidentity:linkedin_legacy.
If it fails
Section titled “If it fails”- The command stops at start:
--password-columnnames a column that no row has. - The passkeys are dropped and listed: the run has no
--same-passkey-rp-id, or the relying party id changed. passkey_failed: the API runs on another relying party id than the old app.