@protobase/cli 0.40.3 → 0.40.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,7 +12,9 @@ const nextMigrationName = (files, name) => {
12
12
  const width = Math.max(3, ...numbers.map((found) => found.length));
13
13
  return `${String(next).padStart(width, "0")}_${name}.sql`;
14
14
  };
15
+ /** What an auth schema migration holds, its first line, whichever command wrote it. */
16
+ const authMigrationTitle = "The auth schema changes this version of Protobase needs";
15
17
  /** The file's contents: what wrote it and why, then Better Auth's statements, one per paragraph. */
16
- const migrationText = (sql) => `-- The auth schema changes this version of Protobase needs, written by \`protobase auth migration\`.\n-- Applied with the project's other migrations; edit or remove statements the project handles differently.\n\n${sql}\n`;
18
+ const migrationText = (sql) => `-- ${authMigrationTitle}, written by \`protobase auth migration\`.\n-- Applied with the project's other migrations; edit or remove statements the project handles differently.\n\n${sql}\n`;
17
19
  //#endregion
18
- export { migrationText, nextMigrationName };
20
+ export { authMigrationTitle, migrationText, nextMigrationName };
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.40.3";
2
+ var version = "0.40.4";
3
3
  //#endregion
4
4
  export { version };
@@ -1,3 +1,4 @@
1
+ import { authMigrationTitle } from "../auth/migration-file.js";
1
2
  import { authSchemaMigration, changesMigration, commentsMigration, computedMigration, isCaptured, jobsSchemaMigration, queryRunnerMigration, webhooksMigration } from "@protobase/server";
2
3
  //#region src/migration/parts.ts
3
4
  /** Every feature the project's config enables, in the order their files are written. */
