caelum0x 261ea5dea7 feat: scribase-migrate — one-command migration from Supabase/Neon/Clerk/Resend onto Scribase
Composes Scribase's own shipped APIs (the `scribase` SDK's imports/migrations/
database/environments resources, plus the GoTrue admin API every self-hosted
Supabase migration tool already uses) rather than reinventing a dump format:

- supabase: wraps the real POST /v1/imports one-call migration (Postgres,
  auth.users with hashes, storage).
- neon: pg_dump schema+data as plain SQL, submitted through POST .../migrations
  (environments.connection() is internal-network-only — verified live — so
  this is the only path that actually reaches a Scribase env from outside);
  auto-generates owner-based RLS so the real migration lint's BLOCK on
  RLS-less public tables is satisfied without ever opening a table to every
  user; branches land in branch_<name> schemas.
- clerk: exports users via the real Backend API, creates them via the
  destination's GoTrue admin API with a one-time password + reset flag
  (Clerk never exposes a portable hash on any plan).
- resend: exports sending domains + broadcasts (as templates) to a portable
  JSON bundle; honest about Scribase having no write endpoint for either yet.

Verified live end-to-end against a real local Supabase-shaped Postgres
(Docker, GoTrue-shaped auth.users with a real bcrypt hash) and a real
Scribase project (ereboslab/scribase-migrate-verify-internal): schema+RLS
applied with 0 lint blocks, data row counts matched via a real HTTP query
(2/2 profiles, 3/3 notes), and a real password-grant login returned a real
access_token for the migrated user. Full artifacts in
test-fixtures/verification-run/.

docs/migrate-page.md is a ready-to-paste scribase.com/migrate page.
2026-11-17 14:54:36 +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 self-hosted Supabase 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 };
}