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

85 lines
3.1 KiB
JavaScript

/**
* Resolves a Scribase access token the same way the official `scribase` CLI
* does, so `scribase-migrate` never asks a user to paste a token it could
* find itself: a project folder's `.env`/`.env.local`, then
* `SCRIBASE_ACCESS_TOKEN` in the shell, then whatever `scribase login`
* already stored (macOS Keychain / Linux Secret Service via the `scribase`
* service name, or the plaintext fallback file at
* `$XDG_CONFIG_HOME/scribase/credentials`).
*
* This mirrors `edge-repos/scribase-cli/src/cli/{token,credentials}.ts`
* on purpose — one account, one token-resolution rule, everywhere.
*/
import { spawnSync } from 'node:child_process';
import { existsSync, readFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
function configDir(env) {
return join(env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'scribase');
}
function parseCredentialsFile(text) {
const out = {};
for (const line of text.split('\n')) {
const at = line.indexOf('=');
if (at < 0) continue;
const key = line.slice(0, at).trim();
const value = line.slice(at + 1).trim();
if (!value) continue;
if (key === 'api_url') out.apiUrl = value;
if (key === 'access_token') out.token = value;
if (key === 'token_store') out.tokenStore = value;
}
return out;
}
function fromKeychain(apiUrl) {
if (process.platform !== 'darwin') return null;
const probe = spawnSync('security', ['--help'], { stdio: 'ignore' });
if (probe.error) return null;
const attempts = apiUrl ? [apiUrl] : [];
for (const account of attempts.length ? attempts : [undefined]) {
const args = ['find-generic-password', '-s', 'scribase', '-w'];
if (account) args.push('-a', account);
const result = spawnSync('security', args, { encoding: 'utf8' });
const token = result.stdout?.trim();
if (result.status === 0 && token) return token;
}
return null;
}
/**
* Resolves `{ apiUrl, token, source }`. Throws a clear, actionable error
* (never a token value) when nothing is found — the equivalent of
* `scribase doctor` telling the user to run `scribase login`.
*/
export function resolveScribaseAuth(env = process.env) {
if (env.SCRIBASE_ACCESS_TOKEN) {
return {
apiUrl: env.SCRIBASE_API_URL || 'https://api.scribase.com',
token: env.SCRIBASE_ACCESS_TOKEN,
source: 'shell (SCRIBASE_ACCESS_TOKEN)',
};
}
const dir = configDir(env);
const credsPath = join(dir, 'credentials');
if (existsSync(credsPath)) {
const creds = parseCredentialsFile(readFileSync(credsPath, 'utf8'));
const apiUrl = creds.apiUrl || 'https://api.scribase.com';
if (creds.tokenStore === 'keychain') {
const token = fromKeychain(apiUrl) ?? fromKeychain(undefined);
if (token) return { apiUrl, token, source: 'scribase login (keychain)' };
} else if (creds.token) {
return { apiUrl, token: creds.token, source: 'scribase login (credentials file)' };
}
}
throw new Error(
'No Scribase access token found. Run `npx scribase login` once (or export ' +
'SCRIBASE_ACCESS_TOKEN), then re-run scribase-migrate.',
);
}