From d25b1f3dfe4ef8933f515cbd8ed285a2d43c0d3e Mon Sep 17 00:00:00 2001 From: Roy Anger Date: Fri, 27 Nov 2026 18:14:16 -0500 Subject: [PATCH 1/3] feat(migrate): merge WorkOS support password hashes into the WorkOS export Add --password-hashes to `clerk migrate export workos`. It reads the CSV WorkOS support sends and copies each password_hash onto the API user with the same email. The workos source picks the Clerk hasher per user from the hash prefix, rewriting $pbkdf2$ into Clerk's layout. Formats Clerk can't verify are dropped and those users reset their password. Refs DOCS-12474 Co-Authored-By: Claude Opus 5.5 --- .changeset/workos-password-hashes.md | 5 + .../cli-core/src/commands/migrate/README.md | 81 +++++++++++-- .../src/commands/migrate/export/index.ts | 8 ++ .../src/commands/migrate/export/registry.ts | 3 +- .../commands/migrate/export/workos.test.ts | 62 +++++++++- .../src/commands/migrate/export/workos.ts | 114 +++++++++++++++--- .../src/commands/migrate/index.test.ts | 1 + .../src/commands/migrate/lib/transform.ts | 5 +- .../commands/migrate/sources/sources.test.ts | 109 ++++++++++++++++- .../src/commands/migrate/sources/workos.ts | 105 ++++++++++++++-- .../cli-core/src/commands/migrate/types.ts | 5 + 11 files changed, 447 insertions(+), 51 deletions(-) create mode 100644 .changeset/workos-password-hashes.md diff --git a/.changeset/workos-password-hashes.md b/.changeset/workos-password-hashes.md new file mode 100644 index 000000000..7c44add0a --- /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. Formats Clerk can't verify, such as `$argon2d$` and `$firebase-scrypt$`, are dropped, and those users 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..7cd4dae32 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,59 @@ 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` | +| `$bcrypt-pbkdf2-sha1$`, `$bcrypt-pbkdf2-sha256$` | `bcrypt_pbkdf2_sha1`, `bcrypt_pbkdf2_sha256` | +| `$bcrypt-ssha$`, `$bcrypt-ssha256$` | `bcrypt_ssha`, `bcrypt_ssha256` | +| `$scrypt$` | `scrypt` | +| `$pbkdf2$` (`d=sha256`, `sha512`, `sha1`) | `pbkdf2_sha256`, `pbkdf2_sha512_hex`, `pbkdf2_sha1`, re-encoded | + +All but `$pbkdf2$` 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. + +- `$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, `pbkdf2_sha512_hex`'s cap. +- 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 +1302,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 @@ -1542,11 +1599,13 @@ reject the user as invalid. Each accepts a single value or an array. Clerk verifies the digest as-is, so `passwordHasher` must name the algorithm the source actually used: -`argon2i`, `argon2id`, `awscognito`, `bcrypt`, `bcrypt_peppered`, -`bcrypt_sha256_django`, `hmac_sha256_utf16_b64`, `ldap_ssha`, `md5`, +`argon2i`, `argon2id`, `awscognito`, `bcrypt`, `bcrypt_pbkdf2_sha1`, +`bcrypt_pbkdf2_sha256`, `bcrypt_peppered`, `bcrypt_sha256_django`, +`bcrypt_ssha`, `bcrypt_ssha256`, `hmac_sha256_utf16_b64`, `ldap_ssha`, `md5`, `md5_phpass`, `md5_salted`, `phpass`, `pbkdf2_sha1`, `pbkdf2_sha256`, -`pbkdf2_sha256_django`, `pbkdf2_sha512`, `pbkdf2_sha512_hex`, `scrypt_firebase`, -`scrypt_werkzeug`, `sha256`, `sha256_salted`, `sha512_symfony` +`pbkdf2_sha256_django`, `pbkdf2_sha512`, `pbkdf2_sha512_hex`, `scrypt`, +`scrypt_firebase`, `scrypt_werkzeug`, `sha256`, `sha256_salted`, +`sha512_symfony` A user with an unrecognized hasher is rejected by the checks, naming the hasher, like any other invalid user. 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..65206e886 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,43 @@ 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"); + }); + + 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..ae5c0fd9c 100644 --- a/packages/cli-core/src/commands/migrate/lib/transform.ts +++ b/packages/cli-core/src/commands/migrate/lib/transform.ts @@ -437,7 +437,10 @@ 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) 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..0c236079f 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,81 @@ 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"], + [ + "bcrypt-pbkdf2-sha1", + `$bcrypt-pbkdf2-sha1$v=1$i=1000,kl=20$${b64(salt)}$${wrapped}`, + "bcrypt_pbkdf2_sha1", + ], + [ + "bcrypt-pbkdf2-sha256", + `$bcrypt-pbkdf2-sha256$v=1$i=1000,kl=32$${b64(salt)}$${wrapped}`, + "bcrypt_pbkdf2_sha256", + ], + ["bcrypt-ssha", `$bcrypt-ssha$v=1$${b64(salt)}$${wrapped}`, "bcrypt_ssha"], + ["bcrypt-ssha256", `$bcrypt-ssha256$v=1$sp=prefix$${b64(salt)}$${wrapped}`, "bcrypt_ssha256"], + ["scrypt", `$scrypt$v=1$n=16384,r=8,p=1,kl=64$${b64(salt)}$${b64(key(64))}`, "scrypt"], + ])("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`], + ["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 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$")], + ["a wrapped format without v=1", `$bcrypt-ssha$${b64(salt)}$${wrapped}`], + ["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..07795b5b7 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,95 @@ 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]; + +/** WorkOS formats Clerk verifies unchanged, named with underscores. */ +const AS_IS = + /^\$(bcrypt-pbkdf2-sha1|bcrypt-pbkdf2-sha256|bcrypt-ssha|bcrypt-ssha256|scrypt)\$v=1\$/; + +// 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, and pbkdf2 outside clerk_go's limits. + */ +export function detectWorkOsHash( + hash: string, +): { password: string; passwordHasher: PasswordHasher } | undefined { + const standard = detectStandardHasher(hash); + if (standard) return { password: hash, passwordHasher: standard }; + + const asIs = AS_IS.exec(hash)?.[1]; + if (asIs) { + return { password: hash, passwordHasher: asIs.replaceAll("-", "_") as PasswordHasher }; + } + + // $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`. Clerk can't verify argon2d, firebase-scrypt, or some pbkdf2 hashes, so those users reset their password.", }, mfa: { level: "no", note: "WorkOS returns TOTP secrets at enrolment only." }, metadata: { @@ -48,10 +118,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" diff --git a/packages/cli-core/src/commands/migrate/types.ts b/packages/cli-core/src/commands/migrate/types.ts index 86b57fe3c..6865e7ebd 100644 --- a/packages/cli-core/src/commands/migrate/types.ts +++ b/packages/cli-core/src/commands/migrate/types.ts @@ -18,8 +18,12 @@ export const PASSWORD_HASHERS = [ "argon2id", "awscognito", "bcrypt", + "bcrypt_pbkdf2_sha1", + "bcrypt_pbkdf2_sha256", "bcrypt_peppered", "bcrypt_sha256_django", + "bcrypt_ssha", + "bcrypt_ssha256", "hmac_sha256_utf16_b64", "md5", "md5_salted", @@ -28,6 +32,7 @@ export const PASSWORD_HASHERS = [ "pbkdf2_sha256_django", "pbkdf2_sha512", "pbkdf2_sha512_hex", + "scrypt", "scrypt_firebase", "scrypt_werkzeug", "sha256", From e171f029c45b18bcb2d7d89e4d656d5d3e2e7e67 Mon Sep 17 00:00:00 2001 From: Roy Anger Date: Tue, 1 Dec 2026 15:14:21 -0500 Subject: [PATCH 2/3] feat(migrate): map only WorkOS formats Clerk already verifies Drop the bcrypt-wrapped and $scrypt$ mappings and their hasher names. Those need clerk_go's new _workos hashers (DOCS-12473), and a follow-up (DOCS-12484) maps them once those ship. Until then these users reset. Refs DOCS-12474 Co-Authored-By: Claude Opus 5.5 --- .changeset/workos-password-hashes.md | 2 +- .../cli-core/src/commands/migrate/README.md | 34 +++++++++---------- .../commands/migrate/sources/sources.test.ts | 20 ++++------- .../src/commands/migrate/sources/workos.ts | 15 +++----- .../cli-core/src/commands/migrate/types.ts | 5 --- 5 files changed, 28 insertions(+), 48 deletions(-) diff --git a/.changeset/workos-password-hashes.md b/.changeset/workos-password-hashes.md index 7c44add0a..2a5079217 100644 --- a/.changeset/workos-password-hashes.md +++ b/.changeset/workos-password-hashes.md @@ -2,4 +2,4 @@ "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. Formats Clerk can't verify, such as `$argon2d$` and `$firebase-scrypt$`, are dropped, and those users reset their password. +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 7cd4dae32..e20819c74 100644 --- a/packages/cli-core/src/commands/migrate/README.md +++ b/packages/cli-core/src/commands/migrate/README.md @@ -737,21 +737,23 @@ 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` | -| `$bcrypt-pbkdf2-sha1$`, `$bcrypt-pbkdf2-sha256$` | `bcrypt_pbkdf2_sha1`, `bcrypt_pbkdf2_sha256` | -| `$bcrypt-ssha$`, `$bcrypt-ssha256$` | `bcrypt_ssha`, `bcrypt_ssha256` | -| `$scrypt$` | `scrypt` | -| `$pbkdf2$` (`d=sha256`, `sha512`, `sha1`) | `pbkdf2_sha256`, `pbkdf2_sha512_hex`, `pbkdf2_sha1`, re-encoded | - -All but `$pbkdf2$` go to Clerk unchanged. `$pbkdf2$` is rewritten into the -matching Clerk layout: padded base64 for `pbkdf2_sha256`, hex for the others. +| 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` @@ -1599,13 +1601,11 @@ reject the user as invalid. Each accepts a single value or an array. Clerk verifies the digest as-is, so `passwordHasher` must name the algorithm the source actually used: -`argon2i`, `argon2id`, `awscognito`, `bcrypt`, `bcrypt_pbkdf2_sha1`, -`bcrypt_pbkdf2_sha256`, `bcrypt_peppered`, `bcrypt_sha256_django`, -`bcrypt_ssha`, `bcrypt_ssha256`, `hmac_sha256_utf16_b64`, `ldap_ssha`, `md5`, +`argon2i`, `argon2id`, `awscognito`, `bcrypt`, `bcrypt_peppered`, +`bcrypt_sha256_django`, `hmac_sha256_utf16_b64`, `ldap_ssha`, `md5`, `md5_phpass`, `md5_salted`, `phpass`, `pbkdf2_sha1`, `pbkdf2_sha256`, -`pbkdf2_sha256_django`, `pbkdf2_sha512`, `pbkdf2_sha512_hex`, `scrypt`, -`scrypt_firebase`, `scrypt_werkzeug`, `sha256`, `sha256_salted`, -`sha512_symfony` +`pbkdf2_sha256_django`, `pbkdf2_sha512`, `pbkdf2_sha512_hex`, `scrypt_firebase`, +`scrypt_werkzeug`, `sha256`, `sha256_salted`, `sha512_symfony` A user with an unrecognized hasher is rejected by the checks, naming the hasher, like any other invalid user. 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 0c236079f..3f55a1e54 100644 --- a/packages/cli-core/src/commands/migrate/sources/sources.test.ts +++ b/packages/cli-core/src/commands/migrate/sources/sources.test.ts @@ -352,19 +352,6 @@ describe("detectWorkOsHash", () => { ["bcrypt", BCRYPT, "bcrypt"], ["argon2id", ARGON2ID, "argon2id"], ["argon2i", ARGON2ID.replace("argon2id", "argon2i"), "argon2i"], - [ - "bcrypt-pbkdf2-sha1", - `$bcrypt-pbkdf2-sha1$v=1$i=1000,kl=20$${b64(salt)}$${wrapped}`, - "bcrypt_pbkdf2_sha1", - ], - [ - "bcrypt-pbkdf2-sha256", - `$bcrypt-pbkdf2-sha256$v=1$i=1000,kl=32$${b64(salt)}$${wrapped}`, - "bcrypt_pbkdf2_sha256", - ], - ["bcrypt-ssha", `$bcrypt-ssha$v=1$${b64(salt)}$${wrapped}`, "bcrypt_ssha"], - ["bcrypt-ssha256", `$bcrypt-ssha256$v=1$sp=prefix$${b64(salt)}$${wrapped}`, "bcrypt_ssha256"], - ["scrypt", `$scrypt$v=1$n=16384,r=8,p=1,kl=64$${b64(salt)}$${b64(key(64))}`, "scrypt"], ])("sends %s unchanged", (_, hash, hasher) => { expect(detectWorkOsHash(hash)).toEqual({ password: hash, passwordHasher: hasher }); }); @@ -401,6 +388,12 @@ describe("detectWorkOsHash", () => { 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", @@ -409,7 +402,6 @@ describe("detectWorkOsHash", () => { ["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$")], - ["a wrapped format without v=1", `$bcrypt-ssha$${b64(salt)}$${wrapped}`], ["plain SSHA", "{SSHA}c29tZWhhc2hzb21lc2FsdA=="], ])("drops %s", (_, hash) => { expect(detectWorkOsHash(hash)).toBeUndefined(); diff --git a/packages/cli-core/src/commands/migrate/sources/workos.ts b/packages/cli-core/src/commands/migrate/sources/workos.ts index 07795b5b7..0caa69081 100644 --- a/packages/cli-core/src/commands/migrate/sources/workos.ts +++ b/packages/cli-core/src/commands/migrate/sources/workos.ts @@ -22,10 +22,6 @@ import { detectStandardHasher, routeByVerification } from "./shared.ts"; type PasswordHasher = (typeof PASSWORD_HASHERS)[number]; -/** WorkOS formats Clerk verifies unchanged, named with underscores. */ -const AS_IS = - /^\$(bcrypt-pbkdf2-sha1|bcrypt-pbkdf2-sha256|bcrypt-ssha|bcrypt-ssha256|scrypt)\$v=1\$/; - // 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; @@ -41,7 +37,9 @@ const PBKDF2_SHA512_MIN_KEY_BYTES = 16; * base64 with the padding trimmed. * * @returns `undefined` for a hash Clerk can't verify: argon2d, - * firebase-scrypt, and pbkdf2 outside clerk_go's limits. + * 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, @@ -49,11 +47,6 @@ export function detectWorkOsHash( const standard = detectStandardHasher(hash); if (standard) return { password: hash, passwordHasher: standard }; - const asIs = AS_IS.exec(hash)?.[1]; - if (asIs) { - return { password: hash, passwordHasher: asIs.replaceAll("-", "_") as PasswordHasher }; - } - // $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; @@ -98,7 +91,7 @@ const workosSource = { carries: { passwords: { level: "partial", - note: "Only from the CSV WorkOS support sends, merged in by `export workos --password-hashes`. Clerk can't verify argon2d, firebase-scrypt, or some pbkdf2 hashes, so those users reset their password.", + 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: { diff --git a/packages/cli-core/src/commands/migrate/types.ts b/packages/cli-core/src/commands/migrate/types.ts index 6865e7ebd..86b57fe3c 100644 --- a/packages/cli-core/src/commands/migrate/types.ts +++ b/packages/cli-core/src/commands/migrate/types.ts @@ -18,12 +18,8 @@ export const PASSWORD_HASHERS = [ "argon2id", "awscognito", "bcrypt", - "bcrypt_pbkdf2_sha1", - "bcrypt_pbkdf2_sha256", "bcrypt_peppered", "bcrypt_sha256_django", - "bcrypt_ssha", - "bcrypt_ssha256", "hmac_sha256_utf16_b64", "md5", "md5_salted", @@ -32,7 +28,6 @@ export const PASSWORD_HASHERS = [ "pbkdf2_sha256_django", "pbkdf2_sha512", "pbkdf2_sha512_hex", - "scrypt", "scrypt_firebase", "scrypt_werkzeug", "sha256", From 401dadd51f83270ab12d2e02b191ba77fb9de9c3 Mon Sep 17 00:00:00 2001 From: Roy Anger Date: Wed, 2 Dec 2026 15:06:32 -0500 Subject: [PATCH 3/3] fix(migrate): reject CSV read errors instead of crashing pipe() doesn't forward errors from the file stream, so an unreadable CSV (a directory, a revoked permission) escaped as an unhandled error. Reject on the file stream too. Also list pbkdf2 sha512 keys under 16 bytes among the WorkOS hashes that reset. Refs DOCS-12474 Co-Authored-By: Claude Opus 5.5 --- packages/cli-core/src/commands/migrate/README.md | 3 ++- .../src/commands/migrate/export/workos.test.ts | 11 +++++++++++ .../cli-core/src/commands/migrate/lib/transform.ts | 3 +++ .../src/commands/migrate/sources/sources.test.ts | 1 + 4 files changed, 17 insertions(+), 1 deletion(-) diff --git a/packages/cli-core/src/commands/migrate/README.md b/packages/cli-core/src/commands/migrate/README.md index e20819c74..84d2f1ffc 100644 --- a/packages/cli-core/src/commands/migrate/README.md +++ b/packages/cli-core/src/commands/migrate/README.md @@ -758,7 +758,8 @@ resets it. The checks count these users, the same as Better Auth's. - `$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, `pbkdf2_sha512_hex`'s cap. +- `$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` 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 65206e886..543f08c9b 100644 --- a/packages/cli-core/src/commands/migrate/export/workos.test.ts +++ b/packages/cli-core/src/commands/migrate/export/workos.test.ts @@ -661,6 +661,17 @@ describe("exportWorkOs", () => { 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( diff --git a/packages/cli-core/src/commands/migrate/lib/transform.ts b/packages/cli-core/src/commands/migrate/lib/transform.ts index ae5c0fd9c..36fdf12cf 100644 --- a/packages/cli-core/src/commands/migrate/lib/transform.ts +++ b/packages/cli-core/src/commands/migrate/lib/transform.ts @@ -444,6 +444,9 @@ export async function readCsv( 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 3f55a1e54..276e7b030 100644 --- a/packages/cli-core/src/commands/migrate/sources/sources.test.ts +++ b/packages/cli-core/src/commands/migrate/sources/sources.test.ts @@ -399,6 +399,7 @@ describe("detectWorkOsHash", () => { "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$")],