@protobase/cli 0.47.1 → 0.48.0

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.
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.47.1";
2
+ var version = "0.48.0";
3
3
  //#endregion
4
4
  export { version };
@@ -37,7 +37,8 @@ const forkApiChild = (options, onExit) => {
37
37
  ready = true;
38
38
  return {
39
39
  port: message.ready.port,
40
- anyUsers: message.ready.anyUsers
40
+ anyUsers: message.ready.anyUsers,
41
+ authDrift: message.ready.authDrift
41
42
  };
42
43
  };
43
44
  return {
@@ -5,6 +5,7 @@ export type ApiProcessMessage = {
5
5
  ready: {
6
6
  port: number;
7
7
  anyUsers?: boolean;
8
+ authDrift: string[];
8
9
  };
9
10
  } | {
10
11
  failed: string;
@@ -53,7 +53,9 @@ const stop = async () => {
53
53
  const start = async () => {
54
54
  sockets = (await vite.ssrLoadModule(support)).apiWebSocketServer();
55
55
  process.env.PROTOBASE_DEV_URL = await devUrl;
56
- const anyUsers = await (await vite.ssrLoadModule(entry)).anyUsers();
56
+ const api = await vite.ssrLoadModule(entry);
57
+ const anyUsers = await api.anyUsers();
58
+ const authDrift = await api.authDrift();
57
59
  logging.started();
58
60
  server = createAdaptorServer({
59
61
  fetch,
@@ -63,7 +65,8 @@ const start = async () => {
63
65
  const port = await listen(server);
64
66
  process.send({ ready: {
65
67
  port,
66
- anyUsers
68
+ anyUsers,
69
+ authDrift
67
70
  } });
68
71
  };
69
72
  process.on("SIGINT", () => void 0);
@@ -0,0 +1,8 @@
1
+ //#region src/dev/auth-drift-lines.ts
2
+ /**
3
+ * The banner's warning that the auth store's tables drifted from its migrations, such as a column changed by hand, one
4
+ * line per difference; nothing when they match.
5
+ */
6
+ const authDriftLines = (drift) => drift.length === 0 ? "" : ` warning the auth store drifted from its migrations; apply the project's migrations, or write a change made by hand as a migration of the project's own:\n${drift.map((finding) => ` ${finding}\n`).join("")}`;
7
+ //#endregion
8
+ export { authDriftLines };
@@ -2,5 +2,10 @@
2
2
  declare const _default: import("hono/hono-base").HonoBase<import("hono/types").BlankEnv, import("hono/types").BlankSchema | import("hono/types").MergeSchemaPath<import("hono/types").BlankSchema, "/">, "/", "/">;
3
3
  /** Whether the auth store has a user yet, for the banner's sign-in line; undefined without one. */
4
4
  export declare const anyUsers: () => Promise<boolean> | Promise<undefined>;
5
+ /**
6
+ * How the auth store's tables differ from what the project's Better Auth needs, for the banner's warnings: the one
7
+ * comparison of the store's tables, made in development only, since a deploy reads the store's record of migrations.
8
+ */
9
+ export declare const authDrift: () => Promise<string[]>;
5
10
  //#endregion
6
11
  export { _default as default };
package/dist/dev/entry.js CHANGED
@@ -7,7 +7,7 @@ import { withDevServiceWorker } from "./service-worker-route.js";
7
7
  import { setMissing, supabaseEnv } from "./supabase-env.js";
8
8
  import { upgradeWebSocket } from "@hono/node-server";
9
9
  import { Hono } from "hono";
10
- import { apiKeySettings, assistantSettings, authStoreTables, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkNotificationsSchema, checkQueryRunner, checkWebhooksSchema, configExports, hasUsers } from "@protobase/server";
10
+ import { apiKeySettings, assistantSettings, authSchemaDrift, authStoreTables, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkNotificationsSchema, checkQueryRunner, checkResourcesOutsideAuthStore, checkWebhooksSchema, configExports, hasUsers } from "@protobase/server";
11
11
  //#region src/dev/entry.ts
12
12
  const projectDir = process.env.PROTOBASE_PROJECT;
13
13
  const project = await loadProject(projectDir, JSON.parse(process.env.PROTOBASE_EXTENSIONS ?? "[]"));
@@ -19,6 +19,7 @@ if (project.auth && !store.__protobaseAuthSchemaChecked) {
19
19
  await checkAuthSchema(project.auth);
20
20
  store.__protobaseAuthSchemaChecked = true;
21
21
  }
22
+ if (project.auth) await checkResourcesOutsideAuthStore(db, resources.map((resource) => resource.toModel()), project.auth);
22
23
  await checkChanges(db, resources.map((resource) => resource.toModel()), project.events);
23
24
  await checkComments(db, resources.map((resource) => resource.toModel()));
24
25
  await checkComputed(db, resources.map((resource) => resource.toModel()));
@@ -51,5 +52,10 @@ await devJobs(db, jobs);
51
52
  var entry_default = withDevServiceWorker(new Hono(), Boolean(project.notifications)).route("/", admin);
52
53
  /** Whether the auth store has a user yet, for the banner's sign-in line; undefined without one. */
53
54
  const anyUsers = () => project.auth ? hasUsers(project.auth) : Promise.resolve(void 0);
55
+ /**
56
+ * How the auth store's tables differ from what the project's Better Auth needs, for the banner's warnings: the one
57
+ * comparison of the store's tables, made in development only, since a deploy reads the store's record of migrations.
58
+ */
59
+ const authDrift = () => project.auth ? authSchemaDrift(project.auth) : Promise.resolve([]);
54
60
  //#endregion
55
- export { anyUsers, entry_default as default };
61
+ export { anyUsers, authDrift, entry_default as default };
package/dist/dev/run.js CHANGED
@@ -2,6 +2,7 @@ import { loadNearestEnvFile } from "./env.js";
2
2
  import { adminAppDir, adminAppMain } from "../project/admin-app.js";
3
3
  import { alsoOnIpv6, checkPortFree } from "./loopback.js";
4
4
  import { checkDatabase } from "./check-database.js";
5
+ import { authDriftLines } from "./auth-drift-lines.js";
5
6
  import { loginLine } from "./login-line.js";
6
7
  import { apiForward } from "./api-forward.js";
7
8
  import { forkApiChild } from "./api-child.js";
@@ -61,8 +62,8 @@ const runDev = async (options, out) => {
61
62
  if (server.httpServer) await alsoOnIpv6(server.httpServer, port).catch(closeAndThrow);
62
63
  const started = await apiChild.start(`http://localhost:${port}`).catch(closeAndThrow);
63
64
  apiReady(started);
64
- const { anyUsers } = started;
65
- out(`protobase dev ready at http://localhost:${port}\n project ${options.projectDir}\n api http://localhost:${port}/api/v1 (docs at /api/docs)\n` + loginLine(anyUsers, process.env.npm_config_user_agent));
65
+ const { anyUsers, authDrift } = started;
66
+ out(`protobase dev ready at http://localhost:${port}\n project ${options.projectDir}\n api http://localhost:${port}/api/v1 (docs at /api/docs)\n` + loginLine(anyUsers, process.env.npm_config_user_agent) + authDriftLines(authDrift));
66
67
  return server;
67
68
  };
68
69
  //#endregion
@@ -2,7 +2,7 @@ import { conventionConfig } from "./convention.js";
2
2
  import { uiDirs } from "./convention-files.js";
3
3
  import { importProjectFiles } from "./import-project-file.js";
4
4
  import path from "node:path";
5
- import { configExports } from "@protobase/server";
5
+ import { configExports } from "@protobase/server/config-exports";
6
6
  //#region src/project/load-data-config.ts
7
7
  /**
8
8
  * The resources, views and pages of a config folder, as the config module has them by convention: config/index.ts and
@@ -44,9 +44,13 @@ const planScaffold = async (input) => {
44
44
  const byTable = new Map(existing.map((resource) => [resource.table, resource]));
45
45
  const wanted = (table) => matchesTarget(input.target, table) && !isExcluded(input.excludes, table);
46
46
  const tables = input.tables.filter((table) => table.kind === "table");
47
- const skipped = protobaseSchemas(tables.filter((table) => matchesTarget(input.target, table)), input.target);
48
- const isProtobase = (table) => skipped.some((schema) => schema.tables.includes(table));
49
- const inProtobaseSchema = (view) => skipped.some(({ schema }) => schema === view.schema && schema !== "public");
47
+ const protobase = protobaseSchemas(tables, input.target);
48
+ const skipped = protobase.map((found) => ({
49
+ ...found,
50
+ tables: found.tables.filter((table) => matchesTarget(input.target, table))
51
+ })).filter((found) => found.tables.length > 0);
52
+ const isProtobase = (table) => protobase.some((schema) => schema.tables.includes(table));
53
+ const inProtobaseSchema = (view) => protobase.some(({ schema }) => schema === view.schema && schema !== "public");
50
54
  const skippedViews = input.tables.filter((table) => table.kind !== "table" && wanted(table) && !byTable.has(tableKey(table)) && !inProtobaseSchema(table));
51
55
  const names = assignNames(tables.filter((table) => !isProtobase(table)), existing);
52
56
  const context = (table) => ({
@@ -1,38 +1,33 @@
1
+ import { migrationsTableName, storeTableNames } from "@protobase/server/auth-store";
1
2
  //#region src/scaffold/protobase-tables.ts
2
3
  const storeCore = [
3
- "user",
4
4
  "session",
5
5
  "account",
6
6
  "verification"
7
7
  ];
8
- const storeTables = /* @__PURE__ */ new Set([
9
- ...storeCore,
10
- "jwks",
11
- "passkey",
12
- "two_factor",
13
- "sign_in_policy",
14
- "staff_sign_in"
15
- ]);
16
- const isStoreTable = (name) => storeTables.has(name) || name.startsWith("oauth_");
17
8
  const bySchema = (tables) => {
18
9
  const groups = /* @__PURE__ */ new Map();
19
10
  for (const table of tables) groups.set(table.schema, [...groups.get(table.schema) ?? [], table]);
20
11
  return groups;
21
12
  };
13
+ const userTableOf = (schema, tables) => tables.find((table) => table.name === "session")?.foreignKeys.find((key) => key.columns.length === 1 && key.columns[0] === "user_id" && key.refSchema === schema)?.refTable;
22
14
  const authStore = (schema, tables) => {
23
15
  if (schema === "auth") return tables;
24
- if (!storeCore.every((name) => tables.some((table) => table.name === name))) return [];
25
- return schema === "public" ? tables.filter((table) => isStoreTable(table.name)) : tables;
16
+ const has = (name) => tables.some((table) => table.name === name);
17
+ const user = userTableOf(schema, tables);
18
+ if (!has(migrationsTableName) && !(storeCore.every(has) && user !== void 0)) return [];
19
+ if (schema !== "public") return tables;
20
+ return tables.filter((table) => storeTableNames.includes(table.name) || table.name === user);
26
21
  };
27
22
  const jobQueue = (schema, tables) => schema === "jobs" && ["job", "version"].every((name) => tables.some((table) => table.name === name)) ? tables : [];
28
23
  const protobaseSchemas = (tables, target) => [...bySchema(tables)].flatMap(([schema, own]) => {
29
- if (target.schema === schema) return [];
30
24
  const store = authStore(schema, own);
31
25
  if (store.length > 0) return [{
32
26
  schema,
33
27
  what: "auth store",
34
28
  tables: store
35
29
  }];
30
+ if (target.schema === schema) return [];
36
31
  const queue = jobQueue(schema, own);
37
32
  return queue.length > 0 ? [{
38
33
  schema,
@@ -12,7 +12,7 @@ const readText = (file) => readFile(file, "utf8").catch((error) => {
12
12
  if (error.code === "ENOENT") return void 0;
13
13
  throw error;
14
14
  });
15
- const skippedLine = ({ schema, what, tables }) => `skipped ${schema === "public" ? tables.map((table) => `public.${table.name}`).join(", ") : `schema ${schema}`}, Protobase's ${what}; pass "${schema}" as the target to scaffold it anyway\n`;
15
+ const skippedLine = ({ schema, what, tables }) => `skipped ${schema === "public" ? tables.map((table) => `public.${table.name}`).join(", ") : `schema ${schema}`}, Protobase's ${what}${what === "job queue" ? `; pass "${schema}" as the target to scaffold it anyway` : ""}\n`;
16
16
  const write = async ({ path: file, after }) => {
17
17
  await mkdir(path.dirname(file), { recursive: true });
18
18
  await writeFile(file, after);
@@ -8,7 +8,7 @@ import { startCleanupTimer } from "./cleanup-timer.js";
8
8
  import { closeSockets } from "./close-sockets.js";
9
9
  import { servedRelease } from "./mobile-release.js";
10
10
  import { createAdaptorServer, upgradeWebSocket } from "@hono/node-server";
11
- import { assistantSettings, authStoreTables, backgroundSettled, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkNotificationsSchema, checkQueryRunner, checkWebhooksSchema, configExports, createFileCleanup, startJobs } from "@protobase/server";
11
+ import { assistantSettings, authStoreTables, backgroundSettled, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkNotificationsSchema, checkQueryRunner, checkResourcesOutsideAuthStore, checkWebhooksSchema, configExports, createFileCleanup, startJobs } from "@protobase/server";
12
12
  import pg from "pg";
13
13
  //#region src/serve/lifecycle.ts
14
14
  const listen = (server, port) => new Promise((resolve, reject) => {
@@ -26,6 +26,7 @@ const startServe = async ({ project, env, createDb = (url) => createPgDb(pg, url
26
26
  const db = project.db ?? ownDb;
27
27
  const { resources, views } = configExports(project.config);
28
28
  const startJobsAndListen = async () => {
29
+ if (env.startupChecks && project.auth) await checkResourcesOutsideAuthStore(db, resources.map((resource) => resource.toModel()), project.auth);
29
30
  if (env.startupChecks) await checkChanges(db, resources.map((resource) => resource.toModel()), project.events);
30
31
  if (env.startupChecks) await checkComments(db, resources.map((resource) => resource.toModel()));
31
32
  if (env.startupChecks) await checkComputed(db, resources.map((resource) => resource.toModel()));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.47.1",
3
+ "version": "0.48.0",
4
4
  "description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -39,11 +39,11 @@
39
39
  "dependencies": {
40
40
  "@better-auth/core": "^1.7.12",
41
41
  "@hono/node-server": "^2.1.3",
42
- "@protobase/layout": "0.47.1",
43
- "@protobase/query": "0.47.1",
44
- "@protobase/schema": "0.47.1",
45
- "@protobase/server": "0.47.1",
46
- "@protobase/ui": "0.47.1",
42
+ "@protobase/layout": "0.48.0",
43
+ "@protobase/query": "0.48.0",
44
+ "@protobase/schema": "0.48.0",
45
+ "@protobase/server": "0.48.0",
46
+ "@protobase/ui": "0.48.0",
47
47
  "@react-email/render": "^2.1.0",
48
48
  "@scalar/hono-api-reference": "^0.12.10",
49
49
  "@tailwindcss/vite": "^4.3.3",
@@ -6,6 +6,7 @@ Sign-in methods, users, roles, organizations and tokens.
6
6
 
7
7
  - [Built-in sign-in](../reference/auth.md): Password sign-in, sessions and short-lived tokens, with no separate identity service.
8
8
  - [First admin](../reference/auth.md#first-run): No account can be made over the web while the app has no users. You create the first admin from the terminal, and the last active admin cannot be deleted, demoted or blocked.
9
+ - [Versioned sign-in tables](../reference/auth.md#migrations): The sign-in tables come from numbered migrations that ship with Protobase, written as the project's own and recorded in the database, so a deploy checks them without comparing tables. Every feature has its tables from the start, so turning one on or off needs no migration.
9
10
  - [Existing users table](../reference/auth.md#an-existing-users-table): Sign-in can use the users table another system keeps in the same database.
10
11
  - [Users page](../reference/auth.md#users-page): Admins find people, set roles, block them, add accounts and invite people by email.
11
12
  - [Password reset](../reference/auth.md#password-reset): People reset a forgotten password through an emailed link.
@@ -32,7 +32,7 @@ The host serves `public/` itself and sends only the manifest's `api` paths to th
32
32
 
33
33
  ## Migrations
34
34
 
35
- Serving never changes the database: the bundle carries the project's `db/migrations` as `migrations/`, and the runtime's `migrate <bundle>` applies the pending ones, the app's and the auth schema's, before a new version serves, with no other writes while it runs. It applies them in one transaction behind a lock, recorded in `public.schema_migrations` as the presets' `db:migrate` does, so a database either script migrated is current for the other. A file that would end that transaction (`BEGIN`, `COMMIT`, `ROLLBACK`) or cannot run in one (`create index concurrently`) is refused, and a refused or failing file leaves the database unchanged. The runtime refuses to start while the auth schema lacks a table or column the new version needs (see [migrations](../reference/auth.md#migrations)). [`protobase migration`](../reference/cli.md#migration) writes the files the config's features need, such as the auth and jobs schemas, as the project's own migrations, and [a self-hosted image](#a-self-hosted-image) runs `migrate` as a step of its own before the app starts.
35
+ Serving never changes the database: the bundle carries the project's `db/migrations` as `migrations/`, and the runtime's `migrate <bundle>` applies the pending ones, the app's and the auth schema's, before a new version serves, with no other writes while it runs. It applies them in one transaction behind a lock, recorded in `public.schema_migrations` as the presets' `db:migrate` does, so a database either script migrated is current for the other. A file that would end that transaction (`BEGIN`, `COMMIT`, `ROLLBACK`) or cannot run in one (`create index concurrently`) is refused, and a refused or failing file leaves the database unchanged. The runtime refuses to start while the auth store has not applied every auth migration of the new version, which it reads from the store's `auth_migrations` table without comparing its tables (see [migrations](../reference/auth.md#migrations)). [`protobase migration`](../reference/cli.md#migration) writes the files the config's features need, such as the auth and jobs schemas, as the project's own migrations, and [a self-hosted image](#a-self-hosted-image) runs `migrate` as a step of its own before the app starts.
36
36
 
37
37
  ## Images
38
38
 
@@ -27,21 +27,25 @@ Build that pool with `appPool(pg, process.env.DATABASE_URL)` (from `@protobase/s
27
27
 
28
28
  ### Migrations
29
29
 
30
- The store's tables are part of the project's migrations, committed in the repository like the application's own: the examples carry them as `db/migrations/*_auth.sql`, and their `db:migrate` applies both. When an upgrade of Protobase (or another Better Auth plugin) needs more tables or columns, write the change as the project's next migration:
30
+ The store's tables come from migrations that ship with Protobase, one version after another, and are part of the project's migrations, committed in the repository like the application's own: the examples carry them as `db/migrations/*_auth.sql`, and their `db:migrate` applies both. The store records each version it applied in its `auth_migrations` table. When an upgrade of Protobase brings new versions, write them as the project's next migration:
31
31
 
32
32
  ```sh
33
33
  bun run db:migrate # the database at the project's current schema
34
- bun run protobase auth migration # compares it with what Better Auth needs; writes db/migrations/NNN_auth.sql
35
- bun run db:migrate # applies it
34
+ bun run protobase auth migration # reads auth_migrations; writes the versions not applied as db/migrations/NNN_auth.sql
35
+ bun run db:migrate # applies them
36
36
  ```
37
37
 
38
- The file only adds tables, columns and indexes, never drops one except the OAuth tables of [MCP](#oauth-for-mcp-clients) once `mcp` is off, and is plain SQL to review, edit or leave out where the project handles the auth schema itself. `--dir` and `--name` choose the folder and the name after the number. [`protobase migration`](cli.md#migration) writes the same file, along with what the config's other features need, such as [jobs](jobs.md).
38
+ Each version's statements are followed by its row in `auth_migrations`. The file only adds tables, columns and indexes, never drops one, and is plain SQL to review, edit or leave out where the project handles the auth schema itself. `--dir` and `--name` choose the folder and the name after the number. [`protobase migration`](cli.md#migration) writes the same file, along with what the config's other features need, such as [jobs](jobs.md).
39
39
 
40
- The store's tables and columns are snake_case, like the app's (`sign_in_policy.platform_sign_in`, `session.user_id`); the code and the API keep Better Auth's camelCase names. A store set up by Protobase 0.6 has Better Auth's camelCase names instead (`"signInPolicy"."platformSignIn"`): for it, `protobase auth migration` writes the migration that renames its tables, columns, indexes and constraints in place, keeping every row. The examples carry it as `db/migrations/*_auth_snake_case.sql`; on a store with the snake_case names it does nothing.
40
+ Every store has the tables of every feature, whether the app turns the feature on or not: [passkeys](#passkeys), [two-factor authentication](#two-factor-authentication), [organizations](#organizations) and the [OAuth provider for MCP](#oauth-for-mcp-clients). Turning a feature on or off needs no migration and drops nothing; the columns a feature adds to the user and session tables are empty until it is on. SAML providers and open sign-up keep nothing in the store.
41
41
 
42
- The server never changes the schema. `protobase serve` and `protobase dev` read it at startup and refuse to start while it lacks a table or column Better Auth needs, naming them and `protobase auth migration`; without that check every sign-in would fail (`500`, "Database schema mismatch"). The examples' `db:migrate` applies all pending files in one transaction, so a migration that fails leaves the database as the running version expects it. The host must guarantee the rest: nothing but the migrations writes while they run, and the new version serves only after they succeeded.
42
+ The store's tables and columns are snake_case, like the app's (`sign_in_policy.platform_sign_in`, `session.user_id`); the code and the API keep Better Auth's camelCase names. The names the app configures, the store's schema (`schemaName`), the [user table](#an-existing-users-table) and its columns, and uuid ids (`generateUserId: 'uuid'`), are the ones in effect when the file is written. Changing one later is a migration of the project's own, such as a rename.
43
43
 
44
- Upgrading from 0.5 or earlier, where `auth:migrate` created the tables, goes through 0.6. With Protobase 0.6, run `protobase auth migration` twice, once with `DATABASE_URL` on an empty database with only the project's own migrations applied (it writes the whole store), then on the project's database (it writes what this version adds). Every statement skips what exists already, so both files apply to new databases and to those `auth:migrate` set up. The `auth:migrate` script and `db/auth-migrate.ts` can then go, and the upgrade goes on as from 0.6.
44
+ The server never changes the schema, and never compares it with what Better Auth needs. `protobase serve` and `protobase dev` read `auth_migrations` at startup and refuse to start while a version of this Protobase is not applied, naming it and `protobase auth migration`, or while the store has a version newer than this Protobase knows. The examples' `db:migrate` applies all pending files in one transaction, so a migration that fails leaves the database as the running version expects it. The host must guarantee the rest: nothing but the migrations writes while they run, and the new version serves only after they succeeded. Only [`protobase dev`](cli.md#dev), on the developer's machine, compares the store's tables with what the app's Better Auth needs, and warns at startup about each table, column or index that drifted, such as one changed by hand.
45
+
46
+ No resource may be over a table of the store, which holds password hashes, sessions, tokens and signing keys: `protobase serve` and `protobase dev` refuse to start with one, naming it, whatever the table is called, and [`protobase scaffold`](cli.md#scaffold) never writes one. The API, the Supabase-compatible endpoints, live updates and MCP read the app's resources only, so none of them reads the store.
47
+
48
+ A store made before 0.48, when `protobase auth migration` compared the database with Better Auth's tables, has no `auth_migrations`. For it, `protobase auth migration` writes the step that adopts it, once: it runs each version in a scratch schema, in a transaction it rolls back, to find the tables and columns that version makes, records each version whose tables and columns the store has, with their types, as applied, and writes the versions whose tables it has none of, such as MCP's for an app that never turned MCP on. The file checks again, when it is applied, that the store has every table and column it adopts, and stops otherwise, naming them. A store that has only some of a version's tables and columns, or has them with other types, is refused, naming what differs: bring it to the schema of Protobase 0.47 first, with that version's `protobase auth migration`. A store set up by Protobase 0.6, with Better Auth's camelCase names, or by `auth:migrate` before it, goes through 0.47 the same way.
45
49
 
46
50
  `createAuth` takes a `pg` Pool or `{ dialect, type: 'postgres', schemaName? }` as `database`; without `schemaName` the tables go to the connection's `search_path` (usually `public`). The examples keep the store in the `auth` schema of `DATABASE_URL`'s database, so their migrations cover both.
47
51
 
@@ -60,11 +64,11 @@ createAuth({
60
64
  ```
61
65
 
62
66
  - `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.
63
- - `users.metadata` names a JSON column for each user's metadata: `createUser(auth, { ..., metadata: { full_name: 'Carol' } })` writes it, so a trigger that reads `raw_user_meta_data->>'full_name'` sees it.
67
+ - `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.
64
68
  - `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
69
  - `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
70
 
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.
71
+ 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.
68
72
 
69
73
  ## Configuration
70
74
 
@@ -518,7 +522,7 @@ The roles are a project setting: `createAuth({ ..., roles: ['admin', 'auditor',
518
522
 
519
523
  A session acts with one role, as it works in one [organization](#organizations): its token carries that role alone, so the API, `/meta` and with it the views, the sidebar and what the app offers follow it, as do the admin-only endpoints (the sign-in policy, the log of staff sign-ins, Better Auth's user management). A new session starts with the role the person last chose, else their first. `POST /api/auth/role/switch` with `{ role }`, one the person holds, moves the session to it; the next token carries it, without signing in again, and the user keeps it (`user.last_role`) for their next session. `GET /api/auth/role/current` answers `{ active, roles }`, the active role and the roles held, each with its label, where the session works. Someone holding one role has nothing to switch.
520
524
 
521
- The app offers the roles in the profile menu, below the organizations, for someone holding more than one. The client has them as `session.roles` (`current`, `switchTo`). With organizations, the roles held are the global ones and those of the membership in the organization the session works in; a role not held there leaves the session with the person's first role there. Managing organizations (creating, entering, inviting and giving app roles) follows every role held. The session keeps its role in `session.active_role`; [`protobase auth migration`](#migrations) writes both columns.
525
+ The app offers the roles in the profile menu, below the organizations, for someone holding more than one. The client has them as `session.roles` (`current`, `switchTo`). With organizations, the roles held are the global ones and those of the membership in the organization the session works in; a role not held there leaves the session with the person's first role there. Managing organizations (creating, entering, inviting and giving app roles) follows every role held. The session keeps its role in `session.active_role`; every store has both columns (see [migrations](#migrations)).
522
526
 
523
527
  ## Organizations
524
528
 
@@ -538,7 +542,7 @@ const auth = createAuth({
538
542
  const authenticate = betterAuthAuthenticator({ auth })
539
543
  ```
540
544
 
541
- It is Better Auth's organization plugin, with its tables named in snake_case (`organization`, `member`, `invitation`, `session.active_organization_id`); `protobase auth migration` writes them, and `user.last_organization_id`, as the project's next migration.
545
+ It is Better Auth's organization plugin, with its tables named in snake_case (`organization`, `member`, `invitation`, `session.active_organization_id`); every store has them, and `user.last_organization_id`, with organizations on or off (see [migrations](#migrations)).
542
546
 
543
547
  **Two kinds of role.** Every membership has an organization role, Better Auth's `owner`, `admin` or `member`, which decides who manages the organization: owners and admins invite, remove and change members and edit its details; only owners hand it over, delete it or make owners. App roles, the project's `roles`, decide what the app shows and allows. A user holds them **globally** (the admin plugin's `role` column, as without organizations), which applies in every organization, or **per membership** (`member.app_roles`), which applies there only. A request's role, `ctx.user.roles`, is the session's [active role](#active-role), of either kind; access rules never see the organization role. `admin` is the superuser: global only, it holds every role. With organizations every role needs a label; `owner` and `member` cannot be app role names, and `user` stands for an account without a global role.
544
548
 
@@ -634,7 +638,7 @@ createAuth({ ..., mcp: { path: '/api/mcp', connectPage: '/-/connect' } })
634
638
  ```
635
639
 
636
640
  - `path` is the MCP endpoint's path on the origin of `baseURL`, its OAuth resource (default `/api/mcp`); `connectPage` is the connect page's path (default `/-/connect`, for a UI at the root); `fetchClientMetadata` replaces how a client's metadata document is fetched (default a transport that refuses private and reserved addresses). `auth.mcp` is `{ resource, path, scope }`, for the endpoint.
637
- - It needs an https `baseURL`, or localhost, and the OAuth tables: run `protobase auth migration` after turning it on (see [migrations](#migrations)). Turning it off is a migration too: `protobase auth migration` writes the drop of the OAuth tables, and the app does not start until it is applied. That disconnects every client and forgets every grant, so turning MCP on again starts from nothing and each client has to be allowed again. With `PROTOBASE_STARTUP_CHECKS=false` the tables and their grants stay until the migration is applied. Clients connect through `baseURL`'s origin only, whatever [other origins](#several-origins) the app has. Changing `path` makes every client connect again.
641
+ - It needs an https `baseURL`, or localhost. Every store has the OAuth tables (see [migrations](#migrations)), so turning MCP on or off needs no migration. Turning it off drops nothing: the clients and grants stay, and work again once MCP is on, so disconnect the clients first to forget them. While MCP is off, ending a person's sessions, banning them or setting their password disconnects none of their clients. Clients connect through `baseURL`'s origin only, whatever [other origins](#several-origins) the app has. Changing `path` makes every client connect again.
638
642
  - Clients find the provider at `/.well-known/oauth-protected-resource` and `/.well-known/oauth-authorization-server`, register at `/api/auth/oauth2/register` (dynamic registration) or are known by an https client id that names their metadata document (CIMD), and are asked for nothing per client. Back-channel logout, a key set URL at registration (`jwks_uri`) and the client credentials grant are refused, though a client with a metadata document may publish its keys on its own origin, and the provider's client management, userinfo, logout and consent endpoints are closed.
639
643
  - The scopes are `mcp` and `offline_access`, which is added when a client leaves it out. Access tokens last 15 minutes, carry the MCP resource as their audience and `typ: at+jwt`, and work for MCP only: the app's API refuses them, and the MCP endpoint refuses the app's own tokens. Refresh tokens roll for 30 days. `betterAuthAuthenticator(...).forAudience(auth.mcp.resource)` verifies them, and with `auth` checks on every request that the person still allows the client, still exists unbanned and still holds each role the token carries, so a disconnected client, a ban, a lowered role or a deleted user stops its access tokens at the next request rather than at their expiry; a lookup that fails refuses the request. A client that binds its tokens to a key (DPoP) sends a proof with each, checked against the resource's URL.
640
644
  - A grant keeps the role and organization the person worked in when they allowed the client. A refresh is refused once they no longer hold that role or may no longer enter that organization, once the [sign-in policy](#sign-in-policy) requires something they have not set up, and while they are banned; access tokens already issued last out their 15 minutes. A grant made without a role is refused.
@@ -48,7 +48,7 @@ protobase scaffold [connection string | --env VAR] [target] [options]
48
48
 
49
49
  Without a connection string or `--env`, the URL is `DATABASE_URL`, from the environment or the nearest `.env` at or above the current directory, as `dev` reads it. `target` is `all` (default), `schema`, `schema.table` or `schema.table.column`. Tables are introspected from `pg_catalog`; `config/<resource>/data.ts` is created or extended.
50
50
 
51
- Protobase's own tables are left out, since they hold password hashes, OAuth tokens and signing keys: the `auth` schema, another schema holding Better Auth's `user`, `session`, `account` and `verification` tables (in `public`, only the auth store's tables), and pg-boss's `jobs` schema. A line names each one skipped; a target naming the schema scaffolds it anyway. A resource an earlier run made over one of them gets a warning to remove it.
51
+ Protobase's own tables are left out, since they hold password hashes, OAuth tokens and signing keys: the auth store, which is the `auth` schema or another schema with the store's `auth_migrations` table, or with Better Auth's `session`, `account` and `verification` tables whose sessions point at a user table (in `public`, only the tables of the store's [migrations](auth.md#migrations) and that user table, whatever it is called), and pg-boss's `jobs` schema. A line names each one skipped. The auth store is left out whatever the target names; a target naming the `jobs` schema scaffolds it anyway. A resource an earlier run made over one of them gets a warning to remove it, and `dev` and `serve` refuse to start with a resource over the auth store.
52
52
 
53
53
  | Option | Effect |
54
54
  | --- | --- |
@@ -131,7 +131,7 @@ One port, two processes: Vite serves the admin app from `@protobase/ui`'s `src/a
131
131
  - **Database:** the URL comes from the variable named by `--env`, read from the environment or the nearest `.env` at or above the project. The connection is checked before anything starts; if it fails, the command names host, port and reason (and, when nothing listens there, points to its `db:up` script when it has one). The project needs `pg` installed, because the API connects with Kysely over the project's own `pg`.
132
132
  - **Port:** the app listens on `--port` at both `127.0.0.1` and `::1`, since `localhost` is either one depending on the runtime and the browser. When another process holds the port on either address the command stops before it starts and names that address; stop the other server or pass another `--port`.
133
133
  - **Cache:** Vite's dependency cache is `node_modules/.vite`; two dev servers sharing it can disturb each other's optimisation, so pass `--cache-dir` for a second one (the integration test does).
134
- - **Login:** real sign-in only, with the `authenticate` and `auth` exported by `protobase.config.ts` (see [Login with Better Auth](auth.md)). A project without an authenticator fails at startup with a message pointing there, one whose auth schema is behind with the tables and columns it lacks (see [`auth migration`](#auth-migration)), and one with a resource whose [events](events.md) or [history](history.md) lack their triggers, or whose [comments](comments.md) lack their table, or whose [rollup and formula fields](data-config.md#rollups-and-formulas) lack their columns or triggers, which it checks again on every reload (see [`migration`](#migration)), and one with an [AI field or action](ai.md#the-model) and no model key; there is no development login. The `login` line of the startup message says how to sign in: while the auth store has no users, it prints the exact command that creates the first admin, such as `bun run protobase users create you@example.com --generate-password` (the package manager that started `dev`, `npx` otherwise). Against a database that has users already, such as an app's hosted one, sign in as one of them or add one with a new email; its own password is set there.
134
+ - **Login:** real sign-in only, with the `authenticate` and `auth` exported by `protobase.config.ts` (see [Login with Better Auth](auth.md)). A project without an authenticator fails at startup with a message pointing there, one whose auth store has not applied every migration of this version, naming them (see [`auth migration`](#auth-migration)), one with a resource over a table of the auth store, and one with a resource whose [events](events.md) or [history](history.md) lack their triggers, or whose [comments](comments.md) lack their table, or whose [rollup and formula fields](data-config.md#rollups-and-formulas) lack their columns or triggers, which it checks again on every reload (see [`migration`](#migration)), and one with an [AI field or action](ai.md#the-model) and no model key; there is no development login. The `login` line of the startup message says how to sign in: while the auth store has no users, it prints the exact command that creates the first admin, such as `bun run protobase users create you@example.com --generate-password` (the package manager that started `dev`, `npx` otherwise). Against a database that has users already, such as an app's hosted one, sign in as one of them or add one with a new email; its own password is set there. A `warning` line follows for each way the auth store's tables differ from what the project's Better Auth needs, such as a column dropped by hand: the one place Protobase compares them, since `serve` reads the store's record of [migrations](auth.md#migrations) alone.
135
135
  - **Mobile releases:** see [below](#mobile-releases).
136
136
  - **Jobs:** with [jobs](jobs.md) in the config it runs them in the API's process, once the jobs schema checks out (see [`migration`](#migration)); an edited job runs its new code from the next job on.
137
137
  - **Tunnels and other hosts:** Vite only answers `localhost` by default. `--allowed-hosts .trycloudflare.com,app.example.com` adds Host headers (a leading dot matches all subdomains). Hot reload needs no extra setting: the Vite client takes protocol, host and port from the page, so behind an HTTPS tunnel it connects over `wss` on 443 as long as the tunnel forwards WebSockets.
@@ -432,7 +432,7 @@ Better Auth and other settings are the project's own variables (`BETTER_AUTH_SEC
432
432
  - **Routes:** `createAdmin` (`/api/v1`, `/api/meta`, `/api/functions/*`, `/api/auth/*`, ...) and `GET /health`, which answers `{"status":"ok"}` without a token and without touching the database. The runtime never serves the UI; `protobase serve <bundle>` serves `public/` for every path outside the manifest's `api` and `/.well-known/webauthn`, after `/health`, with `X-Frame-Options: DENY` and `Content-Security-Policy: frame-ancestors 'none'`, so no other site frames its pages.
433
433
  - **Plugins:** the runtime reads the manifest's `plugins`: `/api/meta` names them, and a view that shows a field with one of their [field types](plugins.md#field-types) that does not show the field's storage type stops startup, naming the view, the field and what the field type shows.
434
434
  - **Manifest:** a config module needs its `protobase.bundle.json` beside it. The runtime checks no version: the host picks the runtime from the manifest's `protobase` (see [Versioning](versioning.md#bundles-and-runtimes)).
435
- - **Startup:** a bundle without a default export, `config` or `authenticate`, or with an `options.basePath` other than `/api/v1`, stops startup with a one-line error and exit code 1, as does a missing `DATABASE_URL`, an auth schema that lacks a table or column, or still has the OAuth tables of [MCP](auth.md#oauth-for-mcp-clients) with `mcp` off (see [`auth migration`](#auth-migration)), a resource whose [events](events.md) or [history](history.md) lack their triggers or have out-of-date ones, or a missing history or [comments](comments.md#the-table) table, a [rollup or formula field](data-config.md#rollups-and-formulas) whose column or trigger is missing or out of date, a jobs schema that is missing or behind for a config with [jobs](jobs.md#the-jobs-schema) (see [`migration`](#migration)), an [AI field or action](ai.md#the-model) without a model key, [encrypted fields](data-config.md#encrypted-fields) without a key, or another resource over their column, or a taken port; `PROTOBASE_STARTUP_CHECKS=false` skips the checks of those schemas and the key. `protobase serve listening on port <port>` means it is ready.
435
+ - **Startup:** a bundle without a default export, `config` or `authenticate`, or with an `options.basePath` other than `/api/v1`, stops startup with a one-line error and exit code 1, as does a missing `DATABASE_URL`, an auth store that has not applied every migration of this version, or has a newer one (see [`auth migration`](#auth-migration)), a resource over a table of the auth store, a resource whose [events](events.md) or [history](history.md) lack their triggers or have out-of-date ones, or a missing history or [comments](comments.md#the-table) table, a [rollup or formula field](data-config.md#rollups-and-formulas) whose column or trigger is missing or out of date, a jobs schema that is missing or behind for a config with [jobs](jobs.md#the-jobs-schema) (see [`migration`](#migration)), an [AI field or action](ai.md#the-model) without a model key, [encrypted fields](data-config.md#encrypted-fields) without a key, or another resource over their column, or a taken port; `PROTOBASE_STARTUP_CHECKS=false` skips the checks of those schemas and the key. `protobase serve listening on port <port>` means it is ready.
436
436
  - **Jobs:** with [jobs](jobs.md) in the config it runs them beside the API, unless `PROTOBASE_JOBS=false`, and with `PROTOBASE_JOBS_DRAIN_TOKEN` it answers `POST /api/jobs/drain` for the operator.
437
437
  - **Shutdown:** the first SIGTERM or SIGINT stops accepting connections, closes open WebSockets with 1001 (dropping any still open after 5 seconds), waits for open requests, gives running jobs 30 seconds to finish, drains the pool `serve` created (a `db` the config exports is the project's to close) and exits with 0.
438
438
  - **Host modules:** under Bun, the runtime registers [the modules it supplies](#the-config-module) as virtual modules, so the bundle needs no `node_modules` for them. `protobase serve`, on Node or Bun, resolves them from the `node_modules` next to the bundle, so keep the bundle inside the project. Native packages load from the bundle's own `node_modules/` under both.
@@ -532,7 +532,7 @@ For a project with [organizations](auth.md#organizations); `<organization>` is a
532
532
  protobase migration [--dir db/migrations] [--extend <dir>]
533
533
  ```
534
534
 
535
- Writes what the database still needs for every feature the config enables, as the project's next migrations in `--dir`, one file per feature: the auth schema when `protobase.config.ts` exports `auth` (`NNN_auth.sql`, as [`auth migration`](#auth-migration) writes it), the [jobs schema](jobs.md#the-jobs-schema) when the config has jobs, `webhooks()` or `notifications()`, or a resource has events, history, comments or an [AI field](ai.md) (`NNN_jobs.sql`), the [capture of events](events.md#migrations-and-startup) and the [history table](history.md#the-table) (`NNN_changes.sql`), the columns of [rollup and formula fields](data-config.md#rollups-and-formulas) and the triggers that keep the rollups (`NNN_computed.sql`), the role the [assistant's read-only queries](assistant.md#the-built-in-backend) run as, when it finds the built-in assistant's key (`NNN_query.sql`), the [comments table](comments.md#the-table) (`NNN_comments.sql`), the [webhook subscriptions](webhooks.md#subscriptions-in-the-admin-app) of `webhooks()` (`NNN_webhooks.sql`), and the [devices and history tables](notifications.md#table-names) of `notifications()` (`NNN_notifications.sql`). It compares the database, with the project's migrations applied, with the config, merged with the configs it extends and those of `--extend` as `dev` merges them, and writes nothing when the database is current. Apply the files with the project's other migrations. It reads the `.env` nearest the current directory and needs `DATABASE_URL` unless the config exports `db`.
535
+ Writes what the database still needs for every feature the config enables, as the project's next migrations in `--dir`, one file per feature: the auth schema when `protobase.config.ts` exports `auth` (`NNN_auth.sql`, as [`auth migration`](#auth-migration) writes it), the [jobs schema](jobs.md#the-jobs-schema) when the config has jobs, `webhooks()` or `notifications()`, or a resource has events, history, comments or an [AI field](ai.md) (`NNN_jobs.sql`), the [capture of events](events.md#migrations-and-startup) and the [history table](history.md#the-table) (`NNN_changes.sql`), the columns of [rollup and formula fields](data-config.md#rollups-and-formulas) and the triggers that keep the rollups (`NNN_computed.sql`), the role the [assistant's read-only queries](assistant.md#the-built-in-backend) run as, when it finds the built-in assistant's key (`NNN_query.sql`), the [comments table](comments.md#the-table) (`NNN_comments.sql`), the [webhook subscriptions](webhooks.md#subscriptions-in-the-admin-app) of `webhooks()` (`NNN_webhooks.sql`), and the [devices and history tables](notifications.md#table-names) of `notifications()` (`NNN_notifications.sql`). It compares the database, with the project's migrations applied, with the config (for the auth schema, it reads the store's record of the migrations it applied), merged with the configs it extends and those of `--extend` as `dev` merges them, and writes nothing when the database is current. Apply the files with the project's other migrations. It reads the `.env` nearest the current directory and needs `DATABASE_URL` unless the config exports `db`.
536
536
 
537
537
  ```sh
538
538
  bun run db:migrate # the database at the project's current schema
@@ -546,7 +546,7 @@ bun run db:migrate # applies them
546
546
  protobase auth migration [--dir db/migrations] [--name auth]
547
547
  ```
548
548
 
549
- Run inside a project whose `protobase.config.ts` exports `auth`, against its database with the project's migrations applied. It compares the database with the tables, columns and indexes Better Auth needs (with Protobase's plugins and the project's own) and writes what is missing as the next migration in `--dir`: `009_auth.sql` after `008_...`. Nothing is written when the schema is current. The file only adds, never drops, except the OAuth tables of MCP once `mcp` is off; apply it with the project's other migrations. For a store with the camelCase names of Protobase 0.6 it writes their rename to snake_case instead, and the startup check asks for that. See [migrations](auth.md#migrations).
549
+ Run inside a project whose `protobase.config.ts` exports `auth`, against its database with the project's migrations applied. It reads the versions the store applied from its `auth_migrations` table and writes the auth migrations of this Protobase it has not, each followed by its row there, as the next migration in `--dir`: `009_auth.sql` after `008_...`, with the store's schema, user table, columns and id type as `createAuth` names them. Nothing is written when the store is current. The file only adds, never drops; apply it with the project's other migrations. For a store made before 0.48, without `auth_migrations`, it writes the step that adopts it once, and refuses one that matches no version, naming what differs. See [migrations](auth.md#migrations).
550
550
 
551
551
  ## `import supabase`
552
552
 
@@ -14,7 +14,7 @@ One option of `createAuth` turns it on:
14
14
  createAuth({ ..., mcp: true })
15
15
  ```
16
16
 
17
- Run `protobase auth migration` after turning it on, for the OAuth tables. The endpoint is `https://<app>/api/mcp`, or the path `mcp.path` names. How clients register, how people sign in and allow them, and how they disconnect them is in [OAuth for MCP clients](auth.md#oauth-for-mcp-clients).
17
+ Every auth store has the OAuth tables, so turning it on needs no migration. The endpoint is `https://<app>/api/mcp`, or the path `mcp.path` names. How clients register, how people sign in and allow them, and how they disconnect them is in [OAuth for MCP clients](auth.md#oauth-for-mcp-clients).
18
18
 
19
19
  ## Connecting a client
20
20