@@ -7,7 +8,7 @@ const migrationParts = (project) => {
7
8
  return [
8
9
  ...project.auth ? [{
9
10
  name: "auth",
10
- title: "The auth schema changes this version of Protobase needs",
11
+ title: authMigrationTitle,
11
12
  sql: () => authSchemaMigration(project.auth)
12
13
  }] : [],
13
14
  ...project.jobs.length > 0 || project.models.some(isCaptured) || comments || aiFields || project.webhooks ? [{
@@ -0,0 +1,53 @@
1
+ import { existsSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { readFile, writeFile } from "node:fs/promises";
4
+ //#region src/supabase/auth-config.ts
5
+ /** createAuth's options for Supabase's auth.users. */
6
+ const supabaseUsers = {
7
+ users: {
8
+ table: "users",
9
+ columns: { role: "app_role" },
10
+ metadata: "raw_user_meta_data"
11
+ },
12
+ passwordHashes: ["bcrypt"],
13
+ generateUserId: "uuid"
14
+ };
15
+ const moduleText = `import type { CreateAuthOptions } from '@protobase/server'
16
+
17
+ /**
18
+ * Supabase's own auth.users as the app's user table, written by \`protobase import supabase\`: every foreign key, trigger
19
+ * and policy naming it keeps working. Its passwords are Supabase's bcrypt hashes, and its ids are UUIDs.
20
+ */
21
+ export const supabaseUsers = {
22
+ // Supabase's \`role\` holds the Postgres role, so the app's roles go to a column of their own.
23
+ users: { table: '${supabaseUsers.users.table}', columns: { role: '${supabaseUsers.users.columns.role}' }, metadata: '${supabaseUsers.users.metadata}' },
24
+ passwordHashes: [${supabaseUsers.passwordHashes.map((name) => `'${name}'`).join(", ")}],
25
+ generateUserId: '${supabaseUsers.generateUserId}',
26
+ } satisfies Partial<CreateAuthOptions>
27
+ `;
28
+ const call = "createAuth({";
29
+ const importLine = "import { supabaseUsers } from './supabase-users'\n";
30
+ /**
31
+ * `auth/auth.ts` with the options spread into its one `createAuth({` call, and their import first; fails, naming what
32
+ * to add, otherwise.
33
+ */
34
+ const withSupabaseUsers = (text, file) => {
35
+ const calls = text.split(call).length - 1;
36
+ if (calls !== 1) throw new Error(`${file} must call \`createAuth({\` once, it does ${calls} times: point it at Supabase's auth.users yourself with ${JSON.stringify(supabaseUsers)}, then import again`);
37
+ return `${importLine}${text.replace(call, `${call}\n ...supabaseUsers,`)}`;
38
+ };
39
+ /** Where the app's Better Auth setup lives, and what it becomes; fails before anything is written when it cannot. */
40
+ const planAuthConfig = async (projectDir) => {
41
+ const file = path.join(projectDir, "auth", "auth.ts");
42
+ if (!existsSync(file)) throw new Error(`The project has no auth/auth.ts with its createAuth: import into a project made by create-protobase`);
43
+ const text = withSupabaseUsers(await readFile(file, "utf8"), path.relative(projectDir, file));
44
+ return {
45
+ file,
46
+ write: async () => {
47
+ await writeFile(path.join(path.dirname(file), "supabase-users.ts"), moduleText, { flag: "wx" });
48
+ await writeFile(file, text);
49
+ }
50
+ };
51
+ };
52
+ //#endregion
53
+ export { planAuthConfig, supabaseUsers, withSupabaseUsers };
@@ -1,19 +1,23 @@
1
- import { nextMigrationName } from "../auth/migration-file.js";
2
1
  import { connect } from "../db/connect.js";
2
+ import { planAuthConfig } from "./auth-config.js";
3
3
  import { checkoutMarkers } from "./checkout.js";
4
4
  import { cronPlan } from "./cron-plan.js";
5
5
  import { planFunctions } from "./functions/plan-functions.js";
6
6
  import { writeFunctions } from "./functions/write-functions.js";
7
7
  import { importPlan, probedExtensions } from "./import-plan.js";
8
8
  import { importState } from "./import-state.js";
9
+ import { writeMigration } from "./migration-files.js";
9
10
  import { runPgTool } from "./pg-tools.js";
10
11
  import { replayScript } from "./replay.js";
11
12
  import { schemaMigration } from "./schema-migration.js";
13
+ import { refuseSsoUsers, ssoUserCount } from "./sso-users.js";
12
14
  import { appSchemas, cronJobs, cronTimezone, databaseMarkers, dumpedTables, extensions, httpTriggers, hypertables, pgmqQueues, pgsodiumColumns, platformMigrationTables, realtimeTables, routinesIn, tablesSize, vaultSecretValues, vaultSecrets } from "./source-facts.js";
13
- import { ensureApiRoles, existingTables } from "./target-checks.js";
15
+ import { authStoreMigrations } from "./store-migrations.js";
16
+ import { ensureApiRoles, existingSchemas, existingTables } from "./target-checks.js";
14
17
  import { creatableExtensions } from "./target-extensions.js";
18
+ import { usersColumnsMigration } from "./users-migrations.js";
15
19
  import path from "node:path";
16
- import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
20
+ import { mkdir, readFile, rm } from "node:fs/promises";
17
21
  import { isSchedule } from "@protobase/server";
18
22
  import postgres from "postgres";
19
23
  //#region src/supabase/dump-phase.ts
@@ -91,13 +95,18 @@ const readSource = async (sql, targetUrl) => {
91
95
  })
92
96
  };
93
97
  };
94
- /** Fails unless the target can take the schema migration: makes the API roles it lacks, and finds no table in the way. */
95
- const checkTarget = async (url, tables) => {
98
+ /**
99
+ * Fails unless the target can take the schema migration: makes the API roles it lacks, and finds no schema or table in
100
+ * the way, such as the auth schema of Protobase's own user table, made by the project's auth migrations.
101
+ */
102
+ const checkTarget = async (url, schemas, tables) => {
96
103
  const sql = postgres(url, {
97
104
  max: 1,
98
105
  onnotice: () => {}
99
106
  });
100
107
  try {
108
+ const schemasThere = await existingSchemas(sql, schemas.filter((schema) => schema !== "public"));
109
+ if (schemasThere.length > 0) throw new Error(`The project's database already has the schemas ${schemasThere.join(", ")}, which the import creates; import into a database without them, such as a new one`);
101
110
  const created = await ensureApiRoles(sql);
102
111
  const existing = await existingTables(sql, tables);
103
112
  if (existing.length > 0) throw new Error(`The project's database already has ${existing.length} of the tables to import, such as ${existing.slice(0, 5).join(", ")}; import into a database without them`);
@@ -110,11 +119,15 @@ const checkTarget = async (url, tables) => {
110
119
  const pattern = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
111
120
  /**
112
121
  * The import's first run: dumps the Supabase database's schemas and data as of one snapshot, writes the schema as
113
- * the project's next migration, with the extensions the project's database can create, and keeps the data dump, the
114
- * replay of Vault's secrets, pgmq's queues and pg_cron's jobs and what the report needs in `supabase-import/` for the run that loads
115
- * it, once the project's migrations are applied.
122
+ * the project's next migration, with the extensions the project's database can create, and the columns Better Auth
123
+ * needs on auth.users as the one after, points the app's Better Auth setup at auth.users in place of the user table
124
+ * the project's auth migrations make, removing them, and keeps the data dump, the replay of Vault's secrets, pgmq's
125
+ * queues and pg_cron's jobs and what the report needs in `supabase-import/` for the run that loads it, once the
126
+ * project's migrations are applied.
116
127
  */
117
128
  const runDumpPhase = async (options, out) => {
129
+ const authConfig = await planAuthConfig(options.projectDir);
130
+ const storeMigrations = await authStoreMigrations(options.migrationsDir);
118
131
  const checkout = checkoutMarkers(options.projectDir);
119
132
  if (checkout.length > 0) out(`found the Supabase project's ${checkout.join(", ")}\n`);
120
133
  const functions = await planFunctions(options.projectDir);
@@ -126,8 +139,9 @@ const runDumpPhase = async (options, out) => {
126
139
  await reserved`begin isolation level repeatable read read only`;
127
140
  const [exported] = await reserved`select pg_export_snapshot() as snapshot`;
128
141
  const snapshot = exported.snapshot;
142
+ refuseSsoUsers(await ssoUserCount((text) => reserved.unsafe(text)));
129
143
  const { manifest: source, plan, replay } = await readSource(reserved, options.targetUrl);
130
- const created = await checkTarget(options.targetUrl, source.tables);
144
+ const created = await checkTarget(options.targetUrl, source.schemas, source.tables);
131
145
  if (created.length > 0) out(`created the roles ${created.join(", ")} in the project's database\n`);
132
146
  await state.prepare();
133
147
  const schemaFile = path.join(state.dir, "schema.sql");
@@ -156,8 +170,10 @@ const runDumpPhase = async (options, out) => {
156
170
  });
157
171
  await rm(schemaFile);
158
172
  await mkdir(options.migrationsDir, { recursive: true });
159
- const file = nextMigrationName(await readdir(options.migrationsDir), "supabase_schema");
160
- await writeFile(path.join(options.migrationsDir, file), migration.text, { flag: "wx" });
173
+ const file = await writeMigration(options.migrationsDir, "supabase_schema", migration.text);
174
+ const usersFile = await writeMigration(options.migrationsDir, "supabase_users", usersColumnsMigration());
175
+ await authConfig.write();
176
+ for (const store of storeMigrations) await rm(path.join(options.migrationsDir, store));
161
177
  const packages = await writeFunctions(options.projectDir, functions);
162
178
  await state.writeManifest({
163
179
  migration: file,
@@ -170,7 +186,10 @@ const runDumpPhase = async (options, out) => {
170
186
  },
171
187
  ...source
172
188
  });
173
- out(`wrote ${path.relative(options.projectDir, path.join(options.migrationsDir, file))}, the schemas ${source.schemas.join(", ")}\n`);
189
+ const relative = (to) => path.relative(options.projectDir, to);
190
+ out(`wrote ${relative(path.join(options.migrationsDir, file))}, the schemas ${source.schemas.join(", ")}\n`);
191
+ out(`wrote ${relative(path.join(options.migrationsDir, usersFile))}, the columns Better Auth needs on auth.users, and pointed ${relative(authConfig.file)} at it\n`);
192
+ for (const store of storeMigrations) out(`removed ${relative(path.join(options.migrationsDir, store))}: auth.users replaces Protobase's own user table it made\n`);
174
193
  if (functions.functions.length > 0) out(`converted ${functions.functions.length} Edge Functions into functions/${packages.length > 0 ? `, adding ${packages.length} packages to package.json: install them` : ""}\n`);
175
194
  out(`dumped ${source.tables.length} tables' data into ${path.relative(options.projectDir, state.data)}, which git ignores\n`);
176
195
  if (replay) out(`kept Vault's secrets, pgmq's queues and pg_cron's jobs to make again in ${path.relative(options.projectDir, state.replay)}, which git ignores\n`);
@@ -0,0 +1,72 @@
1
+ //#region src/supabase/identity-providers.ts
2
+ /** GoTrue's providers that Better Auth names otherwise. */
3
+ const renamed = {
4
+ azure: "microsoft",
5
+ linkedin_oidc: "linkedin",
6
+ slack_oidc: "slack",
7
+ x: "twitter"
8
+ };
9
+ /**
10
+ * Where Better Auth keys the account on a claim other than the subject GoTrue keeps as provider_id: Microsoft's
11
+ * `oid`, which GoTrue keeps among the ID token's custom claims.
12
+ */
13
+ const subjects = { azure: `identity_data->'custom_claims'->>'oid'` };
14
+ /** GoTrue's providers that carry no account over: email and phone sign in on the user, anonymous has nothing to. */
15
+ const withoutAccount = [
16
+ "email",
17
+ "phone",
18
+ "anonymous"
19
+ ];
20
+ /** The social providers Better Auth 1.7 has built in that GoTrue has too, by Better Auth's names. */
21
+ const builtIn = [
22
+ "apple",
23
+ "discord",
24
+ "facebook",
25
+ "figma",
26
+ "github",
27
+ "gitlab",
28
+ "google",
29
+ "kakao",
30
+ "linkedin",
31
+ "microsoft",
32
+ "notion",
33
+ "slack",
34
+ "spotify",
35
+ "twitch",
36
+ "twitter",
37
+ "zoom"
38
+ ];
39
+ const providerFate = (provider) => {
40
+ if (withoutAccount.includes(provider)) return {
41
+ kind: "none",
42
+ reason: provider === "anonymous" ? "anonymous users have nothing to sign in with" : `${provider} sign-in lives on the user, not in an account`
43
+ };
44
+ if (provider.startsWith("sso:")) return {
45
+ kind: "none",
46
+ reason: "single sign-on providers are set up again in the app"
47
+ };
48
+ const providerId = renamed[provider] ?? provider;
49
+ return {
50
+ kind: "account",
51
+ providerId,
52
+ builtIn: builtIn.includes(providerId)
53
+ };
54
+ };
55
+ const literal = (text) => `'${text.replaceAll("'", "''")}'`;
56
+ /** SQL over an auth.identities row: the provider id its account gets. */
57
+ const accountProviderSql = `case provider ${Object.entries(renamed).map(([from, to]) => `when ${literal(from)} then ${literal(to)} `).join("")}else provider end`;
58
+ /** SQL over an auth.identities row: the account id its account gets, NULL where the claim is missing. */
59
+ const accountIdSql = `case provider ${Object.entries(subjects).map(([provider, claim]) => `when ${literal(provider)} then ${claim} `).join("")}else provider_id end`;
60
+ /** SQL over an auth.identities row: whether it carries an account over. */
61
+ const carriesAccountSql = `provider <> all(array[${withoutAccount.map(literal).join(", ")}]) and provider not like 'sso:%'`;
62
+ /**
63
+ * SQL over an auth.identities row: whether its user may sign in with it. GoTrue refuses a provider sign-in to a user
64
+ * with an unconfirmed address, though it keeps the user and the identity, and Better Auth would not refuse it: whoever
65
+ * signed in with a provider account claiming someone else's address could then sign in as them. A user without an
66
+ * address has nobody's to claim, and GoTrue lets those in where the provider's email is optional.
67
+ */
68
+ const confirmedOwnerSql = `user_id in (select id from auth.users where email is null or email_confirmed_at is not null)`;
69
+ /** The loaded auth.identities, counted by provider, for the report. */
70
+ const providerCounts = (sql) => sql.unsafe(`select provider, count(*)::int as identities, count(*) filter (where ${accountIdSql} is null)::int as unkeyed, count(*) filter (where ${accountIdSql} is not null and not (${confirmedOwnerSql}))::int as unconfirmed from auth.identities group by 1 order by 1`);
71
+ //#endregion
72
+ export { accountIdSql, accountProviderSql, carriesAccountSql, confirmedOwnerSql, providerCounts, providerFate };
@@ -1,11 +1,16 @@
1
+ import { loadProjectAuth } from "../users/load-auth.js";
2
+ import { writeAuthMigration } from "../auth/write-migration.js";
1
3
  import { connect } from "../db/connect.js";
2
4
  import { runDoctor } from "../doctor/run.js";
3
5
  import { runScaffold } from "../scaffold/run.js";
4
6
  import { convertedCronJobs } from "./cron-plan.js";
5
7
  import { importState } from "./import-state.js";
8
+ import { writeMigration } from "./migration-files.js";
6
9
  import { runPgTool } from "./pg-tools.js";
7
10
  import { loadScript, qualified } from "./load-script.js";
8
11
  import { existingTables, filledTables, otherTables } from "./target-checks.js";
12
+ import { providerCounts } from "./identity-providers.js";
13
+ import { accountsMigration } from "./users-migrations.js";
9
14
  import { cronJobFilesInTheWay, writeCronJobs } from "./cron-jobs-write.js";
10
15
  import { importReport } from "./report.js";
11
16
  import { existsSync } from "node:fs";
@@ -46,14 +51,17 @@ const doctorOutput = async (url, configDir) => {
46
51
  * The import's second run, once the schema migration is applied: loads the data dump, with the replay of Vault's
47
52
  * secrets, pgmq's queues and pg_cron's jobs when the dump made one, in one transaction, deletes both, scaffolds the
48
53
  * config from the imported tables of the app's schemas, leaving the project's own alone and making those of the
49
- * `supabase_realtime` publication live, writes the pg_cron jobs it converts as the project's recurring jobs, and writes
50
- * the report.
54
+ * `supabase_realtime` publication live, writes the pg_cron jobs it converts as the project's recurring jobs, writes
55
+ * the migrations that let Supabase's users sign in with Better Auth (its own tables, as `protobase auth migration`
56
+ * plans them on the loaded auth.users, then the users' columns and accounts), and writes the report. The project's
57
+ * auth keeps a connection pool open, so the process must end itself.
51
58
  */
52
59
  const runLoadPhase = async (options, out) => {
53
60
  const state = importState(options.projectDir);
54
61
  const manifest = await state.readManifest();
55
62
  if (!existsSync(path.join(options.migrationsDir, manifest.migration))) throw new Error(`The import's migration ${manifest.migration} is not in ${options.migrationsDir}; remove supabase-import/ and import again`);
56
63
  await checkReady(options.targetUrl, options.projectDir, manifest);
64
+ const auth = await loadProjectAuth(options.projectDir);
57
65
  const replay = state.hasReplay() ? state.replay : void 0;
58
66
  await writeFile(state.load, loadScript(state.data, manifest.tables, replay), { mode: 384 });
59
67
  await runPgTool("psql", options.targetUrl, [
@@ -88,8 +96,19 @@ const runLoadPhase = async (options, out) => {
88
96
  const cron = convertedCronJobs(manifest.cronJobs);
89
97
  const jobsWired = await writeCronJobs(options.projectDir, cron);
90
98
  if (cron.length > 0) out(`wrote ${cron.length} of pg_cron's jobs as recurring jobs in jobs/\n`);
91
- await writeFile(state.report, importReport(manifest, await doctorOutput(options.targetUrl, options.configDir), jobsWired, live), { mode: 384 });
99
+ const authFile = await writeAuthMigration({
100
+ auth,
101
+ dir: options.migrationsDir,
102
+ name: "auth"
103
+ });
104
+ if (authFile) out(`wrote ${path.relative(options.projectDir, authFile)}, Better Auth's tables next to auth.users\n`);
105
+ const accountsFile = await writeMigration(options.migrationsDir, "supabase_accounts", accountsMigration());
106
+ out(`wrote ${path.relative(options.projectDir, path.join(options.migrationsDir, accountsFile))}, the users' accounts with their Supabase passwords and social providers\n`);
107
+ const target = connect(options.targetUrl);
108
+ const providers = await providerCounts(target).finally(() => target.end());
109
+ await writeFile(state.report, importReport(manifest, await doctorOutput(options.targetUrl, options.configDir), jobsWired, live, providers), { mode: 384 });
92
110
  out(`wrote ${path.relative(options.projectDir, state.report)}: what the import could not carry over\n`);
111
+ out("next: apply the migrations with the project's migrations; Supabase's users then sign in with their own passwords\n");
93
112
  };
94
113
  //#endregion
95
114
  export { runLoadPhase };
@@ -0,0 +1,12 @@
1
+ import { nextMigrationName } from "../auth/migration-file.js";
2
+ import path from "node:path";
3
+ import { readdir, writeFile } from "node:fs/promises";
4
+ //#region src/supabase/migration-files.ts
5
+ /** Writes `text` as the next migration in `dir`, named `name` after its number, and returns its file name. */
6
+ const writeMigration = async (dir, name, text) => {
7
+ const file = nextMigrationName(await readdir(dir), name);
8
+ await writeFile(path.join(dir, file), text, { flag: "wx" });
9
+ return file;
10
+ };
11
+ //#endregion
12
+ export { writeMigration };
@@ -15,7 +15,7 @@ const projectUrl = (text) => {
15
15
  return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
16
16
  };
17
17
  const registerImport = (program) => {
18
- program.command("import").description("Turn another platform's project into this Protobase project").command("supabase").description("Import a Supabase database into the project in the current directory. The first run dumps it and writes its schemas as the project's next migration; once the project's migrations are applied, the second run loads the data, scaffolds the config and writes supabase-import/report.md. With --storage-url, the second run, or any later one, copies Storage's files into the app's file provider").argument("[source]", "the Supabase database's connection string, for the first run").option("--source-env <variable>", "read the Supabase connection string from this environment variable").option("--env <variable>", "environment variable holding the project's database URL", "DATABASE_URL").option("--dir <dir>", "migrations folder", "db/migrations").option("--config <dir>", "config folder", "config").option("--storage-url <url>", "the Supabase project's URL, such as https://<ref>.supabase.co, to copy Storage's files from").option("--storage-key-env <variable>", "environment variable holding the Supabase project's secret key, for --storage-url", "SUPABASE_SERVICE_ROLE_KEY").option("--yes", "copy Storage's files even when they exceed the file provider's max_bytes", false).action(async (source, opts) => {
18
+ program.command("import").description("Turn another platform's project into this Protobase project").command("supabase").description("Import a Supabase database into the project in the current directory. The first run dumps it and writes its schemas as the project's next migration; once the project's migrations are applied, the second run loads the data, scaffolds the config, writes the migrations that sign its users in with Better Auth and writes supabase-import/report.md. With --storage-url, the second run, or any later one, copies Storage's files into the app's file provider").argument("[source]", "the Supabase database's connection string, for the first run").option("--source-env <variable>", "read the Supabase connection string from this environment variable").option("--env <variable>", "environment variable holding the project's database URL", "DATABASE_URL").option("--dir <dir>", "migrations folder", "db/migrations").option("--config <dir>", "config folder", "config").option("--storage-url <url>", "the Supabase project's URL, such as https://<ref>.supabase.co, to copy Storage's files from").option("--storage-key-env <variable>", "environment variable holding the Supabase project's secret key, for --storage-url", "SUPABASE_SERVICE_ROLE_KEY").option("--yes", "copy Storage's files even when they exceed the file provider's max_bytes", false).action(async (source, opts) => {
19
19
  if (source && opts.sourceEnv) throw new Error("Pass either a connection string or --source-env, not both");
20
20
  const projectDir = process.cwd();
21
21
  loadNearestEnvFile(projectDir);
@@ -31,6 +31,7 @@ const registerImport = (program) => {
31
31
  } : void 0,
32
32
  yes: opts.yes
33
33
  }, out);
34
+ process.exit(0);
34
35
  });
35
36
  };
36
37
  //#endregion
@@ -1,4 +1,5 @@
1
1
  import { convertedCronJobs } from "./cron-plan.js";
2
+ import { providerFate } from "./identity-providers.js";
2
3
  //#region src/supabase/report.ts
3
4
  /** Protobase Cloud's Starter plan holds this much data; the import reports a larger database, it does not refuse it. */
4
5
  const starterBytes = 524288e3;
@@ -44,18 +45,34 @@ const carried = (manifest) => [
44
45
  const queuesLeft = (manifest) => manifest.queues?.filter((queue) => !manifest.queuesReplayed || queue.partitioned).map((queue) => `${queue.name}${queue.partitioned ? ", partitioned" : ""}, with ${plural(queue.messages, "message")}`);
45
46
  /** What uses an extension Supabase dropped after Postgres 15, which a person converts. */
46
47
  const conversions = (manifest) => [...manifest.hypertables.map((table) => `hypertable ${table.schema}.${table.table}, ${plural(table.rows, "row")} in chunks the dump leaves out: make it a plain or pg_partman-partitioned table and copy its rows with \`INSERT … SELECT\``), ...manifest.routinesLeftOut.map((routine) => `function ${routine.name}, written in ${routine.language}: rewrite it in plpgsql or as a Protobase function`)];
48
+ /** What became of one provider's identities. */
49
+ const providerLine = ({ provider, identities, unkeyed, unconfirmed }) => {
50
+ const fate = providerFate(provider);
51
+ const counted = `${code(provider)}, ${identities} identit${identities === 1 ? "y" : "ies"}`;
52
+ if (fate.kind === "none") return `${counted}: not carried over, ${fate.reason}`;
53
+ const name = code(fate.providerId);
54
+ const missing = (unkeyed > 0 ? `; ${unkeyed} lack${unkeyed === 1 ? "s" : ""} the claim Better Auth keys ${name} accounts on and ${unkeyed === 1 ? "is" : "are"} not carried over` : "") + (unconfirmed > 0 ? `; ${unconfirmed} belong${unconfirmed === 1 ? "s" : ""} to users who never confirmed their address, whom Supabase refused, and ${unconfirmed === 1 ? "is" : "are"} not carried over` : "");
55
+ return fate.builtIn ? `${counted}: accounts of Better Auth's ${name}${missing}` : `${counted}: accounts named ${name}, a provider Better Auth has not built in: set it up with Better Auth's generic OAuth plugin under that id${missing}`;
56
+ };
57
+ const signInSection = (providers) => [
58
+ "## Sign-in\n",
59
+ "Supabase's users sign in with their own passwords once the migrations the import wrote are applied; those who never confirmed their address sign in by code instead. Sessions do not carry over, so everyone signs in once; MFA factors and passkeys are set up again. No imported user has a role in the app yet: give the admins theirs with `protobase users set-role <email> admin`.\n",
60
+ providers.length === 0 ? "auth.identities is empty.\n" : `Each identity of a social provider became an account, which signs in once the provider is in \`createAuth\`'s \`socialProviders\`, with the client id and secret the Supabase project used. By provider:\n\n${providers.map((provider) => `- ${providerLine(provider)}`).join("\n")}\n`
61
+ ].join("\n");
47
62
  /**
48
63
  * The import's report: what it loaded, and what it could not carry over, for a person or their AI assistant to finish.
49
64
  * `doctor` is `protobase doctor`'s output on the scaffolded config, or `undefined` when there was no config to check;
50
65
  * `jobsWired` whether protobase.config.ts passes the pg_cron jobs the load wrote as its `jobs`; `live` the tables, as
51
- * `schema.table`, whose resources the scaffold gave `.live()`.
66
+ * `schema.table`, whose resources the scaffold gave `.live()`; `providers` counts the loaded auth.identities by
67
+ * provider.
52
68
  */
53
- const importReport = (manifest, doctor, jobsWired, live) => [
69
+ const importReport = (manifest, doctor, jobsWired, live, providers) => [
54
70
  "# Supabase import\n",
55
71
  `Schemas ${manifest.schemas.join(", ")}, restored by the migration \`${manifest.migration}\`, and their data, loaded in one transaction.\n`,
56
72
  `The imported tables take ${megabytes(manifest.bytes)} in the source database${manifest.bytes > starterBytes ? `, more than the ${megabytes(starterBytes)} of the Starter plan: pick a larger plan` : `, within the ${megabytes(starterBytes)} of the Starter plan`}.\n`,
57
73
  `The migration leaves out ${manifest.leftOut} statement${manifest.leftOut === 1 ? "" : "s"} of the dump, as comments: grants to Supabase's own roles and the like.\n`,
58
74
  "## Rows loaded\n\nEach count matched the source before the load committed.\n\n| Table | Rows |\n| --- | --- |\n" + manifest.tables.map((table) => `| ${table.schema}.${table.table} | ${table.rows} |`).join("\n") + "\n",
75
+ signInSection(providers),
59
76
  section("Made again", "A dump cannot carry these. The load made Vault's secrets and pgmq's queues again through each extension's own API, in the same transaction, and scheduled pg_cron's jobs again with `cron.schedule` where the project's database has pg_cron; elsewhere the import made them the app's recurring jobs, on the same schedule. pg_net sends the HTTP triggers' calls from the project's database, Database Webhooks' through the `supabase_functions.http_request` the migration creates.", carried(manifest)),
60
77
  ...recurringJobs(manifest, jobsWired),
61
78
  section("Cron jobs", "These pg_cron jobs did not come over, each for the reason it gives. Make each a Protobase recurring job, or schedule it where the database has pg_cron.", cronLeft(manifest.cronJobs)),
@@ -0,0 +1,14 @@
1
+ //#region src/supabase/sso-users.ts
2
+ /** How many of auth.users are SSO users; none where GoTrue's schema predates `is_sso_user`. */
3
+ const ssoUserCount = async (query) => {
4
+ if ((await query(`select 1 from information_schema.columns where table_schema = 'auth' and table_name = 'users' and column_name = 'is_sso_user'`)).length === 0) return 0;
5
+ const [row] = await query(`select count(*)::int as count from auth.users where is_sso_user`);
6
+ return row.count;
7
+ };
8
+ /** Fails, saying what to do first, when the Supabase project has SSO users. */
9
+ const refuseSsoUsers = (count) => {
10
+ if (count === 0) return;
11
+ throw new Error(`The Supabase project has ${count} single sign-on (SAML) ${count === 1 ? "user" : "users"}, which the import cannot carry over: Supabase opens them only through their identity provider, and Better Auth would find them by email. Merge them into the users with the same address or delete them in Supabase, then import again`);
12
+ };
13
+ //#endregion
14
+ export { refuseSsoUsers, ssoUserCount };
@@ -0,0 +1,15 @@
1
+ import "../auth/migration-file.js";
2
+ import { existsSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { readFile, readdir } from "node:fs/promises";
5
+ //#region src/supabase/store-migrations.ts
6
+ /** The migrations in `dir` that `protobase auth migration` or `protobase migration` wrote for the auth schema. */
7
+ const authStoreMigrations = async (dir) => {
8
+ if (!existsSync(dir)) return [];
9
+ const files = (await readdir(dir)).filter((file) => file.endsWith(".sql")).sort();
10
+ const found = [];
11
+ for (const file of files) if ((await readFile(path.join(dir, file), "utf8")).startsWith(`-- The auth schema changes this version of Protobase needs, written by `)) found.push(file);
12
+ return found;
13
+ };
14
+ //#endregion
15
+ export { authStoreMigrations };
@@ -35,6 +35,10 @@ const ensureApiRoles = async (sql) => {
35
35
  const existingTables = async (sql, tables) => {
36
36
  return (await sql`select name from unnest(${tables.map(qualified)}::text[]) as name where to_regclass(name) is not null`).map((row) => row.name);
37
37
  };
38
+ /** The schemas of `schemas` that `sql`'s database has already, which the schema migration would fail to create. */
39
+ const existingSchemas = async (sql, schemas) => {
40
+ return (await sql`select nspname as name from pg_namespace where nspname = any(${schemas}) order by 1`).map((row) => row.name);
41
+ };
38
42
  /** The dumped tables that hold rows on the target, which a load would add to. */
39
43
  const filledTables = async (sql, tables) => {
40
44
  const filled = [];
@@ -53,4 +57,4 @@ const otherTables = async (sql, schemas, tables) => {
53
57
  `).map((row) => row.name);
54
58
  };
55
59
  //#endregion
56
- export { ensureApiRoles, existingTables, filledTables, otherTables };
60
+ export { ensureApiRoles, existingSchemas, existingTables, filledTables, otherTables };
@@ -0,0 +1,47 @@
1
+ import { accountIdSql, accountProviderSql, carriesAccountSql, confirmedOwnerSql } from "./identity-providers.js";
2
+ //#region src/supabase/users-migrations.ts
3
+ /** The import's first run: the user columns Better Auth needs that GoTrue's auth.users lacks, empty for now. */
4
+ const usersColumnsMigration = () => `-- The columns Better Auth needs on Supabase's auth.users, written by \`protobase import supabase\`.
5
+ -- Empty until the import's accounts migration fills them from what Supabase recorded; NULL where it recorded nothing.
6
+ alter table auth.users
7
+ add column name text,
8
+ add column email_verified boolean,
9
+ add column image text,
10
+ add column app_role text,
11
+ add column banned boolean,
12
+ add column ban_reason text,
13
+ add column ban_expires timestamptz;
14
+
15
+ -- The value GoTrue writes into every user it makes, for the triggers and policies that read it on new sign-ups.
16
+ alter table auth.users alter column role set default 'authenticated', alter column aud set default 'authenticated';
17
+ `;
18
+ /** The import's second run, once the data is loaded and Better Auth's tables are planned: the users' columns and accounts. */
19
+ const accountsMigration = () => `-- Supabase's users signing in with Better Auth, written by \`protobase import supabase\` once their rows were loaded.
20
+
21
+ -- The user columns, from what Supabase Auth recorded. A ban lasts until banned_until, as on Supabase: Better Auth lifts
22
+ -- it once ban_expires has passed.
23
+ update auth.users set
24
+ name = coalesce(raw_user_meta_data->>'full_name', raw_user_meta_data->>'name'),
25
+ email_verified = email_confirmed_at is not null,
26
+ image = coalesce(raw_user_meta_data->>'avatar_url', raw_user_meta_data->>'picture'),
27
+ banned = case when banned_until is not null then true end,
28
+ ban_expires = banned_until;
29
+
30
+ -- Each password, as Supabase hashed it: Better Auth verifies the bcrypt hash and stores it again as its own on sign-in.
31
+ -- Only for confirmed addresses: GoTrue refuses a password sign-in to an unconfirmed one and Better Auth would not, so
32
+ -- whoever signed up with someone else's address could sign in as them. Those users sign in by code or reset a password.
33
+ insert into auth.account (account_id, provider_id, user_id, password, created_at, updated_at)
34
+ select id::text, 'credential', id, encrypted_password, coalesce(created_at, now()), coalesce(updated_at, now())
35
+ from auth.users where encrypted_password is not null and encrypted_password <> '' and email_confirmed_at is not null;
36
+
37
+ -- Each identity of a social provider, by Better Auth's name for it and the claim it keys the account on. Sessions and
38
+ -- provider tokens stay behind: everyone signs in once. Only for users with a confirmed address or none, for the reason
39
+ -- above: GoTrue refuses a provider sign-in to an unconfirmed one too, though it keeps the identity.
40
+ insert into auth.account (account_id, provider_id, user_id, created_at, updated_at)
41
+ select account_id, provider_id, user_id, created_at, updated_at from (
42
+ select ${accountIdSql} as account_id, ${accountProviderSql} as provider_id, user_id, coalesce(created_at, now()) as created_at, coalesce(updated_at, now()) as updated_at
43
+ from auth.identities where ${carriesAccountSql} and ${confirmedOwnerSql}
44
+ ) identity where account_id is not null;
45
+ `;
46
+ //#endregion
47
+ export { accountsMigration, usersColumnsMigration };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.40.3",
3
+ "version": "0.40.4",
4
4
  "description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -36,11 +36,11 @@
36
36
  "@better-auth/core": "^1.7.12",
37
37
  "@hono/node-server": "^2.1.3",
38
38
  "@hono/vite-dev-server": "^0.26.1",
39
- "@protobase/layout": "0.40.3",
40
- "@protobase/query": "0.40.3",
41
- "@protobase/schema": "0.40.3",
42
- "@protobase/server": "0.40.3",
43
- "@protobase/ui": "0.40.3",
39
+ "@protobase/layout": "0.40.4",
40
+ "@protobase/query": "0.40.4",
41
+ "@protobase/schema": "0.40.4",
42
+ "@protobase/server": "0.40.4",
43
+ "@protobase/ui": "0.40.4",
44
44
  "@react-email/render": "^2.1.0",
45
45
  "@scalar/hono-api-reference": "^0.12.10",
46
46
  "@tailwindcss/vite": "^4.3.3",
@@ -64,7 +64,7 @@ createAuth({
64
64
  - `passwordHashes: ['bcrypt']` also verifies bcrypt hashes (`$2a$`, `$2b$`, `$2y$`), and stores the password again as Better Auth's own scrypt after its first sign-in. The 12-character minimum holds for new passwords only, so a shorter existing one still signs in.
65
65
  - `generateUserId: 'uuid'` makes each new user's id a random UUID in the server, for a table whose `id` is a `uuid` without a default, and makes every id column of the other tables a `uuid` too.
66
66
 
67
- The columns Better Auth needs that the table lacks, filled from what the other system recorded, and each password's `credential` row in `account`, come first, from a migration of the project's own; `protobase auth migration` then writes the other tables next to it.
67
+ The columns Better Auth needs that the table lacks come first, from a migration of the project's own; `protobase auth migration` then writes the other tables next to it, and another migration fills the columns from what the other system recorded and gives each password its `credential` row in `account`. For Supabase, [`protobase import supabase`](cli.md#import-supabase)) writes all three and these options.
68
68
 
69
69
  ## Configuration
70
70
 
@@ -510,15 +510,16 @@ protobase import supabase [<connection> | --source-env <variable>] [--env DATABA
510
510
 
511
511
  Turns a Supabase project's database into the project in the current directory, in two runs with the project's migrations between them. It needs PostgreSQL's `pg_dump` and `psql` on `PATH`, of the Supabase database's major version or newer, and reads the `.env` nearest the current directory for the project's database (`--env`).
512
512
 
513
- 1. **The first run** takes the Supabase database's connection string, for its `postgres` role (the session pooler's or the direct one; the transaction pooler cannot hold the snapshot the dumps share). It fails unless the database has Supabase's `auth` and `storage` schemas and its `supabase_admin` role, and notes the Supabase CLI's `supabase/config.toml`, `supabase/migrations/` and `supabase/functions/` when the checkout has them. It converts `supabase/functions` into the project's `functions/` (see [functions moved from Supabase](../guides/api-functions.md#functions-moved-from-supabase))): `Deno.serve(handler)` and std's `serve(handler)` become `export default defineFunction({ supabase: true }, { fetch: handler })`, an existing default export is wrapped the same way, so each function also answers at `/api/sb/functions/v1/<name>`, `npm:`, `jsr:` and esm.sh imports become bare imports of packages it adds to `package.json`, `Deno.env.get(name)` becomes `process.env[name]`, `EdgeRuntime.waitUntil` becomes `waitUntil` of `@protobase/server`, a function with `verify_jwt = false` in `config.toml` becomes public (`{ public: true, supabase: true }`), and `_shared` and the like are converted beside them. It stops before anything else when `functions/` already has one of their names. It dumps `auth`, `storage` and every schema the app made, schema and data apart, as of one snapshot, leaving out the platform's own migration tables, and writes the schemas as the project's next migration, `NNN_supabase_schema.sql`. It asks the project's database which of the app's extensions its role may create, by trying each in a transaction it rolls back: Postgres alone allows the trusted ones, Supabase's Postgres image all it allowlists, such as pg_net, pgmq and Vault. The migration creates those first, then, where pg_net is among them and the app has Database Webhooks, the `supabase_functions.http_request` function their triggers call, over pg_net; then the dump without what fails there, as comments: grants and default privileges for `dashboard_user`, `supabase_*`, `authenticator` and `postgres`, statements about the `public` schema, Realtime's publication, pgsodium's security labels, the views that decrypt with it and the triggers that encrypt with it, database webhooks without pg_net, functions in plv8, plls or plcoffee where the database has no such language, and a timescaledb hypertable's insert-blocking trigger. The project's database needs the roles `anon`, `authenticated` and `service_role` that the dump's grants and policies name; the command makes them when its role may, and otherwise stops, naming them. The data dump goes to `supabase-import/`, which it adds to `.gitignore`, since it holds every row and the users' password hashes. Where the project's database can create Vault, pgmq and pg_cron, `supabase-import/replay.sql` holds what a dump cannot carry: Vault's secrets with their values, read decrypted since only Supabase's key opens their ciphertext, pgmq's queues with their messages, since pgmq owns their tables, and pg_cron's jobs, which live in its own schema.
513
+ 1. **The first run** takes the Supabase database's connection string, for its `postgres` role (the session pooler's or the direct one; the transaction pooler cannot hold the snapshot the dumps share). It fails unless the database has Supabase's `auth` and `storage` schemas and its `supabase_admin` role, and while `auth.users` has single sign-on (SAML) users, which Supabase opens only through their identity provider and Better Auth would find by email: merge or delete them in Supabase first. It notes the Supabase CLI's `supabase/config.toml`, `supabase/migrations/` and `supabase/functions/` when the checkout has them. It converts `supabase/functions` into the project's `functions/` (see [functions moved from Supabase](../guides/api-functions.md#functions-moved-from-supabase))): `Deno.serve(handler)` and std's `serve(handler)` become `export default defineFunction({ supabase: true }, { fetch: handler })`, an existing default export is wrapped the same way, so each function also answers at `/api/sb/functions/v1/<name>`, `npm:`, `jsr:` and esm.sh imports become bare imports of packages it adds to `package.json`, `Deno.env.get(name)` becomes `process.env[name]`, `EdgeRuntime.waitUntil` becomes `waitUntil` of `@protobase/server`, a function with `verify_jwt = false` in `config.toml` becomes public (`{ public: true, supabase: true }`), and `_shared` and the like are converted beside them. It stops before anything else when `functions/` already has one of their names. It dumps `auth`, `storage` and every schema the app made, schema and data apart, as of one snapshot, leaving out the platform's own migration tables, and writes the schemas as the project's next migration, `NNN_supabase_schema.sql`. It asks the project's database which of the app's extensions its role may create, by trying each in a transaction it rolls back: Postgres alone allows the trusted ones, Supabase's Postgres image all it allowlists, such as pg_net, pgmq and Vault. The migration creates those first, then, where pg_net is among them and the app has Database Webhooks, the `supabase_functions.http_request` function their triggers call, over pg_net; then the dump without what fails there, as comments: grants and default privileges for `dashboard_user`, `supabase_*`, `authenticator` and `postgres`, statements about the `public` schema, Realtime's publication, pgsodium's security labels, the views that decrypt with it and the triggers that encrypt with it, database webhooks without pg_net, functions in plv8, plls or plcoffee where the database has no such language, and a timescaledb hypertable's insert-blocking trigger. It then writes `NNN_supabase_users.sql`, the nullable columns Better Auth needs on `auth.users` (`name`, `email_verified`, `image`, `app_role`, `banned`, `ban_reason`, `ban_expires`) and GoTrue's `'authenticated'` as the default of `role` and `aud`. It points the app at `auth.users`: `auth/auth.ts` gets `...supabaseUsers` in its one `createAuth({` call, from the new `auth/supabase-users.ts` (the table, `role` in `app_role`, `raw_user_meta_data` as the metadata, bcrypt hashes and UUID ids; see [an existing users table](auth.md#an-existing-users-table))). It removes the migrations `protobase auth migration` or `protobase migration` wrote for Protobase's own user table, since `auth.users` replaces it, and stops before writing anything when `auth/auth.ts` is missing or calls `createAuth({` other than once, or when the project's database has a schema the dump creates already, such as the `auth` schema those migrations made. The project's database needs the roles `anon`, `authenticated` and `service_role` that the dump's grants and policies name; the command makes them when its role may, and otherwise stops, naming them. The data dump goes to `supabase-import/`, which it adds to `.gitignore`, since it holds every row and the users' password hashes. Where the project's database can create Vault, pgmq and pg_cron, `supabase-import/replay.sql` holds what a dump cannot carry: Vault's secrets with their values, read decrypted since only Supabase's key opens their ciphertext, pgmq's queues with their messages, since pgmq owns their tables, and pg_cron's jobs, which live in its own schema.
514
514
  2. **Apply the migration** with the project's other migrations, such as `bun run db:migrate`.
515
- 3. **The second run**, without a connection string, loads the data in one transaction, with the app's triggers off so a sign-up trigger on `auth.users` does not run again for users who already have their rows, and fails the transaction unless every table holds the source's number of rows. In the same transaction it makes Vault's secrets and pgmq's queues again through `vault.create_secret`, `pgmq.create` and `pgmq.send`, each message with its headers and the time it becomes visible. Where the project's database has pg_cron, as Supabase's Postgres image does when it serves that database, it schedules pg_cron's jobs again there with `cron.schedule`, run by the importing role, an inactive one inactive. Elsewhere it writes each job of plain SQL as a [recurring job](jobs.md#recurring-jobs)) of its own in `jobs/`, of the same name, schedule and `cron.timezone`, that runs its SQL as the app's database role, tried once each time as pg_cron did, exports it from `jobs/index.ts` and adds `jobs` to `protobase.config.ts` (or writes one); they run once [`migration`](#migration) has added the jobs schema. Recurring jobs wake an app that sleeps, so they run where a host stops an idle app too. A job that calls what the database lacks, such as pg_net's `net.http_*`, `cron` or Vault, an inactive one and a schedule recurring jobs do not take, such as `30 seconds` or `$`, stay in the report, as does a job of another database. It loads only into empty tables, deletes the data dump and the replay, runs [`scaffold`](#scaffold) on the imported tables of the app's schemas (not `auth` or `storage`), giving the tables of the `supabase_realtime` publication [`.live()`](live.md)) so [`/api/sb/realtime/v1`](supabase-realtime.md)) keeps sending their `postgres_changes` once [`migration`](#migration) has written their capture triggers, and writes `supabase-import/report.md`: the rows loaded, the imported tables' size against the Starter plan's 500 MB, what it made again, the tables it made live, and what needs a person: the pg_cron jobs it could not carry over, each with why, Realtime tables it made no resource of, Vault secrets by name and pgmq queues where the database has no such extension (and partitioned queues), the columns pgsodium encrypts, still holding Supabase's ciphertext, whose values to export decrypted in Supabase before declaring them [`.encrypted()`](data-config.md#encrypted-fields)) and running [`encryption apply`](#encryption-apply), the extensions it cannot create, hypertables and plv8, plls or plcoffee functions to convert, triggers that call out over HTTP without pg_net, the converted Edge Functions with the packages to install and the code the conversion left (`deno.land/x` imports, Deno's file, KV and WebSocket APIs, `Supabase.ai`), and the indexes [`doctor`](#doctor) finds missing.
515
+ 3. **The second run**, without a connection string, loads the data in one transaction, with the app's triggers off so a sign-up trigger on `auth.users` does not run again for users who already have their rows, and fails the transaction unless every table holds the source's number of rows. In the same transaction it makes Vault's secrets and pgmq's queues again through `vault.create_secret`, `pgmq.create` and `pgmq.send`, each message with its headers and the time it becomes visible. Where the project's database has pg_cron, as Supabase's Postgres image does when it serves that database, it schedules pg_cron's jobs again there with `cron.schedule`, run by the importing role, an inactive one inactive. Elsewhere it writes each job of plain SQL as a [recurring job](jobs.md#recurring-jobs)) of its own in `jobs/`, of the same name, schedule and `cron.timezone`, that runs its SQL as the app's database role, tried once each time as pg_cron did, exports it from `jobs/index.ts` and adds `jobs` to `protobase.config.ts` (or writes one); they run once [`migration`](#migration) has added the jobs schema. Recurring jobs wake an app that sleeps, so they run where a host stops an idle app too. A job that calls what the database lacks, such as pg_net's `net.http_*`, `cron` or Vault, an inactive one and a schedule recurring jobs do not take, such as `30 seconds` or `$`, stay in the report, as does a job of another database. It loads only into empty tables, deletes the data dump and the replay, runs [`scaffold`](#scaffold) on the imported tables of the app's schemas (not `auth` or `storage`), giving the tables of the `supabase_realtime` publication [`.live()`](live.md)) so [`/api/sb/realtime/v1`](supabase-realtime.md)) keeps sending their `postgres_changes` once [`migration`](#migration) has written their capture triggers, writes Better Auth's other tables next to `auth.users` as [`auth migration`](#auth-migration) does (`NNN_auth.sql`), then `NNN_supabase_accounts.sql`, and writes `supabase-import/report.md`: the rows loaded, the imported tables' size against the Starter plan's 500 MB, each sign-in provider's identities, what it made again, the tables it made live, and what needs a person: the pg_cron jobs it could not carry over, each with why, Realtime tables it made no resource of, Vault secrets by name and pgmq queues where the database has no such extension (and partitioned queues), the columns pgsodium encrypts, still holding Supabase's ciphertext, whose values to export decrypted in Supabase before declaring them [`.encrypted()`](data-config.md#encrypted-fields)) and running [`encryption apply`](#encryption-apply), the extensions it cannot create, hypertables and plv8, plls or plcoffee functions to convert, triggers that call out over HTTP without pg_net, the converted Edge Functions with the packages to install and the code the conversion left (`deno.land/x` imports, Deno's file, KV and WebSocket APIs, `Supabase.ai`), and the indexes [`doctor`](#doctor) finds missing. `NNN_supabase_accounts.sql` fills the user columns from what Supabase Auth recorded and leaves them empty where it recorded nothing: the name from `raw_user_meta_data`'s `full_name` or `name`, the picture from its `avatar_url` or `picture`, `email_verified` from `email_confirmed_at`, and a ban from `banned_until`, which Better Auth lifts once it has passed. It gives each password of a confirmed address, as Supabase hashed it, a `credential` account (a user who never confirmed theirs signs in by code or resets the password, since GoTrue refused their password sign-in too), and each identity of a social provider an account under Better Auth's name for it (`azure` is `microsoft`, keyed on the `oid` claim; `linkedin_oidc` is `linkedin`, `slack_oidc` is `slack`, `x` is `twitter`), unless its user has an address they never confirmed, since GoTrue refused that sign-in too. Email, phone, anonymous and single sign-on identities, sessions, MFA factors and passkeys do not carry over.
516
+ 4. **Apply the migrations** again. Supabase's users then sign in with their own passwords, and with a social provider once it is in `createAuth`'s `socialProviders`; new users get a UUID in `auth.users`, so the app's triggers there run for them.
516
517
 
517
- 4. **Storage's files**: with `--storage-url https://<ref>.supabase.co` and the project's secret key in the variable `--storage-key-env` names, `SUPABASE_SERVICE_ROLE_KEY` by default, the second run, or any run after it, copies the bytes of every object in `storage.objects` from the Supabase project's Storage API into the app's [Storage file provider](supabase-storage.md#where-things-are-kept)), where [`/api/sb/storage/v1`](supabase-storage.md)) serves them, with the type and cache control the rows recorded. It streams each object, checks its byte count against the size Supabase recorded and its MD5 against the ETag where that is one, and deletes a copy that does not match. It first prints each bucket's size and stops when what is left to copy and what the provider holds exceed the provider's `max_bytes`, unless `--yes`. An object that fails does not stop the rest; the run then fails, listing them in `supabase-import/storage.md`, and a rerun copies only what the provider does not hold yet. The key goes only in the requests' headers, never in a file.
518
+ 5. **Storage's files**: with `--storage-url https://<ref>.supabase.co` and the project's secret key in the variable `--storage-key-env` names, `SUPABASE_SERVICE_ROLE_KEY` by default, the second run, or any run after it, copies the bytes of every object in `storage.objects` from the Supabase project's Storage API into the app's [Storage file provider](supabase-storage.md#where-things-are-kept)), where [`/api/sb/storage/v1`](supabase-storage.md)) serves them, with the type and cache control the rows recorded. It streams each object, checks its byte count against the size Supabase recorded and its MD5 against the ETag where that is one, and deletes a copy that does not match. It first prints each bucket's size and stops when what is left to copy and what the provider holds exceed the provider's `max_bytes`, unless `--yes`. An object that fails does not stop the rest; the run then fails, listing them in `supabase-import/storage.md`, and a rerun copies only what the provider does not hold yet. The key goes only in the requests' headers, never in a file.
518
519
 
519
520
  An agent with the `supabase-move` skill of [`skill install`](#skill) finishes what the report leaves: it rewrites each item, checking the project's database for the extensions an item needs, and runs `doctor` and the typecheck until both pass, leaving the values of Vault's secrets for you to enter.
520
521
 
521
- Remove `supabase-import/` to import again. Signing in Supabase's users with Protobase's auth is not part of this command yet.
522
+ Remove `supabase-import/` to import again.
522
523
 
523
524
  ## `mobile`
524
525
 
@@ -36,6 +36,16 @@ description: Finish a move from Supabase to Protobase after `protobase import su
36
36
 
37
37
  Nothing to do: each table's count matched the source before the load committed.
38
38
 
39
+ ### Sign-in
40
+
41
+ Passwords need nothing: the import's migrations carry them over. For each provider listed with accounts:
42
+
43
+ - one Better Auth has built in, such as `github` or `microsoft`: add it to `createAuth`'s `socialProviders` in `auth/auth.ts` under that id, with the client id and secret read from environment variables named after it (`GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`), added empty to `.env.example`. See [Sign-in with GitHub](../protobase/references/reference/auth.md#sign-in-with-github). The values are the ones the Supabase project used: the user enters them;
44
+ - one it has not built in: stop on it and say the user needs Better Auth's generic OAuth plugin under that id;
45
+ - one not carried over: nothing to do.
46
+
47
+ Leave giving the admins their role to the user, as the report says: only they know who the admins are.
48
+
39
49
  ### Made again
40
50
 
41
51
  Nothing to do: the project's database has these extensions and the load made each item again there.