Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/workos-password-hashes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"clerk": minor
---

Add `--password-hashes <path>` 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.
74 changes: 67 additions & 7 deletions packages/cli-core/src/commands/migrate/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -327,6 +328,7 @@ keep `--runs-dir`: the import looks the run ID up there.
| `--api-key <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 <path>` | `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,
Expand Down Expand Up @@ -411,18 +413,20 @@ 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
those users reset their password.

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`)

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 <path>` 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
Expand Down Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions packages/cli-core/src/commands/migrate/export/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,10 @@ export function registerMigrateExport(migrateCommand: Command<[], Record<string,
"Also record each user's OAuth providers — one extra request per user",
)
.option("--no-with-identities", "Skip the OAuth provider fan-out without being asked")
.option(
"--password-hashes <path>",
"CSV of password hashes from a WorkOS support request, merged in by email",
)
.option("-o, --output <path>", "Write the export here instead of the run folder")
.option(
"-y, --yes",
Expand All @@ -230,6 +234,10 @@ export function registerMigrateExport(migrateCommand: Command<[], Record<string,
command: "clerk migrate export workos --api-key sk_…",
description: "Export with an explicit API key",
},
{
command: "clerk migrate export workos --password-hashes ./workos-password-hashes.csv",
description: "Add the password hashes WorkOS support sent",
},
{
command: "clerk migrate export workos",
description: "Read WORKOS_API_KEY, or prompt",
Expand Down
3 changes: 2 additions & 1 deletion packages/cli-core/src/commands/migrate/export/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@ export const exportPlatforms: ExportRegistryEntry[] = [
{
key: "workos",
label: "WorkOS",
description: "A WorkOS tenant, via the User Management API — no password hashes",
description:
"A WorkOS tenant, via the User Management API — password hashes only from a WorkOS support CSV",
sourceKey: "workos",
run: async (options) => exportWorkOs(options),
},
Expand Down
73 changes: 68 additions & 5 deletions packages/cli-core/src/commands/migrate/export/workos.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<string, unknown>[];
}
).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);
});
});

Expand Down
Loading
Loading