diff --git a/.changeset/workos-password-hashes.md b/.changeset/workos-password-hashes.md new file mode 100644 index 000000000..2a5079217 --- /dev/null +++ b/.changeset/workos-password-hashes.md @@ -0,0 +1,5 @@ +--- +"clerk": minor +--- + +Add `--password-hashes ` to `clerk migrate export workos`. It takes the password hash CSV that WorkOS support sends and adds each hash to the user with the same email, so imported users keep their WorkOS passwords. The `workos` source picks the hasher for each user from the hash prefix: bcrypt, argon2, and pbkdf2 carry over. Users with other formats, such as `$bcrypt-ssha$`, `$scrypt$`, or `$argon2d$`, reset their password. diff --git a/packages/cli-core/src/commands/migrate/README.md b/packages/cli-core/src/commands/migrate/README.md index d85e5fd92..84d2f1ffc 100644 --- a/packages/cli-core/src/commands/migrate/README.md +++ b/packages/cli-core/src/commands/migrate/README.md @@ -239,6 +239,7 @@ clerk migrate export authjs --db-url "mysql://user:...@127.0.0.1:3306/authjs" clerk migrate export betterauth --db-url "./db.sqlite" clerk migrate export firebase --service-account ./service-account.json clerk migrate export workos --api-key sk_… +clerk migrate export workos --password-hashes ./workos-password-hashes.csv ``` The platform is an optional positional. Omitted, you get a picker built from @@ -327,6 +328,7 @@ keep `--runs-dir`: the import looks the run ID up there. | `--api-key ` | `workos` | WorkOS secret API key, the one starting `sk_` | | `--with-identities` | `workos` | Also record each user's OAuth providers | | `--no-with-identities` | `workos` | Skip the OAuth provider fan-out without being asked | +| `--password-hashes ` | `workos` | CSV of password hashes from a WorkOS support request | | `--trust-oauth-emails` | `authjs` | Mark the email of a user who signs in with OAuth verified | `export clerk` also takes the targeting flags — it reads from a Clerk instance, @@ -411,9 +413,11 @@ alongside imports. `auth0|` plus `alt_id`, or `_id` when there's no `alt_id`. Copy each `passwordHash` onto the matching user before importing, or migrate without passwords. -- **WorkOS** returns neither password hashes nor TOTP secrets over the API: - hashes go in on import and never come back, and `totp.secret` is returned on - enrol only. WorkOS documents no other way to get them out. +- **WorkOS** returns neither password hashes nor TOTP secrets over the API, + and returns `totp.secret` on enrol only. Hashes come only from a support + request, as a CSV that `--password-hashes` merges in (see + [WorkOS password hashes](#workos-password-hashes)). Without it, every + password user resets. - **Auth.js** core stores no passwords. An app that also uses the Credentials provider stores them wherever it chose to, which the export does not read, even a password column on the user table: migrate those separately, or have @@ -421,8 +425,8 @@ alongside imports. Each prints a warning whenever it exports anyone. `clerk`'s and `workos`'s coverage also counts users who _have_ a password, so the size of the gap is -visible up front — `workos` prints that row at zero unconditionally, because -zero is the only value it can take. +visible up front — without `--password-hashes`, `workos` prints that row at +zero and names the flag. #### Database-backed exports (`supabase`, `authjs`, `betterauth`) @@ -673,7 +677,7 @@ table, not as extra coverage rows: ``` Field coverage ✓ 6/6 have an email address - ✗ 0/6 have a password (WorkOS returns none) + ✗ 0/6 have a password hash (needs --password-hashes) OAuth providers GoogleOAuth 2 users @@ -702,6 +706,62 @@ and every 10 pages during the user fetch. `withSpinner` hands a no-op to anything that is not a TTY, so without this an agent exporting a large tenant would see nothing at all until the run finished. +#### WorkOS password hashes + +The API returns no hashes, but WorkOS support sends them on request, as a CSV +of `email,password_hash,first_name,last_name` +([WorkOS's export guide](https://workos.com/docs/migrate/export-from-workos)). +That file can't be imported on its own: it has no WorkOS `id`, which re-runs +match on, and no `email_verified`, metadata, or `created_at`. +`--password-hashes ` reads it and copies each `password_hash` onto the +API user with the same email, ignoring case. + +```sh +clerk migrate export workos --password-hashes ./workos-password-hashes.csv +``` + +- The file is read before any request, so a wrong path fails without calling + WorkOS. +- It is parsed as CSV, not split on commas: WorkOS warns that some hashes + contain them. +- Rows whose email matches no WorkOS user are counted in a warning and left + out. That usually means the CSV is from another WorkOS environment. +- The coverage row becomes `have a password hash`, counting the users the CSV + matched. + +The flag is on the export, not the import, because an import run is matched +by the export file's sha256 (see [Re-running](#re-running)). A CSV passed at +import time would leave that match unchanged, and a re-run would say +"Already imported". The hashes land in `export.json` inside the gitignored run +folder, as Better Auth's do. + +The `workos` source then names the hasher per user from the hash prefix: + +| WorkOS prefix | `passwordHasher` | +| ----------------------------------------- | --------------------------------------------------------------- | +| `$2a$`, `$2b$`, `$2y$` (cost 4 to 15) | `bcrypt` | +| `$argon2id$`, `$argon2i$` (`v=19`) | `argon2id`, `argon2i` | +| `$pbkdf2$` (`d=sha256`, `sha512`, `sha1`) | `pbkdf2_sha256`, `pbkdf2_sha512_hex`, `pbkdf2_sha1`, re-encoded | + +Passwords set in WorkOS, at signup or reset, are bcrypt at cost 10, so the +first row covers most users. bcrypt and argon2 go to Clerk unchanged. +`$pbkdf2$` is rewritten into the matching Clerk layout: padded base64 for +`pbkdf2_sha256`, hex for the others. + +Anything else is dropped, and that user is imported without a password and +resets it. The checks count these users, the same as Better Auth's. + +- `$bcrypt-pbkdf2-sha1$`, `$bcrypt-pbkdf2-sha256$`, `$bcrypt-ssha$`, + `$bcrypt-ssha256$`, and `$scrypt$`: WorkOS's own layouts, which no Clerk + hasher reads yet. +- `$argon2d$`: Go's argon2 package has no argon2d. +- `$firebase-scrypt$`: not converted yet. +- `$pbkdf2$` sha256 whose key isn't 32 bytes, the only length `pbkdf2_sha256` + derives. +- `$pbkdf2$` sha512 over 420,000 iterations, or with a key shorter than 16 + bytes: `pbkdf2_sha512_hex`'s limits. +- bcrypt outside cost 4 to 15, and any other prefix. + ### `clerk migrate import` Reads an exported user file, maps it onto Clerk's user schema, checks every @@ -1245,7 +1305,7 @@ brings across. Adding a platform is one file in `sources/` plus one line in | `betterauth` | Better Auth export | yes | no | no | | `firebase` | `firebase auth:export` | yes | no | no | | `supabase` | Supabase `auth.users` export | yes | no | partial | -| `workos` | WorkOS User Management API | no | no | yes | +| `workos` | WorkOS User Management API | partial | no | yes | There is no column for social sign-ins, because no source copies them and none needs to. Every source shows the same note instead: enable the same providers in diff --git a/packages/cli-core/src/commands/migrate/export/index.ts b/packages/cli-core/src/commands/migrate/export/index.ts index 1b0f9b2b0..ac45bcfea 100644 --- a/packages/cli-core/src/commands/migrate/export/index.ts +++ b/packages/cli-core/src/commands/migrate/export/index.ts @@ -218,6 +218,10 @@ export function registerMigrateExport(migrateCommand: Command<[], Record", + "CSV of password hashes from a WorkOS support request, merged in by email", + ) .option("-o, --output ", "Write the export here instead of the run folder") .option( "-y, --yes", @@ -230,6 +234,10 @@ export function registerMigrateExport(migrateCommand: Command<[], Record exportWorkOs(options), }, diff --git a/packages/cli-core/src/commands/migrate/export/workos.test.ts b/packages/cli-core/src/commands/migrate/export/workos.test.ts index 2c98243ae..543f08c9b 100644 --- a/packages/cli-core/src/commands/migrate/export/workos.test.ts +++ b/packages/cli-core/src/commands/migrate/export/workos.test.ts @@ -523,13 +523,32 @@ describe("buildWorkOsExport", () => { expect(lines.map((line) => line.status)).toEqual(["exported", "exported"]); }); - // Always shown, always zero: seeing it before the import is the point. - test("reports the password row even though it can only ever be zero", () => { - const { coverage } = buildWorkOsExport([workosUser(0)]); + // Always shown: seeing zero before the import is the point. + test("reports the password row at zero, naming the flag, without the CSV", () => { + const { coverage, unmatchedHashes } = buildWorkOsExport([workosUser(0)]); expect(coverage.at(-1)).toEqual({ - label: "have a password (WorkOS returns none)", + label: "have a password hash (needs --password-hashes)", count: 0, }); + expect(unmatchedHashes).toBe(0); + }); + + test("merges CSV hashes by email, ignoring case, and counts the leftovers", () => { + const hashes = new Map([ + ["a0@x.dev", "$2b$10$hash0"], + ["gone@x.dev", "$2b$10$gone"], + ]); + const { users, coverage, unmatchedHashes } = buildWorkOsExport( + [workosUser(0, { email: "A0@X.dev" }), workosUser(1)], + undefined, + undefined, + hashes, + ); + + expect(users[0]?.password_hash).toBe("$2b$10$hash0"); + expect("password_hash" in (users[1] ?? {})).toBe(false); + expect(coverage.at(-1)).toEqual({ label: "have a password hash", count: 1 }); + expect(unmatchedHashes).toBe(1); }); // Providers get their own block: a coverage row means "N of M users have @@ -613,10 +632,54 @@ describe("exportWorkOs", () => { }); // Finding this out after the import means nobody can sign in. - test("says plainly that no credentials are in the file", async () => { + test("says plainly that no credentials are in the file, and how to add them", async () => { stubWorkOs([[workosUser(0)]]); await exportWorkOs({ apiKey: API_KEY, output: "warned.json" }); expect(captured.err).toContain("does not return password hashes or TOTP secrets"); + expect(captured.err).toContain("--password-hashes"); + }); + + // WorkOS warns that some hashes contain commas. + test("--password-hashes merges the support CSV into the file", async () => { + stubWorkOs([[workosUser(0), workosUser(1)]]); + fs.writeFileSync( + path.join(workDir, "hashes.csv"), + 'email,password_hash,first_name,last_name\nA0@x.dev,"$pbkdf2$i=600000,d=sha256$c2FsdA$a2V5",Given0,Family0\nstranger@x.dev,$2b$10$x,S,T\n', + ); + + await exportWorkOs({ apiKey: API_KEY, output: "hashed.json", passwordHashes: "hashes.csv" }); + + const written = ( + JSON.parse(fs.readFileSync(path.join(workDir, "hashed.json"), "utf-8")) as { + users: Record[]; + } + ).users; + expect(written[0]?.password_hash).toBe("$pbkdf2$i=600000,d=sha256$c2FsdA$a2V5"); + expect("password_hash" in (written[1] ?? {})).toBe(false); + expect(captured.err).toContain("1/2 have a password hash"); + expect(captured.err).toContain("1 row in hashes.csv matched no WorkOS user"); + expect(captured.err).not.toContain("does not return password hashes"); + }); + + // A directory passes the existence check, then fails when the stream reads it. + test("--password-hashes rejects an unreadable path instead of crashing", async () => { + fs.mkdirSync(path.join(workDir, "not-a-file.csv"), { recursive: true }); + stubWorkOs([[workosUser(0)]]); + const error = await exportWorkOs({ apiKey: API_KEY, passwordHashes: "not-a-file.csv" }).catch( + (caught: unknown) => caught, + ); + expect((error as NodeJS.ErrnoException).code).toBe("EISDIR"); + expect(requests).toHaveLength(0); + }); + + test("--password-hashes fails on a missing file before calling WorkOS", async () => { + stubWorkOs([[workosUser(0)]]); + const error = await exportWorkOs({ apiKey: API_KEY, passwordHashes: "nope.csv" }).catch( + (caught: unknown) => caught, + ); + expect(error).toBeInstanceOf(CliError); + expect((error as CliError).message).toContain("No password hash file at"); + expect(requests).toHaveLength(0); }); }); diff --git a/packages/cli-core/src/commands/migrate/export/workos.ts b/packages/cli-core/src/commands/migrate/export/workos.ts index af1739ded..67f4626fd 100644 --- a/packages/cli-core/src/commands/migrate/export/workos.ts +++ b/packages/cli-core/src/commands/migrate/export/workos.ts @@ -6,17 +6,23 @@ * everything the command sends shows up under `--verbose`. See the header of * `auth0.ts` and `.claude/rules/debug-logging.md`. * - * **WorkOS is API-only, and no credential leaves it.** There is no + * **WorkOS is API-only, and its API returns no credentials.** There is no * bring-your-own-database option — apps mirror WorkOS users into their own * store through webhooks, but that mirror is a derived copy holding no secrets, - * which is why this has no `--db-url` sibling. Password hashes are accepted on - * import and never returned; TOTP secrets come back on enrol only, never on - * list or get. So a WorkOS migration moves identities, and every password user - * signs in again by reset. The run says so rather than leaving it to be - * discovered when nobody can sign in. + * which is why this has no `--db-url` sibling. The API never returns password + * hashes, and returns TOTP secrets on enrol only, never on list or get. + * + * Password hashes come only from WorkOS support, as a CSV of + * `email,password_hash,first_name,last_name`. That file has no WorkOS ID, + * verification state, or metadata, so it can't be imported on its own: + * `--password-hashes` merges it into the API's users by email. Without it, + * every password user signs in again by reset, and the run says so rather + * than leaving it to be discovered when nobody can sign in. */ -import { ApiError, CliError, EXIT_CODE, throwUsageError } from "../../../lib/errors.ts"; +import fs from "node:fs"; +import path from "node:path"; +import { ApiError, CliError, ERROR_CODE, EXIT_CODE, throwUsageError } from "../../../lib/errors.ts"; import { loggedFetch } from "../../../lib/fetch.ts"; import { dim } from "../../../lib/color.ts"; import { log } from "../../../lib/log.ts"; @@ -30,6 +36,8 @@ import { isAssumeYes } from "../lib/assume-yes.ts"; import { throwApiFailure, withInputRetry } from "../lib/input-retry.ts"; import { RateLimitExceededError, retryOn429 } from "../lib/retry.ts"; import { createApiScheduler } from "../lib/scheduler.ts"; +import { plural } from "../lib/plural.ts"; +import { readCsv } from "../lib/transform.ts"; import { finishExport, startExportRun, type ExportSection } from "./shared.ts"; const API_BASE = "https://api.workos.com/user_management"; @@ -71,8 +79,44 @@ export type ExportWorkOsOptions = { runsDir?: string; /** Print the result as JSON on stdout; never prompts. */ json?: boolean; + /** The CSV of password hashes WorkOS support sends, merged in by email. */ + passwordHashes?: string; }; +/** Lowercased, so the CSV and the API needn't agree on case. */ +const emailKey = (email: unknown) => + String(email ?? "") + .trim() + .toLowerCase(); + +/** + * Reads the CSV WorkOS support sends, keyed by email. + * + * A CSV parser rather than a split on commas: WorkOS warns that some hashes + * contain commas. Rows without an email or a hash are skipped. + * + * @throws CliError when the file is missing, before any request is sent. + */ +export async function readWorkOsPasswordHashes(file: string): Promise> { + const resolved = path.resolve(process.cwd(), file); + if (!fs.existsSync(resolved)) { + throw new CliError(`No password hash file at ${resolved}.`, { + code: ERROR_CODE.FILE_NOT_FOUND, + docsUrl: DOCS_URL, + }); + } + + const hashes = new Map(); + // ponytail: a repeated email keeps its last hash; WorkOS emails are unique + // per environment, so this only matters for a CSV spanning environments. + for (const row of await readCsv(resolved)) { + const email = emailKey(row.email); + const hash = String(row.password_hash ?? "").trim(); + if (email && hash) hashes.set(email, hash); + } + return hashes; +} + export type WorkOsUser = Record & { id?: string }; export type WorkOsIdentity = { idp_id?: string; type?: string; provider?: string }; @@ -412,7 +456,7 @@ export function buildIdentityReport( /** * Keeps the fields the `workos` transformer maps from, plus `identities` when - * they were fetched. + * they were fetched and `password_hash` when the support CSV had one. * * A copy rather than the raw record: WorkOS also returns `locale`, * `profile_picture_url`, `last_sign_in_at`, and `updated_at`, which the import @@ -423,6 +467,7 @@ export function buildIdentityReport( export function mapWorkOsUserToExport( user: WorkOsUser, identities?: WorkOsIdentity[], + passwordHash?: string, ): Record { const exported: Record = {}; @@ -448,32 +493,46 @@ export function mapWorkOsUserToExport( if (identities && identities.length > 0) exported.identities = identities; + if (passwordHash) exported.password_hash = passwordHash; + return exported; } export type WorkOsExportResult = { users: Record[]; coverage: { label: string; count: number }[]; + /** CSV rows whose email matched no WorkOS user. */ + unmatchedHashes: number; }; +/** + * @param hashes - The support CSV by lowercased email, when `--password-hashes` + * was passed. + */ export function buildWorkOsExport( users: WorkOsUser[], record: (line: UserLine) => void = () => {}, identities?: Map, + hashes?: Map, ): WorkOsExportResult { const exported: Record[] = []; - const counts = { email: 0, firstName: 0, lastName: 0, metadata: 0 }; + const counts = { email: 0, firstName: 0, lastName: 0, metadata: 0, password: 0 }; + const matched = new Set(); for (const user of users) { const userId = String(user.id ?? ""); try { - const mapped = mapWorkOsUserToExport(user, identities?.get(userId)); + const key = emailKey(user.email); + const hash = hashes?.get(key); + if (hash) matched.add(key); + const mapped = mapWorkOsUserToExport(user, identities?.get(userId), hash); exported.push(mapped); if (mapped.email) counts.email++; if (mapped.first_name) counts.firstName++; if (mapped.last_name) counts.lastName++; if (mapped.metadata) counts.metadata++; + if (mapped.password_hash) counts.password++; record({ sourceId: userId, status: "exported" }); } catch (error) { @@ -488,14 +547,22 @@ export function buildWorkOsExport( { label: "have a first name", count: counts.firstName }, { label: "have a last name", count: counts.lastName }, { label: "have metadata", count: counts.metadata }, - // Always present, always zero. WorkOS returns no digest for anyone, and - // seeing that before the import is the whole reason the row is here. - { label: "have a password (WorkOS returns none)", count: 0 }, + // Always present: zero without the CSV, and seeing that before the + // import is the whole reason the row is here. + { + label: hashes ? "have a password hash" : "have a password hash (needs --password-hashes)", + count: counts.password, + }, ], + unmatchedHashes: hashes ? hashes.size - matched.size : 0, }; } export async function exportWorkOs(options: ExportWorkOsOptions): Promise { + // Read first, so a wrong path fails before any request is sent. + const hashes = options.passwordHashes + ? await readWorkOsPasswordHashes(options.passwordHashes) + : undefined; const resolved = await resolveWorkOsApiKey(options); await withGutter("Exporting users from WorkOS", async () => { @@ -522,11 +589,11 @@ export async function exportWorkOs(options: ExportWorkOsOptions): Promise : undefined; const run = await startExportRun(options, { platform: "workos" }); - const { users: exported, coverage } = buildWorkOsExport( - users, - run.append, - providers?.identities, - ); + const { + users: exported, + coverage, + unmatchedHashes, + } = buildWorkOsExport(users, run.append, providers?.identities, hashes); finishExport({ run, options, @@ -537,9 +604,18 @@ export async function exportWorkOs(options: ExportWorkOsOptions): Promise : [], }); + if (unmatchedHashes > 0) { + log.warn( + `${plural(unmatchedHashes, "row")} in ${options.passwordHashes} matched no WorkOS user by email, so the export left those hashes out. Check that the CSV is from the same WorkOS environment as the API key.`, + ); + } + if (exported.length > 0) { + const passwords = hashes + ? "WorkOS's API does not return TOTP secrets. Imported users whose hash is missing from the CSV, or is in a format Clerk can't verify, must reset their password on their first Clerk sign-in." + : "WorkOS's API does not return password hashes or TOTP secrets. Imported users who signed in with a password must reset it on their first Clerk sign-in. To keep their passwords, ask WorkOS support for a password hash export and pass the CSV with --password-hashes."; log.warn( - "WorkOS's API does not return password hashes or TOTP secrets. Imported users who signed in with a password must reset it on their first Clerk sign-in, and anyone using an authenticator app has to re-enrol. SSO and social users don't need a reset, but set up those providers in Clerk first: social accounts link by verified email, and SSO needs an enterprise connection.", + `${passwords} Anyone using an authenticator app has to re-enrol. SSO and social users don't need a reset, but set up those providers in Clerk first: social accounts link by verified email, and SSO needs an enterprise connection.`, ); log.info(dim(`See ${DOCS_URL}`)); } diff --git a/packages/cli-core/src/commands/migrate/index.test.ts b/packages/cli-core/src/commands/migrate/index.test.ts index 5439c07c4..127d36805 100644 --- a/packages/cli-core/src/commands/migrate/index.test.ts +++ b/packages/cli-core/src/commands/migrate/index.test.ts @@ -128,6 +128,7 @@ describe("registerMigrate", () => { "--api-key", "--with-identities", "--no-with-identities", + "--password-hashes", "--output", "--yes", "--runs-dir", diff --git a/packages/cli-core/src/commands/migrate/lib/transform.ts b/packages/cli-core/src/commands/migrate/lib/transform.ts index b5ce1b597..36fdf12cf 100644 --- a/packages/cli-core/src/commands/migrate/lib/transform.ts +++ b/packages/cli-core/src/commands/migrate/lib/transform.ts @@ -437,10 +437,16 @@ export function transformUsers( * * @param headers - Column names, for a CSV with no header row. */ -async function readCsv(filePath: string, headers?: string[]): Promise[]> { +export async function readCsv( + filePath: string, + headers?: string[], +): Promise[]> { return new Promise((resolve, reject) => { const users: Record[] = []; fs.createReadStream(filePath) + // pipe() doesn't forward read errors (a directory, a revoked + // permission), so the file stream rejects on its own. + .on("error", reject) // Excel's "CSV UTF-8" starts with a BOM, which would otherwise become // part of the first header and hide that column from every row. .pipe( diff --git a/packages/cli-core/src/commands/migrate/sources/sources.test.ts b/packages/cli-core/src/commands/migrate/sources/sources.test.ts index 3fe7bcb5a..276e7b030 100644 --- a/packages/cli-core/src/commands/migrate/sources/sources.test.ts +++ b/packages/cli-core/src/commands/migrate/sources/sources.test.ts @@ -8,6 +8,10 @@ import type { FirebaseHashConfig, User } from "../types.ts"; import { isAuthJsVerified } from "./authjs.ts"; import { getSource, isSourcePath, sourceKeys, sources } from "./registry.ts"; import { isVerified, toIsoDate } from "./shared.ts"; +import { detectWorkOsHash } from "./workos.ts"; + +const BCRYPT = "$2b$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy"; +const ARGON2ID = "$argon2id$v=19$m=65536,t=3,p=4$c29tZXNhbHQ$RdescudvJCsgt3ub+b+dWRWJTmaaJObG"; const FIREBASE_HASH: FirebaseHashConfig = { base64_signer_key: "SIGNERKEY==", @@ -296,12 +300,36 @@ describe("workos", () => { expect("workosExternalId" in (users[0] ?? {})).toBe(false); }); - // No other transformer omits it. WorkOS never returns a digest, so naming a - // hasher would imply a password column that cannot exist. - test("names no password hasher, because WorkOS returns no hashes", () => { + // One support CSV can hold several formats, so the hasher is set per user. + test("names no default password hasher", () => { expect(getSource("workos").defaults).toBeUndefined(); }); + test("sets the hasher from a merged password_hash", () => { + const user = one("workos", { ...base, email_verified: true, password_hash: BCRYPT }); + expect(user?.password).toBe(BCRYPT); + expect(user?.passwordHasher).toBe("bcrypt"); + expect(user?.passwordDropped).toBeUndefined(); + }); + + // The user is still imported, and resets their password. + test("drops a hash Clerk can't verify, and flags it", () => { + const user = one("workos", { + ...base, + email_verified: true, + password_hash: ARGON2ID.replace("argon2id", "argon2d"), + }); + expect(user?.password).toBeUndefined(); + expect(user?.passwordHasher).toBeUndefined(); + expect(user?.passwordDropped).toBe(true); + }); + + test("leaves a user without a hash alone", () => { + const user = one("workos", { ...base, email_verified: true }); + expect(user?.password).toBeUndefined(); + expect(user?.passwordDropped).toBeUndefined(); + }); + // The export carries these so whoever runs the migration can see who used // social sign-in; Clerk's import has no field for them. test("drops OAuth identities carried through from the export", async () => { @@ -313,6 +341,74 @@ describe("workos", () => { }); }); +describe("detectWorkOsHash", () => { + // WorkOS trims base64 padding; Clerk's pbkdf2_sha256 wants it back. + const b64 = (bytes: Buffer) => bytes.toString("base64").replace(/=+$/, ""); + const salt = Buffer.from("sixteen-byte-slt"); + const key = (bytes: number) => Buffer.alloc(bytes, 7); + const wrapped = b64(Buffer.from(BCRYPT)); + + test.each([ + ["bcrypt", BCRYPT, "bcrypt"], + ["argon2id", ARGON2ID, "argon2id"], + ["argon2i", ARGON2ID.replace("argon2id", "argon2i"), "argon2i"], + ])("sends %s unchanged", (_, hash, hasher) => { + expect(detectWorkOsHash(hash)).toEqual({ password: hash, passwordHasher: hasher }); + }); + + test.each([ + [ + "sha256", + `$pbkdf2$i=600000,d=sha256$${b64(salt)}$${b64(key(32))}`, + `pbkdf2_sha256$600000$${salt.toString("base64")}$${key(32).toString("base64")}`, + "pbkdf2_sha256", + ], + [ + "sha256 with the params reversed", + `$pbkdf2$d=sha256,i=600000$${b64(salt)}$${b64(key(32))}`, + `pbkdf2_sha256$600000$${salt.toString("base64")}$${key(32).toString("base64")}`, + "pbkdf2_sha256", + ], + [ + "sha512", + `$pbkdf2$i=210000,d=sha512$${b64(salt)}$${b64(key(64))}`, + `pbkdf2_sha512_hex$210000$${salt.toString("hex")}$${key(64).toString("hex")}`, + "pbkdf2_sha512_hex", + ], + [ + "sha1", + `$pbkdf2$i=1000,d=sha1$${b64(salt)}$${b64(key(20))}`, + `pbkdf2_sha1$1000$${salt.toString("hex")}$${key(20).toString("hex")}$20`, + "pbkdf2_sha1", + ], + ])("rewrites pbkdf2 %s into Clerk's layout", (_, hash, password, hasher) => { + expect(detectWorkOsHash(hash)).toEqual({ password, passwordHasher: hasher }); + }); + + test.each([ + ["argon2d", ARGON2ID.replace("argon2id", "argon2d")], + ["firebase-scrypt", `$firebase-scrypt$v=1$r=8,m=14,ss=Bw,sk=c2lnbmVy$${b64(salt)}$abc`], + // Until clerk_go's `_workos` hashers ship (DOCS-12473, DOCS-12484). + ["bcrypt-pbkdf2-sha1", `$bcrypt-pbkdf2-sha1$v=1$i=1000,kl=20$${b64(salt)}$${wrapped}`], + ["bcrypt-pbkdf2-sha256", `$bcrypt-pbkdf2-sha256$v=1$i=1000,kl=32$${b64(salt)}$${wrapped}`], + ["bcrypt-ssha", `$bcrypt-ssha$v=1$${b64(salt)}$${wrapped}`], + ["bcrypt-ssha256", `$bcrypt-ssha256$v=1$sp=prefix$${b64(salt)}$${wrapped}`], + ["scrypt", `$scrypt$v=1$n=16384,r=8,p=1,kl=64$${b64(salt)}$${b64(key(64))}`], + ["pbkdf2 sha256 with a 36-byte key", `$pbkdf2$i=600000,d=sha256$${b64(salt)}$${b64(key(36))}`], + [ + "pbkdf2 sha512 over 420,000 iterations", + `$pbkdf2$i=500000,d=sha512$${b64(salt)}$${b64(key(64))}`, + ], + ["pbkdf2 sha512 with an 8-byte key", `$pbkdf2$i=210000,d=sha512$${b64(salt)}$${b64(key(8))}`], + ["pbkdf2 without iterations", `$pbkdf2$d=sha256$${b64(salt)}$${b64(key(32))}`], + ["pbkdf2 with an unknown digest", `$pbkdf2$i=1000,d=md5$${b64(salt)}$${b64(key(16))}`], + ["bcrypt over Clerk's cost cap", BCRYPT.replace("$10$", "$31$")], + ["plain SSHA", "{SSHA}c29tZWhhc2hzb21lc2FsdA=="], + ])("drops %s", (_, hash) => { + expect(detectWorkOsHash(hash)).toBeUndefined(); + }); +}); + describe("authjs", () => { const base = { id: "cuid1", email: "a@x.dev" }; diff --git a/packages/cli-core/src/commands/migrate/sources/workos.ts b/packages/cli-core/src/commands/migrate/sources/workos.ts index 5952d8b22..0caa69081 100644 --- a/packages/cli-core/src/commands/migrate/sources/workos.ts +++ b/packages/cli-core/src/commands/migrate/sources/workos.ts @@ -1,5 +1,5 @@ -import type { SourceEntry } from "../types.ts"; -import { routeByVerification } from "./shared.ts"; +import type { PASSWORD_HASHERS, SourceEntry } from "../types.ts"; +import { detectStandardHasher, routeByVerification } from "./shared.ts"; /** * WorkOS → Clerk transformer. @@ -10,25 +10,88 @@ import { routeByVerification } from "./shared.ts"; * in private metadata as `workosExternalId`: private because users can edit * unsafe metadata, and an ID other records key on must not be editable. * - * **There is no `passwordHasher` default here, and that is deliberate.** Every - * other source names the hasher its platform ships so a digest can be - * verified; WorkOS returns no digest to verify. It accepts password hashes on - * import and never gives them back, and its TOTP secrets are returned on enrol - * only — so a WorkOS migration moves identities, not credentials. Naming a - * hasher here would imply a password column that cannot exist. + * **Password hashes come only from WorkOS support.** The API returns none, and + * returns TOTP secrets only at enrolment. WorkOS support sends hashes on + * request as a CSV, which `export workos --password-hashes` merges in as + * `password_hash`. There is no `passwordHasher` default: one export can hold + * several formats, so `detectWorkOsHash` names the hasher per user. * * WorkOS has no phone number and no username, which is why the map is short: * those fields have nothing to come from. */ + +type PasswordHasher = (typeof PASSWORD_HASHERS)[number]; + +// clerk_go's limits (pkg/hash): pbkdf2_sha256 derives exactly 32 bytes, and +// pbkdf2_sha512_hex takes at most 420,000 iterations and at least a 16-byte key. +const PBKDF2_SHA256_KEY_BYTES = 32; +const PBKDF2_SHA512_MAX_ITERATIONS = 420_000; +const PBKDF2_SHA512_MIN_KEY_BYTES = 16; + +/** + * Names the Clerk hasher for one hash from a WorkOS export, rewriting it into + * that hasher's layout where WorkOS's PHC string differs. + * + * The formats are listed under "Password hash formats" in + * https://workos.com/docs/migrate/export-from-workos. Salts and digests are + * base64 with the padding trimmed. + * + * @returns `undefined` for a hash Clerk can't verify: argon2d, + * firebase-scrypt, pbkdf2 outside clerk_go's limits, and the formats that + * wait on clerk_go's `_workos` hashers (`$bcrypt-pbkdf2-*$`, + * `$bcrypt-ssha*$`, `$scrypt$`). + */ +export function detectWorkOsHash( + hash: string, +): { password: string; passwordHasher: PasswordHasher } | undefined { + const standard = detectStandardHasher(hash); + if (standard) return { password: hash, passwordHasher: standard }; + + // $pbkdf2$i=600000,d=sha256$$, with the params in any order. + const pbkdf2 = /^\$pbkdf2\$([^$]+)\$([A-Za-z0-9+/]+)\$([A-Za-z0-9+/]+)$/.exec(hash); + if (!pbkdf2) return undefined; + const [, rawParams = "", rawSalt = "", rawKey = ""] = pbkdf2; + const params = new URLSearchParams(rawParams.replaceAll(",", "&")); + const iterations = params.get("i") ?? ""; + if (!/^[1-9]\d*$/.test(iterations)) return undefined; + const salt = Buffer.from(rawSalt, "base64"); + const key = Buffer.from(rawKey, "base64"); + + switch (params.get("d")) { + case "sha256": + if (key.length !== PBKDF2_SHA256_KEY_BYTES) return undefined; + return { + password: `pbkdf2_sha256$${iterations}$${salt.toString("base64")}$${key.toString("base64")}`, + passwordHasher: "pbkdf2_sha256", + }; + case "sha512": + if (Number(iterations) > PBKDF2_SHA512_MAX_ITERATIONS) return undefined; + if (key.length < PBKDF2_SHA512_MIN_KEY_BYTES) return undefined; + return { + password: `pbkdf2_sha512_hex$${iterations}$${salt.toString("hex")}$${key.toString("hex")}`, + passwordHasher: "pbkdf2_sha512_hex", + }; + case "sha1": + // WorkOS re-hashes sha1 with bcrypt at import, so this is only a + // fallback. The fifth segment is the key length; clerk_go assumes 32. + return { + password: `pbkdf2_sha1$${iterations}$${salt.toString("hex")}$${key.toString("hex")}$${key.length}`, + passwordHasher: "pbkdf2_sha1", + }; + default: + return undefined; + } +} + const workosSource = { key: "workos", label: "WorkOS", description: - "Works with WorkOS's User Management API. WorkOS returns no password hashes, so imported users sign in by reset or SSO.", + "Works with WorkOS's User Management API. Password hashes come from WorkOS support as a CSV, merged in by `export workos --password-hashes`.", carries: { passwords: { - level: "no", - note: "WorkOS's API never returns password hashes. Users reset their password, or sign in with SSO.", + level: "partial", + note: "Only from the CSV WorkOS support sends, merged in by `export workos --password-hashes`. bcrypt, argon2, and most pbkdf2 hashes carry over. Users with any other format reset their password.", }, mfa: { level: "no", note: "WorkOS returns TOTP secrets at enrolment only." }, metadata: { @@ -48,10 +111,23 @@ const workosSource = { metadata: "privateMetadata", external_id: "workosExternalId", created_at: "createdAt", + password_hash: "password", }, postTransform: (user) => { routeByVerification(user, "email", "emailVerified", "boolean"); + if (typeof user.password === "string" && user.password) { + const detected = detectWorkOsHash(user.password); + if (detected) { + user.password = detected.password; + user.passwordHasher = detected.passwordHasher; + } else { + // Imported without it rather than rejected: the user resets instead. + delete user.password; + user.passwordDropped = true; + } + } + if (user.workosExternalId) { const metadata = user.privateMetadata && typeof user.privateMetadata === "object"