2026-11-28 00:59:25 +03:00

111 lines
4.4 KiB
JavaScript

/**
* Clerk -> Scribase users. Clerk's Backend API (`api.clerk.com`) never
* exposes a portable password hash (hosted auth, no "export the bcrypt
* column" button exists on any plan), so this is the same honest shape
* every real Clerk-migration script uses: export the user directory
* (email, phone, OAuth identities, metadata, timestamps) with a real
* Clerk API token, create matching users on the destination with a random
* one-time password via the destination environment's GoTrue admin API
* (the same `/auth/v1/admin/users` every Supabase-compatible migration
* tool calls with a service-role key), and hand back the list that needs a
* password-reset email — nothing silently drops a user's access.
*/
import { randomBytes } from 'node:crypto';
const CLERK_API = 'https://api.clerk.com/v1';
/** Pages through every Clerk user via the real Backend API. */
export async function exportClerkUsers({ secretKey, fetchImpl = fetch, onLog }) {
const users = [];
let offset = 0;
const limit = 100;
for (;;) {
const response = await fetchImpl(`${CLERK_API}/users?limit=${limit}&offset=${offset}`, {
headers: { authorization: `Bearer ${secretKey}` },
});
if (!response.ok) {
const detail = await response.text().catch(() => '');
throw new Error(`Clerk users list failed (${response.status}): ${detail.slice(0, 500)}`);
}
const page = await response.json();
users.push(...page);
onLog?.(`fetched ${users.length} Clerk users`);
if (page.length < limit) break;
offset += limit;
}
return users.map(normalizeClerkUser);
}
function normalizeClerkUser(user) {
const primaryEmail = (user.email_addresses ?? []).find(
(e) => e.id === user.primary_email_address_id,
)?.email_address;
return {
clerkId: user.id,
email: primaryEmail ?? user.email_addresses?.[0]?.email_address ?? null,
phone: user.phone_numbers?.[0]?.phone_number ?? null,
firstName: user.first_name ?? null,
lastName: user.last_name ?? null,
createdAtEpochMs: user.created_at,
externalAccounts: (user.external_accounts ?? []).map((a) => a.provider),
publicMetadata: user.public_metadata ?? {},
};
}
function randomPassword() {
return randomBytes(24).toString('base64url') + 'Aa1!';
}
/**
* Creates one destination user per exported Clerk user via the GoTrue
* admin API, `email_confirm: true` (Clerk already verified the email), a
* random password, and `app_metadata.migrated_from = 'clerk'` so the
* destination app can force a password reset on first login. Skips (does
* not error on) users with no email — Clerk supports phone-only accounts
* GoTrue's REST admin API cannot create without a phone provider configured.
*/
export async function createGoTrueUsers({ apiUrl, serviceRoleKey, users, fetchImpl = fetch, onLog }) {
const base = String(apiUrl).replace(/\/+$/, '');
const created = [];
const skipped = [];
const needsPasswordReset = [];
for (const user of users) {
if (!user.email) {
skipped.push({ clerkId: user.clerkId, reason: 'no email address' });
continue;
}
const password = randomPassword();
const response = await fetchImpl(`${base}/auth/v1/admin/users`, {
method: 'POST',
headers: {
'content-type': 'application/json',
authorization: `Bearer ${serviceRoleKey}`,
apikey: serviceRoleKey,
},
body: JSON.stringify({
email: user.email,
password,
email_confirm: true,
phone: user.phone ?? undefined,
user_metadata: { first_name: user.firstName, last_name: user.lastName, ...user.publicMetadata },
app_metadata: { migrated_from: 'clerk', clerk_id: user.clerkId, password_reset_required: true },
}),
});
if (response.status === 422 || response.status === 409) {
// Already exists (re-run of a partially completed migration) — not a failure.
skipped.push({ clerkId: user.clerkId, reason: 'already exists on destination' });
continue;
}
if (!response.ok) {
const detail = await response.text().catch(() => '');
throw new Error(`creating ${user.email} failed (${response.status}): ${detail.slice(0, 500)}`);
}
const body = await response.json();
created.push({ clerkId: user.clerkId, email: user.email, destinationId: body.id });
needsPasswordReset.push(user.email);
onLog?.(`created ${user.email}`);
}
return { created, skipped, needsPasswordReset };
}