@protobase/cli 0.50.0 → 0.51.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/package.js +1 -1
- package/dist/supabase/dump-phase.js +9 -4
- package/dist/supabase/realtime-policies.js +60 -0
- package/package.json +7 -7
- package/skills/protobase/references/features/compatibility.md +1 -1
- package/skills/protobase/references/reference/access.md +12 -0
- package/skills/protobase/references/reference/assistant.md +1 -1
- package/skills/protobase/references/reference/cli.md +1 -1
- package/skills/protobase/references/reference/data-config.md +1 -1
- package/skills/protobase/references/reference/languages.md +3 -1
- package/skills/protobase/references/reference/mcp.md +3 -3
- package/skills/protobase/references/reference/supabase-realtime.md +36 -2
- package/skills/protobase/references/reference/supabase-rest.md +1 -1
package/dist/cli/package.js
CHANGED
|
@@ -8,6 +8,7 @@ import { importPlan, probedExtensions } from "./import-plan.js";
|
|
|
8
8
|
import { importState } from "./import-state.js";
|
|
9
9
|
import { writeMigration } from "./migration-files.js";
|
|
10
10
|
import { runPgTool } from "./pg-tools.js";
|
|
11
|
+
import { realtimeMigration, realtimePolicies } from "./realtime-policies.js";
|
|
11
12
|
import { replayScript } from "./replay.js";
|
|
12
13
|
import { schemaMigration } from "./schema-migration.js";
|
|
13
14
|
import { refuseSsoUsers, ssoUserCount } from "./sso-users.js";
|
|
@@ -88,6 +89,7 @@ const readSource = async (sql, targetUrl) => {
|
|
|
88
89
|
routinesLeftOut: await routinesIn(sql, schemas, plan.missing.languages)
|
|
89
90
|
},
|
|
90
91
|
plan,
|
|
92
|
+
realtimePolicies: await realtimePolicies((text, params) => sql.unsafe(text, params)),
|
|
91
93
|
replay: replayScript({
|
|
92
94
|
secrets: secrets ?? [],
|
|
93
95
|
queues: replayed,
|
|
@@ -120,8 +122,9 @@ const pattern = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
|
|
|
120
122
|
/**
|
|
121
123
|
* The import's first run: dumps the Supabase database's schemas and data as of one snapshot, writes the schema as
|
|
122
124
|
* the project's next migration, with the extensions the project's database can create, and the columns Better Auth
|
|
123
|
-
* needs on auth.users as the one after,
|
|
124
|
-
* the
|
|
125
|
+
* needs on auth.users as the one after, then `realtime.messages` with its policies, which authorize private Realtime
|
|
126
|
+
* channels, when the source has any, points the app's Better Auth setup at auth.users in place of the user table the
|
|
127
|
+
* project's auth migrations make, removing them, and keeps the data dump, the replay of Vault's secrets, pgmq's
|
|
125
128
|
* queues and pg_cron's jobs and what the report needs in `supabase-import/` for the run that loads it, once the
|
|
126
129
|
* project's migrations are applied.
|
|
127
130
|
*/
|
|
@@ -140,8 +143,8 @@ const runDumpPhase = async (options, out) => {
|
|
|
140
143
|
const [exported] = await reserved`select pg_export_snapshot() as snapshot`;
|
|
141
144
|
const snapshot = exported.snapshot;
|
|
142
145
|
refuseSsoUsers(await ssoUserCount((text) => reserved.unsafe(text)));
|
|
143
|
-
const { manifest: source, plan, replay } = await readSource(reserved, options.targetUrl);
|
|
144
|
-
const created = await checkTarget(options.targetUrl, source.schemas, source.tables);
|
|
146
|
+
const { manifest: source, plan, realtimePolicies: policies, replay } = await readSource(reserved, options.targetUrl);
|
|
147
|
+
const created = await checkTarget(options.targetUrl, policies.length > 0 ? [...source.schemas, "realtime"] : source.schemas, source.tables);
|
|
145
148
|
if (created.length > 0) out(`created the roles ${created.join(", ")} in the project's database\n`);
|
|
146
149
|
await state.prepare();
|
|
147
150
|
const schemaFile = path.join(state.dir, "schema.sql");
|
|
@@ -172,6 +175,7 @@ const runDumpPhase = async (options, out) => {
|
|
|
172
175
|
await mkdir(options.migrationsDir, { recursive: true });
|
|
173
176
|
const file = await writeMigration(options.migrationsDir, "supabase_schema", migration.text);
|
|
174
177
|
const usersFile = await writeMigration(options.migrationsDir, "supabase_users", usersColumnsMigration());
|
|
178
|
+
const realtimeFile = policies.length > 0 ? await writeMigration(options.migrationsDir, "supabase_realtime", realtimeMigration(policies)) : void 0;
|
|
175
179
|
await authConfig.write();
|
|
176
180
|
for (const store of storeMigrations) await rm(path.join(options.migrationsDir, store));
|
|
177
181
|
const packages = await writeFunctions(options.projectDir, functions);
|
|
@@ -189,6 +193,7 @@ const runDumpPhase = async (options, out) => {
|
|
|
189
193
|
const relative = (to) => path.relative(options.projectDir, to);
|
|
190
194
|
out(`wrote ${relative(path.join(options.migrationsDir, file))}, the schemas ${source.schemas.join(", ")}\n`);
|
|
191
195
|
out(`wrote ${relative(path.join(options.migrationsDir, usersFile))}, the columns Better Auth needs on auth.users, and pointed ${relative(authConfig.file)} at it\n`);
|
|
196
|
+
if (realtimeFile) out(`wrote ${relative(path.join(options.migrationsDir, realtimeFile))}, realtime.messages with its ${policies.length} policies, which authorize private Realtime channels\n`);
|
|
192
197
|
for (const store of storeMigrations) out(`removed ${relative(path.join(options.migrationsDir, store))}: auth.users replaces Protobase's own user table it made\n`);
|
|
193
198
|
if (functions.functions.length > 0) out(`converted ${functions.functions.length} Edge Functions into functions/${packages.length > 0 ? `, adding ${packages.length} packages to package.json: install them` : ""}\n`);
|
|
194
199
|
out(`dumped ${source.tables.length} tables' data into ${path.relative(options.projectDir, state.data)}, which git ignores\n`);
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { isSupabaseRole } from "./rewrite.js";
|
|
2
|
+
//#region src/supabase/realtime-policies.ts
|
|
3
|
+
/**
|
|
4
|
+
* The source's row security policies on `realtime.messages`, which authorize private Realtime channels, their
|
|
5
|
+
* expressions read with an empty search_path so that every name in them is schema-qualified; it is put back after, for
|
|
6
|
+
* the reads that follow in the same transaction.
|
|
7
|
+
*/
|
|
8
|
+
const realtimePolicies = async (query) => {
|
|
9
|
+
const [setting] = await query("select current_setting('search_path') as path");
|
|
10
|
+
await query("select set_config('search_path', '', true)");
|
|
11
|
+
const policies = await query(`select policyname as name, permissive = 'PERMISSIVE' as permissive, roles::text[] as roles, cmd as command, qual as "using", with_check as "withCheck"
|
|
12
|
+
from pg_policies where schemaname = 'realtime' and tablename = 'messages' order by policyname`);
|
|
13
|
+
await query("select set_config('search_path', $1, true)", [setting.path]);
|
|
14
|
+
return policies;
|
|
15
|
+
};
|
|
16
|
+
const quoted = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
|
|
17
|
+
const schema = `create schema realtime;
|
|
18
|
+
|
|
19
|
+
create table realtime.messages (
|
|
20
|
+
topic text not null,
|
|
21
|
+
extension text not null,
|
|
22
|
+
payload jsonb,
|
|
23
|
+
event text,
|
|
24
|
+
private boolean,
|
|
25
|
+
updated_at timestamp without time zone not null default now(),
|
|
26
|
+
inserted_at timestamp without time zone not null default now(),
|
|
27
|
+
id uuid not null default gen_random_uuid() primary key
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
create function realtime.topic() returns text language sql stable as $$ select nullif(current_setting('realtime.topic', true), '')::text $$;
|
|
31
|
+
|
|
32
|
+
alter table realtime.messages enable row level security;
|
|
33
|
+
grant usage on schema realtime to anon, authenticated, service_role;
|
|
34
|
+
grant select, insert, update, delete on realtime.messages to anon, authenticated, service_role;
|
|
35
|
+
`;
|
|
36
|
+
const policySql = (policy) => {
|
|
37
|
+
const roles = policy.roles.filter((role) => !isSupabaseRole(role));
|
|
38
|
+
if (roles.length === 0) return `-- Left out by protobase import supabase: the policy ${JSON.stringify(policy.name)} names only Supabase's own roles.\n`;
|
|
39
|
+
return [
|
|
40
|
+
`create policy ${quoted(policy.name)} on realtime.messages as ${policy.permissive ? "permissive" : "restrictive"} for ${policy.command}`,
|
|
41
|
+
` to ${roles.map((role) => role === "public" ? "public" : quoted(role)).join(", ")}`,
|
|
42
|
+
policy.using === null ? "" : ` using (${policy.using})`,
|
|
43
|
+
policy.withCheck === null ? "" : ` with check (${policy.withCheck})`,
|
|
44
|
+
";\n"
|
|
45
|
+
].join("");
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* The migration that makes Supabase's `realtime.messages` and `realtime.topic()` with the source's policies on it, which
|
|
49
|
+
* decide who may join, hear and send on a private channel of `/api/sb/realtime/v1`. The role that applies it owns the
|
|
50
|
+
* table; the server's probes need the app's database role to own it or to bypass row security.
|
|
51
|
+
*/
|
|
52
|
+
const realtimeMigration = (policies) => [
|
|
53
|
+
"-- realtime.messages of a Supabase database with its row security policies, which authorize private Realtime\n",
|
|
54
|
+
"-- channels, written by `protobase import supabase`.\n\n",
|
|
55
|
+
schema,
|
|
56
|
+
"\n",
|
|
57
|
+
...policies.map(policySql)
|
|
58
|
+
].join("");
|
|
59
|
+
//#endregion
|
|
60
|
+
export { realtimeMigration, realtimePolicies };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@protobase/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.51.0",
|
|
4
4
|
"description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -41,12 +41,12 @@
|
|
|
41
41
|
"dependencies": {
|
|
42
42
|
"@better-auth/core": "^1.7.12",
|
|
43
43
|
"@hono/node-server": "^2.1.3",
|
|
44
|
-
"@protobase/config": "0.
|
|
45
|
-
"@protobase/layout": "0.
|
|
46
|
-
"@protobase/query": "0.
|
|
47
|
-
"@protobase/schema": "0.
|
|
48
|
-
"@protobase/server": "0.
|
|
49
|
-
"@protobase/ui": "0.
|
|
44
|
+
"@protobase/config": "0.51.0",
|
|
45
|
+
"@protobase/layout": "0.51.0",
|
|
46
|
+
"@protobase/query": "0.51.0",
|
|
47
|
+
"@protobase/schema": "0.51.0",
|
|
48
|
+
"@protobase/server": "0.51.0",
|
|
49
|
+
"@protobase/ui": "0.51.0",
|
|
50
50
|
"@react-email/render": "^2.1.0",
|
|
51
51
|
"@scalar/hono-api-reference": "^0.12.10",
|
|
52
52
|
"@tailwindcss/vite": "^4.3.3",
|
|
@@ -10,5 +10,5 @@ Apps written for other systems that keep working on Protobase, and moving their
|
|
|
10
10
|
- [Supabase client API](../reference/supabase-rest.md): supabase-js `from()` and `rpc()` calls keep working, under the tables' RLS policies.
|
|
11
11
|
- [Supabase Auth](../reference/auth.md#supabase-js-and-supabasessr): `supabase.auth` and `@supabase/ssr` calls keep working.
|
|
12
12
|
- [Supabase Storage](../reference/supabase-storage.md): supabase-js storage calls keep working, over the app's file storage.
|
|
13
|
-
- [Supabase Realtime](../reference/supabase-realtime.md): Database changes, broadcast and presence through supabase-js channels.
|
|
13
|
+
- [Supabase Realtime](../reference/supabase-realtime.md): Database changes, broadcast and presence through supabase-js channels, private ones authorized by the policies on `realtime.messages`.
|
|
14
14
|
- [Edge Functions](../guides/api-functions.md#functions-moved-from-supabase): Functions moved from Supabase answer at their old addresses.
|
|
@@ -190,6 +190,18 @@ export const apps = resource('apps')
|
|
|
190
190
|
- **Rows of another organization are read-only in the list.** Their `permissions` say `update: false` and `delete: false`. The admin app opens one by switching the session to its organization first: a record page the session's organization does not have looks the record up across the lists, for a resource with a key of one filterable field, so the page and everything on it are read in the record's own organization.
|
|
191
191
|
- **Where the memberships come from.** The authenticator of the app's sign-in (`auth`) reads them from the store, once per request that lists across organizations. An [authenticator](auth.md#tokens-and-roles) of your own gives them as the session's `memberships`, a function answering `[{ tenant, roles }]`, and must answer only organizations the person is a member of. Without it, as with `authenticate: { jwksUrl }` instead of `auth`, a list reads the session's organization alone.
|
|
192
192
|
|
|
193
|
+
## Rules that read the record
|
|
194
|
+
|
|
195
|
+
A rule that reads its record, such as `read: (ctx, record) => record.owner_id === ctx.user.id`, is checked against the stored row wherever one record is read or written: a get, a reveal, history, comments, and every update and delete. The resolver calls each rule once without the record to learn whether it needs one; reading the record then, even as `record?.status` or through a default parameter, counts.
|
|
196
|
+
|
|
197
|
+
A list cannot run such a rule on each row without breaking its pages and counts, so a caller for whom the `read` or `list` rule reads the record may not list: a list, `:search`, `:seek`, their counts, aggregates, charts and map, exports, the labels of the records other lists point at, and the assistant's and MCP's list tool answer `403`, and a blocked delete does not name the resource. An explicit `list` rule beside such a `read` is refused too, since nothing proves it is as narrow. A caller whose verdict does not depend on the record, such as an admin under `ctx.user.roles.includes('admin') || record.owner_id === ctx.user.id`, lists as usual. To list, write the rule as a row filter, which a get and a list apply alike:
|
|
198
|
+
|
|
199
|
+
```ts
|
|
200
|
+
.access({ read: (ctx) => where.eq('owner_id', ctx.user.id) })
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
<gap>A resource whose read rule reads the record cannot be listed because declaring a row filter as the rule's list form is not implemented.</gap> <gap>A rollup of a readable record counts and adds up related records that their read rule or row filter hides because rollups are not computed per caller.</gap> These rules apply to `/api/v1` and what is built on it; `/api/sb/rest/v1` and its realtime use the tables' grants and RLS policies only.
|
|
204
|
+
|
|
193
205
|
## Restricted model and row filters
|
|
194
206
|
|
|
195
207
|
[`resolveAccess`](https://docs.protobase.net/api/schema/functions/resolveaccess/) returns everything a request may do. Use [`restrictModel(model, access)`](https://docs.protobase.net/api/schema/functions/restrictmodel/) for everything user-facing (checking filters and sorts, queries, OpenAPI, `/meta`): hidden fields are gone, so they cannot be referenced, searched, sorted or leaked. Key columns always stay, because records are addressed by them.
|
|
@@ -68,7 +68,7 @@ Making the query role needs `CREATEROLE` once, for the role that applies the mig
|
|
|
68
68
|
|
|
69
69
|
`assistant/tools.ts` adds tools of the app's own, which the built-in backend offers after its two: its default export is an array of tools, found by that path when the app starts. A tool is `defineTool({ name, description, parameters, run })` from `@protobase/server`: `parameters` is the JSON Schema of its arguments, and `run(args, context)` returns the text the model reads. A name must be 1 to 64 letters, digits, `_` or `-`, and a name taken twice stops the server at startup. A backend elsewhere has its own tools, so the file does nothing there, nor with `assistant: false`. A tool's `annotations` are MCP's tool hints (`readOnlyHint`, `destructiveHint`, ...), which the dock ignores; the same tools can be offered over the app's [MCP endpoint](mcp.md#building-on-it).
|
|
70
70
|
|
|
71
|
-
`context` holds the user's `session`, `show(part)` to add a part to the answer, `approve(request)` for an approval card, `conversation` (the dock's, absent over MCP), `resources()` (the resources the user may read, restricted to their fields, with their views), and `records`: `list(resource, params)` with the REST API's list parameters, `get(resource, key)`, `create(resource, data)`, `update(resource, key, data, { etag? })` (without an ETag it updates any version), `delete(resource, key, { etag? })` (soft on a resource with `.softDelete()`) and `softDeleteField(resource)` (the field a delete sets, or `undefined` when a delete removes the record) on the app's resources **as the user**, through their access rules, tenant scope, validation and write hooks, as in the REST API. `get`, `create`, `update` and `delete` each answer `{ record, etag }`, and `list` a page of records. `batch(operations)` runs the operations of a REST [batch write](api.md#batch-writes) in one transaction and answers its `results`; a refusal or a missing record rejects with an `HttpProblem`, whose `detail` a tool can return to the model as text.
|
|
71
|
+
`context` holds the user's `session`, `locale` (the language they read, `'en'` or `'nl'`, for the texts a tool shows them such as its approvals; set over MCP, absent in the dock), `show(part)` to add a part to the answer, `approve(request)` for an approval card, `conversation` (the dock's, absent over MCP), `resources()` (the resources the user may read, restricted to their fields, with their views), and `records`: `list(resource, params)` with the REST API's list parameters, `get(resource, key)`, `create(resource, data)`, `update(resource, key, data, { etag? })` (without an ETag it updates any version), `delete(resource, key, { etag? })` (soft on a resource with `.softDelete()`) and `softDeleteField(resource)` (the field a delete sets, or `undefined` when a delete removes the record) on the app's resources **as the user**, through their access rules, tenant scope, validation and write hooks, as in the REST API. `get`, `create`, `update` and `delete` each answer `{ record, etag }`, and `list` a page of records. `batch(operations)` runs the operations of a REST [batch write](api.md#batch-writes) in one transaction and answers its `results`; a refusal or a missing record rejects with an `HttpProblem`, whose `detail` a tool can return to the model as text.
|
|
72
72
|
|
|
73
73
|
A tool with a [widget](#widget-parts) creates or finds what it is about, shows a widget with its id, and returns the id and the state at that moment:
|
|
74
74
|
|
|
@@ -536,7 +536,7 @@ protobase import supabase [<connection> | --source-env <variable>] [--env DATABA
|
|
|
536
536
|
|
|
537
537
|
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`).
|
|
538
538
|
|
|
539
|
-
1. **The first run** takes the Supabase database's connection string, for its `postgres` role (the session pooler's or the direct one; the transaction pooler cannot hold the snapshot the dumps share). It fails unless the database has Supabase's `auth` and `storage` schemas and its `supabase_admin` role, and while `auth.users` has single sign-on (SAML) users, which Supabase opens only through their identity provider and Better Auth would find by email: merge or delete them in Supabase first. It notes the Supabase CLI's `supabase/config.toml`, `supabase/migrations/` and `supabase/functions/` when the checkout has them. It converts `supabase/functions` into the project's `functions/` (see [functions moved from Supabase](../guides/api-functions.md#functions-moved-from-supabase)): `Deno.serve(handler)` and std's `serve(handler)` become `export default defineFunction({ supabase: true }, { fetch: handler })`, an existing default export is wrapped the same way, so each function also answers at `/api/sb/functions/v1/<name>`, `npm:`, `jsr:` and esm.sh imports become bare imports of packages it adds to `package.json`, `Deno.env.get(name)` becomes `process.env[name]`, `EdgeRuntime.waitUntil` becomes `waitUntil` of `@protobase/server`, a function with `verify_jwt = false` in `config.toml` becomes public (`{ public: true, supabase: true }`), and `_shared` and the like are converted beside them. It stops before anything else when `functions/` already has one of their names. It dumps `auth`, `storage` and every schema the app made, schema and data apart, as of one snapshot, leaving out the platform's own migration tables, and writes the schemas as the project's next migration, `NNN_supabase_schema.sql`. It asks the project's database which of the app's extensions its role may create, by trying each in a transaction it rolls back: Postgres alone allows the trusted ones, Supabase's Postgres image all it allowlists, such as pg_net, pgmq and Vault. The migration creates those first, then, where pg_net is among them and the app has Database Webhooks, the `supabase_functions.http_request` function their triggers call, over pg_net; then the dump without what fails there, as comments: grants and default privileges for `dashboard_user`, `supabase_*`, `authenticator` and `postgres`, statements about the `public` schema, Realtime's publication, pgsodium's security labels, the views that decrypt with it and the triggers that encrypt with it, database webhooks without pg_net, functions in plv8, plls or plcoffee where the database has no such language, and a timescaledb hypertable's insert-blocking trigger. It then writes `NNN_supabase_users.sql`, the nullable columns Better Auth needs on `auth.users` (`name`, `email_verified`, `image`, `app_role`, `banned`, `ban_reason`, `ban_expires`) and GoTrue's `'authenticated'` as the default of `role` and `aud`. It points the app at `auth.users`: the `auth` of `protobase.config.ts` gets `users: { table: 'users', columns: { role: 'app_role' }, metadata: 'raw_user_meta_data' }`, `passwordHashes: ['bcrypt']` and `generateUserId: 'uuid'`, or the config gets an `auth` of them when it has none (see [an existing users table](auth.md#an-existing-users-table)). It removes the migrations `protobase auth migration` or `protobase migration` wrote for Protobase's own user table, since `auth.users` replaces it, and stops before writing anything when the project has no `protobase.config.ts`, or one whose `auth` is not an object it can see, or when the project's database has a schema the dump creates already, such as the `auth` schema those migrations made. The project's database needs the roles `anon`, `authenticated` and `service_role` that the dump's grants and policies name; the command makes them when its role may, and otherwise stops, naming them. The data dump goes to `supabase-import/`, which it adds to `.gitignore`, since it holds every row and the users' password hashes. Where the project's database can create Vault, pgmq and pg_cron, `supabase-import/replay.sql` holds what a dump cannot carry: Vault's secrets with their values, read decrypted since only Supabase's key opens their ciphertext, pgmq's queues with their messages, since pgmq owns their tables, and pg_cron's jobs, which live in its own schema.
|
|
539
|
+
1. **The first run** takes the Supabase database's connection string, for its `postgres` role (the session pooler's or the direct one; the transaction pooler cannot hold the snapshot the dumps share). It fails unless the database has Supabase's `auth` and `storage` schemas and its `supabase_admin` role, and while `auth.users` has single sign-on (SAML) users, which Supabase opens only through their identity provider and Better Auth would find by email: merge or delete them in Supabase first. It notes the Supabase CLI's `supabase/config.toml`, `supabase/migrations/` and `supabase/functions/` when the checkout has them. It converts `supabase/functions` into the project's `functions/` (see [functions moved from Supabase](../guides/api-functions.md#functions-moved-from-supabase)): `Deno.serve(handler)` and std's `serve(handler)` become `export default defineFunction({ supabase: true }, { fetch: handler })`, an existing default export is wrapped the same way, so each function also answers at `/api/sb/functions/v1/<name>`, `npm:`, `jsr:` and esm.sh imports become bare imports of packages it adds to `package.json`, `Deno.env.get(name)` becomes `process.env[name]`, `EdgeRuntime.waitUntil` becomes `waitUntil` of `@protobase/server`, a function with `verify_jwt = false` in `config.toml` becomes public (`{ public: true, supabase: true }`), and `_shared` and the like are converted beside them. It stops before anything else when `functions/` already has one of their names. It dumps `auth`, `storage` and every schema the app made, schema and data apart, as of one snapshot, leaving out the platform's own migration tables, and writes the schemas as the project's next migration, `NNN_supabase_schema.sql`. It asks the project's database which of the app's extensions its role may create, by trying each in a transaction it rolls back: Postgres alone allows the trusted ones, Supabase's Postgres image all it allowlists, such as pg_net, pgmq and Vault. The migration creates those first, then, where pg_net is among them and the app has Database Webhooks, the `supabase_functions.http_request` function their triggers call, over pg_net; then the dump without what fails there, as comments: grants and default privileges for `dashboard_user`, `supabase_*`, `authenticator` and `postgres`, statements about the `public` schema, Realtime's publication, pgsodium's security labels, the views that decrypt with it and the triggers that encrypt with it, database webhooks without pg_net, functions in plv8, plls or plcoffee where the database has no such language, and a timescaledb hypertable's insert-blocking trigger. It then writes `NNN_supabase_users.sql`, the nullable columns Better Auth needs on `auth.users` (`name`, `email_verified`, `image`, `app_role`, `banned`, `ban_reason`, `ban_expires`) and GoTrue's `'authenticated'` as the default of `role` and `aud`. When the source has row security policies on `realtime.messages`, it writes `NNN_supabase_realtime.sql`, which makes `realtime.messages` and `realtime.topic()` with those policies, so the app's [private channels](supabase-realtime.md#private-channels) keep their access; a policy that names only Supabase's own roles is left out as a comment. It points the app at `auth.users`: the `auth` of `protobase.config.ts` gets `users: { table: 'users', columns: { role: 'app_role' }, metadata: 'raw_user_meta_data' }`, `passwordHashes: ['bcrypt']` and `generateUserId: 'uuid'`, or the config gets an `auth` of them when it has none (see [an existing users table](auth.md#an-existing-users-table)). It removes the migrations `protobase auth migration` or `protobase migration` wrote for Protobase's own user table, since `auth.users` replaces it, and stops before writing anything when the project has no `protobase.config.ts`, or one whose `auth` is not an object it can see, or when the project's database has a schema the dump creates already, such as the `auth` schema those migrations made. The project's database needs the roles `anon`, `authenticated` and `service_role` that the dump's grants and policies name; the command makes them when its role may, and otherwise stops, naming them. The data dump goes to `supabase-import/`, which it adds to `.gitignore`, since it holds every row and the users' password hashes. Where the project's database can create Vault, pgmq and pg_cron, `supabase-import/replay.sql` holds what a dump cannot carry: Vault's secrets with their values, read decrypted since only Supabase's key opens their ciphertext, pgmq's queues with their messages, since pgmq owns their tables, and pg_cron's jobs, which live in its own schema.
|
|
540
540
|
2. **Apply the migration** with the project's other migrations, such as `bun run db:migrate`.
|
|
541
541
|
3. **The second run**, without a connection string, loads the data in one transaction, with the app's triggers off so a sign-up trigger on `auth.users` does not run again for users who already have their rows, and fails the transaction unless every table holds the source's number of rows. In the same transaction it makes Vault's secrets and pgmq's queues again through `vault.create_secret`, `pgmq.create` and `pgmq.send`, each message with its headers and the time it becomes visible. Where the project's database has pg_cron, as Supabase's Postgres image does when it serves that database, it schedules pg_cron's jobs again there with `cron.schedule`, run by the importing role, an inactive one inactive. Elsewhere it writes each job of plain SQL as a [recurring job](jobs.md#recurring-jobs) of its own in `jobs/`, of the same name, schedule and `cron.timezone`, that runs its SQL as the app's database role, tried once each time as pg_cron did, and declares it in the `jobs` of `protobase.config.ts` (or writes one); they run once [`migration`](#migration) has added the jobs schema. Recurring jobs wake an app that sleeps, so they run where a host stops an idle app too. A job that calls what the database lacks, such as pg_net's `net.http_*`, `cron` or Vault, an inactive one and a schedule recurring jobs do not take, such as `30 seconds` or `$`, stay in the report, as does a job of another database. It loads only into empty tables, deletes the data dump and the replay, runs [`scaffold`](#scaffold) on the imported tables of the app's schemas (not `auth` or `storage`), giving the tables of the `supabase_realtime` publication [`.live()`](live.md) so [`/api/sb/realtime/v1`](supabase-realtime.md) keeps sending their `postgres_changes` once [`migration`](#migration) has written their capture triggers, writes Better Auth's other tables next to `auth.users` as [`auth migration`](#auth-migration) does (`NNN_auth.sql`), then `NNN_supabase_accounts.sql`, and writes `supabase-import/report.md`: the rows loaded, the imported tables' size against the Starter plan's 500 MB, each sign-in provider's identities, what it made again, the tables it made live, and what needs a person: the pg_cron jobs it could not carry over, each with why, Realtime tables it made no resource of, Vault secrets by name and pgmq queues where the database has no such extension (and partitioned queues), the columns pgsodium encrypts, still holding Supabase's ciphertext, whose values to export decrypted in Supabase before declaring them [`.encrypted()`](data-config.md#encrypted-fields) and running [`encryption apply`](#encryption-apply), the extensions it cannot create, hypertables and plv8, plls or plcoffee functions to convert, triggers that call out over HTTP without pg_net, the converted Edge Functions with the packages to install and the code the conversion left (`deno.land/x` imports, Deno's file, KV and WebSocket APIs, `Supabase.ai`), and the indexes [`doctor`](#doctor) finds missing. `NNN_supabase_accounts.sql` fills the user columns from what Supabase Auth recorded and leaves them empty where it recorded nothing: the name from `raw_user_meta_data`'s `full_name` or `name`, the picture from its `avatar_url` or `picture`, `email_verified` from `email_confirmed_at`, and a ban from `banned_until`, which Better Auth lifts once it has passed. It gives each password of a confirmed address, as Supabase hashed it, a `credential` account (a user who never confirmed theirs signs in by code or resets the password, since GoTrue refused their password sign-in too), and each identity of a social provider an account under Better Auth's name for it (`azure` is `microsoft`, keyed on the `oid` claim; `linkedin_oidc` is `linkedin`, `slack_oidc` is `slack`, `x` is `twitter`), unless its user has an address they never confirmed, since GoTrue refused that sign-in too. Email, phone, anonymous and single sign-on identities and sessions do not carry over. <gap>The import cannot carry over MFA factors because that is not implemented.</gap> <gap>The import cannot carry over passkeys because that is not implemented.</gap>
|
|
542
542
|
4. **Apply the migrations** again. Supabase's users then sign in with their own passwords, and with a social provider once it is in the `socialProviders` of the config's `auth`; new users get a UUID in `auth.users`, so the app's triggers there run for them.
|
|
@@ -355,7 +355,7 @@ Every builder, option and type that `@protobase/schema` exports has a doc commen
|
|
|
355
355
|
|
|
356
356
|
Without rules everyone who can sign in may do everything. Rules come in three kinds, and the [Access](access.md) reference explains the defaults:
|
|
357
357
|
|
|
358
|
-
- **Per operation** (`list`, `read`, `create`, `update`, `delete`): `.access({ update: rule })`. A rule returns `true`, `false`, or an AIP-160 filter that limits the rows, like row-level security. A rule that reads the record (`record.status`) is checked against the stored row.
|
|
358
|
+
- **Per operation** (`list`, `read`, `create`, `update`, `delete`): `.access({ update: rule })`. A rule returns `true`, `false`, or an AIP-160 filter that limits the rows, like row-level security. A rule that reads the record (`record.status`) is checked against the stored row on a get and a write; a caller it reads the record for may not list, so a rule that should list is a filter. See [Rules that read the record](access.md#rules-that-read-the-record).
|
|
359
359
|
- **Per row**: a filter from a rule, or a `.own` or `.team` capability with `.owner(...)`: `.own` gives the records whose owner is the user, `.team` those owned by the users that `defineRoles(roles, { teamOf: (user) => ids })` returns for them.
|
|
360
360
|
- **Per field**: `.access({ read, create, update })` on the field. Field rules see only the user, never a record, so the fields a user can read are the same for every row.
|
|
361
361
|
|
|
@@ -26,4 +26,6 @@ Numbers, amounts and dates use the conventions of the language: English as writt
|
|
|
26
26
|
|
|
27
27
|
Every built-in screen is translated: the shell with its sidebar, top bar, search, notification bell, profile menu and bottom bar; the list page with all its displays (table, cards, board, calendar, timeline and map), filters, search, sort, imports and exports; the record page with its actions, related lists, history, comments, gallery, saving, conflicts and deleting; the create page and composed pages; saved searches and favorites; the sign-in, sign-up and two-factor screens, the account and sign-in policy pages, and the organization, people and invitation pages; public forms; and the messages, toasts and confirmations around them. So are counts, relative times ("5 minutes ago"), yes, no and the other values the app writes itself, and the notices shown while the app loads.
|
|
28
28
|
|
|
29
|
-
The
|
|
29
|
+
The approvals an AI client asks for over [MCP](mcp.md#writes) are translated too, with their buttons and the refusal for a client that cannot ask: in the app's `locale`, or else in the language the client's request accepts.
|
|
30
|
+
|
|
31
|
+
The other texts a plugin or the server writes itself, such as an error message the API sends back or why a plugin could not be loaded, show as they are written.
|
|
@@ -70,7 +70,7 @@ export default defineConfig({ auth: { mcp: true }, mcpEndpoint: { writes: true }
|
|
|
70
70
|
|
|
71
71
|
Each write goes through the REST API as the person: their role's access rules, `validate`, write hooks, events and webhooks apply, so the client can do only what the person may do in the app.
|
|
72
72
|
|
|
73
|
-
Before each write the client asks the person to approve it,
|
|
73
|
+
Before each write the client asks the person to approve it, through MCP's form elicitation. The approval names the record as the record page's breadcrumb does, by the resource's label, its key and its title, such as `Update Task #42 "Fix the sign-in lockout"?`. An update lists each field it changes by its label, with its value before and after (`Status: In flight -> Done`); a create lists the new record's fields by their labels; a delete says whether the record can be restored, and for a resource without a soft delete says plainly that it cannot be undone. Enum values show by their labels, a [sensitive](data-config.md#sensitive-fields) field's value is hidden, and a value is cut at 200 characters. A record or field the person may not read is named by its key or its name in words, and an update or delete of a record changed since its `etag` is refused before asking. The approval, its button and the refusal for a client that cannot ask are in the person's [language](languages.md): the app's `locale`, or else the one the client's request accepts (`Accept-Language`). Nothing is written until they approve, and declining writes nothing. A client's own setting that always allows a tool is not this approval. An approval holds only for the call it was asked for, with the same arguments, by the same person in the same app, organization and client, and only once, within 10 minutes; any other call is asked again. A client that cannot ask, one without form elicitation or one on the 2025 protocol, gets each write refused with a message saying so.
|
|
74
74
|
|
|
75
75
|
<gap>An approval cannot be answered on another server instance or after a restart because a shared approval store is not implemented.</gap> Behind a load balancer, send an MCP client's calls to the same instance.
|
|
76
76
|
|
|
@@ -125,8 +125,8 @@ The endpoint serves each request on its own, without an MCP session: a `GET` or
|
|
|
125
125
|
|
|
126
126
|
`@protobase/server` exports the pieces the endpoint is made of, for an MCP server of your own with tools of your own:
|
|
127
127
|
|
|
128
|
-
- `mcpHandler({ authenticate, resource, scope, server })`: the endpoint as a fetch handler. It checks the host, admits a valid token (`mcpGate`) and serves the request with the server that `server(session)` builds for its caller.
|
|
129
|
-
- `mcpServer({ info, tools, context, report, rolesWithoutApproval, approvals })`: an MCP server offering [assistant tools](assistant.md#the-apps-own-tools), each with its JSON Schema and its `annotations`, MCP's tool hints. `context` is the tools' context without `approve
|
|
128
|
+
- `mcpHandler({ authenticate, resource, scope, server })`: the endpoint as a fetch handler. It checks the host, admits a valid token (`mcpGate`) and serves the request with the server that `server(session, request)` builds for its caller; `request` is the HTTP request, such as for the language the person reads.
|
|
129
|
+
- `mcpServer({ info, tools, context, report, rolesWithoutApproval, approvals })`: an MCP server offering [assistant tools](assistant.md#the-apps-own-tools), each with its JSON Schema and its `annotations`, MCP's tool hints. `context` is the tools' context without `approve`, with the `locale` its approvals are asked in (English when absent): each call gets its own, which asks the client's user, or approves at once when the session's user holds one of `rolesWithoutApproval`. `approvals` is `mcpApprovals()`, built once and passed to every server the endpoint builds: it keeps the approvals asked for until they are answered or expire.
|
|
130
130
|
- `mcpTools({ db, sql, writes })`: the default tools for a session; `writes` is `true`, `false` or `{ resources, rolesWithoutApproval }`.
|
|
131
131
|
- `readRecordTools()`, or `listResourcesTool()`, `listRecordsTool()` and `getRecordTool()`: the read tools alone; `readOnlyQueryTool(db)` is `run_read_only_query`, and `readWriteQueryTool(db)` proposes one write statement that the user approves before it runs.
|
|
132
132
|
- `writeRecordTools({ resources })`, or `createRecordTool(...)`, `updateRecordTool(...)` and `deleteRecordTool(...)`: the single write tools alone, on the listed resources or, without `resources`, on any; `batchWriteTool({ resources })` is `batch_write` alone.
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
# Supabase Realtime
|
|
4
4
|
|
|
5
|
-
The Realtime-compatible /api/sb/realtime/v1 that supabase-js's channel() joins, for postgres_changes checked under the subscriber's RLS policies, broadcasts and presence.
|
|
5
|
+
The Realtime-compatible /api/sb/realtime/v1 that supabase-js's channel() joins, for postgres_changes checked under the subscriber's RLS policies, broadcasts and presence, on public and private channels.
|
|
6
6
|
|
|
7
7
|
An app with API keys also serves `/api/sb/realtime/v1/websocket`, the socket that supabase-js's `channel()` joins. An app moved from Supabase keeps its `postgres_changes` listeners, broadcasts and presence: point the client at the app's `/api/sb` and give it the publishable key.
|
|
8
8
|
|
|
@@ -24,7 +24,7 @@ The server serves the socket when the host gives `createAdmin` its WebSocket upg
|
|
|
24
24
|
|
|
25
25
|
## Which tables
|
|
26
26
|
|
|
27
|
-
A channel may listen to the tables of the resources with [`.live()`](live.md), by `schema` (`*` for any), `table` (every live table of the schema when left out), `event` (`INSERT`, `UPDATE`, `DELETE` or `*`) and `filter`. A table that is not live is refused when the channel joins, with Supabase's message; [`import supabase`](cli.md#import-supabase) makes the tables of the project's `supabase_realtime` publication live. A filter is Supabase's: `column=operator.value`, with `eq`, `neq`, `lt`, `lte`, `gt`, `gte`, `in.(a,b)`, `like`, `ilike`, `match`, `imatch`, `is` and `isdistinct`, `not.` before the operator, and several conditions joined by commas, all of which must hold. Postgres compares each value as the column's type. <gap>A channel cannot `select` columns because that is not supported yet.</gap>
|
|
27
|
+
A channel may listen to the tables of the resources with [`.live()`](live.md), by `schema` (`*` for any), `table` (every live table of the schema when left out), `event` (`INSERT`, `UPDATE`, `DELETE` or `*`) and `filter`. A table that is not live is refused when the channel joins, with Supabase's message; [`import supabase`](cli.md#import-supabase) makes the tables of the project's `supabase_realtime` publication live. A filter is Supabase's: `column=operator.value`, with `eq`, `neq`, `lt`, `lte`, `gt`, `gte`, `in.(a,b)`, `like`, `ilike`, `match`, `imatch`, `is` and `isdistinct`, `not.` before the operator, and several conditions joined by commas, all of which must hold. Postgres compares each value as the column's type. <gap>A channel cannot `select` columns because that is not supported yet.</gap>
|
|
28
28
|
|
|
29
29
|
## Broadcast and presence
|
|
30
30
|
|
|
@@ -48,6 +48,40 @@ Limits, near Supabase's Free plan, apply per socket and per topic. A socket send
|
|
|
48
48
|
|
|
49
49
|
Broadcasts and presence go between the channels of one serving process, which is how a cloud app runs; <gap>Several processes behind one address do not reach each other's channels, because broadcasts and presence are not shared between processes.</gap> <gap>Sending without a joined channel, which supabase-js does over `POST /api/sb/realtime/v1/api/broadcast`, is not supported.</gap>
|
|
50
50
|
|
|
51
|
+
## Private channels
|
|
52
|
+
|
|
53
|
+
A channel joined with `private: true` is authorized as Supabase Realtime Authorization does it: by the row security policies on `realtime.messages`, which say who may receive and who may send each extension's messages, `broadcast` or `presence`, and `realtime.topic()`, the channel's topic without its `realtime:` prefix:
|
|
54
|
+
|
|
55
|
+
```sql
|
|
56
|
+
create policy "members hear their rooms" on realtime.messages for select to authenticated
|
|
57
|
+
using (realtime.messages.extension in ('broadcast', 'presence') and exists (
|
|
58
|
+
select 1 from public.room_members m where m.user_id = (select auth.uid()) and 'room:' || m.room_id = (select realtime.topic())));
|
|
59
|
+
|
|
60
|
+
create policy "members send to their rooms" on realtime.messages for insert to authenticated
|
|
61
|
+
with check (exists (
|
|
62
|
+
select 1 from public.room_members m where m.user_id = (select auth.uid()) and 'room:' || m.room_id = (select realtime.topic())));
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
const room = supabase.channel('room:42', { config: { private: true } })
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
When a channel joins, the server checks, under the subscriber's role and claims, whether it may select a `broadcast` message of the topic, and a `presence` one when the channel listens to presence. A channel that may receive neither is refused with Supabase's `Unauthorized: You do not have permissions to read from this Channel topic: room:42`; one that may receive only one of them does not hear the other. The first broadcast and the first presence track a channel sends check whether it may insert such a message; one it may not is answered with an error and goes to no one. What a check finds holds until the channel's next token, which checks again, and a new token that takes away what the old one allowed ends the channel, with `You no longer have permission to read from this Channel topic: room:42`. A policy that fails, such as one calling a function that raises, allows nothing. <gap>A policy cannot read the socket's headers in `request.headers` because passing them to the checks is not implemented.</gap>
|
|
70
|
+
|
|
71
|
+
[`import supabase`](cli.md#import-supabase) carries a project's policies on `realtime.messages` over. A project that writes its own makes the table first, with Supabase's columns, in a migration:
|
|
72
|
+
|
|
73
|
+
```sql
|
|
74
|
+
create schema realtime;
|
|
75
|
+
create table realtime.messages (topic text not null, extension text not null, payload jsonb, event text, private boolean,
|
|
76
|
+
updated_at timestamp not null default now(), inserted_at timestamp not null default now(), id uuid not null default gen_random_uuid() primary key);
|
|
77
|
+
create function realtime.topic() returns text language sql stable as $$ select nullif(current_setting('realtime.topic', true), '')::text $$;
|
|
78
|
+
alter table realtime.messages enable row level security;
|
|
79
|
+
grant usage on schema realtime to anon, authenticated;
|
|
80
|
+
grant select, insert on realtime.messages to anon, authenticated;
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Each check inserts its messages in a transaction it rolls back, so the table stays empty: the app's database role must own it, or bypass row security, to insert the message a join checks. Without `realtime.messages`, every private channel is refused.
|
|
84
|
+
|
|
51
85
|
## What a subscriber receives
|
|
52
86
|
|
|
53
87
|
Each change is checked for each subscriber before it is sent. The database needs the `anon` and `authenticated` roles, and the app's role must be allowed to `SET ROLE` to them. In one transaction per batch of changes, the server sets the subscriber's role with `SET LOCAL ROLE` and its claims in `request.jwt.claims` and `request.jwt.claim.sub`, so Supabase's `auth.uid()` and `auth.jwt()` work, reads the changed rows by key, and sends an insert or update only when the table's RLS policies let the subscriber select the row, with the columns its role may select. Subscribers with the same role and claims, such as one user's tabs, are checked once. The check holds one pooled connection per serving process, and only while it runs, never one per socket.
|
|
@@ -23,7 +23,7 @@ The keys are `apiKeys` in `protobase.config.ts`, `{ publishable_key, secret_key
|
|
|
23
23
|
| either key and a signed-in user's token | `authenticated` |
|
|
24
24
|
| the secret key | the app's own role, which owns the tables |
|
|
25
25
|
|
|
26
|
-
The transaction sets the role with `SET LOCAL ROLE` and the token's claims in `request.jwt.claims` and `request.jwt.claim.sub`, so Supabase's `auth.uid()`, `auth.role()` and `auth.jwt()` work, and the tables' RLS policies decide what the request may read and write. The `role` claim is the database role, as on Supabase. The database needs the `anon` and `authenticated` roles, and the app's role must be allowed to `SET ROLE` to them.
|
|
26
|
+
The transaction sets the role with `SET LOCAL ROLE` and the token's claims in `request.jwt.claims` and `request.jwt.claim.sub`, so Supabase's `auth.uid()`, `auth.role()` and `auth.jwt()` work, and the tables' RLS policies decide what the request may read and write. The resources' access rules (`.access(...)`) do not apply here: a table needs its own grants and policies, and one without a grant to `anon` or `authenticated` refuses them. The `role` claim is the database role, as on Supabase. The database needs the `anon` and `authenticated` roles, and the app's role must be allowed to `SET ROLE` to them.
|
|
27
27
|
|
|
28
28
|
`/api/sb/rest/v1` serves the tables the app declares as resources, in the `public` schema, under their table names. Any other table is `404`.
|
|
29
29
|
|