@protobase/cli 0.58.6 → 0.58.7

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.
@@ -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 \`protobase auth migration\`.\n-- Applied with the project's other migrations; edit or remove statements the project handles differently.\n\n${sql}\n`;
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
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.58.6";
2
+ var version = "0.58.7";
3
3
  //#endregion
4
4
  export { version };
@@ -4,7 +4,7 @@ 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",
@@ -14,45 +14,75 @@ const supabaseUsers = {
14
14
  passwordHashes: ["bcrypt"],
15
15
  generateUserId: "uuid"
16
16
  };
17
- const settingsText = (indent) => [
18
- "// Supabase's own auth.users as the app's user table, written by `protobase import supabase`: every foreign key,",
19
- "// trigger and policy naming it keeps working. Its passwords are bcrypt hashes, its ids UUIDs, and its `role` the",
20
- "// Postgres role, so the app's roles go to a column of their own.",
21
- `users: { table: '${supabaseUsers.users.table}', columns: { role: '${supabaseUsers.users.columns.role}' }, metadata: '${supabaseUsers.users.metadata}' },`,
22
- `passwordHashes: [${supabaseUsers.passwordHashes.map((name) => `'${name}'`).join(", ")}],`,
23
- `generateUserId: '${supabaseUsers.generateUserId}',`
24
- ].map((line) => `${indent}${line}`).join("\n");
25
- const settingsObject = `{ users: { table: '${supabaseUsers.users.table}', columns: { role: '${supabaseUsers.users.columns.role}' }, metadata: '${supabaseUsers.users.metadata}' }, passwordHashes: ['bcrypt'], generateUserId: 'uuid' }`;
17
+ /** The schema of the app's own sign-in data on a Supabase database, beside Supabase's `auth`. */
18
+ const sharedUsersSchema = "app_auth";
19
+ /** The `auth` settings for a view over Supabase's auth.users, on a Supabase database the app shares with Supabase Auth. */
20
+ const supabaseUsersView = {
21
+ schema: sharedUsersSchema,
22
+ users: {
23
+ ...supabaseUsers.users,
24
+ keyTable: {
25
+ schema: "auth",
26
+ table: "users"
27
+ }
28
+ },
29
+ passwordHashes: supabaseUsers.passwordHashes,
30
+ generateUserId: supabaseUsers.generateUserId
31
+ };
32
+ const importedUsersConfig = {
33
+ settings: supabaseUsers,
34
+ comment: [
35
+ "Supabase's own auth.users as the app's user table, written by `protobase import supabase`: every foreign key,",
36
+ "trigger and policy naming it keeps working. Its passwords are bcrypt hashes, its ids UUIDs, and its `role` the",
37
+ "Postgres role, so the app's roles go to a column of their own."
38
+ ]
39
+ };
40
+ const sharedUsersConfig = {
41
+ settings: supabaseUsersView,
42
+ comment: [
43
+ `Supabase's users, read through the view ${sharedUsersSchema}.users over auth.users, written by \`create protobase\`: the app`,
44
+ `keeps only its own sign-in data, in ${sharedUsersSchema}, and Supabase's auth schema stays as Supabase set it up. Their`,
45
+ "passwords are bcrypt hashes, their ids UUIDs, and `role` in auth.users the Postgres role, so the app's roles go to a",
46
+ "column of their own."
47
+ ]
48
+ };
49
+ const literal = (value) => {
50
+ if (typeof value === "string") return `'${value}'`;
51
+ if (Array.isArray(value)) return `[${value.map(literal).join(", ")}]`;
52
+ if (typeof value === "object" && value !== null) return `{ ${Object.entries(value).map(([key, item]) => `${key}: ${literal(item)}`).join(", ")} }`;
53
+ throw new Error(`Not implemented: a setting of type ${typeof value}`);
54
+ };
55
+ 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
56
  /**
27
57
  * protobase.config.ts with the settings first in its `auth`, or with an `auth` of them when it has none, sign-in being
28
58
  * on by default; fails, naming what to add, when it exports no object the import can see or its `auth` is not one.
29
59
  */
