@protobase/cli 0.34.0 → 0.34.2

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.
@@ -0,0 +1,17 @@
1
+ import { bundleMigrations } from "../bundle/manifest.js";
2
+ import { existsSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { copyFile, mkdir, readdir } from "node:fs/promises";
5
+ //#region src/build/bundle-migrations.ts
6
+ const projectMigrations = "db/migrations";
7
+ const copyMigrations = async ({ projectDir, outDir }) => {
8
+ const source = path.join(projectDir, projectMigrations);
9
+ if (!existsSync(source)) return void 0;
10
+ const target = path.join(outDir, bundleMigrations);
11
+ await mkdir(target, { recursive: true });
12
+ const files = (await readdir(source, { withFileTypes: true })).filter((entry) => entry.isFile() && entry.name.endsWith(".sql"));
13
+ for (const file of files) await copyFile(path.join(source, file.name), path.join(target, file.name));
14
+ return bundleMigrations;
15
+ };
16
+ //#endregion
17
+ export { copyMigrations, projectMigrations };
@@ -1,5 +1,6 @@
1
- import { bundleLayout, bundleNodeModules, manifestFile } from "../bundle/manifest.js";
1
+ import { bundleLayout, bundleMigrations, bundleNodeModules, manifestFile } from "../bundle/manifest.js";
2
2
  import { buildBundlePlugins } from "./bundle-plugins.js";
3
+ import { copyMigrations } from "./bundle-migrations.js";
3
4
  import { buildConfigBundle } from "./config-bundle.js";
4
5
  import { protobaseVersion } from "../version/version.js";
5
6
  import { copyPackages } from "./packages/copy-packages.js";
@@ -13,11 +14,11 @@ import { existsSync } from "node:fs";
13
14
  import path from "node:path";
14
15
  import { cp, readFile, rm, writeFile } from "node:fs/promises";
15
16
  //#region src/build/deploy-bundle.ts
16
- const removeOwnNodeModules = async (outDir) => {
17
- const dir = path.join(outDir, bundleNodeModules);
17
+ const removeOwnFolder = async (outDir, name, key) => {
18
+ const dir = path.join(outDir, name);
18
19
  if (!existsSync(dir)) return;
19
20
  const manifest = path.join(outDir, manifestFile);
20
- if ((existsSync(manifest) ? JSON.parse(await readFile(manifest, "utf8")) : void 0)?.nodeModules !== "node_modules") throw new Error(`${dir} was not written by \`protobase build\`; build into another folder (--out)`);
21
+ if ((existsSync(manifest) ? JSON.parse(await readFile(manifest, "utf8")) : void 0)?.[key] !== name) throw new Error(`${dir} was not written by \`protobase build\`; build into another folder (--out)`);
21
22
  await rm(dir, {
22
23
  recursive: true,
23
24
  force: true
@@ -44,7 +45,8 @@ const copyShell = async (publicDir, sourceMaps) => {
44
45
  return shell;
45
46
  };
46
47
  const buildDeployBundle = async ({ projectDir, outDir, bun, extensions = [], sourceMaps = false, onWarning }) => {
47
- await removeOwnNodeModules(outDir);
48
+ await removeOwnFolder(outDir, bundleNodeModules, "nodeModules");
49
+ await removeOwnFolder(outDir, bundleMigrations, "migrations");
48
50
  const components = /* @__PURE__ */ new Set();
49
51
  const native = await buildConfigBundle({
50
52
  projectDir,
@@ -58,6 +60,10 @@ const buildDeployBundle = async ({ projectDir, outDir, bun, extensions = [], sou
58
60
  const packages = native.length > 0 ? await copyPackages(native, path.join(outDir, bundleNodeModules)) : [];
59
61
  const publicDir = path.join(outDir, bundleLayout.public);
60
62
  const shell = await copyShell(publicDir, sourceMaps);
63
+ const migrations = await copyMigrations({
64
+ projectDir,
65
+ outDir
66
+ });
61
67
  const plugins = await buildBundlePlugins({
62
68
  projectDir,
63
69
  publicDir,
@@ -81,7 +87,8 @@ const buildDeployBundle = async ({ projectDir, outDir, bun, extensions = [], sou
81
87
  plugins,
82
88
  shell,
83
89
  icons,
84
- ...packages.length > 0 ? { nodeModules: bundleNodeModules } : {}
90
+ ...packages.length > 0 ? { nodeModules: bundleNodeModules } : {},
91
+ ...migrations ? { migrations } : {}
85
92
  };
86
93
  await writeFile(path.join(outDir, manifestFile), `${JSON.stringify(manifest, null, 2)}\n`);
87
94
  return manifest;
@@ -13,6 +13,7 @@ const bundleLayout = {
13
13
  theme: "protobase.theme.css"
14
14
  };
15
15
  const bundleNodeModules = "node_modules";
16
+ const bundleMigrations = "migrations";
16
17
  const isStringList = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
17
18
  const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
18
19
  const isFieldTypes = (value) => isObject(value) && Object.values(value).every(isStringList);
@@ -22,12 +23,13 @@ const isIcons = (value) => isObject(value) && typeof value.favicon === "boolean"
22
23
  const parseManifest = (value, file) => {
23
24
  const manifest = value;
24
25
  if (manifest?.version !== 3) throw new Error(`${file} is not a version 3 bundle manifest; rebuild it with \`protobase build\``);
25
- const { server, public: publicDir, api, spa, plugins, theme, shell, icons, nodeModules } = manifest;
26
+ const { server, public: publicDir, api, spa, plugins, theme, shell, icons, nodeModules, migrations } = manifest;
26
27
  if (typeof server !== "string" || typeof publicDir !== "string" || typeof spa !== "string" || typeof theme !== "string" || !isStringList(api)) throw new Error(`${file} needs server, public, spa and theme paths and an api list`);
27
28
  if (!Array.isArray(plugins) || !plugins.every(isPlugin)) throw new Error(`${file} needs a plugins list, each with a name, path, api and protobase`);
28
29
  if (!isShell(shell)) throw new Error(`${file} needs a shell with its protobase version, pluginApi and paths`);
29
30
  if (icons !== void 0 && !isIcons(icons)) throw new Error(`${file} has icons that are not a favicon flag and a list of PNG icons`);
30
31
  if (nodeModules !== void 0 && typeof nodeModules !== "string") throw new Error(`${file} has a nodeModules that is no path`);
32
+ if (migrations !== void 0 && typeof migrations !== "string") throw new Error(`${file} has a migrations that is no path`);
31
33
  return {
32
34
  version: 3,
33
35
  server,
@@ -38,7 +40,8 @@ const parseManifest = (value, file) => {
38
40
  theme,
39
41
  shell,
40
42
  ...icons && { icons },
41
- ...nodeModules === void 0 ? {} : { nodeModules }
43
+ ...nodeModules === void 0 ? {} : { nodeModules },
44
+ ...migrations === void 0 ? {} : { migrations }
42
45
  };
43
46
  };
44
47
  const readManifest = async (bundleDir) => {
@@ -46,4 +49,4 @@ const readManifest = async (bundleDir) => {
46
49
  return parseManifest(JSON.parse(await readFile(file, "utf8")), file);
47
50
  };
48
51
  //#endregion
49
- export { bundleBasePath, bundleLayout, bundleNodeModules, isApiPath, manifestFile, parseManifest, readManifest };
52
+ export { bundleBasePath, bundleLayout, bundleMigrations, bundleNodeModules, isApiPath, manifestFile, parseManifest, readManifest };
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.34.0";
2
+ var version = "0.34.2";
3
3
  //#endregion
4
4
  export { version };
@@ -0,0 +1,30 @@
1
+ import path from "node:path";
2
+ import { readFile, readdir } from "node:fs/promises";
3
+ //#region src/migration/apply-migrations.ts
4
+ const lockKey = 7311946202;
5
+ const executeFile = "do $migration$ begin execute current_setting('migrations.file'); end $migration$";
6
+ /**
7
+ * Applies the `*.sql` files of `dir` not yet recorded in `public.schema_migrations`, in file name order and in one
8
+ * transaction behind an advisory lock: when one fails, none is applied. Run it before a new version serves, while
9
+ * nothing else writes. Returns the names it applied.
10
+ */
11
+ const applyMigrations = async (sql, dir, out) => {
12
+ const files = (await readdir(dir)).filter((file) => file.endsWith(".sql")).sort();
13
+ const applied = await sql.begin(async (tx) => {
14
+ await tx`select pg_advisory_xact_lock(${lockKey})`;
15
+ await tx`create table if not exists public.schema_migrations (name text primary key, applied_at timestamptz not null default now())`;
16
+ const done = new Set((await tx`select name from public.schema_migrations`).map((row) => row.name));
17
+ const pending = files.filter((file) => !done.has(file));
18
+ for (const file of pending) {
19
+ out(`applying ${file}\n`);
20
+ await tx`select set_config('migrations.file', ${await readFile(path.join(dir, file), "utf8")}, true)`;
21
+ await tx.unsafe(executeFile);
22
+ await tx`insert into public.schema_migrations (name) values (${file})`;
23
+ }
24
+ return pending;
25
+ });
26
+ out(applied.length > 0 ? `applied ${applied.length} migrations\n` : "the database is up to date\n");
27
+ return applied;
28
+ };
29
+ //#endregion
30
+ export { applyMigrations };
@@ -0,0 +1,9 @@
1
+ import path from "node:path";
2
+ //#region src/serve/bundle-site.ts
3
+ const bundleSite = (dir, manifest) => ({
4
+ publicDir: path.resolve(dir, manifest.public),
5
+ spa: manifest.spa,
6
+ api: manifest.api
7
+ });
8
+ //#endregion
9
+ export { bundleSite };
@@ -0,0 +1,25 @@
1
+ import { checkBundleVersion } from "./bundle-version.js";
2
+ import { loadBundle } from "./load-bundle.js";
3
+ import { bundleConfigFile } from "../worker/start-worker.js";
4
+ import { readHidden } from "../users/password.js";
5
+ import { createUserCommand } from "../users/commands.js";
6
+ import { usersApi } from "../users/users-api.js";
7
+ import { checkAuthSchema } from "@protobase/server";
8
+ //#region src/serve/create-admin.ts
9
+ const createAdminInBundle = async (bundle, email, options, out) => {
10
+ const file = await bundleConfigFile(bundle);
11
+ await checkBundleVersion(file);
12
+ const project = await loadBundle(file);
13
+ if (!project.auth) throw new Error("The bundle exports no `auth`: users are managed by Better Auth");
14
+ await checkAuthSchema(project.auth);
15
+ await createUserCommand(usersApi(project.auth), {
16
+ email,
17
+ role: "admin",
18
+ ...options
19
+ }, {
20
+ stdin: process.stdin,
21
+ prompt: readHidden
22
+ }, out);
23
+ };
24
+ //#endregion
25
+ export { createAdminInBundle };
@@ -1,13 +1,24 @@
1
- import { serveBundle } from "./serve-bundle.js";
1
+ import { createAdminInBundle } from "./create-admin.js";
2
2
  import { provideHostModules } from "./host-modules.js";
3
+ import { migrateBundle } from "./migrate-bundle.js";
4
+ import { runtimeProgram } from "./runtime-program.js";
5
+ import { serveBundlePath } from "./serve-bundle-path.js";
3
6
  //#region src/serve/main.ts
4
7
  const fail = (message) => {
5
8
  process.stderr.write(`error: ${message}\n`);
6
9
  process.exit(1);
7
10
  };
11
+ const out = (text) => process.stdout.write(text);
8
12
  provideHostModules();
9
- const [file, ...extra] = process.argv.slice(2);
10
- if (!file || extra.length > 0) fail("usage: protobase-serve.js <bundle.js>");
11
- await serveBundle(file, process.env, (text) => process.stdout.write(text)).catch((error) => fail(error.message));
13
+ await runtimeProgram({
14
+ serve: async (bundle) => {
15
+ await serveBundlePath(bundle, process.env, out);
16
+ },
17
+ migrate: (bundle) => migrateBundle(bundle, process.env, out),
18
+ createAdmin: async (bundle, email, options) => {
19
+ await createAdminInBundle(bundle, email, options, out);
20
+ process.exit(0);
21
+ }
22
+ }).parseAsync(process.argv).catch((error) => fail(error.message));
12
23
  //#endregion
13
24
  export {};
@@ -0,0 +1,31 @@
1
+ import { readManifest } from "../bundle/manifest.js";
2
+ import { checkBundleVersion } from "./bundle-version.js";
3
+ import { bundleConfigFile } from "../worker/start-worker.js";
4
+ import { applyMigrations } from "../migration/apply-migrations.js";
5
+ import path from "node:path";
6
+ import postgres from "postgres";
7
+ //#region src/serve/migrate-bundle.ts
8
+ /**
9
+ * The runtime's `migrate`: applies the migrations the bundle carries to DATABASE_URL (see applyMigrations). It never
10
+ * imports the config module, so it runs no code of the app and needs none of its settings. On a failure the error
11
+ * ends the process, which closes the connection.
12
+ */
13
+ const migrateBundle = async (bundle, env, out) => {
14
+ const file = await bundleConfigFile(bundle);
15
+ await checkBundleVersion(file);
16
+ const dir = path.dirname(file);
17
+ const manifest = await readManifest(dir);
18
+ if (!manifest.migrations) {
19
+ out("the bundle has no migrations\n");
20
+ return;
21
+ }
22
+ if (!env.DATABASE_URL) throw new Error("No database: set DATABASE_URL");
23
+ const sql = postgres(env.DATABASE_URL, {
24
+ max: 1,
25
+ onnotice: () => {}
26
+ });
27
+ await applyMigrations(sql, path.join(dir, manifest.migrations), out);
28
+ await sql.end();
29
+ };
30
+ //#endregion
31
+ export { migrateBundle };
@@ -0,0 +1,23 @@
1
+ import { rejectPasswordArgument } from "../users/password.js";
2
+ import { Command, Option } from "commander";
3
+ //#region src/serve/runtime-program.ts
4
+ /**
5
+ * The serve runtime's commands. `serve` is the default, so `protobase-serve <config module>`, which hosts run, keeps
6
+ * serving that module's API alone; given the bundle folder it serves the app too.
7
+ */
8
+ const runtimeProgram = (actions) => {
9
+ const program = new Command("protobase-serve").description("Protobase's serve runtime for a bundle from `protobase build`");
10
+ program.command("serve", { isDefault: true }).description("Serve a bundle: its folder serves the app and the API, its config module the API alone").argument("<bundle>").action((bundle) => actions.serve(bundle));
11
+ program.command("migrate").description("Apply the bundle's pending migrations in one transaction, before a new version serves (DATABASE_URL)").argument("<bundle>").action((bundle) => actions.migrate(bundle));
12
+ program.command("create-admin").description("Create an admin user of the bundle's app").argument("<bundle>").argument("<email>").option("--name <name>", "display name").option("--password-stdin", "read the password from stdin", false).option("--generate-password", "generate a strong password and print it once", false).addOption(new Option("--password <value>").hideHelp()).action((bundle, email, opts) => {
13
+ rejectPasswordArgument(opts.password);
14
+ return actions.createAdmin(bundle, email, {
15
+ name: opts.name,
16
+ passwordStdin: opts.passwordStdin,
17
+ generatePassword: opts.generatePassword
18
+ });
19
+ });
20
+ return program;
21
+ };
22
+ //#endregion
23
+ export { runtimeProgram };
@@ -0,0 +1,13 @@
1
+ import { readManifest } from "../bundle/manifest.js";
2
+ import { serveBundle } from "./serve-bundle.js";
3
+ import { bundleSite } from "./bundle-site.js";
4
+ import { statSync } from "node:fs";
5
+ import path from "node:path";
6
+ //#region src/serve/serve-bundle-path.ts
7
+ const serveBundlePath = async (bundle, env, out) => {
8
+ if (!statSync(bundle).isDirectory()) return serveBundle(bundle, env, out);
9
+ const manifest = await readManifest(bundle);
10
+ return serveBundle(path.join(bundle, manifest.server), env, out, bundleSite(bundle, manifest));
11
+ };
12
+ //#endregion
13
+ export { serveBundlePath };
@@ -1,6 +1,7 @@
1
1
  import { readManifest } from "../bundle/manifest.js";
2
2
  import { installedShellDir } from "../build/shell.js";
3
3
  import { serveBundle } from "./serve-bundle.js";
4
+ import { bundleSite } from "./bundle-site.js";
4
5
  import { servedShell, shellVariable } from "./served-shell.js";
5
6
  import path from "node:path";
6
7
  //#region src/serve/serve-dir.ts
@@ -9,9 +10,7 @@ const serveBundleDir = async (dir, env, out) => {
9
10
  const own = env["PROTOBASE_SHELL"] ? path.resolve(env[shellVariable]) : installedShellDir;
10
11
  const { shell, note } = await servedShell(manifest, own);
11
12
  const site = {
12
- publicDir: path.resolve(dir, manifest.public),
13
- spa: manifest.spa,
14
- api: manifest.api,
13
+ ...bundleSite(dir, manifest),
15
14
  ...shell && { shell }
16
15
  };
17
16
  const server = await serveBundle(path.join(dir, manifest.server), env, out, site);
@@ -9,7 +9,7 @@ import { importState } from "./import-state.js";
9
9
  import { runPgTool } from "./pg-tools.js";
10
10
  import { replayScript } from "./replay.js";
11
11
  import { schemaMigration } from "./schema-migration.js";
12
- import { appSchemas, cronJobs, cronTimezone, databaseMarkers, dumpedTables, extensions, httpTriggers, hypertables, pgmqQueues, platformMigrationTables, realtimeTables, routinesIn, tablesSize, vaultSecretValues, vaultSecrets } from "./source-facts.js";
12
+ import { appSchemas, cronJobs, cronTimezone, databaseMarkers, dumpedTables, extensions, httpTriggers, hypertables, pgmqQueues, pgsodiumColumns, platformMigrationTables, realtimeTables, routinesIn, tablesSize, vaultSecretValues, vaultSecrets } from "./source-facts.js";
13
13
  import { ensureApiRoles, existingTables } from "./target-checks.js";
14
14
  import { creatableExtensions } from "./target-extensions.js";
15
15
  import path from "node:path";
@@ -69,6 +69,7 @@ const readSource = async (sql, targetUrl) => {
69
69
  cronJobs: cron,
70
70
  vaultSecrets: await vaultSecrets(sql),
71
71
  vaultReplayed: secrets !== void 0,
72
+ pgsodiumColumns: await pgsodiumColumns(sql, schemas),
72
73
  queues: queues?.map((queue) => ({
73
74
  name: queue.name,
74
75
  partitioned: queue.partitioned,
@@ -150,7 +151,8 @@ const runDumpPhase = async (options, out) => {
150
151
  schemas: source.schemas,
151
152
  extensions: plan.extensions,
152
153
  webhooks: plan.webhooks,
153
- missing: plan.missing
154
+ missing: plan.missing,
155
+ encryptedColumns: source.pgsodiumColumns
154
156
  });
155
157
  await rm(schemaFile);
156
158
  await mkdir(options.migrationsDir, { recursive: true });
@@ -62,6 +62,7 @@ const importReport = (manifest, doctor, jobsWired, live) => [
62
62
  ...liveTables(live),
63
63
  section("Realtime tables", "The `supabase_realtime` publication sends these tables' changes to Realtime clients, but the scaffold made no resource of them, such as for a table without a primary key or one in auth or storage, so `/api/sb/realtime/v1` refuses them. Give each a resource with `.live()` where the app listens to its changes.", manifest.realtimeTables.map(tableName).filter((table) => !live.includes(table))),
64
64
  section("Vault secrets", "The project's database has no Vault, or the importing role could not read the secrets' values, so they stay in Supabase. Enter each again where the app reads it, such as an environment variable.", manifest.vaultReplayed ? [] : manifest.vaultSecrets?.map(secretName)),
65
+ section("pgsodium encrypted columns", "pgsodium encrypts these columns with the Supabase project's root key, which never leaves Supabase, so the import copied their ciphertext as it is. The migration leaves out pgsodium's labels, its decrypted views and its encrypting triggers, as comments: they stay in Supabase. Export each column's values decrypted in Supabase, from its decrypted view (`decrypted_<table>` beside the table unless the table's label names another), and write them over the ciphertext; then declare the field `.encrypted()` and run `protobase encryption apply`, which encrypts them with the app's own key.", manifest.pgsodiumColumns.map((column) => `${column.schema}.${column.table}.${column.column}`)),
65
66
  section("pgmq queues", "pgmq owns its queues' tables, so the dump leaves them out. Make each again with pgmq where the project's database has it, partitioned ones with `pgmq.create_partitioned`, and send its messages again.", queuesLeft(manifest)),
66
67
  section("Extensions left out", "The project's database does not let the importing role create these, so the migration does not. Replace what the app uses them for, or have the database's administrator make them available.", manifest.extensionsLeftOut.map((extension) => `${extension.name} (schema ${extension.schema})`)),
67
68
  section("To convert", "Supabase dropped timescaledb, plv8, plls and plcoffee after Postgres 15. The migration restores a hypertable as a plain table without its rows, and leaves out a function in a language the project's database does not have, as comments; convert each.", conversions(manifest)),
@@ -50,26 +50,55 @@ const routineAt = (statement, tokens, at) => {
50
50
  signature: statement.slice(tokens[at].start, tokens[close].end)
51
51
  };
52
52
  };
53
- /** A CREATE FUNCTION or PROCEDURE in a missing language, left out, or a statement naming one left out before. */
54
- const routineVerdict = (statement, tokens, missing, routines) => {
53
+ /**
54
+ * pgsodium's trigger function encrypting `column`, which it makes beside the table: it calls pgsodium, which the
55
+ * project's database never has, and would encrypt the values written to the column with that database's key.
56
+ */
57
+ const pgsodiumTrigger = (column) => `${column.schema}.${column.table}_encrypt_secret_${column.column}`;
58
+ /**
59
+ * A CREATE FUNCTION or PROCEDURE in a missing language or pgsodium's for an encrypted column, left out, or a statement
60
+ * naming one left out before.
61
+ */
62
+ const routineVerdict = (statement, tokens, missing, encrypted, routines) => {
55
63
  const at = (...words) => wordsAt(statement, tokens, 0, words);
56
64
  const create = at("create", "function") || at("create", "procedure") ? 2 : at("create", "or", "replace", "function") || at("create", "or", "replace", "procedure") ? 4 : -1;
57
65
  if (create !== -1) {
58
66
  const name = tokens[tokens.findIndex((token, i) => i > create && token.depth === 0 && wordsAt(statement, tokens, i, ["language"])) + 1]?.word;
59
67
  const routine = routineAt(statement, tokens, create);
60
- if (!name || !routine || !missing.languages.includes(name)) return void 0;
68
+ if (!routine) return void 0;
69
+ const pgsodium = encrypted.some((column) => pgsodiumTrigger(column) === routine.name);
70
+ if (!pgsodium && !(name && missing.languages.includes(name))) return void 0;
61
71
  routines.names.add(routine.name);
62
72
  routines.signatures.add(routine.signature);
73
+ if (pgsodium) return { drop: "it is pgsodium's, encrypting a column with the Supabase project's key; the report lists the column" };
63
74
  return { drop: `it is written in ${name}, which the project's database does not have; the report lists it for conversion` };
64
75
  }
65
76
  if (routines.signatures.size === 0) return void 0;
66
77
  return tokens.some((token, i) => (token.word === "function" || token.word === "procedure") && routines.signatures.has(routineAt(statement, tokens, i + 1)?.signature ?? "")) ? { drop: "it names a function left out above" } : void 0;
67
78
  };
79
+ /** Whether the tokens name `schema.name` somewhere, as a word, a dot and a word. */
80
+ const names = (statement, tokens, qualified) => tokens.some((token, i) => statement[tokens[i + 1]?.start ?? 0] === "." && qualified.has(`${token.word}.${tokens[i + 2]?.word}`));
81
+ /**
82
+ * pgsodium's security labels, and the views decrypting with it, such as its `decrypted_<table>`, left out, or a
83
+ * statement naming such a view: the project's database never has pgsodium, and only Supabase's key decrypts.
84
+ */
85
+ const pgsodiumVerdict = (statement, tokens, views) => {
86
+ const at = (...words) => wordsAt(statement, tokens, 0, words);
87
+ if (at("security", "label", "for", "pgsodium")) return { drop: "it labels a column pgsodium encrypts with the Supabase project's key; the report lists the column" };
88
+ const create = at("create", "view") ? 2 : at("create", "or", "replace", "view") ? 4 : -1;
89
+ if (create !== -1 && tokens.some((token, i) => token.word === "pgsodium" && statement[tokens[i + 1]?.start ?? 0] === ".")) {
90
+ views.add(`${tokens[create]?.word}.${tokens[create + 2]?.word}`);
91
+ return { drop: "it decrypts with pgsodium, which only the Supabase project's key opens; the report lists its columns" };
92
+ }
93
+ if (views.size > 0 && names(statement, tokens, views)) return { drop: "it names a view left out above" };
94
+ };
68
95
  /** A statement as it should restore on a Protobase database, or why it is left out. */
69
- const rewriteStatement = (statement, missing, routines) => {
96
+ const rewriteStatement = (statement, missing, encrypted, left) => {
70
97
  const tokens = tokenize(statement);
71
98
  const at = (...words) => wordsAt(statement, tokens, 0, words);
72
- const routine = routineVerdict(statement, tokens, missing, routines);
99
+ const pgsodium = pgsodiumVerdict(statement, tokens, left.views);
100
+ if (pgsodium) return pgsodium;
101
+ const routine = routineVerdict(statement, tokens, missing, encrypted, left);
73
102
  if (routine) return routine;
74
103
  if (at("grant") || at("revoke")) return withoutSupabaseGrantees(statement, tokens, 0);
75
104
  if (at("alter", "default", "privileges")) return defaultPrivileges(statement, tokens);
@@ -79,7 +108,7 @@ const rewriteStatement = (statement, missing, routines) => {
79
108
  const call = tokens.findIndex((_, i) => wordsAt(statement, tokens, i, ["execute", "function"]) || wordsAt(statement, tokens, i, ["execute", "procedure"]));
80
109
  const called = call === -1 ? void 0 : routineAt(statement, tokens, call + 2);
81
110
  if (called && missing.triggerSchemas.includes(called.name.split(".")[0])) return { drop: `it calls ${called.name}, which the import does not carry over; the report lists it` };
82
- if (called && routines.names.has(called.name)) return { drop: "it calls a function left out above" };
111
+ if (called && left.names.has(called.name)) return { drop: "it calls a function left out above" };
83
112
  }
84
113
  return keep(statement);
85
114
  };
@@ -87,20 +116,22 @@ const rewriteStatement = (statement, missing, routines) => {
87
116
  const leftOut = (statement, reason) => `-- Left out by protobase import supabase: ${reason}.\n${statement.replace(/^/gm, "-- ")}`;
88
117
  /**
89
118
  * A `pg_dump --schema-only` of a Supabase database, rewritten to restore without errors as a role that is not a
90
- * superuser and has none of Supabase's own roles, on a database lacking what `missing` names, and how many statements
91
- * it leaves out. Statements are parsed, so a rule never touches a function body or a string.
119
+ * superuser and has none of Supabase's own roles, on a database lacking what `missing` names and pgsodium, whose
120
+ * `encrypted` columns keep their ciphertext without its trigger, and how many statements it leaves out. Statements are
121
+ * parsed, so a rule never touches a function body or a string.
92
122
  */
93
- const rewriteSchemaDump = (dump, missing) => {
123
+ const rewriteSchemaDump = (dump, missing, encrypted) => {
94
124
  let leftOutCount = 0;
95
- const routines = {
125
+ const left = {
96
126
  names: /* @__PURE__ */ new Set(),
97
- signatures: /* @__PURE__ */ new Set()
127
+ signatures: /* @__PURE__ */ new Set(),
128
+ views: /* @__PURE__ */ new Set()
98
129
  };
99
130
  return {
100
131
  sql: splitDump(dump).map((piece) => {
101
132
  if (piece.kind === "meta") return "";
102
133
  if (piece.kind === "gap") return piece.text;
103
- const verdict = rewriteStatement(piece.text, missing, routines);
134
+ const verdict = rewriteStatement(piece.text, missing, encrypted, left);
104
135
  if ("keep" in verdict) return verdict.keep;
105
136
  leftOutCount++;
106
137
  return leftOut(piece.text, verdict.drop);
@@ -10,7 +10,7 @@ import { resetSettings, sessionSettings } from "./session-settings.js";
10
10
  * statements it leaves out.
11
11
  */
12
12
  const schemaMigration = (dump, input) => {
13
- const rewritten = rewriteSchemaDump(dump, input.missing);
13
+ const rewritten = rewriteSchemaDump(dump, input.missing, input.encryptedColumns);
14
14
  return {
15
15
  text: [
16
16
  `-- The schemas ${input.schemas.join(", ")} of a Supabase database, written by \`protobase import supabase\`.\n`,
@@ -113,6 +113,18 @@ const vaultSecretValues = async (sql) => {
113
113
  return sql`select name, description, decrypted_secret as secret from vault.decrypted_secrets order by created_at, id`;
114
114
  };
115
115
  /**
116
+ * The columns of `schemas` pgsodium's Transparent Column Encryption encrypts, by a security label: their ciphertext
117
+ * opens only with the Supabase project's root key, so the dump copies it as it is.
118
+ */
119
+ const pgsodiumColumns = (sql, schemas) => sql`
120
+ select n.nspname as schema, c.relname as table, a.attname as column
121
+ from pg_seclabel l
122
+ join pg_class c on c.oid = l.objoid join pg_namespace n on n.oid = c.relnamespace
123
+ join pg_attribute a on a.attrelid = c.oid and a.attnum = l.objsubid
124
+ where l.provider = 'pgsodium' and l.classoid = 'pg_class'::regclass and l.objsubid > 0 and n.nspname = any(${schemas})
125
+ order by 1, 2, 3
126
+ `;
127
+ /**
116
128
  * pgmq's queues with their messages, in order. The extension owns the queues' tables, so pg_dump leaves them out.
117
129
  * `undefined` when the role may not read them.
118
130
  */
@@ -178,4 +190,4 @@ const httpTriggers = (sql, schemas) => sql`
178
190
  order by 1, 2, 3
179
191
  `;
180
192
  //#endregion
181
- export { appSchemas, cronJobs, cronTimezone, databaseMarkers, dumpedTables, extensions, httpTriggers, hypertables, pgmqQueues, platformMigrationTables, realtimeTables, routinesIn, tablesSize, vaultSecretValues, vaultSecrets };
193
+ export { appSchemas, cronJobs, cronTimezone, databaseMarkers, dumpedTables, extensions, httpTriggers, hypertables, pgmqQueues, pgsodiumColumns, platformMigrationTables, realtimeTables, routinesIn, tablesSize, vaultSecretValues, vaultSecrets };
@@ -1,3 +1,4 @@
1
+ import { passwordLength } from "@protobase/server";
1
2
  import { randomBytes } from "node:crypto";
2
3
  //#region src/users/password.ts
3
4
  const rejectPasswordArgument = (value) => {
@@ -43,6 +44,10 @@ const readHidden = (question) => new Promise((resolve, reject) => {
43
44
  };
44
45
  stdin.on("data", onData);
45
46
  });
47
+ const checkPasswordLength = (password) => {
48
+ const { min, max } = passwordLength;
49
+ if (password.length < min || password.length > max) throw new Error(`Choose a password of ${min} to ${max} characters`);
50
+ };
46
51
  const resolvePassword = async (options, deps) => {
47
52
  if ([
48
53
  options.passwordStdin,
@@ -54,12 +59,9 @@ const resolvePassword = async (options, deps) => {
54
59
  password: generatePassword(),
55
60
  generated: true
56
61
  };
57
- if (options.passwordStdin) return {
58
- password: await readPasswordFromStream(deps.stdin),
59
- generated: false
60
- };
61
- const password = await deps.prompt("Password: ");
62
- if (password !== await deps.prompt("Repeat password: ")) throw new Error("The passwords do not match");
62
+ const password = options.passwordStdin ? await readPasswordFromStream(deps.stdin) : await deps.prompt("Password: ");
63
+ if (!options.passwordStdin && password !== await deps.prompt("Repeat password: ")) throw new Error("The passwords do not match");
64
+ checkPasswordLength(password);
63
65
  return {
64
66
  password,
65
67
  generated: false
@@ -5,23 +5,12 @@ import { readHidden, rejectPasswordArgument } from "./password.js";
5
5
  import { createUserCommand, listRolesCommand, listUsersCommand } from "./commands.js";
6
6
  import { deleteUserCommand, setDisabledCommand, setRoleCommand } from "./manage.js";
7
7
  import { parseTtl } from "./ttl.js";
8
+ import { usersApi } from "./users-api.js";
8
9
  import { Option } from "commander";
9
- import { createUser, deleteUser, hasUsers, issueToken, listUsers, roleChoices, setUserBanned, setUserRole } from "@protobase/server";
10
+ import { issueToken } from "@protobase/server";
10
11
  import { createInterface } from "node:readline/promises";
11
12
  //#region src/users/register.ts
12
13
  const out = (text) => process.stdout.write(text);
13
- const usersApi = (auth) => ({
14
- hasUsers: () => hasUsers(auth),
15
- roles: async () => ({
16
- roles: roleChoices(auth),
17
- defaultRole: auth.defaultRole
18
- }),
19
- createUser: (input) => createUser(auth, input),
20
- listUsers: () => listUsers(auth),
21
- deleteUser: (email) => deleteUser(auth, email),
22
- setUserRole: (input) => setUserRole(auth, input),
23
- setUserBanned: (input) => setUserBanned(auth, input)
24
- });
25
14
  const projectApi = async () => usersApi(await loadProjectAuth(process.cwd()));
26
15
  const ask = async (question) => {
27
16
  if (!process.stdin.isTTY) throw new Error("Confirmation needs a terminal; pass --yes to skip it");
@@ -102,4 +91,4 @@ const registerToken = (program) => {
102
91
  });
103
92
  };
104
93
  //#endregion
105
- export { registerToken, registerUsers, usersApi };
94
+ export { registerToken, registerUsers };
@@ -0,0 +1,16 @@
1
+ import { createUser, deleteUser, hasUsers, listUsers, roleChoices, setUserBanned, setUserRole } from "@protobase/server";
2
+ //#region src/users/users-api.ts
3
+ const usersApi = (auth) => ({
4
+ hasUsers: () => hasUsers(auth),
5
+ roles: async () => ({
6
+ roles: roleChoices(auth),
7
+ defaultRole: auth.defaultRole
8
+ }),
9
+ createUser: (input) => createUser(auth, input),
10
+ listUsers: () => listUsers(auth),
11
+ deleteUser: (email) => deleteUser(auth, email),
12
+ setUserRole: (input) => setUserRole(auth, input),
13
+ setUserBanned: (input) => setUserBanned(auth, input)
14
+ });
15
+ //#endregion
16
+ export { usersApi };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.34.0",
3
+ "version": "0.34.2",
4
4
  "description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -36,11 +36,11 @@
36
36
  "@better-auth/core": "^1.7.12",
37
37
  "@hono/node-server": "^2.1.3",
38
38
  "@hono/vite-dev-server": "^0.26.1",
39
- "@protobase/layout": "0.34.0",
40
- "@protobase/query": "0.34.0",
41
- "@protobase/schema": "0.34.0",
42
- "@protobase/server": "0.34.0",
43
- "@protobase/ui": "0.34.0",
39
+ "@protobase/layout": "0.34.2",
40
+ "@protobase/query": "0.34.2",
41
+ "@protobase/schema": "0.34.2",
42
+ "@protobase/server": "0.34.2",
43
+ "@protobase/ui": "0.34.2",
44
44
  "@react-email/render": "^2.1.0",
45
45
  "@scalar/hono-api-reference": "^0.12.10",
46
46
  "@tailwindcss/vite": "^4.3.3",
@@ -14,11 +14,12 @@ bun --no-install /opt/protobase/protobase-serve.js /app/protobase.config.js #
14
14
 
15
15
  Both builds write plain JavaScript that Node and Bun load as it is. For a host that runs Bun, as the images below do, add `--bun` to either: Bun's bundler then writes the final file, the form Bun loads without transpiling, and the build needs `bun` on `PATH` ([details](../reference/cli.md#the-config-module))).
16
16
 
17
- The bundle holds three things, four when the config uses native add-ons:
17
+ The bundle holds three things, more when the project has migrations or the config uses native add-ons:
18
18
 
19
19
  ```
20
20
  dist/
21
21
  protobase.config.js the config module, run by the serve runtime
22
+ migrations/ only with migrations: the project's db/migrations/*.sql, which `migrate` applies
22
23
  node_modules/ only with native add-ons: those packages, with linux x64 and arm64 binaries
23
24
  public/ the admin app (index.html and content-hashed assets/), the project's UI as plugins in
24
25
  plugins/, its theme, protobase.theme.css, and its icons, protobase.favicon.svg
@@ -27,7 +28,7 @@ dist/
27
28
  plugins and the app's version
28
29
  ```
29
30
 
30
- The host serves `public/` itself and sends only the manifest's `api` paths to the runtime (`/api` and the two OAuth discovery documents of [MCP clients](../reference/auth.md#oauth-for-mcp-clients)), and `/.well-known/webauthn`, for an app on [several origins](../reference/auth.md#several-origins))), so loading the UI never needs a running container. With the UI it sends `X-Frame-Options: DENY` and `Content-Security-Policy: frame-ancestors 'none'`, as `protobase serve` does, so no other site frames the app's pages. The runtime serves the API alone; `protobase serve dist` serves the whole folder the same way, to check a bundle locally. The host passes `DATABASE_URL`, `PORT` (default 8787) and optionally `PROTOBASE_DB_CONNECTIONS` (the connections the app may open, so its functions and jobs leave one to requests, see [`serve`](../reference/cli.md#serve))), `REQUEST_LOG`, `PROTOBASE_SMTP_URL` and `PROTOBASE_MAIL_FROM` (the mail server and sender for [password reset](../reference/auth.md#password-reset)) and emailed sign-in codes) `PROTOBASE_APP_NAME` (the app's name in that mail, see [`appName`](../reference/auth.md#configuration))) `PROTOBASE_SIGN_IN_*` (a provider people with an account sign in with, the [platform sign-in provider](../reference/auth.md#platform-sign-in-provider))) `PROTOBASE_OPERATOR_*` (the provider its staff sign in with for [staff sign-in](../reference/auth.md#staff-sign-in))), `PROTOBASE_ORIGINS` and `PROTOBASE_PASSKEY_DOMAIN` (the app's [other origins](../reference/auth.md#several-origins)) and its passkey domain) `PROTOBASE_CORS_ORIGINS` (the websites that may call its API, see [CORS](../reference/api.md#cors))), `PROTOBASE_TRUSTED_PROXIES` (the proxies in front of the runtime, whose `X-Forwarded-For` names the client the sign-in limits count, see [Client addresses](../reference/auth.md#client-addresses))) and `PROTOBASE_SENTRY_DSN` (the app's [error tracker](../reference/api.md#error-reporting))), plus the project's own settings (`BETTER_AUTH_SECRET`, ...). The runtime and the config module are plain JavaScript for Bun: no install, no TypeScript, no writes. The runtime supplies protobase and the dependencies it runs on the server (`pg`, `postgres`, `kysely`, `better-auth`, ...), so the config module carries only the project's code and the other packages it uses. The runtime serves only bundles built by a compatible Protobase version, below 1.0 the same minor (see [Versioning](../reference/versioning.md#bundles-and-runtimes))), so rebuild the bundle when the host's runtime moves to another one. Nothing in the bundle or the runtime changes the database: run the project's `db:migrate`, which applies its migrations and those of the auth schema, before a new version serves it, with no other writes while it runs. The runtime refuses to start while the auth schema lacks a table or column the new version needs (see [migrations](../reference/auth.md#migrations))). The manifest format and the routing rules are in the CLI reference: [`build`](../reference/cli.md#build)), [`build-serve`](../reference/cli.md#build-serve)) and [`serve`](../reference/cli.md#serve)).
31
+ The host serves `public/` itself and sends only the manifest's `api` paths to the runtime (`/api` and the two OAuth discovery documents of [MCP clients](../reference/auth.md#oauth-for-mcp-clients)), and `/.well-known/webauthn`, for an app on [several origins](../reference/auth.md#several-origins))), so loading the UI never needs a running container. With the UI it sends `X-Frame-Options: DENY` and `Content-Security-Policy: frame-ancestors 'none'`, as `protobase serve` does, so no other site frames the app's pages. The runtime serves the API alone; `protobase serve dist` serves the whole folder the same way, to check a bundle locally. The host passes `DATABASE_URL`, `PORT` (default 8787) and optionally `PROTOBASE_DB_CONNECTIONS` (the connections the app may open, so its functions and jobs leave one to requests, see [`serve`](../reference/cli.md#serve))), `REQUEST_LOG`, `PROTOBASE_SMTP_URL` and `PROTOBASE_MAIL_FROM` (the mail server and sender for [password reset](../reference/auth.md#password-reset)) and emailed sign-in codes) `PROTOBASE_APP_NAME` (the app's name in that mail, see [`appName`](../reference/auth.md#configuration))) `PROTOBASE_SIGN_IN_*` (a provider people with an account sign in with, the [platform sign-in provider](../reference/auth.md#platform-sign-in-provider))) `PROTOBASE_OPERATOR_*` (the provider its staff sign in with for [staff sign-in](../reference/auth.md#staff-sign-in))), `PROTOBASE_ORIGINS` and `PROTOBASE_PASSKEY_DOMAIN` (the app's [other origins](../reference/auth.md#several-origins)) and its passkey domain) `PROTOBASE_CORS_ORIGINS` (the websites that may call its API, see [CORS](../reference/api.md#cors))), `PROTOBASE_TRUSTED_PROXIES` (the proxies in front of the runtime, whose `X-Forwarded-For` names the client the sign-in limits count, see [Client addresses](../reference/auth.md#client-addresses))) and `PROTOBASE_SENTRY_DSN` (the app's [error tracker](../reference/api.md#error-reporting))), plus the project's own settings (`BETTER_AUTH_SECRET`, ...). The runtime and the config module are plain JavaScript for Bun: no install, no TypeScript, no writes. The runtime supplies protobase and the dependencies it runs on the server (`pg`, `postgres`, `kysely`, `better-auth`, ...), so the config module carries only the project's code and the other packages it uses. The runtime serves only bundles built by a compatible Protobase version, below 1.0 the same minor (see [Versioning](../reference/versioning.md#bundles-and-runtimes))), so rebuild the bundle when the host's runtime moves to another one. 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))). The manifest format and the routing rules are in the CLI reference: [`build`](../reference/cli.md#build)), [`build-serve`](../reference/cli.md#build-serve)) and [`serve`](../reference/cli.md#serve)).
31
32
 
32
33
  ## Images
33
34
 
@@ -35,7 +36,7 @@ Every release pushes two public images to GitHub's registry, for `linux/amd64` a
35
36
 
36
37
  | Image | What it holds |
37
38
  | --- | --- |
38
- | `ghcr.io/prototeamhq/protobase:<version>` | the serve runtime, compiled with Bun into `/opt/protobase/protobase-serve`, which serves the API of the bundle mounted at `/app`; the release's prebuilt admin app at `/opt/protobase/shell`, which a host may serve for the bundle's [shell paths](../reference/plugins.md#the-shell)) instead of the bundle's copy; Bun for its healthcheck on `/health`, and the C++ runtime native add-ons link. It runs as `nonroot` (65532) and writes nothing, so it runs with a read-only root filesystem |
39
+ | `ghcr.io/prototeamhq/protobase:<version>` | the serve runtime, compiled with Bun into `/opt/protobase/protobase-serve`, which serves the API of the bundle mounted at `/app` (and, given the folder, its app too, see [a self-hosted image](#a-self-hosted-image)); the release's prebuilt admin app at `/opt/protobase/shell`, which a host may serve for the bundle's [shell paths](../reference/plugins.md#the-shell)) instead of the bundle's copy; Bun for its healthcheck on `/health`, and the C++ runtime native add-ons link. It runs as `nonroot` (65532) and writes nothing, so it runs with a read-only root filesystem |
39
40
  | `ghcr.io/prototeamhq/protobase-dev:<version>` | Bun and the presets at `/opt/protobase/presets/<name>` (`erp`, `real-estate`, `scratch`), with the dependencies they share installed in `/workspace` and Bun's cache in `/opt/bun-cache`. It has no Node: the presets' scripts and the `protobase` command run on Bun. It runs as `bun` (1000) |
40
41
 
41
42
  ```sh
@@ -51,3 +52,120 @@ bun run images:context # dist/images/protobase and dist/images/protobase-dev
51
52
  docker build -f docker/protobase/Dockerfile -t protobase dist/images/protobase
52
53
  docker build -f docker/protobase-dev/Dockerfile -t protobase-dev dist/images/protobase-dev
53
54
  ```
55
+
56
+ ## A self-hosted image
57
+
58
+ A product built on Protobase ships to self-hosters as one image: the runtime image with the bundle inside. Build the bundle with `protobase build --bun`, then:
59
+
60
+ ```dockerfile
61
+ # The runtime of the @protobase/cli version that built dist/.
62
+ FROM ghcr.io/prototeamhq/protobase:0.2.0
63
+ COPY dist /app
64
+ CMD ["/app"]
65
+ ```
66
+
67
+ The image runs three commands:
68
+
69
+ - `/app` serves the admin app and its API.
70
+ - `migrate /app` applies the bundle's pending migrations with `DATABASE_URL` alone. It runs none of the app's code.
71
+ - `create-admin /app <email>` creates an admin, with `--generate-password` (printed once) or `--password-stdin`. It refuses a schema that is behind.
72
+
73
+ ### Compose template
74
+
75
+ Two files next to `compose.yaml` hold the settings. `.env`, which compose reads itself:
76
+
77
+ ```sh
78
+ APP_VERSION=1.0.0
79
+ POSTGRES_PASSWORD=... # openssl rand -hex 24
80
+ APP_DB_PASSWORD=... # openssl rand -hex 24
81
+ ```
82
+
83
+ `app.env`, the app's own settings:
84
+
85
+ ```sh
86
+ BETTER_AUTH_SECRET=... # openssl rand -base64 32
87
+ BETTER_AUTH_URL=http://localhost:8787
88
+ ```
89
+
90
+ `BETTER_AUTH_URL` is the address the browser opens, exactly: sign-in from `http://127.0.0.1:8787` is refused as another origin. Add the app's other variables to `app.env` too.
91
+
92
+ ```yaml
93
+ services:
94
+ postgres:
95
+ image: postgres:18
96
+ restart: unless-stopped
97
+ environment:
98
+ POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set it in .env}
99
+ APP_DB_PASSWORD: ${APP_DB_PASSWORD:?set it in .env}
100
+ configs:
101
+ - source: app-database
102
+ target: /docker-entrypoint-initdb.d/app-database.sql
103
+ volumes:
104
+ - db:/var/lib/postgresql
105
+ healthcheck:
106
+ test: ["CMD", "pg_isready", "-h", "127.0.0.1", "-U", "app", "-d", "app"]
107
+ interval: 2s
108
+ retries: 30
109
+
110
+ migrate:
111
+ image: ghcr.io/example/my-app:${APP_VERSION:?set it in .env}
112
+ command: ["migrate", "/app"]
113
+ environment:
114
+ DATABASE_URL: postgres://app:${APP_DB_PASSWORD:?set it in .env}@postgres:5432/app
115
+ depends_on:
116
+ postgres:
117
+ condition: service_healthy
118
+
119
+ app:
120
+ image: ghcr.io/example/my-app:${APP_VERSION:?set it in .env}
121
+ restart: unless-stopped
122
+ env_file: app.env
123
+ environment:
124
+ DATABASE_URL: postgres://app:${APP_DB_PASSWORD:?set it in .env}@postgres:5432/app
125
+ ports:
126
+ - "127.0.0.1:8787:8787"
127
+ depends_on:
128
+ migrate:
129
+ condition: service_completed_successfully
130
+
131
+ configs:
132
+ app-database:
133
+ content: |
134
+ \getenv app_password APP_DB_PASSWORD
135
+ create role app login password :'app_password';
136
+ create database app owner app;
137
+
138
+ volumes:
139
+ db:
140
+ ```
141
+
142
+ `docker compose up -d` starts Postgres, runs `migrate` once and starts the app only when it succeeded. The app and `migrate` connect as `app`, which owns its database but is no superuser (see the [assistant](../reference/assistant.md)) on why that matters); the superuser's password stays in `.env` and the `postgres` service. Postgres runs the init file only on an empty volume. `configs` with `content` needs a recent Compose v2 (tested with 2.39.4).
143
+
144
+ ### Local only by default
145
+
146
+ The template publishes the app on `127.0.0.1:8787` only, so only the machine running it can open `http://localhost:8787`, and it speaks plain HTTP. To try it on a remote server, tunnel it with `ssh -L 8787:localhost:8787 <server>` and open `http://localhost:8787` on your own machine.
147
+
148
+ Before other machines may reach it, put HTTPS in front: a reverse proxy on the host that forwards to `127.0.0.1:8787`, with `BETTER_AUTH_URL` set to the `https://` address. Only then are the session cookies `Secure` and passwords and codes encrypted on the way. Do not change the port to `8787:8787`: that publishes plain HTTP on every interface, ahead of host firewall rules such as ufw. On Docker Engine older than 28.0, hosts on the same local network can still reach a port published to `127.0.0.1`, so use 28.0 or newer.
149
+
150
+ ### First admin
151
+
152
+ ```sh
153
+ docker compose run --rm --no-deps app create-admin /app you@example.com --generate-password
154
+ ```
155
+
156
+ Then open `http://localhost:8787` and sign in with that email and the printed password. `--no-deps` keeps compose from running `migrate` first, which during an upgrade would migrate under the old version while it serves; use it with every `docker compose run … app`. Where container logs leave the host, pass the password on stdin instead: `docker compose run --rm --no-deps -T app create-admin /app you@example.com --password-stdin < password.txt`.
157
+
158
+ ### Upgrade
159
+
160
+ ```sh
161
+ docker compose exec -T postgres pg_dump -U app app > backup.sql
162
+ # set APP_VERSION in .env to the new version
163
+ docker compose pull
164
+ docker compose stop app # the old version stops, so nothing writes
165
+ docker compose run --rm migrate
166
+ docker compose up -d
167
+ ```
168
+
169
+ Stop any `protobase worker` processes before `migrate` too.
170
+
171
+ When a migration fails, `migrate` exits with an error and its transaction is rolled back, so the schema is unchanged. Set `APP_VERSION` back and `docker compose start app` brings the old version back on it. A plain `docker compose up -d` with the new version also stops the old one before `migrate`, but after a failure nothing serves until `APP_VERSION` is set back and `up -d` runs again. Going back after a migration that succeeded needs the backup.
@@ -175,6 +175,7 @@ Writes the project's deploy bundle, the folder a deployment ships:
175
175
  ```
176
176
  dist/
177
177
  protobase.config.js the config module for serve
178
+ migrations/ the project's db/migrations/*.sql, which the runtime's migrate applies; only with some
178
179
  node_modules/ the packages it loads from disk, only when it imports native add-ons
179
180
  public/
180
181
  index.html, assets/ the admin app: the shell, the same for every project
@@ -187,7 +188,7 @@ dist/
187
188
  protobase.bundle.json the manifest
188
189
  ```
189
190
 
190
- The output folder is not emptied; `public/` and `node_modules/` are replaced on every build. `node_modules/` is deleted only when the previous build's manifest names it, so a build into a folder with a project's own `node_modules` fails instead. Of the project's server config only the config folder runs at build time, `config/index.ts` and `config/*/ui.ts` with what they import, never `protobase.config.ts`, so the build needs no secrets and no database. It is loaded once in Node to check each view against its resource: a filter widget or the chart on a field that is not `.filterable()`, a list sorted by one that is not `.sortable()`, or a list search on a field outside the resource's `.search(...)` fails the build, naming the view and the field, since the API would refuse it once a page asked. Whether an index serves those reads needs the database, which [`doctor`](#doctor) checks. Its browser code is loaded once in Node too: to check its component names (see [The UI](#the-ui)) and to read the field types each plugin registers.
191
+ The output folder is not emptied; `public/`, `migrations/` and `node_modules/` are replaced on every build. `migrations/` and `node_modules/` are deleted only when the previous build's manifest names them, so a build into a folder with a project's own `node_modules` fails instead. Of the project's server config only the config folder runs at build time, `config/index.ts` and `config/*/ui.ts` with what they import, never `protobase.config.ts`, so the build needs no secrets and no database. It is loaded once in Node to check each view against its resource: a filter widget or the chart on a field that is not `.filterable()`, a list sorted by one that is not `.sortable()`, or a list search on a field outside the resource's `.search(...)` fails the build, naming the view and the field, since the API would refuse it once a page asked. Whether an index serves those reads needs the database, which [`doctor`](#doctor) checks. Its browser code is loaded once in Node too: to check its component names (see [The UI](#the-ui)) and to read the field types each plugin registers.
191
192
 
192
193
  A token the [theme](theme.md)) sets that the app does not read prints a `warning:` line, a likely typo; the build still succeeds.
193
194
 
@@ -220,16 +221,18 @@ By default the bundle runs on Node and on Bun. `--bun` makes it a bundle for Bun
220
221
  { "name": "app", "path": "plugins/app/plugin.json", "api": 1, "protobase": ">=0.12.0", "fields": { "steps": ["enum"] } }
221
222
  ],
222
223
  "shell": { "protobase": "0.12.0", "pluginApi": 1, "paths": ["/index.html", "/assets", "/protobase.sw.js"] },
223
- "nodeModules": "node_modules"
224
+ "nodeModules": "node_modules",
225
+ "migrations": "migrations"
224
226
  }
225
227
  ```
226
228
 
227
229
  - `protobase` is the Protobase version that built the bundle. The serve runtime serves only bundles of a compatible version: below 1.0 the same minor, from 1.0 the same major and the runtime's minor or an older one (see [Versioning](versioning.md#bundles-and-runtimes))).
228
- - `server`, `public` and `nodeModules` are relative to the bundle folder; `spa`, `theme` and each plugin's `path` to `public`.
230
+ - `server`, `public`, `nodeModules` and `migrations` are relative to the bundle folder; `spa`, `theme` and each plugin's `path` to `public`.
229
231
  - `plugins` are the bundle's own plugins, in the order the app merges them: the extensions', then the project's (`app`). Each names its `plugin.json`, the plugin API and Protobase versions it is built for, and the [field types](plugins.md#field-types)) it registers with the storage types each shows, which the serve runtime checks the views against at startup. `/api/meta` names them to everyone, before any other plugin.
230
232
  - `shell` is the admin app `public/` holds a copy of: its Protobase version and plugin API, and its files as URL paths. A host with a shell of its own, of a release every plugin of the bundle loads in, may serve its own for those paths instead (see [The UI](#the-ui)), so the app gets that release's fixes without a rebuild.
231
233
  - `theme` is the project's [theme](theme.md)), which the app links at `/protobase.theme.css`. It is always there, empty when the project has none.
232
234
  - `nodeModules` is present only when the config module imports [native packages](#native-packages). It is always the `node_modules` folder beside `server`, where Bun and Node resolve the module's imports from, and holds plain packages: JavaScript, `package.json` files and native binaries for linux x64 and arm64 (glibc), which the runtime loads with `dlopen`. A host keeps it next to the server module and must not mount it `noexec` (an add-on there then fails with `failed to map segment from shared object`). Its binaries link nothing but glibc, `libstdc++.so.6`, `libgcc_s.so.1` and libraries in the bundle itself, so the run image must have those three. Without `nodeModules`, the server module is the only file the runtime reads.
235
+ - `migrations` is present only when the project has a `db/migrations` folder: its `.sql` files, which the runtime's `migrate` applies (see [Deploy](../guides/deploy.md))). A host never serves it.
233
236
  - `api` lists the path prefixes the server answers. A path is under a prefix when it equals it or continues it with `/` (`/api` covers `/api/meta` and `/api/v1:batchWrite`, not `/apiary`). It is always `/api` and the two OAuth discovery documents [MCP clients](auth.md#oauth-for-mcp-clients)) read, which answer 404 without MCP: a bundle assumes the API lives under `/api`, with the resources at the default `basePath` `/api/v1`, `/api/meta`, the docs, the API functions and the built-in assistant beside them and Better Auth at `/api/auth`. A bundle built before them sends them to the UI: rebuild it. The serve runtime refuses a config that sets another `options.basePath`.
234
237
  - Every other path is the UI's. A `GET` or `HEAD` for a file in `public` gets that file; a folder gets its `index.html`. Otherwise a request whose `Accept` header contains `text/html` (a navigation) gets `spa` with status 200, so deep links such as `/orders/42` load the app; anything else gets 404. Other methods get 405.
235
238
  - Files under an `assets/` folder, `public/assets/` and each plugin's, are named by their content hash and never change: serve them with `Cache-Control: public, max-age=31536000, immutable`, and everything else, `index.html`, each `plugin.json` and the theme, with `no-cache`.
@@ -345,6 +348,14 @@ protobase build-serve [--out dist/protobase-serve.js] [--bun] # or, in this re
345
348
 
346
349
  Bundles the serve runtime (`@protobase/cli`'s `src/serve/main.ts`) and all its dependencies into one file, about 3 MB. A host needs Bun and this file, nothing else. `--bun` has Bun's bundler write the file, as for [`build`](#build), and needs `bun` on `PATH`; the `protobase` image is built from such a file. The file carries the Protobase version it was built from, which decides [the bundles it serves](versioning.md#bundles-and-runtimes)).
347
350
 
351
+ ```sh
352
+ bun --no-install protobase-serve.js [serve] <bundle> # the folder: the app and the API; the config module: the API
353
+ bun --no-install protobase-serve.js migrate <bundle> # apply the bundle's migrations to DATABASE_URL
354
+ bun --no-install protobase-serve.js create-admin <bundle> <email> # --generate-password or --password-stdin
355
+ ```
356
+
357
+ `migrate` runs none of the app's code and needs only `DATABASE_URL`; `create-admin` loads the app with its settings and refuses an auth schema that is behind. Given the folder, the runtime serves the bundle's own copy of the app. [Deploy](../guides/deploy.md#a-self-hosted-image)) puts the three in a self-hosted image.
358
+
348
359
  ## `serve`
349
360
 
350
361
  ```sh
@@ -449,7 +460,7 @@ protobase users delete <email> [--yes]
449
460
 
450
461
  Run inside a project whose `protobase.config.ts` exports `auth` (Better Auth). There is no web setup page, and [open sign-up](auth.md#open-sign-up)), when a project turns it on, waits for the first admin: the first admin is created here. The first user is always an admin, whatever `--role` says; later users get `--role`, or the project's default role (`createAuth({ roles, defaultRole })`). `protobase users roles` lists the roles of the project; anything else is refused with that list. `set-role` also takes comma separated roles (`sales,accountant`). `--github-id` links the new user to a GitHub user id (the number, not the login), so signing in with GitHub, the app's own provider or the [platform's](auth.md#platform-sign-in-provider)), finds them whatever address GitHub reports; an id that signs in another user already is refused. `createUser(auth, { ..., accounts: [{ providerId, accountId }] })` does the same from code.
451
462
 
452
- The password is typed at a hidden prompt with confirmation, read from stdin with `--password-stdin` (for scripts, e.g. `pass show erp | protobase users create me@example.com --password-stdin`), or generated with `--generate-password` and printed once. `--no-password` makes an account without one, which signs in by [emailed code](auth.md#emailed-sign-in-codes)), passkey or a sign-in provider, as with an app whose [sign-in policy](auth.md#sign-in-policy)) turns passwords off. A password is never accepted as an argument, since it would end up in shell history. `users list` prints email, role and creation date (and `disabled` for banned users), never credentials.
463
+ The password is typed at a hidden prompt with confirmation, read from stdin with `--password-stdin` (for scripts, e.g. `pass show erp | protobase users create me@example.com --password-stdin`), or generated with `--generate-password` and printed once; it must be 12 to 128 characters, the length the app requires of every new password. `--no-password` makes an account without one, which signs in by [emailed code](auth.md#emailed-sign-in-codes)), passkey or a sign-in provider, as with an app whose [sign-in policy](auth.md#sign-in-policy)) turns passwords off. A password is never accepted as an argument, since it would end up in shell history. `users list` prints email, role and creation date (and `disabled` for banned users), never credentials.
453
464
 
454
465
  `delete` asks you to type the email back (or pass `--yes`), and needs a terminal otherwise. `delete`, `set-role` and `disable` refuse to touch the last admin, so the project cannot lock itself out. `disable` bans the user and revokes their sessions; tokens already issued stop working on their next request, and `protobase token` refuses disabled users. With [MCP](auth.md#oauth-for-mcp-clients)) on, it also disconnects their MCP clients. `enable` lifts the ban; the clients have to be allowed again. `protobase dev` prints "No users yet. Create the first admin with: protobase users create you@example.com" at startup while the user table is empty.
455
466
 
@@ -499,9 +510,9 @@ protobase import supabase [<connection> | --source-env <variable>] [--env DATABA
499
510
 
500
511
  Turns a Supabase project's database into the project in the current directory, in two runs with the project's migrations between them. It needs PostgreSQL's `pg_dump` and `psql` on `PATH`, of the Supabase database's major version or newer, and reads the `.env` nearest the current directory for the project's database (`--env`).
501
512
 
502
- 1. **The first run** takes the Supabase database's connection string, for its `postgres` role (the session pooler's or the direct one; the transaction pooler cannot hold the snapshot the dumps share). It fails unless the database has Supabase's `auth` and `storage` schemas and its `supabase_admin` role, and notes the Supabase CLI's `supabase/config.toml`, `supabase/migrations/` and `supabase/functions/` when the checkout has them. It converts `supabase/functions` into the project's `functions/` (see [functions moved from Supabase](../guides/api-functions.md#functions-moved-from-supabase))): `Deno.serve(handler)` and std's `serve(handler)` become `export default defineFunction({ supabase: true }, { fetch: handler })`, an existing default export is wrapped the same way, so each function also answers at `/api/sb/functions/v1/<name>`, `npm:`, `jsr:` and esm.sh imports become bare imports of packages it adds to `package.json`, `Deno.env.get(name)` becomes `process.env[name]`, `EdgeRuntime.waitUntil` becomes `waitUntil` of `@protobase/server`, a function with `verify_jwt = false` in `config.toml` becomes public (`{ public: true, supabase: true }`), and `_shared` and the like are converted beside them. It stops before anything else when `functions/` already has one of their names. It dumps `auth`, `storage` and every schema the app made, schema and data apart, as of one snapshot, leaving out the platform's own migration tables, and writes the schemas as the project's next migration, `NNN_supabase_schema.sql`. It asks the project's database which of the app's extensions its role may create, by trying each in a transaction it rolls back: Postgres alone allows the trusted ones, Supabase's Postgres image all it allowlists, such as pg_net, pgmq and Vault. The migration creates those first, then, where pg_net is among them and the app has Database Webhooks, the `supabase_functions.http_request` function their triggers call, over pg_net; then the dump without what fails there, as comments: grants and default privileges for `dashboard_user`, `supabase_*`, `authenticator` and `postgres`, statements about the `public` schema, Realtime's publication, database webhooks without pg_net, functions in plv8, plls or plcoffee where the database has no such language, and a timescaledb hypertable's insert-blocking trigger. The project's database needs the roles `anon`, `authenticated` and `service_role` that the dump's grants and policies name; the command makes them when its role may, and otherwise stops, naming them. The data dump goes to `supabase-import/`, which it adds to `.gitignore`, since it holds every row and the users' password hashes. Where the project's database can create Vault, pgmq and pg_cron, `supabase-import/replay.sql` holds what a dump cannot carry: Vault's secrets with their values, read decrypted since only Supabase's key opens their ciphertext, pgmq's queues with their messages, since pgmq owns their tables, and pg_cron's jobs, which live in its own schema.
513
+ 1. **The first run** takes the Supabase database's connection string, for its `postgres` role (the session pooler's or the direct one; the transaction pooler cannot hold the snapshot the dumps share). It fails unless the database has Supabase's `auth` and `storage` schemas and its `supabase_admin` role, and notes the Supabase CLI's `supabase/config.toml`, `supabase/migrations/` and `supabase/functions/` when the checkout has them. It converts `supabase/functions` into the project's `functions/` (see [functions moved from Supabase](../guides/api-functions.md#functions-moved-from-supabase))): `Deno.serve(handler)` and std's `serve(handler)` become `export default defineFunction({ supabase: true }, { fetch: handler })`, an existing default export is wrapped the same way, so each function also answers at `/api/sb/functions/v1/<name>`, `npm:`, `jsr:` and esm.sh imports become bare imports of packages it adds to `package.json`, `Deno.env.get(name)` becomes `process.env[name]`, `EdgeRuntime.waitUntil` becomes `waitUntil` of `@protobase/server`, a function with `verify_jwt = false` in `config.toml` becomes public (`{ public: true, supabase: true }`), and `_shared` and the like are converted beside them. It stops before anything else when `functions/` already has one of their names. It dumps `auth`, `storage` and every schema the app made, schema and data apart, as of one snapshot, leaving out the platform's own migration tables, and writes the schemas as the project's next migration, `NNN_supabase_schema.sql`. It asks the project's database which of the app's extensions its role may create, by trying each in a transaction it rolls back: Postgres alone allows the trusted ones, Supabase's Postgres image all it allowlists, such as pg_net, pgmq and Vault. The migration creates those first, then, where pg_net is among them and the app has Database Webhooks, the `supabase_functions.http_request` function their triggers call, over pg_net; then the dump without what fails there, as comments: grants and default privileges for `dashboard_user`, `supabase_*`, `authenticator` and `postgres`, statements about the `public` schema, Realtime's publication, pgsodium's security labels, the views that decrypt with it and the triggers that encrypt with it, database webhooks without pg_net, functions in plv8, plls or plcoffee where the database has no such language, and a timescaledb hypertable's insert-blocking trigger. The project's database needs the roles `anon`, `authenticated` and `service_role` that the dump's grants and policies name; the command makes them when its role may, and otherwise stops, naming them. The data dump goes to `supabase-import/`, which it adds to `.gitignore`, since it holds every row and the users' password hashes. Where the project's database can create Vault, pgmq and pg_cron, `supabase-import/replay.sql` holds what a dump cannot carry: Vault's secrets with their values, read decrypted since only Supabase's key opens their ciphertext, pgmq's queues with their messages, since pgmq owns their tables, and pg_cron's jobs, which live in its own schema.
503
514
  2. **Apply the migration** with the project's other migrations, such as `bun run db:migrate`.
504
- 3. **The second run**, without a connection string, loads the data in one transaction, with the app's triggers off so a sign-up trigger on `auth.users` does not run again for users who already have their rows, and fails the transaction unless every table holds the source's number of rows. In the same transaction it makes Vault's secrets and pgmq's queues again through `vault.create_secret`, `pgmq.create` and `pgmq.send`, each message with its headers and the time it becomes visible. Where the project's database has pg_cron, as Supabase's Postgres image does when it serves that database, it schedules pg_cron's jobs again there with `cron.schedule`, run by the importing role, an inactive one inactive. Elsewhere it writes each job of plain SQL as a [recurring job](jobs.md#recurring-jobs)) of its own in `jobs/`, of the same name, schedule and `cron.timezone`, that runs its SQL as the app's database role, tried once each time as pg_cron did, exports it from `jobs/index.ts` and adds `jobs` to `protobase.config.ts` (or writes one); they run once [`migration`](#migration) has added the jobs schema. Recurring jobs wake an app that sleeps, so they run where a host stops an idle app too. A job that calls what the database lacks, such as pg_net's `net.http_*`, `cron` or Vault, an inactive one and a schedule recurring jobs do not take, such as `30 seconds` or `$`, stay in the report, as does a job of another database. It loads only into empty tables, deletes the data dump and the replay, runs [`scaffold`](#scaffold) on the imported tables of the app's schemas (not `auth` or `storage`), giving the tables of the `supabase_realtime` publication [`.live()`](live.md)) so [`/api/sb/realtime/v1`](supabase-realtime.md)) keeps sending their `postgres_changes` once [`migration`](#migration) has written their capture triggers, and writes `supabase-import/report.md`: the rows loaded, the imported tables' size against the Starter plan's 500 MB, what it made again, the tables it made live, and what needs a person: the pg_cron jobs it could not carry over, each with why, Realtime tables it made no resource of, Vault secrets by name and pgmq queues where the database has no such extension (and partitioned queues), the extensions it cannot create, hypertables and plv8, plls or plcoffee functions to convert, triggers that call out over HTTP without pg_net, the converted Edge Functions with the packages to install and the code the conversion left (`deno.land/x` imports, Deno's file, KV and WebSocket APIs, `Supabase.ai`), and the indexes [`doctor`](#doctor) finds missing.
515
+ 3. **The second run**, without a connection string, loads the data in one transaction, with the app's triggers off so a sign-up trigger on `auth.users` does not run again for users who already have their rows, and fails the transaction unless every table holds the source's number of rows. In the same transaction it makes Vault's secrets and pgmq's queues again through `vault.create_secret`, `pgmq.create` and `pgmq.send`, each message with its headers and the time it becomes visible. Where the project's database has pg_cron, as Supabase's Postgres image does when it serves that database, it schedules pg_cron's jobs again there with `cron.schedule`, run by the importing role, an inactive one inactive. Elsewhere it writes each job of plain SQL as a [recurring job](jobs.md#recurring-jobs)) of its own in `jobs/`, of the same name, schedule and `cron.timezone`, that runs its SQL as the app's database role, tried once each time as pg_cron did, exports it from `jobs/index.ts` and adds `jobs` to `protobase.config.ts` (or writes one); they run once [`migration`](#migration) has added the jobs schema. Recurring jobs wake an app that sleeps, so they run where a host stops an idle app too. A job that calls what the database lacks, such as pg_net's `net.http_*`, `cron` or Vault, an inactive one and a schedule recurring jobs do not take, such as `30 seconds` or `$`, stay in the report, as does a job of another database. It loads only into empty tables, deletes the data dump and the replay, runs [`scaffold`](#scaffold) on the imported tables of the app's schemas (not `auth` or `storage`), giving the tables of the `supabase_realtime` publication [`.live()`](live.md)) so [`/api/sb/realtime/v1`](supabase-realtime.md)) keeps sending their `postgres_changes` once [`migration`](#migration) has written their capture triggers, and writes `supabase-import/report.md`: the rows loaded, the imported tables' size against the Starter plan's 500 MB, what it made again, the tables it made live, and what needs a person: the pg_cron jobs it could not carry over, each with why, Realtime tables it made no resource of, Vault secrets by name and pgmq queues where the database has no such extension (and partitioned queues), the columns pgsodium encrypts, still holding Supabase's ciphertext, whose values to export decrypted in Supabase before declaring them [`.encrypted()`](data-config.md#encrypted-fields)) and running [`encryption apply`](#encryption-apply), the extensions it cannot create, hypertables and plv8, plls or plcoffee functions to convert, triggers that call out over HTTP without pg_net, the converted Edge Functions with the packages to install and the code the conversion left (`deno.land/x` imports, Deno's file, KV and WebSocket APIs, `Supabase.ai`), and the indexes [`doctor`](#doctor) finds missing.
505
516
 
506
517
  4. **Storage's files**: with `--storage-url https://<ref>.supabase.co` and the project's secret key in the variable `--storage-key-env` names, `SUPABASE_SERVICE_ROLE_KEY` by default, the second run, or any run after it, copies the bytes of every object in `storage.objects` from the Supabase project's Storage API into the app's [Storage file provider](supabase-storage.md#where-things-are-kept)), where [`/api/sb/storage/v1`](supabase-storage.md)) serves them, with the type and cache control the rows recorded. It streams each object, checks its byte count against the size Supabase recorded and its MD5 against the ETag where that is one, and deletes a copy that does not match. It first prints each bucket's size and stops when what is left to copy and what the provider holds exceed the provider's `max_bytes`, unless `--yes`. An object that fails does not stop the rest; the run then fails, listing them in `supabase-import/storage.md`, and a rerun copies only what the provider does not hold yet. The key goes only in the requests' headers, never in a file.
507
518
 
@@ -69,6 +69,15 @@ Each secret moves to an environment variable the user enters again. Name it afte
69
69
  - where code read it (`vault.decrypted_secrets` in SQL, a function or a cron job), read `requireEnv('<NAME>')` in TypeScript instead. SQL that needs the secret moves into a job or function that does;
70
70
  - never write the value anywhere, and never put one in `.env.example`.
71
71
 
72
+ ### pgsodium encrypted columns
73
+
74
+ Each column holds ciphertext only Supabase's key opens, so the values come from the user, never from the imported column. The import's migration left out pgsodium's labels, decrypted views and encrypting triggers: the decrypted view stays in Supabase, so make no view or trigger again for it.
75
+
76
+ Then:
77
+
78
+ - ask the user to export the column's values decrypted from its decrypted view in Supabase, with the table's primary key, and to write them over the ciphertext; never guess or derive a value;
79
+ - once the column holds those values, declare the field `.encrypted()` (see the `protobase` skill's encrypted fields), change the rules, validators and hooks that read it, and run `protobase encryption apply`. Never run it while a column still holds Supabase's ciphertext: it would encrypt the ciphertext as if it were the value.
80
+
72
81
  ### pgmq queues
73
82
 
74
83
  With pgmq in the database, make each queue again in a migration (`select pgmq.create('<name>')`, or `pgmq.create_partitioned`); the user sends the messages again, since the report gives only their count. Without pgmq, move the queue's producers and consumers to a Protobase job: `defineJob` with the consumer's work as `run`, and `jobs.enqueue('<name>', payload)` where SQL called `pgmq.send`. See [Jobs](../protobase/references/reference/jobs.md#from-sql).