@protobase/cli 0.50.0 → 0.50.1
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/cli.md +1 -1
- package/skills/protobase/references/reference/supabase-realtime.md +36 -2
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.50.
|
|
3
|
+
"version": "0.50.1",
|
|
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.50.
|
|
45
|
-
"@protobase/layout": "0.50.
|
|
46
|
-
"@protobase/query": "0.50.
|
|
47
|
-
"@protobase/schema": "0.50.
|
|
48
|
-
"@protobase/server": "0.50.
|
|
49
|
-
"@protobase/ui": "0.50.
|
|
44
|
+
"@protobase/config": "0.50.1",
|
|
45
|
+
"@protobase/layout": "0.50.1",
|
|
46
|
+
"@protobase/query": "0.50.1",
|
|
47
|
+
"@protobase/schema": "0.50.1",
|
|
48
|
+
"@protobase/server": "0.50.1",
|
|
49
|
+
"@protobase/ui": "0.50.1",
|
|
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.
|
|
@@ -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.
|
|
@@ -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.
|