30
- const withSupabaseUsers = (text, file) => {
60
+ const withSupabaseUsers = (text, file, users) => {
31
61
  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(supabaseUsers)}, then import again`);
62
+ 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
63
  if (!config) throw refused();
34
64
  const auth = config.getProperty("auth");
35
65
  if (!auth) {
36
66
  const last = config.getProperties().at(-1);
37
- if (!last) return `${text.slice(0, config.getStart())}{ auth: ${settingsObject} }${text.slice(config.getEnd())}`;
38
- return `${text.slice(0, last.getEnd())}, auth: ${settingsObject}${text.slice(last.getEnd())}`;
67
+ if (!last) return `${text.slice(0, config.getStart())}{ auth: ${literal(users.settings)} }${text.slice(config.getEnd())}`;
68
+ return `${text.slice(0, last.getEnd())}, auth: ${literal(users.settings)}${text.slice(last.getEnd())}`;
39
69
  }
40
70
  const object = Node.isPropertyAssignment(auth) ? auth.getInitializer() : void 0;
41
71
  if (!object || !Node.isObjectLiteralExpression(object)) throw refused();
42
72
  const first = object.getProperties()[0];
43
73
  const indent = first ? " ".repeat(first.getStartLinePos() === first.getStart() ? 0 : first.getStart() - first.getStartLinePos()) : " ";
44
74
  const at = object.getStart() + 1;
45
- return `${text.slice(0, at)}\n${settingsText(indent)}${first ? "" : "\n"}${text.slice(at)}`;
75
+ return `${text.slice(0, at)}\n${settingsText(users, indent)}${first ? "" : "\n"}${text.slice(at)}`;
46
76
  };
47
77
  /** 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) => {
78
+ const planAuthConfig = async (projectDir, users) => {
49
79
  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`: import into a project made by create-protobase");
51
- const text = withSupabaseUsers(await readFile(file, "utf8"), path.relative(projectDir, file));
80
+ if (!existsSync(file)) throw new Error("The project has no protobase.config.ts with its `auth`: start from a project made by create-protobase");
81
+ const text = withSupabaseUsers(await readFile(file, "utf8"), path.relative(projectDir, file), users);
52
82
  return {
53
83
  file,
54
84
  write: () => writeFile(file, text)
55
85
  };
56
86
  };
57
87
  //#endregion
58
- export { planAuthConfig, supabaseUsers, withSupabaseUsers };
88
+ 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 auth.users, as `protobase import
4
- * supabase` does on its copy: points its Better Auth setup at auth.users, removes the migrations of Protobase's own user
5
- * table, and writes, in `db/migrations`, the columns Better Auth needs on auth.users, Better Auth's tables next to it
6
- * and the users' accounts with their Supabase passwords and social providers. It only reads the database, which the
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 auth.users, as `protobase import
12
- * supabase` does on its copy: points its Better Auth setup at auth.users, removes the migrations of Protobase's own user
13
- * table, and writes, in `db/migrations`, the columns Better Auth needs on auth.users, Better Auth's tables next to it
14
- * and the users' accounts with their Supabase passwords and social providers. It only reads the database, which the
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: auth.users replaces it\n`);
27
- out(`wrote ${relative(path.join(migrationsDir, usersFile))}, the columns Better Auth needs on auth.users, and pointed ${relative(authConfig.file)} at it\n`);
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 next to auth.users\n`);
34
- const accountsFile = await writeMigration(migrationsDir, "supabase_accounts", accountsMigration());
35
- out(`wrote ${relative(path.join(migrationsDir, accountsFile))}, the users' accounts with their Supabase passwords and social providers\n`);
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.6",
3
+ "version": "0.58.7",
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.6",
46
- "@protobase/layout": "0.58.6",
47
- "@protobase/query": "0.58.6",
48
- "@protobase/schema": "0.58.6",
49
- "@protobase/server": "0.58.6",
50
- "@protobase/ui": "0.58.6",
45
+ "@protobase/config": "0.58.7",
46
+ "@protobase/layout": "0.58.7",
47
+ "@protobase/query": "0.58.7",
48
+ "@protobase/schema": "0.58.7",
49
+ "@protobase/server": "0.58.7",
50
+ "@protobase/ui": "0.58.7",
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, not Protobase's. It leaves out `auth`, `storage` and the platform's other schemas, such as `realtime` and `supabase_migrations`, as Supabase's own tables, and signs the project in on Supabase's `auth.users`, as the import does: it points `protobase.config.ts` at `auth.users` and writes migrations in place of those of Protobase's own user table, the columns Better Auth needs on `auth.users`, Better Auth's tables next to it, and each user's account with their Supabase password and social providers. `bun run db:migrate` then applies them, and Supabase's users sign in with their own passwords. <gap>A user who signs up through Supabase Auth after that cannot sign in to the app with their password because carrying later sign-ups over is not implemented.</gap>
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
@@ -65,6 +65,21 @@ auth: {
65
65
 
66
66
  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
67
 
68
+ ### A view over another system's users
69
+
70
+ 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:
71
+
72
+ ```ts
73
+ auth: {
74
+ schema: 'app_auth',
75
+ users: { table: 'users', keyTable: { schema: 'auth', table: 'users' }, columns: { role: 'app_role' }, metadata: 'raw_user_meta_data' },
76
+ passwordHashes: ['bcrypt'],
77
+ generateUserId: 'uuid',
78
+ }
79
+ ```
80
+
81
+ 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. On a Supabase database, [`npm create protobase`](../getting-started.md#on-an-existing-database) writes these settings and the view.
82
+
68
83
  ## Configuration
69
84
 
70
85
  | Variable | |
@@ -211,10 +211,10 @@ 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 } }`
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).
218
218
 
219
219
  ```ts
220
220
  export default defineConfig({