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.
243 lines
9.3 KiB
JavaScript
Executable File
243 lines
9.3 KiB
JavaScript
Executable File
#!/usr/bin/env node
|
|
/**
|
|
* scribase-migrate — one command to move a team onto Scribase from
|
|
* Supabase, Neon, Clerk and Resend. See README.md for the full flag
|
|
* reference; `scribase-migrate <source> --help` prints that source's.
|
|
*/
|
|
|
|
import { parseArgs } from 'node:util';
|
|
import { writeFile, mkdir } from 'node:fs/promises';
|
|
import { dirname } from 'node:path';
|
|
|
|
import { scribaseClient } from '../lib/client.mjs';
|
|
import { ensureProject } from '../lib/project.mjs';
|
|
import { migrateSupabase } from '../lib/sources/supabase.mjs';
|
|
import { migrateNeon, verifyRowCounts } from '../lib/sources/neon.mjs';
|
|
import { exportClerkUsers, createGoTrueUsers } from '../lib/sources/clerk.mjs';
|
|
import { exportResend } from '../lib/sources/resend.mjs';
|
|
|
|
const USAGE = `scribase-migrate <source> [flags]
|
|
|
|
Sources:
|
|
supabase Postgres schema+data, auth.users (password hashes), storage — one real API call
|
|
neon Postgres schema+data (branches -> branch_<name> schemas)
|
|
clerk Users (email/phone/metadata), created with a one-time password + reset flag
|
|
resend Sending domains + broadcast templates, exported as a re-importable JSON bundle
|
|
|
|
Shared destination flags:
|
|
--to <org>/<project>/<environment> Scribase destination (default environment: production)
|
|
--create-project Create the project+environment first if missing
|
|
--region <region> Region for --create-project (default us-east)
|
|
--kind <preview|staging|production> Environment kind for --create-project (default production;
|
|
note: production cannot be deleted later — use preview to try this out)
|
|
--dry-run Plan only, write nothing
|
|
--out <path> Write the full JSON result here too
|
|
--json Print only the JSON result to stdout
|
|
|
|
supabase flags:
|
|
--source-ref <ref> --source-url <postgres://...> --source-service-key <key>
|
|
--verify-login-email <email> [--verify-login-password <password>]
|
|
--no-storage
|
|
|
|
neon flags:
|
|
--source-url <postgres://...>
|
|
--schema <name> (repeatable; default public)
|
|
--migrate-auth-users Also copy an auth.users-shaped table's rows
|
|
--branch name=<url> (repeatable; each lands in branch_<name>)
|
|
--verify-row-counts <schema.table> (repeatable)
|
|
|
|
clerk flags:
|
|
--secret-key <sk_...>
|
|
--target-api-url <url> --target-service-key <key> (from \`scribase-migrate project-info\`)
|
|
|
|
resend flags:
|
|
--api-key <re_...>
|
|
|
|
Also: scribase-migrate project-info --to <org>/<project>/<environment>
|
|
prints the destination's api_url + keys (never the secrets to stdout
|
|
unless --reveal-secrets), the inputs clerk/resend need.
|
|
`;
|
|
|
|
function fail(message) {
|
|
process.stderr.write(`scribase-migrate: ${message}\n`);
|
|
process.exit(1);
|
|
}
|
|
|
|
function parseTo(value) {
|
|
if (!value) fail('--to <org>/<project>/<environment> is required');
|
|
const parts = value.split('/');
|
|
if (parts.length < 2 || parts.length > 3) fail(`--to "${value}" must be org/project or org/project/environment`);
|
|
const [organizationId, projectId, environmentId = 'production'] = parts;
|
|
return { organizationId, projectId, environmentId };
|
|
}
|
|
|
|
async function writeResult(opts, result) {
|
|
if (opts.out) {
|
|
await mkdir(dirname(opts.out), { recursive: true }).catch(() => {});
|
|
await writeFile(opts.out, JSON.stringify(result, null, 2));
|
|
}
|
|
if (opts.json) {
|
|
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
} else {
|
|
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
if (opts.out) process.stderr.write(`\nFull result also written to ${opts.out}\n`);
|
|
}
|
|
}
|
|
|
|
async function resolveDestination(client, destArg, rawArgs) {
|
|
const dest = parseTo(destArg);
|
|
if (rawArgs.includes('--create-project')) {
|
|
const region = rawArgs[rawArgs.indexOf('--region') + 1] ?? 'us-east';
|
|
const kindIndex = rawArgs.indexOf('--kind');
|
|
const kind = kindIndex >= 0 ? rawArgs[kindIndex + 1] : 'production';
|
|
const project = await ensureProject(client, { ...dest, region, kind, dataMode: 'snapshot' });
|
|
return project;
|
|
}
|
|
const environment = await client.environments.get(dest);
|
|
const connection = await client.environments.connection(dest);
|
|
const apiKeys = await client.environments.apiKeys(dest);
|
|
return { ...dest, environment, connection, apiKeys };
|
|
}
|
|
|
|
async function main() {
|
|
const [source, ...rest] = process.argv.slice(2);
|
|
if (!source || source === '--help' || source === '-h') {
|
|
process.stdout.write(USAGE);
|
|
process.exit(source ? 0 : 1);
|
|
}
|
|
|
|
const { values } = parseArgs({
|
|
args: rest,
|
|
options: {
|
|
to: { type: 'string' },
|
|
'create-project': { type: 'boolean' },
|
|
region: { type: 'string' },
|
|
'dry-run': { type: 'boolean' },
|
|
out: { type: 'string' },
|
|
json: { type: 'boolean' },
|
|
'source-ref': { type: 'string' },
|
|
'source-url': { type: 'string' },
|
|
'source-service-key': { type: 'string' },
|
|
'verify-login-email': { type: 'string' },
|
|
'verify-login-password': { type: 'string' },
|
|
'no-storage': { type: 'boolean' },
|
|
'migrate-auth-users': { type: 'boolean' },
|
|
'secret-key': { type: 'string' },
|
|
'target-api-url': { type: 'string' },
|
|
'target-service-key': { type: 'string' },
|
|
'api-key': { type: 'string' },
|
|
'reveal-secrets': { type: 'boolean' },
|
|
schema: { type: 'string', multiple: true },
|
|
branch: { type: 'string', multiple: true },
|
|
'verify-row-counts': { type: 'string', multiple: true },
|
|
},
|
|
allowPositionals: false,
|
|
strict: false,
|
|
});
|
|
|
|
if (source === 'project-info') {
|
|
const { client } = scribaseClient();
|
|
const dest = await resolveDestination(client, values.to, rest);
|
|
const out = {
|
|
organizationId: dest.organizationId,
|
|
projectId: dest.projectId,
|
|
environmentId: dest.environmentId,
|
|
apiUrl: dest.apiKeys.api_url,
|
|
anonKey: dest.apiKeys.anon_key,
|
|
...(values['reveal-secrets']
|
|
? { serviceRoleKey: dest.apiKeys.service_role_key, connectionUri: dest.connection.connection_uri }
|
|
: { serviceRoleKey: '(hidden, pass --reveal-secrets)', connectionUri: '(hidden, pass --reveal-secrets)' }),
|
|
};
|
|
await writeResult(values, out);
|
|
return;
|
|
}
|
|
|
|
const { client } = scribaseClient();
|
|
const dest = await resolveDestination(client, values.to, rest);
|
|
const destination = {
|
|
organizationId: dest.organizationId,
|
|
projectId: dest.projectId,
|
|
environmentId: dest.environmentId,
|
|
};
|
|
|
|
if (source === 'supabase') {
|
|
if (!values['source-ref'] || !values['source-url'] || !values['source-service-key']) {
|
|
fail('supabase needs --source-ref, --source-url and --source-service-key');
|
|
}
|
|
const result = await migrateSupabase(client, {
|
|
sourceProjectRef: values['source-ref'],
|
|
sourceConnectionString: values['source-url'],
|
|
sourceServiceKey: values['source-service-key'],
|
|
destination,
|
|
includeStorage: !values['no-storage'],
|
|
dryRun: values['dry-run'],
|
|
...(values['verify-login-email']
|
|
? { verifyLogin: { email: values['verify-login-email'], password: values['verify-login-password'] } }
|
|
: {}),
|
|
onProgress: (job) => process.stderr.write(` ${job.status}${job.phase ? ` (${job.phase})` : ''}\n`),
|
|
});
|
|
await writeResult(values, result);
|
|
return;
|
|
}
|
|
|
|
if (source === 'neon') {
|
|
if (!values['source-url']) fail('neon needs --source-url');
|
|
const schemas = values.schema ?? [];
|
|
const branches = (values.branch ?? []).map((pair) => {
|
|
const at = pair.indexOf('=');
|
|
return { name: pair.slice(0, at), url: pair.slice(at + 1) };
|
|
});
|
|
const result = await migrateNeon(client, {
|
|
sourceUrl: values['source-url'],
|
|
destination,
|
|
schemas: schemas.length ? schemas : undefined,
|
|
migrateAuthUsers: values['migrate-auth-users'],
|
|
branches,
|
|
apply: !values['dry-run'],
|
|
onLog: (line) => process.stderr.write(` ${line}\n`),
|
|
});
|
|
const verifyTables = values['verify-row-counts'] ?? [];
|
|
if (verifyTables.length) {
|
|
result.rowCounts = await verifyRowCounts(client, destination, values['source-url'], verifyTables);
|
|
}
|
|
await writeResult(values, result);
|
|
return;
|
|
}
|
|
|
|
if (source === 'clerk') {
|
|
if (!values['secret-key']) fail('clerk needs --secret-key');
|
|
const apiUrl = values['target-api-url'] ?? dest.apiKeys.api_url;
|
|
const serviceRoleKey = values['target-service-key'] ?? dest.apiKeys.service_role_key;
|
|
if (!apiUrl || !serviceRoleKey) fail('could not resolve the destination api_url/service_role_key — pass --target-api-url/--target-service-key');
|
|
const users = await exportClerkUsers({
|
|
secretKey: values['secret-key'],
|
|
onLog: (line) => process.stderr.write(` ${line}\n`),
|
|
});
|
|
const result = await createGoTrueUsers({
|
|
apiUrl,
|
|
serviceRoleKey,
|
|
users,
|
|
onLog: (line) => process.stderr.write(` ${line}\n`),
|
|
});
|
|
await writeResult(values, { exported: users.length, ...result });
|
|
return;
|
|
}
|
|
|
|
if (source === 'resend') {
|
|
if (!values['api-key']) fail('resend needs --api-key');
|
|
const result = await exportResend({
|
|
apiKey: values['api-key'],
|
|
onLog: (line) => process.stderr.write(` ${line}\n`),
|
|
});
|
|
await writeResult(values, result);
|
|
return;
|
|
}
|
|
|
|
fail(`unknown source "${source}" — one of: supabase, neon, clerk, resend, project-info`);
|
|
}
|
|
|
|
main().catch((error) => {
|
|
process.stderr.write(`scribase-migrate: ${error.message}\n`);
|
|
process.exitCode = 1;
|
|
});
|