@protobase/cli 0.34.1 → 0.34.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/package.js +1 -1
- package/dist/supabase/dump-phase.js +4 -2
- package/dist/supabase/report.js +1 -0
- package/dist/supabase/rewrite.js +43 -12
- package/dist/supabase/schema-migration.js +1 -1
- package/dist/supabase/source-facts.js +13 -1
- package/dist/users/register.js +4 -3
- package/dist/users/set-disabled.js +10 -0
- package/package.json +6 -6
- package/skills/protobase/references/reference/auth.md +2 -2
- package/skills/protobase/references/reference/cli.md +4 -4
- package/skills/supabase-move/SKILL.md +9 -0
package/dist/cli/package.js
CHANGED
|
@@ -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 });
|
package/dist/supabase/report.js
CHANGED
|
@@ -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)),
|
package/dist/supabase/rewrite.js
CHANGED
|
@@ -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
|
-
/**
|
|
54
|
-
|
|
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 (!
|
|
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,
|
|
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
|
|
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 &&
|
|
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
|
|
91
|
-
*
|
|
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
|
|
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,
|
|
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 };
|
package/dist/users/register.js
CHANGED
|
@@ -3,9 +3,10 @@ import { addMemberCommand } from "../organizations/commands.js";
|
|
|
3
3
|
import { organizationsApi } from "../organizations/register.js";
|
|
4
4
|
import { readHidden, rejectPasswordArgument } from "./password.js";
|
|
5
5
|
import { createUserCommand, listRolesCommand, listUsersCommand } from "./commands.js";
|
|
6
|
-
import { deleteUserCommand,
|
|
7
|
-
import { parseTtl } from "./ttl.js";
|
|
6
|
+
import { deleteUserCommand, setRoleCommand } from "./manage.js";
|
|
8
7
|
import { usersApi } from "./users-api.js";
|
|
8
|
+
import { setDisabledInProject } from "./set-disabled.js";
|
|
9
|
+
import { parseTtl } from "./ttl.js";
|
|
9
10
|
import { Option } from "commander";
|
|
10
11
|
import { issueToken } from "@protobase/server";
|
|
11
12
|
import { createInterface } from "node:readline/promises";
|
|
@@ -63,7 +64,7 @@ const registerUsers = (program) => {
|
|
|
63
64
|
finish(0);
|
|
64
65
|
});
|
|
65
66
|
for (const disabled of [true, false]) users.command(disabled ? "disable" : "enable").description(disabled ? "Ban a user and revoke their sessions" : "Lift a ban").argument("<email>").action(async (email) => {
|
|
66
|
-
await
|
|
67
|
+
await setDisabledInProject(await loadProjectAuth(process.cwd()), {
|
|
67
68
|
email,
|
|
68
69
|
disabled
|
|
69
70
|
}, out);
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { setDisabledCommand } from "./manage.js";
|
|
2
|
+
import { usersApi } from "./users-api.js";
|
|
3
|
+
import { checkAuthSchema } from "@protobase/server";
|
|
4
|
+
//#region src/users/set-disabled.ts
|
|
5
|
+
const setDisabledInProject = async (auth, options, out) => {
|
|
6
|
+
await checkAuthSchema(auth);
|
|
7
|
+
await setDisabledCommand(usersApi(auth), options, out);
|
|
8
|
+
};
|
|
9
|
+
//#endregion
|
|
10
|
+
export { setDisabledInProject };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@protobase/cli",
|
|
3
|
-
"version": "0.34.
|
|
3
|
+
"version": "0.34.3",
|
|
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.
|
|
40
|
-
"@protobase/query": "0.34.
|
|
41
|
-
"@protobase/schema": "0.34.
|
|
42
|
-
"@protobase/server": "0.34.
|
|
43
|
-
"@protobase/ui": "0.34.
|
|
39
|
+
"@protobase/layout": "0.34.3",
|
|
40
|
+
"@protobase/query": "0.34.3",
|
|
41
|
+
"@protobase/schema": "0.34.3",
|
|
42
|
+
"@protobase/server": "0.34.3",
|
|
43
|
+
"@protobase/ui": "0.34.3",
|
|
44
44
|
"@react-email/render": "^2.1.0",
|
|
45
45
|
"@scalar/hono-api-reference": "^0.12.10",
|
|
46
46
|
"@tailwindcss/vite": "^4.3.3",
|
|
@@ -35,7 +35,7 @@ bun run protobase auth migration # compares it with what Better Auth needs; w
|
|
|
35
35
|
bun run db:migrate # applies it
|
|
36
36
|
```
|
|
37
37
|
|
|
38
|
-
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)).
|
|
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)).
|
|
39
39
|
|
|
40
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.
|
|
41
41
|
|
|
@@ -517,7 +517,7 @@ createAuth({ ..., mcp: { path: '/api/mcp', connectPage: '/-/connect' } })
|
|
|
517
517
|
```
|
|
518
518
|
|
|
519
519
|
- `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.
|
|
520
|
-
- It needs an https `baseURL`, or localhost, and the OAuth tables: run `protobase auth migration` after turning it on (see [migrations](#migrations)). Clients connect through `baseURL`'s origin only, whatever [other origins](#several-origins) the app has. Changing `path` makes every client connect again.
|
|
520
|
+
- 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.
|
|
521
521
|
- 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.
|
|
522
522
|
- 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; a client that binds its tokens to a key (DPoP) sends a proof with each, checked against the resource's URL.
|
|
523
523
|
- 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.
|
|
@@ -400,7 +400,7 @@ Better Auth and other settings are the project's own variables (`BETTER_AUTH_SEC
|
|
|
400
400
|
- **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.
|
|
401
401
|
- **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.
|
|
402
402
|
- **Version:** before loading the config module, the runtime reads `protobase.bundle.json` beside it and refuses a bundle built by a Protobase version it does not serve, or one without a version, with an error naming both versions (see [Versioning](versioning.md#bundles-and-runtimes))). A config module needs its manifest beside it.
|
|
403
|
-
- **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 (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.
|
|
403
|
+
- **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.
|
|
404
404
|
- **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.
|
|
405
405
|
- **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.
|
|
406
406
|
- **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.
|
|
@@ -499,7 +499,7 @@ bun run db:migrate # applies them
|
|
|
499
499
|
protobase auth migration [--dir db/migrations] [--name auth]
|
|
500
500
|
```
|
|
501
501
|
|
|
502
|
-
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; 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)).
|
|
502
|
+
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)).
|
|
503
503
|
|
|
504
504
|
## `import supabase`
|
|
505
505
|
|
|
@@ -510,9 +510,9 @@ protobase import supabase [<connection> | --source-env <variable>] [--env DATABA
|
|
|
510
510
|
|
|
511
511
|
Turns a Supabase project's database into the project in the current directory, in two runs with the project's migrations between them. It needs PostgreSQL's `pg_dump` and `psql` on `PATH`, of the Supabase database's major version or newer, and reads the `.env` nearest the current directory for the project's database (`--env`).
|
|
512
512
|
|
|
513
|
-
1. **The first run** takes the Supabase database's connection string, for its `postgres` role (the session pooler's or the direct one; the transaction pooler cannot hold the snapshot the dumps share). It fails unless the database has Supabase's `auth` and `storage` schemas and its `supabase_admin` role, and notes the Supabase CLI's `supabase/config.toml`, `supabase/migrations/` and `supabase/functions/` when the checkout has them. It converts `supabase/functions` into the project's `functions/` (see [functions moved from Supabase](../guides/api-functions.md#functions-moved-from-supabase))): `Deno.serve(handler)` and std's `serve(handler)` become `export default defineFunction({ supabase: true }, { fetch: handler })`, an existing default export is wrapped the same way, so each function also answers at `/api/sb/functions/v1/<name>`, `npm:`, `jsr:` and esm.sh imports become bare imports of packages it adds to `package.json`, `Deno.env.get(name)` becomes `process.env[name]`, `EdgeRuntime.waitUntil` becomes `waitUntil` of `@protobase/server`, a function with `verify_jwt = false` in `config.toml` becomes public (`{ public: true, supabase: true }`), and `_shared` and the like are converted beside them. It stops before anything else when `functions/` already has one of their names. It dumps `auth`, `storage` and every schema the app made, schema and data apart, as of one snapshot, leaving out the platform's own migration tables, and writes the schemas as the project's next migration, `NNN_supabase_schema.sql`. It asks the project's database which of the app's extensions its role may create, by trying each in a transaction it rolls back: Postgres alone allows the trusted ones, Supabase's Postgres image all it allowlists, such as pg_net, pgmq and Vault. The migration creates those first, then, where pg_net is among them and the app has Database Webhooks, the `supabase_functions.http_request` function their triggers call, over pg_net; then the dump without what fails there, as comments: grants and default privileges for `dashboard_user`, `supabase_*`, `authenticator` and `postgres`, statements about the `public` schema, Realtime's publication, 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.
|
|
514
514
|
2. **Apply the migration** with the project's other migrations, such as `bun run db:migrate`.
|
|
515
|
-
3. **The second run**, without a connection string, loads the data in one transaction, with the app's triggers off so a sign-up trigger on `auth.users` does not run again for users who already have their rows, and fails the transaction unless every table holds the source's number of rows. In the same transaction it makes Vault's secrets and pgmq's queues again through `vault.create_secret`, `pgmq.create` and `pgmq.send`, each message with its headers and the time it becomes visible. Where the project's database has pg_cron, as Supabase's Postgres image does when it serves that database, it schedules pg_cron's jobs again there with `cron.schedule`, run by the importing role, an inactive one inactive. Elsewhere it writes each job of plain SQL as a [recurring job](jobs.md#recurring-jobs)) of its own in `jobs/`, of the same name, schedule and `cron.timezone`, that runs its SQL as the app's database role, tried once each time as pg_cron did, exports it from `jobs/index.ts` and adds `jobs` to `protobase.config.ts` (or writes one); they run once [`migration`](#migration) has added the jobs schema. Recurring jobs wake an app that sleeps, so they run where a host stops an idle app too. A job that calls what the database lacks, such as pg_net's `net.http_*`, `cron` or Vault, an inactive one and a schedule recurring jobs do not take, such as `30 seconds` or `$`, stay in the report, as does a job of another database. It loads only into empty tables, deletes the data dump and the replay, runs [`scaffold`](#scaffold) on the imported tables of the app's schemas (not `auth` or `storage`), giving the tables of the `supabase_realtime` publication [`.live()`](live.md)) so [`/api/sb/realtime/v1`](supabase-realtime.md)) keeps sending their `postgres_changes` once [`migration`](#migration) has written their capture triggers, and writes `supabase-import/report.md`: the rows loaded, the imported tables' size against the Starter plan's 500 MB, what it made again, the tables it made live, and what needs a person: the pg_cron jobs it could not carry over, each with why, Realtime tables it made no resource of, Vault secrets by name and pgmq queues where the database has no such extension (and partitioned queues), the 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.
|
|
516
516
|
|
|
517
517
|
4. **Storage's files**: with `--storage-url https://<ref>.supabase.co` and the project's secret key in the variable `--storage-key-env` names, `SUPABASE_SERVICE_ROLE_KEY` by default, the second run, or any run after it, copies the bytes of every object in `storage.objects` from the Supabase project's Storage API into the app's [Storage file provider](supabase-storage.md#where-things-are-kept)), where [`/api/sb/storage/v1`](supabase-storage.md)) serves them, with the type and cache control the rows recorded. It streams each object, checks its byte count against the size Supabase recorded and its MD5 against the ETag where that is one, and deletes a copy that does not match. It first prints each bucket's size and stops when what is left to copy and what the provider holds exceed the provider's `max_bytes`, unless `--yes`. An object that fails does not stop the rest; the run then fails, listing them in `supabase-import/storage.md`, and a rerun copies only what the provider does not hold yet. The key goes only in the requests' headers, never in a file.
|
|
518
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).
|