@protobase/cli 0.58.6 → 0.58.8
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.
- package/dist/auth/migration-file.js +2 -2
- package/dist/auth/write-migration.js +2 -2
- package/dist/cli/package.js +1 -1
- package/dist/dev/entry.js +4 -1
- package/dist/migration/load-project.js +4 -1
- package/dist/serve/lifecycle.js +4 -1
- package/dist/supabase/auth-config.js +53 -20
- package/dist/supabase/dump-phase.js +3 -3
- package/dist/supabase/load-phase.js +1 -1
- package/dist/supabase/project-users.d.ts +5 -5
- package/dist/supabase/project-users.js +15 -15
- package/dist/supabase/shared-users-migration.js +120 -0
- package/package.json +7 -7
- package/skills/protobase/references/features/compatibility.md +1 -0
- package/skills/protobase/references/getting-started.md +1 -1
- package/skills/protobase/references/reference/auth.md +17 -1
- package/skills/protobase/references/reference/cli.md +1 -1
- package/skills/protobase/references/reference/config/sign-in.md +3 -3
|
@@ -14,7 +14,7 @@ const nextMigrationName = (files, name) => {
|
|
|
14
14
|
};
|
|
15
15
|
/** What an auth schema migration holds, its first line, whichever command wrote it. */
|
|
16
16
|
const authMigrationTitle = "The auth schema changes this version of Protobase needs";
|
|
17
|
-
/** The file's contents: what wrote it and why, then Better Auth's statements, one per paragraph. */
|
|
18
|
-
const migrationText = (sql) => `-- ${authMigrationTitle}, written by
|
|
17
|
+
/** The file's contents: what wrote it, `writer`, and why, then Better Auth's statements, one per paragraph. */
|
|
18
|
+
const migrationText = (sql, writer = "protobase auth migration") => `-- ${authMigrationTitle}, written by \`${writer}\`.\n-- Applied with the project's other migrations; edit or remove statements the project handles differently.\n\n${sql}\n`;
|
|
19
19
|
//#endregion
|
|
20
20
|
export { authMigrationTitle, migrationText, nextMigrationName };
|
|
@@ -8,12 +8,12 @@ import { authSchemaMigration } from "@protobase/server";
|
|
|
8
8
|
* `undefined` when the database is current. The changes are found by comparing the database with what Better Auth
|
|
9
9
|
* needs, so the project's earlier migrations must be applied to it first.
|
|
10
10
|
*/
|
|
11
|
-
const writeAuthMigration = async ({ auth, dir, name }) => {
|
|
11
|
+
const writeAuthMigration = async ({ auth, dir, name, writer }) => {
|
|
12
12
|
const sql = await authSchemaMigration(auth);
|
|
13
13
|
if (sql === void 0) return void 0;
|
|
14
14
|
await mkdir(dir, { recursive: true });
|
|
15
15
|
const file = path.join(dir, nextMigrationName(await readdir(dir), name));
|
|
16
|
-
await writeFile(file, migrationText(sql), { flag: "wx" });
|
|
16
|
+
await writeFile(file, migrationText(sql, writer), { flag: "wx" });
|
|
17
17
|
return file;
|
|
18
18
|
};
|
|
19
19
|
//#endregion
|
package/dist/cli/package.js
CHANGED
package/dist/dev/entry.js
CHANGED
|
@@ -26,7 +26,10 @@ if (project.auth) await checkResourcesOutsideAuthStore(db, resources.map((resour
|
|
|
26
26
|
await checkChanges(db, resources.map((resource) => resource.toModel()), project.events);
|
|
27
27
|
await checkComments(db, resources.map((resource) => resource.toModel()));
|
|
28
28
|
await checkComputed(db, resources.map((resource) => resource.toModel()));
|
|
29
|
-
if (assistantSettings(project.options?.assistant, process.env)?.kind === "built-in") await checkQueryRunner(db, project.auth ? authStoreTables(project.auth) :
|
|
29
|
+
if (assistantSettings(project.options?.assistant, process.env)?.kind === "built-in") await checkQueryRunner(db, project.auth ? authStoreTables(project.auth) : {
|
|
30
|
+
tables: [],
|
|
31
|
+
schemas: []
|
|
32
|
+
});
|
|
30
33
|
checkAi({
|
|
31
34
|
models: resources.map((resource) => resource.toModel()),
|
|
32
35
|
views: views.map((source) => source.toModel()),
|
|
@@ -42,7 +42,10 @@ const migrationProject = async (config, url) => {
|
|
|
42
42
|
...notifications && { notifications },
|
|
43
43
|
jobs,
|
|
44
44
|
readOnlyQueries: assistantSettings(config.assistant, process.env)?.kind === "built-in",
|
|
45
|
-
authTables: auth ? authStoreTables(auth) :
|
|
45
|
+
authTables: auth ? authStoreTables(auth) : {
|
|
46
|
+
tables: [],
|
|
47
|
+
schemas: []
|
|
48
|
+
},
|
|
46
49
|
close: async () => {
|
|
47
50
|
await database.db.destroy();
|
|
48
51
|
}
|
package/dist/serve/lifecycle.js
CHANGED
|
@@ -32,7 +32,10 @@ const startServe = async ({ config, env, openDb = (url) => openAppDatabase(pg, u
|
|
|
32
32
|
if (env.startupChecks) await checkChanges(db, resources.map((resource) => resource.toModel()), project.events);
|
|
33
33
|
if (env.startupChecks) await checkComments(db, resources.map((resource) => resource.toModel()));
|
|
34
34
|
if (env.startupChecks) await checkComputed(db, resources.map((resource) => resource.toModel()));
|
|
35
|
-
if (env.startupChecks && assistantSettings(project.options?.assistant, process.env)?.kind === "built-in") await checkQueryRunner(db, project.auth ? authStoreTables(project.auth) :
|
|
35
|
+
if (env.startupChecks && assistantSettings(project.options?.assistant, process.env)?.kind === "built-in") await checkQueryRunner(db, project.auth ? authStoreTables(project.auth) : {
|
|
36
|
+
tables: [],
|
|
37
|
+
schemas: []
|
|
38
|
+
});
|
|
36
39
|
if (env.startupChecks) checkAi({
|
|
37
40
|
models: resources.map((resource) => resource.toModel()),
|
|
38
41
|
views: views.map((source) => source.toModel()),
|
|
@@ -4,55 +4,88 @@ import path from "node:path";
|
|
|
4
4
|
import { readFile, writeFile } from "node:fs/promises";
|
|
5
5
|
import { Node } from "ts-morph";
|
|
6
6
|
//#region src/supabase/auth-config.ts
|
|
7
|
-
/** The `auth` settings for Supabase's auth.users. */
|
|
7
|
+
/** The `auth` settings for Supabase's auth.users as the user table, on a copy of the database the import owns. */
|
|
8
8
|
const supabaseUsers = {
|
|
9
9
|
users: {
|
|
10
10
|
table: "users",
|
|
11
11
|
columns: { role: "app_role" },
|
|
12
|
-
metadata: "raw_user_meta_data"
|
|
12
|
+
metadata: "raw_user_meta_data",
|
|
13
|
+
guardedSchemas: ["auth"]
|
|
13
14
|
},
|
|
14
15
|
passwordHashes: ["bcrypt"],
|
|
15
16
|
generateUserId: "uuid"
|
|
16
17
|
};
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
18
|
+
/** The schema of the app's own sign-in data on a Supabase database, beside Supabase's `auth`. */
|
|
19
|
+
const sharedUsersSchema = "app_auth";
|
|
20
|
+
/** The `auth` settings for a view over Supabase's auth.users, on a Supabase database the app shares with Supabase Auth. */
|
|
21
|
+
const supabaseUsersView = {
|
|
22
|
+
schema: sharedUsersSchema,
|
|
23
|
+
users: {
|
|
24
|
+
...supabaseUsers.users,
|
|
25
|
+
keyTable: {
|
|
26
|
+
schema: "auth",
|
|
27
|
+
table: "users"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
passwordHashes: supabaseUsers.passwordHashes,
|
|
31
|
+
generateUserId: supabaseUsers.generateUserId
|
|
32
|
+
};
|
|
33
|
+
const importedUsersConfig = {
|
|
34
|
+
settings: supabaseUsers,
|
|
35
|
+
comment: [
|
|
36
|
+
"Supabase's own auth.users as the app's user table, written by `protobase import supabase`: every foreign key,",
|
|
37
|
+
"trigger and policy naming it keeps working. Its passwords are bcrypt hashes, its ids UUIDs, and its `role` the",
|
|
38
|
+
"Postgres role, so the app's roles go to a column of their own. No resource may be over a table of auth, where",
|
|
39
|
+
"Supabase Auth keeps its sessions, tokens and secrets, and the assistant never reads one."
|
|
40
|
+
]
|
|
41
|
+
};
|
|
42
|
+
const sharedUsersConfig = {
|
|
43
|
+
settings: supabaseUsersView,
|
|
44
|
+
comment: [
|
|
45
|
+
`Supabase's users, read through the view ${sharedUsersSchema}.users over auth.users, written by \`create protobase\`: the app`,
|
|
46
|
+
`keeps only its own sign-in data, in ${sharedUsersSchema}, and Supabase's auth schema stays as Supabase set it up. Their`,
|
|
47
|
+
"passwords are bcrypt hashes, their ids UUIDs, and `role` in auth.users the Postgres role, so the app's roles go to a",
|
|
48
|
+
"column of their own. No resource may be over a table of auth, where Supabase Auth keeps its sessions, tokens and",
|
|
49
|
+
"secrets, and the assistant never reads one."
|
|
50
|
+
]
|
|
51
|
+
};
|
|
52
|
+
const literal = (value) => {
|
|
53
|
+
if (typeof value === "string") return `'${value}'`;
|
|
54
|
+
if (Array.isArray(value)) return `[${value.map(literal).join(", ")}]`;
|
|
55
|
+
if (typeof value === "object" && value !== null) return `{ ${Object.entries(value).map(([key, item]) => `${key}: ${literal(item)}`).join(", ")} }`;
|
|
56
|
+
throw new Error(`Not implemented: a setting of type ${typeof value}`);
|
|
57
|
+
};
|
|
58
|
+
const settingsText = ({ settings, comment }, indent) => [...comment.map((line) => `// ${line}`), ...Object.entries(settings).map(([key, value]) => `${key}: ${literal(value)},`)].map((line) => `${indent}${line}`).join("\n");
|
|
26
59
|
/**
|
|
27
60
|
* protobase.config.ts with the settings first in its `auth`, or with an `auth` of them when it has none, sign-in being
|
|
28
61
|
* on by default; fails, naming what to add, when it exports no object the import can see or its `auth` is not one.
|
|
29
62
|
*/
|
|
30
|
-
const withSupabaseUsers = (text, file) => {
|
|
63
|
+
const withSupabaseUsers = (text, file, users) => {
|
|
31
64
|
const config = exportedConfigObject(text).object;
|
|
32
|
-
const refused = () => /* @__PURE__ */ new Error(`${file} must export a config with an \`auth: { ... }\` object: point it at Supabase's auth.users yourself with ${JSON.stringify(
|
|
65
|
+
const refused = () => /* @__PURE__ */ new Error(`${file} must export a config with an \`auth: { ... }\` object: point it at Supabase's auth.users yourself with ${JSON.stringify(users.settings)}, then try again`);
|
|
33
66
|
if (!config) throw refused();
|
|
34
67
|
const auth = config.getProperty("auth");
|
|
35
68
|
if (!auth) {
|
|
36
69
|
const last = config.getProperties().at(-1);
|
|
37
|
-
if (!last) return `${text.slice(0, config.getStart())}{ auth: ${
|
|
38
|
-
return `${text.slice(0, last.getEnd())}, auth: ${
|
|
70
|
+
if (!last) return `${text.slice(0, config.getStart())}{ auth: ${literal(users.settings)} }${text.slice(config.getEnd())}`;
|
|
71
|
+
return `${text.slice(0, last.getEnd())}, auth: ${literal(users.settings)}${text.slice(last.getEnd())}`;
|
|
39
72
|
}
|
|
40
73
|
const object = Node.isPropertyAssignment(auth) ? auth.getInitializer() : void 0;
|
|
41
74
|
if (!object || !Node.isObjectLiteralExpression(object)) throw refused();
|
|
42
75
|
const first = object.getProperties()[0];
|
|
43
76
|
const indent = first ? " ".repeat(first.getStartLinePos() === first.getStart() ? 0 : first.getStart() - first.getStartLinePos()) : " ";
|
|
44
77
|
const at = object.getStart() + 1;
|
|
45
|
-
return `${text.slice(0, at)}\n${settingsText(indent)}${first ? "" : "\n"}${text.slice(at)}`;
|
|
78
|
+
return `${text.slice(0, at)}\n${settingsText(users, indent)}${first ? "" : "\n"}${text.slice(at)}`;
|
|
46
79
|
};
|
|
47
80
|
/** Where the app's Better Auth settings live, and what they become; fails before anything is written when it cannot. */
|
|
48
|
-
const planAuthConfig = async (projectDir) => {
|
|
81
|
+
const planAuthConfig = async (projectDir, users) => {
|
|
49
82
|
const file = path.join(projectDir, "protobase.config.ts");
|
|
50
|
-
if (!existsSync(file)) throw new Error("The project has no protobase.config.ts with its `auth`:
|
|
51
|
-
const text = withSupabaseUsers(await readFile(file, "utf8"), path.relative(projectDir, file));
|
|
83
|
+
if (!existsSync(file)) throw new Error("The project has no protobase.config.ts with its `auth`: start from a project made by create-protobase");
|
|
84
|
+
const text = withSupabaseUsers(await readFile(file, "utf8"), path.relative(projectDir, file), users);
|
|
52
85
|
return {
|
|
53
86
|
file,
|
|
54
87
|
write: () => writeFile(file, text)
|
|
55
88
|
};
|
|
56
89
|
};
|
|
57
90
|
//#endregion
|
|
58
|
-
export { planAuthConfig, supabaseUsers, withSupabaseUsers };
|
|
91
|
+
export { importedUsersConfig, planAuthConfig, sharedUsersConfig, sharedUsersSchema, supabaseUsers, supabaseUsersView, withSupabaseUsers };
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { connect } from "../db/connect.js";
|
|
2
2
|
import { databaseMarkers, missingMarkers } from "./platform-schemas.js";
|
|
3
|
-
import { planAuthConfig } from "./auth-config.js";
|
|
3
|
+
import { importedUsersConfig, planAuthConfig } from "./auth-config.js";
|
|
4
4
|
import { writeMigration } from "./migration-files.js";
|
|
5
5
|
import { authStoreMigrations } from "./store-migrations.js";
|
|
6
|
-
import { usersColumnsMigration } from "./users-migrations.js";
|
|
7
6
|
import { checkoutMarkers } from "./checkout.js";
|
|
8
7
|
import { cronPlan } from "./cron-plan.js";
|
|
9
8
|
import { planFunctions } from "./functions/plan-functions.js";
|
|
@@ -18,6 +17,7 @@ import { countSsoUsers, refuseSsoUsers } from "./sso-users.js";
|
|
|
18
17
|
import { appSchemas, cronJobs, cronTimezone, dumpedTables, extensions, httpTriggers, hypertables, pgmqQueues, pgsodiumColumns, platformMigrationTables, realtimeTables, routinesIn, tablesSize, vaultSecretValues, vaultSecrets } from "./source-facts.js";
|
|
19
18
|
import { ensureApiRoles, existingSchemas, existingTables } from "./target-checks.js";
|
|
20
19
|
import { creatableExtensions } from "./target-extensions.js";
|
|
20
|
+
import { usersColumnsMigration } from "./users-migrations.js";
|
|
21
21
|
import path from "node:path";
|
|
22
22
|
import { mkdir, readFile, rm } from "node:fs/promises";
|
|
23
23
|
import { isSchedule } from "@protobase/server";
|
|
@@ -131,7 +131,7 @@ const pattern = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
|
|
|
131
131
|
* project's migrations are applied.
|
|
132
132
|
*/
|
|
133
133
|
const runDumpPhase = async (options, out) => {
|
|
134
|
-
const authConfig = await planAuthConfig(options.projectDir);
|
|
134
|
+
const authConfig = await planAuthConfig(options.projectDir, importedUsersConfig);
|
|
135
135
|
const storeMigrations = await authStoreMigrations(options.migrationsDir);
|
|
136
136
|
const checkout = checkoutMarkers(options.projectDir);
|
|
137
137
|
if (checkout.length > 0) out(`found the Supabase project's ${checkout.join(", ")}\n`);
|
|
@@ -5,13 +5,13 @@ import { runScaffold } from "../scaffold/run.js";
|
|
|
5
5
|
import { writeAuthMigration } from "../auth/write-migration.js";
|
|
6
6
|
import { writeMigration } from "./migration-files.js";
|
|
7
7
|
import { providerCounts } from "./identity-providers.js";
|
|
8
|
-
import { accountsMigration } from "./users-migrations.js";
|
|
9
8
|
import { runDoctor } from "../doctor/run.js";
|
|
10
9
|
import { convertedCronJobs } from "./cron-plan.js";
|
|
11
10
|
import { importState } from "./import-state.js";
|
|
12
11
|
import { runPgTool } from "./pg-tools.js";
|
|
13
12
|
import { loadScript, qualified } from "./load-script.js";
|
|
14
13
|
import { existingTables, filledTables, otherTables } from "./target-checks.js";
|
|
14
|
+
import { accountsMigration } from "./users-migrations.js";
|
|
15
15
|
import { cronJobFilesInTheWay, writeCronJobs } from "./cron-jobs-write.js";
|
|
16
16
|
import { importReport } from "./report.js";
|
|
17
17
|
import { existsSync } from "node:fs";
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
//#region src/supabase/project-users.d.ts
|
|
2
2
|
/**
|
|
3
|
-
* Signs the project in `projectDir`, made on a Supabase database, in on Supabase's own
|
|
4
|
-
*
|
|
5
|
-
* table, and writes, in `db/migrations`,
|
|
6
|
-
* and the users' accounts with their Supabase passwords and social providers. It
|
|
7
|
-
* project's auth keeps a connection pool open on, so the process must end itself.
|
|
3
|
+
* Signs the project in `projectDir`, made on a Supabase database, in on Supabase's own users, changing nothing in
|
|
4
|
+
* Supabase's `auth` schema: points its Better Auth setup at a view over auth.users in a schema of its own, removes the
|
|
5
|
+
* migrations of Protobase's own user table, and writes, in `db/migrations`, Better Auth's tables in that schema, then
|
|
6
|
+
* the view, its side table and trigger, and the users' accounts with their Supabase passwords and social providers. It
|
|
7
|
+
* only reads the database, which the project's auth keeps a connection pool open on, so the process must end itself.
|
|
8
8
|
*/
|
|
9
9
|
export declare const useSupabaseUsers: (projectDir: string, out: (text: string) => void) => Promise<void>;
|
|
10
10
|
//#endregion
|
|
@@ -1,38 +1,38 @@
|
|
|
1
1
|
import { loadProjectAuth } from "../users/load-auth.js";
|
|
2
2
|
import { writeAuthMigration } from "../auth/write-migration.js";
|
|
3
|
-
import { planAuthConfig } from "./auth-config.js";
|
|
3
|
+
import { planAuthConfig, sharedUsersConfig, sharedUsersSchema } from "./auth-config.js";
|
|
4
4
|
import { writeMigration } from "./migration-files.js";
|
|
5
|
+
import { sharedUsersMigration } from "./shared-users-migration.js";
|
|
5
6
|
import { authStoreMigrations } from "./store-migrations.js";
|
|
6
|
-
import { accountsMigration, usersColumnsMigration } from "./users-migrations.js";
|
|
7
7
|
import path from "node:path";
|
|
8
8
|
import { mkdir, rm } from "node:fs/promises";
|
|
9
9
|
//#region src/supabase/project-users.ts
|
|
10
10
|
/**
|
|
11
|
-
* Signs the project in `projectDir`, made on a Supabase database, in on Supabase's own
|
|
12
|
-
*
|
|
13
|
-
* table, and writes, in `db/migrations`,
|
|
14
|
-
* and the users' accounts with their Supabase passwords and social providers. It
|
|
15
|
-
* project's auth keeps a connection pool open on, so the process must end itself.
|
|
11
|
+
* Signs the project in `projectDir`, made on a Supabase database, in on Supabase's own users, changing nothing in
|
|
12
|
+
* Supabase's `auth` schema: points its Better Auth setup at a view over auth.users in a schema of its own, removes the
|
|
13
|
+
* migrations of Protobase's own user table, and writes, in `db/migrations`, Better Auth's tables in that schema, then
|
|
14
|
+
* the view, its side table and trigger, and the users' accounts with their Supabase passwords and social providers. It
|
|
15
|
+
* only reads the database, which the project's auth keeps a connection pool open on, so the process must end itself.
|
|
16
16
|
*/
|
|
17
17
|
const useSupabaseUsers = async (projectDir, out) => {
|
|
18
18
|
const migrationsDir = path.join(projectDir, "db", "migrations");
|
|
19
|
-
const authConfig = await planAuthConfig(projectDir);
|
|
19
|
+
const authConfig = await planAuthConfig(projectDir, sharedUsersConfig);
|
|
20
20
|
const storeMigrations = await authStoreMigrations(migrationsDir);
|
|
21
21
|
const relative = (to) => path.relative(projectDir, to);
|
|
22
22
|
for (const store of storeMigrations) await rm(path.join(migrationsDir, store));
|
|
23
23
|
await mkdir(migrationsDir, { recursive: true });
|
|
24
|
-
const usersFile = await writeMigration(migrationsDir, "supabase_users", usersColumnsMigration());
|
|
25
24
|
await authConfig.write();
|
|
26
|
-
if (storeMigrations.length > 0) out(`removed ${storeMigrations.length} migrations of Protobase's own user table:
|
|
27
|
-
out(`
|
|
25
|
+
if (storeMigrations.length > 0) out(`removed ${storeMigrations.length} migrations of Protobase's own user table: Supabase's users replace it\n`);
|
|
26
|
+
out(`pointed ${relative(authConfig.file)} at ${sharedUsersSchema}.users, a view over auth.users\n`);
|
|
28
27
|
const authFile = await writeAuthMigration({
|
|
29
28
|
auth: await loadProjectAuth(projectDir),
|
|
30
29
|
dir: migrationsDir,
|
|
31
|
-
name: "auth"
|
|
30
|
+
name: "auth",
|
|
31
|
+
writer: "create protobase"
|
|
32
32
|
});
|
|
33
|
-
if (authFile) out(`wrote ${relative(authFile)}, Better Auth's tables
|
|
34
|
-
const
|
|
35
|
-
out(`wrote ${relative(path.join(migrationsDir,
|
|
33
|
+
if (authFile) out(`wrote ${relative(authFile)}, Better Auth's tables in ${sharedUsersSchema}, pointing at auth.users\n`);
|
|
34
|
+
const usersFile = await writeMigration(migrationsDir, "supabase_users", sharedUsersMigration());
|
|
35
|
+
out(`wrote ${relative(path.join(migrationsDir, usersFile))}, the view over auth.users and the users' accounts with their Supabase passwords and social providers\n`);
|
|
36
36
|
};
|
|
37
37
|
//#endregion
|
|
38
38
|
export { useSupabaseUsers };
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { sharedUsersSchema } from "./auth-config.js";
|
|
2
|
+
import { accountIdSql, accountProviderSql, carriesAccountSql } from "./identity-providers.js";
|
|
3
|
+
//#region src/supabase/shared-users-migration.ts
|
|
4
|
+
const signsIn = (u) => `${u}.email is not null and ${u}.email <> '' and ${u}.deleted_at is null and not coalesce(${u}.is_anonymous, false)`;
|
|
5
|
+
const viewSql = `-- Each user as Better Auth reads them. The name and picture are read from Supabase's user metadata, where a change made
|
|
6
|
+
-- in Supabase shows at once. A ban is the app's own, in the side table, or Supabase's while it lasts: lifting the app's
|
|
7
|
+
-- never lifts Supabase's. No password, token or app metadata of auth.users is in it.
|
|
8
|
+
create view ${sharedUsersSchema}.users with (security_invoker = on) as
|
|
9
|
+
select u.id,
|
|
10
|
+
coalesce(u.raw_user_meta_data->>'full_name', u.raw_user_meta_data->>'name') as name,
|
|
11
|
+
u.email::text as email,
|
|
12
|
+
u.email_confirmed_at is not null as email_verified,
|
|
13
|
+
u.email_confirmed_at,
|
|
14
|
+
coalesce(u.raw_user_meta_data->>'avatar_url', u.raw_user_meta_data->>'picture') as image,
|
|
15
|
+
u.created_at,
|
|
16
|
+
u.updated_at,
|
|
17
|
+
x.app_role,
|
|
18
|
+
case when x.banned then true when u.banned_until > now() then true end as banned,
|
|
19
|
+
case when x.banned then x.ban_reason end as ban_reason,
|
|
20
|
+
case when x.banned then x.ban_expires when u.banned_until > now() then u.banned_until end as ban_expires,
|
|
21
|
+
x.last_role,
|
|
22
|
+
x.two_factor_enabled,
|
|
23
|
+
x.last_organization_id,
|
|
24
|
+
u.raw_user_meta_data
|
|
25
|
+
from auth.users u left join ${sharedUsersSchema}.user_extra x on x.id = u.id
|
|
26
|
+
where ${signsIn("u")};`;
|
|
27
|
+
const sideTypes = {
|
|
28
|
+
app_role: "text",
|
|
29
|
+
banned: "boolean",
|
|
30
|
+
ban_reason: "text",
|
|
31
|
+
ban_expires: "timestamptz",
|
|
32
|
+
last_role: "text",
|
|
33
|
+
two_factor_enabled: "boolean",
|
|
34
|
+
last_organization_id: "text"
|
|
35
|
+
};
|
|
36
|
+
const sideColumns = Object.keys(sideTypes);
|
|
37
|
+
const changedSide = sideColumns.map((column) => `${column} = case when new.${column} is distinct from old.${column} then new.${column} else x.${column} end`).join(",\n ");
|
|
38
|
+
const triggerSql = `-- Writes through the view. A user the app creates gets a row in auth.users as Supabase Auth makes one, with '' in the
|
|
39
|
+
-- token columns it reads as text, and Supabase's own role, audience and app metadata; an id or email auth.users has
|
|
40
|
+
-- already fails on its constraints. An update writes only what it changes: the metadata keys it changes are merged into
|
|
41
|
+
-- the row's current metadata, so a change Supabase makes meanwhile to another key stays. Deleting a user deletes them
|
|
42
|
+
-- from auth.users, and with them their accounts, sessions and side row.
|
|
43
|
+
create function ${sharedUsersSchema}.users_write() returns trigger language plpgsql security invoker set search_path = '' as $$
|
|
44
|
+
declare
|
|
45
|
+
patch jsonb := '{}';
|
|
46
|
+
begin
|
|
47
|
+
if tg_op = 'DELETE' then
|
|
48
|
+
delete from auth.users where id = old.id;
|
|
49
|
+
return old;
|
|
50
|
+
end if;
|
|
51
|
+
if tg_op = 'INSERT' then
|
|
52
|
+
new.id := coalesce(new.id, gen_random_uuid());
|
|
53
|
+
new.created_at := coalesce(new.created_at, now());
|
|
54
|
+
new.updated_at := coalesce(new.updated_at, now());
|
|
55
|
+
insert into auth.users (instance_id, id, aud, role, email, email_confirmed_at, created_at, updated_at, raw_app_meta_data, raw_user_meta_data,
|
|
56
|
+
confirmation_token, recovery_token, email_change_token_new, email_change)
|
|
57
|
+
values ('00000000-0000-0000-0000-000000000000', new.id, 'authenticated', 'authenticated', new.email,
|
|
58
|
+
case when new.email_verified then coalesce(new.email_confirmed_at, now()) end, new.created_at, new.updated_at,
|
|
59
|
+
'{"provider":"email","providers":["email"]}',
|
|
60
|
+
coalesce(new.raw_user_meta_data, '{}') || jsonb_strip_nulls(jsonb_build_object('full_name', new.name, 'avatar_url', new.image)),
|
|
61
|
+
'', '', '', '');
|
|
62
|
+
insert into ${sharedUsersSchema}.user_extra (id, ${sideColumns.join(", ")})
|
|
63
|
+
values (new.id, ${sideColumns.map((column) => `new.${column}`).join(", ")});
|
|
64
|
+
return new;
|
|
65
|
+
end if;
|
|
66
|
+
if new.raw_user_meta_data is distinct from old.raw_user_meta_data then
|
|
67
|
+
select coalesce(jsonb_object_agg(key, value), '{}') into patch from jsonb_each(coalesce(new.raw_user_meta_data, '{}'))
|
|
68
|
+
where old.raw_user_meta_data -> key is distinct from value;
|
|
69
|
+
end if;
|
|
70
|
+
if new.name is distinct from old.name then patch := patch || jsonb_build_object('full_name', new.name); end if;
|
|
71
|
+
if new.image is distinct from old.image then patch := patch || jsonb_build_object('avatar_url', new.image); end if;
|
|
72
|
+
update auth.users u set
|
|
73
|
+
email = case when new.email is distinct from old.email then new.email else u.email end,
|
|
74
|
+
email_confirmed_at = case
|
|
75
|
+
when new.email_verified is not distinct from old.email_verified and new.email_confirmed_at is not distinct from old.email_confirmed_at then u.email_confirmed_at
|
|
76
|
+
when new.email_verified then coalesce(new.email_confirmed_at, u.email_confirmed_at, now())
|
|
77
|
+
end,
|
|
78
|
+
raw_user_meta_data = coalesce(u.raw_user_meta_data, '{}') || patch,
|
|
79
|
+
updated_at = coalesce(new.updated_at, now())
|
|
80
|
+
where u.id = old.id;
|
|
81
|
+
insert into ${sharedUsersSchema}.user_extra (id) values (old.id) on conflict (id) do nothing;
|
|
82
|
+
update ${sharedUsersSchema}.user_extra x set
|
|
83
|
+
${changedSide}
|
|
84
|
+
where x.id = old.id;
|
|
85
|
+
return new;
|
|
86
|
+
end $$;
|
|
87
|
+
|
|
88
|
+
create trigger users_write instead of insert or update or delete on ${sharedUsersSchema}.users for each row execute function ${sharedUsersSchema}.users_write();`;
|
|
89
|
+
/** The side table, the view over auth.users and its trigger, then the users' accounts, as `create protobase` writes them. */
|
|
90
|
+
const sharedUsersMigration = () => `-- Supabase's users signing in with Better Auth, written by \`create protobase\`: nothing in Supabase's auth schema changes.
|
|
91
|
+
|
|
92
|
+
-- The columns only Better Auth has, for each user of auth.users that has any.
|
|
93
|
+
create table ${sharedUsersSchema}.user_extra (
|
|
94
|
+
id uuid primary key references auth.users (id) on delete cascade,
|
|
95
|
+
${Object.entries(sideTypes).map(([column, type]) => `${column} ${type}`).join(",\n ")}
|
|
96
|
+
);
|
|
97
|
+
|
|
98
|
+
${viewSql}
|
|
99
|
+
|
|
100
|
+
${triggerSql}
|
|
101
|
+
|
|
102
|
+
-- Each password, as Supabase hashed it: Better Auth verifies the bcrypt hash and stores it again as its own on sign-in.
|
|
103
|
+
-- Only for confirmed addresses: Supabase Auth refuses a password sign-in to an unconfirmed one and Better Auth would
|
|
104
|
+
-- not, so whoever signed up with someone else's address could sign in as them. Users who sign up through Supabase Auth
|
|
105
|
+
-- later have no password in the app.
|
|
106
|
+
insert into ${sharedUsersSchema}.account (account_id, provider_id, user_id, password, created_at, updated_at)
|
|
107
|
+
select id::text, 'credential', id, encrypted_password, coalesce(created_at, now()), coalesce(updated_at, now())
|
|
108
|
+
from auth.users where encrypted_password is not null and encrypted_password <> '' and email_confirmed_at is not null and ${signsIn("auth.users")};
|
|
109
|
+
|
|
110
|
+
-- Each identity of a social provider, by Better Auth's name for it and the claim it keys the account on, for the users
|
|
111
|
+
-- the view holds with a confirmed address, for the reason above.
|
|
112
|
+
insert into ${sharedUsersSchema}.account (account_id, provider_id, user_id, created_at, updated_at)
|
|
113
|
+
select account_id, provider_id, user_id, created_at, updated_at from (
|
|
114
|
+
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
|
|
115
|
+
from auth.identities where ${carriesAccountSql}
|
|
116
|
+
and user_id in (select id from auth.users where email_confirmed_at is not null and ${signsIn("auth.users")})
|
|
117
|
+
) identity where account_id is not null;
|
|
118
|
+
`;
|
|
119
|
+
//#endregion
|
|
120
|
+
export { sharedUsersMigration };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@protobase/cli",
|
|
3
|
-
"version": "0.58.
|
|
3
|
+
"version": "0.58.8",
|
|
4
4
|
"description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -42,12 +42,12 @@
|
|
|
42
42
|
"dependencies": {
|
|
43
43
|
"@better-auth/core": "^1.7.12",
|
|
44
44
|
"@hono/node-server": "^2.1.3",
|
|
45
|
-
"@protobase/config": "0.58.
|
|
46
|
-
"@protobase/layout": "0.58.
|
|
47
|
-
"@protobase/query": "0.58.
|
|
48
|
-
"@protobase/schema": "0.58.
|
|
49
|
-
"@protobase/server": "0.58.
|
|
50
|
-
"@protobase/ui": "0.58.
|
|
45
|
+
"@protobase/config": "0.58.8",
|
|
46
|
+
"@protobase/layout": "0.58.8",
|
|
47
|
+
"@protobase/query": "0.58.8",
|
|
48
|
+
"@protobase/schema": "0.58.8",
|
|
49
|
+
"@protobase/server": "0.58.8",
|
|
50
|
+
"@protobase/ui": "0.58.8",
|
|
51
51
|
"@react-email/render": "^2.1.0",
|
|
52
52
|
"@scalar/hono-api-reference": "^0.12.10",
|
|
53
53
|
"@tailwindcss/vite": "^4.3.3",
|
|
@@ -7,6 +7,7 @@ Apps written for other systems that keep working on Protobase, and moving their
|
|
|
7
7
|
## Supabase
|
|
8
8
|
|
|
9
9
|
- [Supabase import](../reference/cli.md#import-supabase): Moves a Supabase project into Protobase, with schema, data, users, functions, storage and scheduled jobs.
|
|
10
|
+
- [Create a project on a Supabase database](../getting-started.md#on-an-existing-database) (beta): your Supabase users sign in to the new project with their own passwords, and Supabase's own auth schema stays as Supabase set it up.
|
|
10
11
|
- [Supabase client API](../reference/supabase-rest.md): supabase-js `from()` and `rpc()` calls keep working, under the tables' RLS policies.
|
|
11
12
|
- [Supabase Auth](../reference/auth.md#supabase-js-and-supabasessr): `supabase.auth` and `@supabase/ssr` calls keep working.
|
|
12
13
|
- [Supabase Storage](../reference/supabase-storage.md): supabase-js storage calls keep working, over the app's file storage.
|
|
@@ -61,7 +61,7 @@ Then it runs that `scaffold` in the project and prints the next steps. Without a
|
|
|
61
61
|
|
|
62
62
|
It never writes to the database. The first of the next steps does: `bun run db:migrate` adds the `auth` schema that sign-in keeps its users in, and the `migrations` schema, where the script records the migrations it applied in `migrations.applied`. A `public.schema_migrations` another migration tool keeps is left as it is.
|
|
63
63
|
|
|
64
|
-
On a Supabase database, which it knows by its `auth` and `storage` schemas and its `supabase_admin` role, as [`import supabase`](reference/cli.md#import-supabase) does, the `auth` schema is Supabase Auth's,
|
|
64
|
+
On a Supabase database, which it knows by its `auth` and `storage` schemas and its `supabase_admin` role, as [`import supabase`](reference/cli.md#import-supabase) does, the `auth` schema is Supabase Auth's, and the project changes nothing in it. It leaves out `auth`, `storage` and the platform's other schemas, such as `realtime` and `supabase_migrations`, as Supabase's own tables. The project reads Supabase's users through a view over `auth.users` and keeps only its own sign-in data, in a schema of its own, `app_auth`: it points `protobase.config.ts` at the view, with [`users.keyTable`](reference/auth.md#a-view-over-another-systems-users), and writes migrations in place of those of Protobase's own user table: Better Auth's tables in `app_auth`, pointing at `auth.users`, then the view, its side table of the columns only Better Auth has, and each user's account with their Supabase password and social providers. `bun run db:migrate` applies them as the `postgres` role a Supabase connection string signs in as, and Supabase's users sign in with their own passwords, under their own ids. You can create, disable and delete users from either side, and a name changed in Supabase shows at once. <gap>A user who signs up through Supabase Auth later is a user of the project at once but cannot sign in with a password because sharing passwords with Supabase Auth is not implemented.</gap> Supabase's phone-only and anonymous users are not users of the project, since sign-in needs an email. A ban set in the project stays the project's own, while a ban set in Supabase holds in the project too.
|
|
65
65
|
|
|
66
66
|
```sh
|
|
67
67
|
cd shop
|
|
@@ -52,19 +52,35 @@ The store can use a users table another system made, such as Supabase's `auth.us
|
|
|
52
52
|
|
|
53
53
|
```ts
|
|
54
54
|
auth: {
|
|
55
|
-
users: { table: 'users', columns: { role: 'app_role' }, metadata: 'raw_user_meta_data' },
|
|
55
|
+
users: { table: 'users', columns: { role: 'app_role' }, metadata: 'raw_user_meta_data', guardedSchemas: ['auth'] },
|
|
56
56
|
passwordHashes: ['bcrypt'],
|
|
57
57
|
generateUserId: 'uuid',
|
|
58
58
|
}
|
|
59
59
|
```
|
|
60
60
|
|
|
61
61
|
- `users.table` names the table, default `user`. `users.columns` maps a column, by the name Protobase gives it (`name`, `email`, `email_verified`, `email_confirmed_at`, `image`, `created_at`, `updated_at`, `role`, `banned`, `ban_reason`, `ban_expires`, `two_factor_enabled`, `last_role`, `last_organization_id`), to the table's own; here the app's roles go to `app_role`, since Supabase's `role` holds the Postgres role. The other tables keep their names and point at this one.
|
|
62
|
+
- `users.guardedSchemas` names the schemas where the other system keeps the rest of its sign-in data, such as Supabase Auth's `auth`, with its identities, sessions, refresh tokens and two-factor secrets. Every table in them, including one the other system adds later, counts among the store's tables: no resource may be over it and the assistant's queries never read it. Name only a schema that holds none of the app's own tables.
|
|
62
63
|
- `users.metadata` names a JSON column for each user's metadata, which the migrations add as `jsonb` when the table lacks it: `createUser(auth, { ..., metadata: { full_name: 'Carol' } })` writes it, so a trigger that reads `raw_user_meta_data->>'full_name'` sees it.
|
|
63
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.
|
|
64
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.
|
|
65
66
|
|
|
66
67
|
The store's migrations make the user table only when it is missing, and add each of its columns only when the table lacks it, so a table another system made keeps its own. A required column (`name`, `email`, `email_verified`) cannot be added to a table with rows, so the columns Better Auth needs that the table lacks come first, nullable, 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.
|
|
67
68
|
|
|
69
|
+
### A view over another system's users
|
|
70
|
+
|
|
71
|
+
Where the app may not change the other system's users table, as on a Supabase database, where only Supabase Auth may change its `auth` schema, the user table can be a view of the app's own over it. `users.keyTable` names the table that holds the user ids:
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
auth: {
|
|
75
|
+
schema: 'app_auth',
|
|
76
|
+
users: { table: 'users', keyTable: { schema: 'auth', table: 'users' }, guardedSchemas: ['auth'], columns: { role: 'app_role' }, metadata: 'raw_user_meta_data' },
|
|
77
|
+
passwordHashes: ['bcrypt'],
|
|
78
|
+
generateUserId: 'uuid',
|
|
79
|
+
}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
The store's migrations then make nothing of the user table, which a migration of the project's own makes as a view with an `instead of` trigger for Better Auth's writes, and every foreign key points at the key table. `protobase dev` compares the view's columns with what Better Auth needs, rather than reporting it as a missing table. The key table counts among the store's tables, so no resource may be over it and the assistant's queries never read it, since it holds the other system's password hashes. The key table's schema is not guarded on its own, since it may hold the app's tables; `users.guardedSchemas` guards the other system's other tables, here Supabase Auth's whole `auth` schema. On a Supabase database, [`npm create protobase`](../getting-started.md#on-an-existing-database) writes these settings and the view.
|
|
83
|
+
|
|
68
84
|
## Configuration
|
|
69
85
|
|
|
70
86
|
| Variable | |
|
|
@@ -571,7 +571,7 @@ protobase import supabase [<connection> | --source-env <variable>] [--env DATABA
|
|
|
571
571
|
|
|
572
572
|
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`).
|
|
573
573
|
|
|
574
|
-
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, so the import cannot carry them over. It then says how many share their address with another user and how many have one of their own, and prints `select id, email from auth.users where is_sso_user` to list them rather than their addresses. Deleting a user in Supabase deletes or breaks the app's rows that reference it, so what to do about these users is the developer's decision, made in Supabase before importing again. 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 writes `NNN_supabase_realtime.sql`, which makes `realtime.messages`, `realtime.topic()`, and Supabase's `realtime.send()` and `realtime.broadcast_changes()`, so the app's triggers and SQL keep [broadcasting from the database](supabase-realtime.md#broadcast-from-the-database), with the source's row security policies on `realtime.messages`, so its [private channels](supabase-realtime.md#private-channels) keep their access; a policy that names only Supabase's own roles is left out as a comment. It points the app at `auth.users`: the `auth` of `protobase.config.ts` gets `users: { table: 'users', columns: { role: 'app_role' }, metadata: 'raw_user_meta_data' }`, `passwordHashes: ['bcrypt']` and `generateUserId: 'uuid'`, or the config gets an `auth` of them when it has none (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 the project has no `protobase.config.ts`, or one whose `auth` is not an object it can see, 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.
|
|
574
|
+
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, so the import cannot carry them over. It then says how many share their address with another user and how many have one of their own, and prints `select id, email from auth.users where is_sso_user` to list them rather than their addresses. Deleting a user in Supabase deletes or breaks the app's rows that reference it, so what to do about these users is the developer's decision, made in Supabase before importing again. 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 writes `NNN_supabase_realtime.sql`, which makes `realtime.messages`, `realtime.topic()`, and Supabase's `realtime.send()` and `realtime.broadcast_changes()`, so the app's triggers and SQL keep [broadcasting from the database](supabase-realtime.md#broadcast-from-the-database), with the source's row security policies on `realtime.messages`, so its [private channels](supabase-realtime.md#private-channels) keep their access; a policy that names only Supabase's own roles is left out as a comment. It points the app at `auth.users`: the `auth` of `protobase.config.ts` gets `users: { table: 'users', columns: { role: 'app_role' }, metadata: 'raw_user_meta_data', guardedSchemas: ['auth'] }`, `passwordHashes: ['bcrypt']` and `generateUserId: 'uuid'`, or the config gets an `auth` of them when it has none (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 the project has no `protobase.config.ts`, or one whose `auth` is not an object it can see, 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.
|
|
575
575
|
2. **Apply the migration** with the project's other migrations, such as `bun run db:migrate`.
|
|
576
576
|
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, and declares it in the `jobs` of `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 API keys `/api/sb` needs and the `createClient` change to the app's `/api/sb` and its publishable key, 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 and sessions do not carry over. <gap>The import cannot carry over MFA factors because that is not implemented.</gap> <gap>The import cannot carry over passkeys because that is not implemented.</gap>
|
|
577
577
|
4. **Apply the migrations** again. Supabase's users then sign in with their own passwords, and with a social provider once it is in the `socialProviders` of the config's `auth`; new users get a UUID in `auth.users`, so the app's triggers there run for them.
|
|
@@ -211,14 +211,14 @@ export default defineConfig({ auth: { accountDeletion: false } })
|
|
|
211
211
|
|
|
212
212
|
## auth.users
|
|
213
213
|
|
|
214
|
-
- **Type:** `{ table?: string; columns?: Record<string, string>; metadata?: string }`
|
|
214
|
+
- **Type:** `{ table?: string; columns?: Record<string, string>; metadata?: string; keyTable?: { schema: string; table: string }; guardedSchemas?: string[] }`
|
|
215
215
|
- **Default:** the table `protobase auth migration` makes
|
|
216
216
|
|
|
217
|
-
The user table, when another system made it, such as Supabase's `auth.users`: its name, the columns named otherwise than Protobase names them, and a JSON column for each user's metadata. See [An existing users table](../auth.md#an-existing-users-table).
|
|
217
|
+
The user table, when another system made it, such as Supabase's `auth.users`: its name, the columns named otherwise than Protobase names them, and a JSON column for each user's metadata. See [An existing users table](../auth.md#an-existing-users-table). `keyTable` makes the user table a view of the app's own over another system's, the table it names, which holds the user ids: the store's migrations leave the view to the app and point their foreign keys at that table. See [A view over another system's users](../auth.md#a-view-over-another-systems-users). `guardedSchemas` names the schemas the other system keeps the rest of its sign-in data in, such as Supabase Auth's `auth`: no resource may be over any table in them, and the assistant's queries never read one.
|
|
218
218
|
|
|
219
219
|
```ts
|
|
220
220
|
export default defineConfig({
|
|
221
|
-
auth: { schema: 'auth', users: { table: 'users', columns: { role: 'app_role' }, metadata: 'raw_user_meta_data' } },
|
|
221
|
+
auth: { schema: 'auth', users: { table: 'users', columns: { role: 'app_role' }, metadata: 'raw_user_meta_data', guardedSchemas: ['auth'] } },
|
|
222
222
|
})
|
|
223
223
|
```
|
|
224
224
|
|