@protobase/cli 0.58.5 → 0.58.7
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/auth/migration-file.js +2 -2
- package/dist/auth/write-migration.js +2 -2
- package/dist/cli/package.js +1 -1
- package/dist/config/build-project.js +2 -1
- package/dist/project/project-admin.js +1 -0
- package/dist/supabase/auth-config.js +49 -19
- package/dist/supabase/dump-phase.js +3 -3
- package/dist/supabase/load-phase.js +1 -1
- package/dist/supabase/project-users.d.ts +5 -5
- package/dist/supabase/project-users.js +15 -15
- package/dist/supabase/shared-users-migration.js +120 -0
- package/package.json +7 -7
- package/skills/protobase/SKILL.md +1 -0
- package/skills/protobase/references/features/calls.md +12 -0
- package/skills/protobase/references/features/compatibility.md +1 -0
- package/skills/protobase/references/features.md +1 -0
- package/skills/protobase/references/getting-started.md +1 -1
- package/skills/protobase/references/guides/api-functions.md +2 -1
- package/skills/protobase/references/reference/auth.md +15 -0
- package/skills/protobase/references/reference/calls.md +103 -0
- package/skills/protobase/references/reference/config/api.md +13 -0
- package/skills/protobase/references/reference/config/sign-in.md +2 -2
- package/skills/protobase/references/reference/config.md +1 -1
|
@@ -14,7 +14,7 @@ const nextMigrationName = (files, name) => {
|
|
|
14
14
|
};
|
|
15
15
|
/** What an auth schema migration holds, its first line, whichever command wrote it. */
|
|
16
16
|
const authMigrationTitle = "The auth schema changes this version of Protobase needs";
|
|
17
|
-
/** The file's contents: what wrote it and why, then Better Auth's statements, one per paragraph. */
|
|
18
|
-
const migrationText = (sql) => `-- ${authMigrationTitle}, written by
|
|
17
|
+
/** The file's contents: what wrote it, `writer`, and why, then Better Auth's statements, one per paragraph. */
|
|
18
|
+
const migrationText = (sql, writer = "protobase auth migration") => `-- ${authMigrationTitle}, written by \`${writer}\`.\n-- Applied with the project's other migrations; edit or remove statements the project handles differently.\n\n${sql}\n`;
|
|
19
19
|
//#endregion
|
|
20
20
|
export { authMigrationTitle, migrationText, nextMigrationName };
|
|
@@ -8,12 +8,12 @@ import { authSchemaMigration } from "@protobase/server";
|
|
|
8
8
|
* `undefined` when the database is current. The changes are found by comparing the database with what Better Auth
|
|
9
9
|
* needs, so the project's earlier migrations must be applied to it first.
|
|
10
10
|
*/
|
|
11
|
-
const writeAuthMigration = async ({ auth, dir, name }) => {
|
|
11
|
+
const writeAuthMigration = async ({ auth, dir, name, writer }) => {
|
|
12
12
|
const sql = await authSchemaMigration(auth);
|
|
13
13
|
if (sql === void 0) return void 0;
|
|
14
14
|
await mkdir(dir, { recursive: true });
|
|
15
15
|
const file = path.join(dir, nextMigrationName(await readdir(dir), name));
|
|
16
|
-
await writeFile(file, migrationText(sql), { flag: "wx" });
|
|
16
|
+
await writeFile(file, migrationText(sql, writer), { flag: "wx" });
|
|
17
17
|
return file;
|
|
18
18
|
};
|
|
19
19
|
//#endregion
|
package/dist/cli/package.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { projectFiles, projectFunctions, projectJobs, projectNotifications, projectOptions, projectResources, projectWebhooks } from "./project-parts.js";
|
|
2
|
-
import { buildAppAuth, buildAuthenticator } from "@protobase/server/internal";
|
|
2
|
+
import { buildAppAuth, buildAuthenticator, checkCallsOptions } from "@protobase/server/internal";
|
|
3
3
|
//#region src/config/build-project.ts
|
|
4
4
|
/**
|
|
5
5
|
* The app's own mailer, the default export of its auth/mailer.ts: what sign-in and the jobs (`context.mail`) both send
|
|
@@ -70,6 +70,7 @@ const buildProject = async (config, database) => {
|
|
|
70
70
|
...webhooks && { webhooks },
|
|
71
71
|
...config.realtime && { realtime: config.realtime },
|
|
72
72
|
...notifications && { notifications },
|
|
73
|
+
...config.calls && { calls: checkCallsOptions(config.calls) },
|
|
73
74
|
...mailer && { mailer },
|
|
74
75
|
...config.mobile && { mobile: config.mobile },
|
|
75
76
|
...config.secret && { secret: config.secret },
|
|
@@ -28,6 +28,7 @@ const projectAdmin = (project, db, ui, reporter, upgradeWebSocket) => {
|
|
|
28
28
|
...project.webhooks && { webhooks: project.webhooks },
|
|
29
29
|
...project.realtime && { realtime: project.realtime },
|
|
30
30
|
...project.notifications && { notifications: project.notifications },
|
|
31
|
+
...project.calls && { calls: project.calls },
|
|
31
32
|
...project.mobile && { mobile: project.mobile },
|
|
32
33
|
...project.app && { app: project.app },
|
|
33
34
|
...ui?.icons && { icons: ui.icons },
|
|
@@ -4,7 +4,7 @@ import path from "node:path";
|
|
|
4
4
|
import { readFile, writeFile } from "node:fs/promises";
|
|
5
5
|
import { Node } from "ts-morph";
|
|
6
6
|
//#region src/supabase/auth-config.ts
|
|
7
|
-
/** The `auth` settings for Supabase's auth.users. */
|
|
7
|
+
/** The `auth` settings for Supabase's auth.users as the user table, on a copy of the database the import owns. */
|
|
8
8
|
const supabaseUsers = {
|
|
9
9
|
users: {
|
|
10
10
|
table: "users",
|
|
@@ -14,45 +14,75 @@ const supabaseUsers = {
|
|
|
14
14
|
passwordHashes: ["bcrypt"],
|
|
15
15
|
generateUserId: "uuid"
|
|
16
16
|
};
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
17
|
+
/** The schema of the app's own sign-in data on a Supabase database, beside Supabase's `auth`. */
|
|
18
|
+
const sharedUsersSchema = "app_auth";
|
|
19
|
+
/** The `auth` settings for a view over Supabase's auth.users, on a Supabase database the app shares with Supabase Auth. */
|
|
20
|
+
const supabaseUsersView = {
|
|
21
|
+
schema: sharedUsersSchema,
|
|
22
|
+
users: {
|
|
23
|
+
...supabaseUsers.users,
|
|
24
|
+
keyTable: {
|
|
25
|
+
schema: "auth",
|
|
26
|
+
table: "users"
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
passwordHashes: supabaseUsers.passwordHashes,
|
|
30
|
+
generateUserId: supabaseUsers.generateUserId
|
|
31
|
+
};
|
|
32
|
+
const importedUsersConfig = {
|
|
33
|
+
settings: supabaseUsers,
|
|
34
|
+
comment: [
|
|
35
|
+
"Supabase's own auth.users as the app's user table, written by `protobase import supabase`: every foreign key,",
|
|
36
|
+
"trigger and policy naming it keeps working. Its passwords are bcrypt hashes, its ids UUIDs, and its `role` the",
|
|
37
|
+
"Postgres role, so the app's roles go to a column of their own."
|
|
38
|
+
]
|
|
39
|
+
};
|
|
40
|
+
const sharedUsersConfig = {
|
|
41
|
+
settings: supabaseUsersView,
|
|
42
|
+
comment: [
|
|
43
|
+
`Supabase's users, read through the view ${sharedUsersSchema}.users over auth.users, written by \`create protobase\`: the app`,
|
|
44
|
+
`keeps only its own sign-in data, in ${sharedUsersSchema}, and Supabase's auth schema stays as Supabase set it up. Their`,
|
|
45
|
+
"passwords are bcrypt hashes, their ids UUIDs, and `role` in auth.users the Postgres role, so the app's roles go to a",
|
|
46
|
+
"column of their own."
|
|
47
|
+
]
|
|
48
|
+
};
|
|
49
|
+
const literal = (value) => {
|
|
50
|
+
if (typeof value === "string") return `'${value}'`;
|
|
51
|
+
if (Array.isArray(value)) return `[${value.map(literal).join(", ")}]`;
|
|
52
|
+
if (typeof value === "object" && value !== null) return `{ ${Object.entries(value).map(([key, item]) => `${key}: ${literal(item)}`).join(", ")} }`;
|
|
53
|
+
throw new Error(`Not implemented: a setting of type ${typeof value}`);
|
|
54
|
+
};
|
|
55
|
+
const settingsText = ({ settings, comment }, indent) => [...comment.map((line) => `// ${line}`), ...Object.entries(settings).map(([key, value]) => `${key}: ${literal(value)},`)].map((line) => `${indent}${line}`).join("\n");
|
|
26
56
|
/**
|
|
27
57
|
* protobase.config.ts with the settings first in its `auth`, or with an `auth` of them when it has none, sign-in being
|
|
28
58
|
* on by default; fails, naming what to add, when it exports no object the import can see or its `auth` is not one.
|
|
29
59
|
*/
|
|
30
|
-
const withSupabaseUsers = (text, file) => {
|
|
60
|
+
const withSupabaseUsers = (text, file, users) => {
|
|
31
61
|
const config = exportedConfigObject(text).object;
|
|
32
|
-
const refused = () => /* @__PURE__ */ new Error(`${file} must export a config with an \`auth: { ... }\` object: point it at Supabase's auth.users yourself with ${JSON.stringify(
|
|
62
|
+
const refused = () => /* @__PURE__ */ new Error(`${file} must export a config with an \`auth: { ... }\` object: point it at Supabase's auth.users yourself with ${JSON.stringify(users.settings)}, then try again`);
|
|
33
63
|
if (!config) throw refused();
|
|
34
64
|
const auth = config.getProperty("auth");
|
|
35
65
|
if (!auth) {
|
|
36
66
|
const last = config.getProperties().at(-1);
|
|
37
|
-
if (!last) return `${text.slice(0, config.getStart())}{ auth: ${
|
|
38
|
-
return `${text.slice(0, last.getEnd())}, auth: ${
|
|
67
|
+
if (!last) return `${text.slice(0, config.getStart())}{ auth: ${literal(users.settings)} }${text.slice(config.getEnd())}`;
|
|
68
|
+
return `${text.slice(0, last.getEnd())}, auth: ${literal(users.settings)}${text.slice(last.getEnd())}`;
|
|
39
69
|
}
|
|
40
70
|
const object = Node.isPropertyAssignment(auth) ? auth.getInitializer() : void 0;
|
|
41
71
|
if (!object || !Node.isObjectLiteralExpression(object)) throw refused();
|
|
42
72
|
const first = object.getProperties()[0];
|
|
43
73
|
const indent = first ? " ".repeat(first.getStartLinePos() === first.getStart() ? 0 : first.getStart() - first.getStartLinePos()) : " ";
|
|
44
74
|
const at = object.getStart() + 1;
|
|
45
|
-
return `${text.slice(0, at)}\n${settingsText(indent)}${first ? "" : "\n"}${text.slice(at)}`;
|
|
75
|
+
return `${text.slice(0, at)}\n${settingsText(users, indent)}${first ? "" : "\n"}${text.slice(at)}`;
|
|
46
76
|
};
|
|
47
77
|
/** Where the app's Better Auth settings live, and what they become; fails before anything is written when it cannot. */
|
|
48
|
-
const planAuthConfig = async (projectDir) => {
|
|
78
|
+
const planAuthConfig = async (projectDir, users) => {
|
|
49
79
|
const file = path.join(projectDir, "protobase.config.ts");
|
|
50
|
-
if (!existsSync(file)) throw new Error("The project has no protobase.config.ts with its `auth`:
|
|
51
|
-
const text = withSupabaseUsers(await readFile(file, "utf8"), path.relative(projectDir, file));
|
|
80
|
+
if (!existsSync(file)) throw new Error("The project has no protobase.config.ts with its `auth`: start from a project made by create-protobase");
|
|
81
|
+
const text = withSupabaseUsers(await readFile(file, "utf8"), path.relative(projectDir, file), users);
|
|
52
82
|
return {
|
|
53
83
|
file,
|
|
54
84
|
write: () => writeFile(file, text)
|
|
55
85
|
};
|
|
56
86
|
};
|
|
57
87
|
//#endregion
|
|
58
|
-
export { planAuthConfig, supabaseUsers, withSupabaseUsers };
|
|
88
|
+
export { importedUsersConfig, planAuthConfig, sharedUsersConfig, sharedUsersSchema, supabaseUsers, supabaseUsersView, withSupabaseUsers };
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { connect } from "../db/connect.js";
|
|
2
2
|
import { databaseMarkers, missingMarkers } from "./platform-schemas.js";
|
|
3
|
-
import { planAuthConfig } from "./auth-config.js";
|
|
3
|
+
import { importedUsersConfig, planAuthConfig } from "./auth-config.js";
|
|
4
4
|
import { writeMigration } from "./migration-files.js";
|
|
5
5
|
import { authStoreMigrations } from "./store-migrations.js";
|
|
6
|
-
import { usersColumnsMigration } from "./users-migrations.js";
|
|
7
6
|
import { checkoutMarkers } from "./checkout.js";
|
|
8
7
|
import { cronPlan } from "./cron-plan.js";
|
|
9
8
|
import { planFunctions } from "./functions/plan-functions.js";
|
|
@@ -18,6 +17,7 @@ import { countSsoUsers, refuseSsoUsers } from "./sso-users.js";
|
|
|
18
17
|
import { appSchemas, cronJobs, cronTimezone, dumpedTables, extensions, httpTriggers, hypertables, pgmqQueues, pgsodiumColumns, platformMigrationTables, realtimeTables, routinesIn, tablesSize, vaultSecretValues, vaultSecrets } from "./source-facts.js";
|
|
19
18
|
import { ensureApiRoles, existingSchemas, existingTables } from "./target-checks.js";
|
|
20
19
|
import { creatableExtensions } from "./target-extensions.js";
|
|
20
|
+
import { usersColumnsMigration } from "./users-migrations.js";
|
|
21
21
|
import path from "node:path";
|
|
22
22
|
import { mkdir, readFile, rm } from "node:fs/promises";
|
|
23
23
|
import { isSchedule } from "@protobase/server";
|
|
@@ -131,7 +131,7 @@ const pattern = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
|
|
|
131
131
|
* project's migrations are applied.
|
|
132
132
|
*/
|
|
133
133
|
const runDumpPhase = async (options, out) => {
|
|
134
|
-
const authConfig = await planAuthConfig(options.projectDir);
|
|
134
|
+
const authConfig = await planAuthConfig(options.projectDir, importedUsersConfig);
|
|
135
135
|
const storeMigrations = await authStoreMigrations(options.migrationsDir);
|
|
136
136
|
const checkout = checkoutMarkers(options.projectDir);
|
|
137
137
|
if (checkout.length > 0) out(`found the Supabase project's ${checkout.join(", ")}\n`);
|
|
@@ -5,13 +5,13 @@ import { runScaffold } from "../scaffold/run.js";
|
|
|
5
5
|
import { writeAuthMigration } from "../auth/write-migration.js";
|
|
6
6
|
import { writeMigration } from "./migration-files.js";
|
|
7
7
|
import { providerCounts } from "./identity-providers.js";
|
|
8
|
-
import { accountsMigration } from "./users-migrations.js";
|
|
9
8
|
import { runDoctor } from "../doctor/run.js";
|
|
10
9
|
import { convertedCronJobs } from "./cron-plan.js";
|
|
11
10
|
import { importState } from "./import-state.js";
|
|
12
11
|
import { runPgTool } from "./pg-tools.js";
|
|
13
12
|
import { loadScript, qualified } from "./load-script.js";
|
|
14
13
|
import { existingTables, filledTables, otherTables } from "./target-checks.js";
|
|
14
|
+
import { accountsMigration } from "./users-migrations.js";
|
|
15
15
|
import { cronJobFilesInTheWay, writeCronJobs } from "./cron-jobs-write.js";
|
|
16
16
|
import { importReport } from "./report.js";
|
|
17
17
|
import { existsSync } from "node:fs";
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
//#region src/supabase/project-users.d.ts
|
|
2
2
|
/**
|
|
3
|
-
* Signs the project in `projectDir`, made on a Supabase database, in on Supabase's own
|
|
4
|
-
*
|
|
5
|
-
* table, and writes, in `db/migrations`,
|
|
6
|
-
* and the users' accounts with their Supabase passwords and social providers. It
|
|
7
|
-
* project's auth keeps a connection pool open on, so the process must end itself.
|
|
3
|
+
* Signs the project in `projectDir`, made on a Supabase database, in on Supabase's own users, changing nothing in
|
|
4
|
+
* Supabase's `auth` schema: points its Better Auth setup at a view over auth.users in a schema of its own, removes the
|
|
5
|
+
* migrations of Protobase's own user table, and writes, in `db/migrations`, Better Auth's tables in that schema, then
|
|
6
|
+
* the view, its side table and trigger, and the users' accounts with their Supabase passwords and social providers. It
|
|
7
|
+
* only reads the database, which the project's auth keeps a connection pool open on, so the process must end itself.
|
|
8
8
|
*/
|
|
9
9
|
export declare const useSupabaseUsers: (projectDir: string, out: (text: string) => void) => Promise<void>;
|
|
10
10
|
//#endregion
|
|
@@ -1,38 +1,38 @@
|
|
|
1
1
|
import { loadProjectAuth } from "../users/load-auth.js";
|
|
2
2
|
import { writeAuthMigration } from "../auth/write-migration.js";
|
|
3
|
-
import { planAuthConfig } from "./auth-config.js";
|
|
3
|
+
import { planAuthConfig, sharedUsersConfig, sharedUsersSchema } from "./auth-config.js";
|
|
4
4
|
import { writeMigration } from "./migration-files.js";
|
|
5
|
+
import { sharedUsersMigration } from "./shared-users-migration.js";
|
|
5
6
|
import { authStoreMigrations } from "./store-migrations.js";
|
|
6
|
-
import { accountsMigration, usersColumnsMigration } from "./users-migrations.js";
|
|
7
7
|
import path from "node:path";
|
|
8
8
|
import { mkdir, rm } from "node:fs/promises";
|
|
9
9
|
//#region src/supabase/project-users.ts
|
|
10
10
|
/**
|
|
11
|
-
* Signs the project in `projectDir`, made on a Supabase database, in on Supabase's own
|
|
12
|
-
*
|
|
13
|
-
* table, and writes, in `db/migrations`,
|
|
14
|
-
* and the users' accounts with their Supabase passwords and social providers. It
|
|
15
|
-
* project's auth keeps a connection pool open on, so the process must end itself.
|
|
11
|
+
* Signs the project in `projectDir`, made on a Supabase database, in on Supabase's own users, changing nothing in
|
|
12
|
+
* Supabase's `auth` schema: points its Better Auth setup at a view over auth.users in a schema of its own, removes the
|
|
13
|
+
* migrations of Protobase's own user table, and writes, in `db/migrations`, Better Auth's tables in that schema, then
|
|
14
|
+
* the view, its side table and trigger, and the users' accounts with their Supabase passwords and social providers. It
|
|
15
|
+
* only reads the database, which the project's auth keeps a connection pool open on, so the process must end itself.
|
|
16
16
|
*/
|
|
17
17
|
const useSupabaseUsers = async (projectDir, out) => {
|
|
18
18
|
const migrationsDir = path.join(projectDir, "db", "migrations");
|
|
19
|
-
const authConfig = await planAuthConfig(projectDir);
|
|
19
|
+
const authConfig = await planAuthConfig(projectDir, sharedUsersConfig);
|
|
20
20
|
const storeMigrations = await authStoreMigrations(migrationsDir);
|
|
21
21
|
const relative = (to) => path.relative(projectDir, to);
|
|
22
22
|
for (const store of storeMigrations) await rm(path.join(migrationsDir, store));
|
|
23
23
|
await mkdir(migrationsDir, { recursive: true });
|
|
24
|
-
const usersFile = await writeMigration(migrationsDir, "supabase_users", usersColumnsMigration());
|
|
25
24
|
await authConfig.write();
|
|
26
|
-
if (storeMigrations.length > 0) out(`removed ${storeMigrations.length} migrations of Protobase's own user table:
|
|
27
|
-
out(`
|
|
25
|
+
if (storeMigrations.length > 0) out(`removed ${storeMigrations.length} migrations of Protobase's own user table: Supabase's users replace it\n`);
|
|
26
|
+
out(`pointed ${relative(authConfig.file)} at ${sharedUsersSchema}.users, a view over auth.users\n`);
|
|
28
27
|
const authFile = await writeAuthMigration({
|
|
29
28
|
auth: await loadProjectAuth(projectDir),
|
|
30
29
|
dir: migrationsDir,
|
|
31
|
-
name: "auth"
|
|
30
|
+
name: "auth",
|
|
31
|
+
writer: "create protobase"
|
|
32
32
|
});
|
|
33
|
-
if (authFile) out(`wrote ${relative(authFile)}, Better Auth's tables
|
|
34
|
-
const
|
|
35
|
-
out(`wrote ${relative(path.join(migrationsDir,
|
|
33
|
+
if (authFile) out(`wrote ${relative(authFile)}, Better Auth's tables in ${sharedUsersSchema}, pointing at auth.users\n`);
|
|
34
|
+
const usersFile = await writeMigration(migrationsDir, "supabase_users", sharedUsersMigration());
|
|
35
|
+
out(`wrote ${relative(path.join(migrationsDir, usersFile))}, the view over auth.users and the users' accounts with their Supabase passwords and social providers\n`);
|
|
36
36
|
};
|
|
37
37
|
//#endregion
|
|
38
38
|
export { useSupabaseUsers };
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { sharedUsersSchema } from "./auth-config.js";
|
|
2
|
+
import { accountIdSql, accountProviderSql, carriesAccountSql } from "./identity-providers.js";
|
|
3
|
+
//#region src/supabase/shared-users-migration.ts
|
|
4
|
+
const signsIn = (u) => `${u}.email is not null and ${u}.email <> '' and ${u}.deleted_at is null and not coalesce(${u}.is_anonymous, false)`;
|
|
5
|
+
const viewSql = `-- Each user as Better Auth reads them. The name and picture are read from Supabase's user metadata, where a change made
|
|
6
|
+
-- in Supabase shows at once. A ban is the app's own, in the side table, or Supabase's while it lasts: lifting the app's
|
|
7
|
+
-- never lifts Supabase's. No password, token or app metadata of auth.users is in it.
|
|
8
|
+
create view ${sharedUsersSchema}.users with (security_invoker = on) as
|
|
9
|
+
select u.id,
|
|
10
|
+
coalesce(u.raw_user_meta_data->>'full_name', u.raw_user_meta_data->>'name') as name,
|
|
11
|
+
u.email::text as email,
|
|
12
|
+
u.email_confirmed_at is not null as email_verified,
|
|
13
|
+
u.email_confirmed_at,
|
|
14
|
+
coalesce(u.raw_user_meta_data->>'avatar_url', u.raw_user_meta_data->>'picture') as image,
|
|
15
|
+
u.created_at,
|
|
16
|
+
u.updated_at,
|
|
17
|
+
x.app_role,
|
|
18
|
+
case when x.banned then true when u.banned_until > now() then true end as banned,
|
|
19
|
+
case when x.banned then x.ban_reason end as ban_reason,
|
|
20
|
+
case when x.banned then x.ban_expires when u.banned_until > now() then u.banned_until end as ban_expires,
|
|
21
|
+
x.last_role,
|
|
22
|
+
x.two_factor_enabled,
|
|
23
|
+
x.last_organization_id,
|
|
24
|
+
u.raw_user_meta_data
|
|
25
|
+
from auth.users u left join ${sharedUsersSchema}.user_extra x on x.id = u.id
|
|
26
|
+
where ${signsIn("u")};`;
|
|
27
|
+
const sideTypes = {
|
|
28
|
+
app_role: "text",
|
|
29
|
+
banned: "boolean",
|
|
30
|
+
ban_reason: "text",
|
|
31
|
+
ban_expires: "timestamptz",
|
|
32
|
+
last_role: "text",
|
|
33
|
+
two_factor_enabled: "boolean",
|
|
34
|
+
last_organization_id: "text"
|
|
35
|
+
};
|
|
36
|
+
const sideColumns = Object.keys(sideTypes);
|
|
37
|
+
const changedSide = sideColumns.map((column) => `${column} = case when new.${column} is distinct from old.${column} then new.${column} else x.${column} end`).join(",\n ");
|
|
38
|
+
const triggerSql = `-- Writes through the view. A user the app creates gets a row in auth.users as Supabase Auth makes one, with '' in the
|
|
39
|
+
-- token columns it reads as text, and Supabase's own role, audience and app metadata; an id or email auth.users has
|
|
40
|
+
-- already fails on its constraints. An update writes only what it changes: the metadata keys it changes are merged into
|
|
41
|
+
-- the row's current metadata, so a change Supabase makes meanwhile to another key stays. Deleting a user deletes them
|
|
42
|
+
-- from auth.users, and with them their accounts, sessions and side row.
|
|
43
|
+
create function ${sharedUsersSchema}.users_write() returns trigger language plpgsql security invoker set search_path = '' as $$
|
|
44
|
+
declare
|
|
45
|
+
patch jsonb := '{}';
|
|
46
|
+
begin
|
|
47
|
+
if tg_op = 'DELETE' then
|
|
48
|
+
delete from auth.users where id = old.id;
|
|
49
|
+
return old;
|
|
50
|
+
end if;
|
|
51
|
+
if tg_op = 'INSERT' then
|
|
52
|
+
new.id := coalesce(new.id, gen_random_uuid());
|
|
53
|
+
new.created_at := coalesce(new.created_at, now());
|
|
54
|
+
new.updated_at := coalesce(new.updated_at, now());
|
|
55
|
+
insert into auth.users (instance_id, id, aud, role, email, email_confirmed_at, created_at, updated_at, raw_app_meta_data, raw_user_meta_data,
|
|
56
|
+
confirmation_token, recovery_token, email_change_token_new, email_change)
|
|
57
|
+
values ('00000000-0000-0000-0000-000000000000', new.id, 'authenticated', 'authenticated', new.email,
|
|
58
|
+
case when new.email_verified then coalesce(new.email_confirmed_at, now()) end, new.created_at, new.updated_at,
|
|
59
|
+
'{"provider":"email","providers":["email"]}',
|
|
60
|
+
coalesce(new.raw_user_meta_data, '{}') || jsonb_strip_nulls(jsonb_build_object('full_name', new.name, 'avatar_url', new.image)),
|
|
61
|
+
'', '', '', '');
|
|
62
|
+
insert into ${sharedUsersSchema}.user_extra (id, ${sideColumns.join(", ")})
|
|
63
|
+
values (new.id, ${sideColumns.map((column) => `new.${column}`).join(", ")});
|
|
64
|
+
return new;
|
|
65
|
+
end if;
|
|
66
|
+
if new.raw_user_meta_data is distinct from old.raw_user_meta_data then
|
|
67
|
+
select coalesce(jsonb_object_agg(key, value), '{}') into patch from jsonb_each(coalesce(new.raw_user_meta_data, '{}'))
|
|
68
|
+
where old.raw_user_meta_data -> key is distinct from value;
|
|
69
|
+
end if;
|
|
70
|
+
if new.name is distinct from old.name then patch := patch || jsonb_build_object('full_name', new.name); end if;
|
|
71
|
+
if new.image is distinct from old.image then patch := patch || jsonb_build_object('avatar_url', new.image); end if;
|
|
72
|
+
update auth.users u set
|
|
73
|
+
email = case when new.email is distinct from old.email then new.email else u.email end,
|
|
74
|
+
email_confirmed_at = case
|
|
75
|
+
when new.email_verified is not distinct from old.email_verified and new.email_confirmed_at is not distinct from old.email_confirmed_at then u.email_confirmed_at
|
|
76
|
+
when new.email_verified then coalesce(new.email_confirmed_at, u.email_confirmed_at, now())
|
|
77
|
+
end,
|
|
78
|
+
raw_user_meta_data = coalesce(u.raw_user_meta_data, '{}') || patch,
|
|
79
|
+
updated_at = coalesce(new.updated_at, now())
|
|
80
|
+
where u.id = old.id;
|
|
81
|
+
insert into ${sharedUsersSchema}.user_extra (id) values (old.id) on conflict (id) do nothing;
|
|
82
|
+
update ${sharedUsersSchema}.user_extra x set
|
|
83
|
+
${changedSide}
|
|
84
|
+
where x.id = old.id;
|
|
85
|
+
return new;
|
|
86
|
+
end $$;
|
|
87
|
+
|
|
88
|
+
create trigger users_write instead of insert or update or delete on ${sharedUsersSchema}.users for each row execute function ${sharedUsersSchema}.users_write();`;
|
|
89
|
+
/** The side table, the view over auth.users and its trigger, then the users' accounts, as `create protobase` writes them. */
|
|
90
|
+
const sharedUsersMigration = () => `-- Supabase's users signing in with Better Auth, written by \`create protobase\`: nothing in Supabase's auth schema changes.
|
|
91
|
+
|
|
92
|
+
-- The columns only Better Auth has, for each user of auth.users that has any.
|
|
93
|
+
create table ${sharedUsersSchema}.user_extra (
|
|
94
|
+
id uuid primary key references auth.users (id) on delete cascade,
|
|
95
|
+
${Object.entries(sideTypes).map(([column, type]) => `${column} ${type}`).join(",\n ")}
|
|
96
|
+
);
|
|
97
|
+
|
|
98
|
+
${viewSql}
|
|
99
|
+
|
|
100
|
+
${triggerSql}
|
|
101
|
+
|
|
102
|
+
-- Each password, as Supabase hashed it: Better Auth verifies the bcrypt hash and stores it again as its own on sign-in.
|
|
103
|
+
-- Only for confirmed addresses: Supabase Auth refuses a password sign-in to an unconfirmed one and Better Auth would
|
|
104
|
+
-- not, so whoever signed up with someone else's address could sign in as them. Users who sign up through Supabase Auth
|
|
105
|
+
-- later have no password in the app.
|
|
106
|
+
insert into ${sharedUsersSchema}.account (account_id, provider_id, user_id, password, created_at, updated_at)
|
|
107
|
+
select id::text, 'credential', id, encrypted_password, coalesce(created_at, now()), coalesce(updated_at, now())
|
|
108
|
+
from auth.users where encrypted_password is not null and encrypted_password <> '' and email_confirmed_at is not null and ${signsIn("auth.users")};
|
|
109
|
+
|
|
110
|
+
-- Each identity of a social provider, by Better Auth's name for it and the claim it keys the account on, for the users
|
|
111
|
+
-- the view holds with a confirmed address, for the reason above.
|
|
112
|
+
insert into ${sharedUsersSchema}.account (account_id, provider_id, user_id, created_at, updated_at)
|
|
113
|
+
select account_id, provider_id, user_id, created_at, updated_at from (
|
|
114
|
+
select ${accountIdSql} as account_id, ${accountProviderSql} as provider_id, user_id, coalesce(created_at, now()) as created_at, coalesce(updated_at, now()) as updated_at
|
|
115
|
+
from auth.identities where ${carriesAccountSql}
|
|
116
|
+
and user_id in (select id from auth.users where email_confirmed_at is not null and ${signsIn("auth.users")})
|
|
117
|
+
) identity where account_id is not null;
|
|
118
|
+
`;
|
|
119
|
+
//#endregion
|
|
120
|
+
export { sharedUsersMigration };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@protobase/cli",
|
|
3
|
-
"version": "0.58.
|
|
3
|
+
"version": "0.58.7",
|
|
4
4
|
"description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -42,12 +42,12 @@
|
|
|
42
42
|
"dependencies": {
|
|
43
43
|
"@better-auth/core": "^1.7.12",
|
|
44
44
|
"@hono/node-server": "^2.1.3",
|
|
45
|
-
"@protobase/config": "0.58.
|
|
46
|
-
"@protobase/layout": "0.58.
|
|
47
|
-
"@protobase/query": "0.58.
|
|
48
|
-
"@protobase/schema": "0.58.
|
|
49
|
-
"@protobase/server": "0.58.
|
|
50
|
-
"@protobase/ui": "0.58.
|
|
45
|
+
"@protobase/config": "0.58.7",
|
|
46
|
+
"@protobase/layout": "0.58.7",
|
|
47
|
+
"@protobase/query": "0.58.7",
|
|
48
|
+
"@protobase/schema": "0.58.7",
|
|
49
|
+
"@protobase/server": "0.58.7",
|
|
50
|
+
"@protobase/ui": "0.58.7",
|
|
51
51
|
"@react-email/render": "^2.1.0",
|
|
52
52
|
"@scalar/hono-api-reference": "^0.12.10",
|
|
53
53
|
"@tailwindcss/vite": "^4.3.3",
|
|
@@ -88,6 +88,7 @@ Reference:
|
|
|
88
88
|
- When running background jobs → read [Jobs](references/reference/jobs.md)
|
|
89
89
|
- When sending email → read [Email](references/reference/email.md)
|
|
90
90
|
- When registering users' devices for push notifications → read [Notifications](references/reference/notifications.md)
|
|
91
|
+
- When adding audio and video calls, through LiveKit or peer to peer → read [Calls](references/reference/calls.md)
|
|
91
92
|
- When setting roles, capabilities and row filters → read [Access](references/reference/access.md)
|
|
92
93
|
- When configuring sign-in, tokens and the auth schema → read [Login with Better Auth](references/reference/auth.md)
|
|
93
94
|
- When using the typed client and hooks → read [Client and live UI](references/reference/client.md)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
<!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/features/calls.md: run `bun run docs:skill`, do not edit. -->
|
|
2
|
+
|
|
3
|
+
# Calls
|
|
4
|
+
|
|
5
|
+
Audio and video calls between an app's users, through LiveKit or peer to peer, with Protobase deciding who is in a call and who hears whom.
|
|
6
|
+
|
|
7
|
+
- [Calls](../reference/calls.md#turning-them-on) (in development): `calls: { backend }` in the config carries calls' audio and video through a media plugin inside the server, and an app without it loads none of it.
|
|
8
|
+
- [LiveKit](../reference/calls.md#livekit) (in development): The media goes through a LiveKit server, self-hosted or LiveKit Cloud, which Protobase speaks to for each member.
|
|
9
|
+
- [Peer to peer](../reference/calls.md#peer-to-peer) (in development): With no media server, the members' browsers send their media straight to each other, for small calls.
|
|
10
|
+
- [Admitting members](../reference/calls.md#admitting-members) (in development): A function of your own admits the caller to a call with what they may send and whose tracks they hear.
|
|
11
|
+
- [Joining from the browser](../reference/calls.md#joining-from-the-browser) (in development): `joinCall` from `@protobase/client/calls` sends the camera, microphone and screen in plain WebRTC, with no media library in the app.
|
|
12
|
+
- [Reconnecting](../reference/calls.md#reconnecting) (in development): A call keeps its media through a deploy or a dropped connection, and resumes on any process serving the app.
|
|
@@ -7,6 +7,7 @@ Apps written for other systems that keep working on Protobase, and moving their
|
|
|
7
7
|
## Supabase
|
|
8
8
|
|
|
9
9
|
- [Supabase import](../reference/cli.md#import-supabase): Moves a Supabase project into Protobase, with schema, data, users, functions, storage and scheduled jobs.
|
|
10
|
+
- [Create a project on a Supabase database](../getting-started.md#on-an-existing-database) (beta): your Supabase users sign in to the new project with their own passwords, and Supabase's own auth schema stays as Supabase set it up.
|
|
10
11
|
- [Supabase client API](../reference/supabase-rest.md): supabase-js `from()` and `rpc()` calls keep working, under the tables' RLS policies.
|
|
11
12
|
- [Supabase Auth](../reference/auth.md#supabase-js-and-supabasessr): `supabase.auth` and `@supabase/ssr` calls keep working.
|
|
12
13
|
- [Supabase Storage](../reference/supabase-storage.md): supabase-js storage calls keep working, over the app's file storage.
|
|
@@ -32,6 +32,7 @@ A feature without a mark is stable. The others say so after their name:
|
|
|
32
32
|
- [History, comments and live updates](features/history-comments-and-live-updates.md): The changes of each record, comments on it, and pages that refresh as records change.
|
|
33
33
|
- [Events, webhooks and jobs](features/events-webhooks-and-jobs.md): React to changes, deliver them to other systems, and run work in the background.
|
|
34
34
|
- [Notifications](features/notifications.md): A bell in the top bar and push to browsers and phones, for what your app tells its users.
|
|
35
|
+
- [Calls](features/calls.md): Audio and video calls between an app's users, with Protobase deciding who is in a call and who hears whom.
|
|
35
36
|
- [Email and public forms](features/email-and-public-forms.md): Mail the app sends, and forms for people without an account.
|
|
36
37
|
- [AI](features/ai.md): Fields and actions filled by a model, the assistant beside the admin, and MCP.
|
|
37
38
|
- [Compatibility and moving from other systems](features/compatibility.md): Apps written for other systems that keep working on Protobase, and moving their data and code over.
|
|
@@ -61,7 +61,7 @@ Then it runs that `scaffold` in the project and prints the next steps. Without a
|
|
|
61
61
|
|
|
62
62
|
It never writes to the database. The first of the next steps does: `bun run db:migrate` adds the `auth` schema that sign-in keeps its users in, and the `migrations` schema, where the script records the migrations it applied in `migrations.applied`. A `public.schema_migrations` another migration tool keeps is left as it is.
|
|
63
63
|
|
|
64
|
-
On a Supabase database, which it knows by its `auth` and `storage` schemas and its `supabase_admin` role, as [`import supabase`](reference/cli.md#import-supabase) does, the `auth` schema is Supabase Auth's,
|
|
64
|
+
On a Supabase database, which it knows by its `auth` and `storage` schemas and its `supabase_admin` role, as [`import supabase`](reference/cli.md#import-supabase) does, the `auth` schema is Supabase Auth's, and the project changes nothing in it. It leaves out `auth`, `storage` and the platform's other schemas, such as `realtime` and `supabase_migrations`, as Supabase's own tables. The project reads Supabase's users through a view over `auth.users` and keeps only its own sign-in data, in a schema of its own, `app_auth`: it points `protobase.config.ts` at the view, with [`users.keyTable`](reference/auth.md#a-view-over-another-systems-users), and writes migrations in place of those of Protobase's own user table: Better Auth's tables in `app_auth`, pointing at `auth.users`, then the view, its side table of the columns only Better Auth has, and each user's account with their Supabase password and social providers. `bun run db:migrate` applies them as the `postgres` role a Supabase connection string signs in as, and Supabase's users sign in with their own passwords, under their own ids. You can create, disable and delete users from either side, and a name changed in Supabase shows at once. <gap>A user who signs up through Supabase Auth later is a user of the project at once but cannot sign in with a password because sharing passwords with Supabase Auth is not implemented.</gap> Supabase's phone-only and anonymous users are not users of the project, since sign-in needs an email. A ban set in the project stays the project's own, while a ban set in Supabase holds in the project too.
|
|
65
65
|
|
|
66
66
|
```sh
|
|
67
67
|
cd shop
|
|
@@ -52,9 +52,10 @@ The second argument of a handler (`c.env` in a [Hono app](#hono-apps)):
|
|
|
52
52
|
| `caller()` | Resolves to `{ session, records }`. Public functions use it to ask for a caller when they need one. |
|
|
53
53
|
| `decryptField(resource, key, field)` | An [encrypted field](../reference/data-config.md#reading-in-jobs-and-functions)'s value, skipping access rules like `db`; each read is audited, naming the function and the caller. |
|
|
54
54
|
| `acceptWebSocket(events)` | Answers a WebSocket upgrade with a socket; return its response. See [WebSockets](#websockets). |
|
|
55
|
+
| `calls.join(member)` | The events of a member's socket in a call, for `acceptWebSocket`. See [Calls](../reference/calls.md). |
|
|
55
56
|
| `name` | The function's name. |
|
|
56
57
|
|
|
57
|
-
A [public function](#public-functions-and-webhooks) has only `db`, `caller()`, `acceptWebSocket` and `name`.
|
|
58
|
+
A [public function](#public-functions-and-webhooks) has only `db`, `caller()`, `acceptWebSocket`, `calls` and `name`.
|
|
58
59
|
|
|
59
60
|
## Reading and writing records as the caller
|
|
60
61
|
|
|
@@ -65,6 +65,21 @@ auth: {
|
|
|
65
65
|
|
|
66
66
|
The store's migrations make the user table only when it is missing, and add each of its columns only when the table lacks it, so a table another system made keeps its own. A required column (`name`, `email`, `email_verified`) cannot be added to a table with rows, so the columns Better Auth needs that the table lacks come first, nullable, from a migration of the project's own; `protobase auth migration` then writes the other tables next to it, and another migration fills the columns from what the other system recorded and gives each password its `credential` row in `account`. For Supabase, [`protobase import supabase`](cli.md#import-supabase) writes all three and these options.
|
|
67
67
|
|
|
68
|
+
### A view over another system's users
|
|
69
|
+
|
|
70
|
+
Where the app may not change the other system's users table, as on a Supabase database, where only Supabase Auth may change its `auth` schema, the user table can be a view of the app's own over it. `users.keyTable` names the table that holds the user ids:
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
auth: {
|
|
74
|
+
schema: 'app_auth',
|
|
75
|
+
users: { table: 'users', keyTable: { schema: 'auth', table: 'users' }, columns: { role: 'app_role' }, metadata: 'raw_user_meta_data' },
|
|
76
|
+
passwordHashes: ['bcrypt'],
|
|
77
|
+
generateUserId: 'uuid',
|
|
78
|
+
}
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
The store's migrations then make nothing of the user table, which a migration of the project's own makes as a view with an `instead of` trigger for Better Auth's writes, and every foreign key points at the key table. `protobase dev` compares the view's columns with what Better Auth needs, rather than reporting it as a missing table. The key table counts among the store's tables, so no resource may be over it and the assistant's queries never read it, since it holds the other system's password hashes. On a Supabase database, [`npm create protobase`](../getting-started.md#on-an-existing-database) writes these settings and the view.
|
|
82
|
+
|
|
68
83
|
## Configuration
|
|
69
84
|
|
|
70
85
|
| Variable | |
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
<!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/reference/calls.md: run `bun run docs:skill`, do not edit. -->
|
|
2
|
+
|
|
3
|
+
# Calls
|
|
4
|
+
|
|
5
|
+
Audio and video calls between an app's users, through a LiveKit server or straight between browsers, with Protobase deciding who is in a call, who may send and who hears whom.
|
|
6
|
+
|
|
7
|
+
## Turning them on
|
|
8
|
+
|
|
9
|
+
:::caution[In development]
|
|
10
|
+
Members join through a function of your own and the browser client. Call rows, a lobby, stage mode, recording, guests and the call UI are not built yet, and only Chrome has been tested.
|
|
11
|
+
:::
|
|
12
|
+
|
|
13
|
+
Calls carry audio and video between an app's users. The browser runs plain WebRTC and talks only to Protobase, which relays its offers, answers and candidates to the call's media plugin, inside the Protobase server: [LiveKit](#livekit), whose server carries the media, or [peer to peer](#peer-to-peer), where the browsers send it to each other. Either way the media never passes through Protobase, which decides who is in a call, who may send and who hears whom, and apps load no media library.
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
// protobase.config.ts
|
|
17
|
+
import { defineConfig } from '@protobase/config'
|
|
18
|
+
|
|
19
|
+
export default defineConfig(({ env }) => ({
|
|
20
|
+
calls: {
|
|
21
|
+
backend: { kind: 'livekit', url: env.LIVEKIT_URL!, apiKey: env.LIVEKIT_API_KEY!, apiSecret: env.LIVEKIT_API_SECRET! },
|
|
22
|
+
},
|
|
23
|
+
}))
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
- `url`: the LiveKit server, self-hosted or LiveKit Cloud, such as `wss://livekit.example.com`.
|
|
27
|
+
- `apiKey`, `apiSecret`: the key Protobase signs each member's LiveKit token with.
|
|
28
|
+
|
|
29
|
+
Or, with no media server, `backend: { kind: 'peer' }`, with `iceServers` for the STUN and TURN servers browsers reach each other through: `[{ urls: ['stun:stun.example.com:3478'] }]`.
|
|
30
|
+
|
|
31
|
+
Without `calls`, an app has none of it: the server loads no calls code, and only a page that imports `@protobase/client/calls` bundles the browser side.
|
|
32
|
+
|
|
33
|
+
Running LiveKit on your own machine: `bun run calls:up` in the Protobase repository starts one from `docker-compose.yml`, at `ws://127.0.0.1:7880` with the key `devkey` and the secret `secretsecretsecretsecretsecretsecret`.
|
|
34
|
+
|
|
35
|
+
## Admitting members
|
|
36
|
+
|
|
37
|
+
A member joins a call through an [API function](../guides/api-functions.md) of your own, which decides whether the caller may join, then answers with `acceptWebSocket(await calls.join(member))`:
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
// functions/meeting.ts
|
|
41
|
+
import { defineFunction } from '@protobase/server'
|
|
42
|
+
|
|
43
|
+
export default defineFunction(async (request, { session, records, acceptWebSocket, calls }) => {
|
|
44
|
+
const id = new URL(request.url).searchParams.get('call')!
|
|
45
|
+
// The caller's access to the meeting record decides whether they may join; a refusal is a problem, as in any function.
|
|
46
|
+
const meeting = await records.get('meetings', id)
|
|
47
|
+
return acceptWebSocket(
|
|
48
|
+
await calls.join({ call: id, member: String(session.user.id), publish: meeting.host === session.user.id ? true : ['microphone'] }),
|
|
49
|
+
)
|
|
50
|
+
})
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
| | |
|
|
54
|
+
| --- | --- |
|
|
55
|
+
| `call` | The call: members with the same `call` meet. |
|
|
56
|
+
| `member` | Who joins, unique in the call, such as the user's id. LiveKit knows the member by nothing else: no name, no metadata. |
|
|
57
|
+
| `publish` | `true` to send any source, a list of `'camera'`, `'microphone'`, `'screen'` and `'screen-audio'`, or `false` to only listen. |
|
|
58
|
+
| `hears` | Optional: which of the others' tracks the member hears, as `(track) => boolean` of `{ member, kind, source }`; every track by default. |
|
|
59
|
+
|
|
60
|
+
The socket is checked again every minute like any function's: a caller who would now be refused is closed out of the socket and leaves the call. The function's own checks, such as access to the meeting, are repeated only when it passes them as `recheck`.
|
|
61
|
+
|
|
62
|
+
## Joining from the browser
|
|
63
|
+
|
|
64
|
+
`joinCall` from `@protobase/client/calls` opens the function's socket, with the browser's session cookie, and resolves once the member is in the call:
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
import { joinCall } from '@protobase/client/calls'
|
|
68
|
+
|
|
69
|
+
const call = await joinCall({
|
|
70
|
+
url: `/api/functions/meeting?call=${id}`,
|
|
71
|
+
onTracks: (tracks) => render(tracks), // [{ sid, member, kind, source, muted, track? }]
|
|
72
|
+
onState: (state) => showState(state), // connecting, joined, resuming, or left with its reason
|
|
73
|
+
})
|
|
74
|
+
const media = await navigator.mediaDevices.getUserMedia({ video: true, audio: true })
|
|
75
|
+
await call.publish({ camera: media.getVideoTracks()[0], microphone: media.getAudioTracks()[0] }, { simulcast: true })
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
| | |
|
|
79
|
+
| --- | --- |
|
|
80
|
+
| `publish(tracks, { simulcast })` | Sends tracks under their sources; rejects when the member may not. With `simulcast` and LiveKit, video goes in three sizes. |
|
|
81
|
+
| `unpublish(source)` | Stops sending the source; the track itself goes on until the page stops it. |
|
|
82
|
+
| `mute(source, muted)` | Mutes or unmutes a sent track; the others see `muted` on it. |
|
|
83
|
+
| `view(sids, { width, height })` | With LiveKit: how large the page shows remote video, so it receives the size that fits; `'hidden'` receives none. |
|
|
84
|
+
| `restartIce()` | New network paths, such as after a network change; a failed connection restarts by itself. |
|
|
85
|
+
| `leave()` | Leaves the call. |
|
|
86
|
+
|
|
87
|
+
`onSpeakers` gets who speaks how loudly, and `onUnpublished` a source the media server stopped, such as after the member lost the right to send.
|
|
88
|
+
|
|
89
|
+
## Reconnecting
|
|
90
|
+
|
|
91
|
+
When the socket to Protobase closes, such as during a deploy, media keeps flowing and the browser opens a new socket that resumes the member from its own state. With LiveKit any process serving the app can take it; when LiveKit no longer knows the member, the browser joins again and sends the same tracks. After `maxRetries` tries in a row, 8 by default, the call is left.
|
|
92
|
+
|
|
93
|
+
## LiveKit
|
|
94
|
+
|
|
95
|
+
`kind: 'livekit'`. Protobase speaks LiveKit's signal protocol, version 17, on each member's behalf, over its single peer connection endpoint (`/rtc/v1`, LiveKit 1.9.1 and later), so media goes straight between the browser and LiveKit. Each member is a LiveKit participant of their own, which subscribes to nothing until Protobase lets them hear a track. LiveKit's data messages are not used: chat and reactions go over Protobase.
|
|
96
|
+
|
|
97
|
+
## Peer to peer
|
|
98
|
+
|
|
99
|
+
`kind: 'peer'`. Each member's browser keeps a peer connection to every other member's and sends them its media directly; Protobase passes their descriptions and candidates between them and tells each member who else is in the call and which tracks they hear. It suits small calls: a browser uploads its media once per other member. Members meet only on the same process, which keeps who is in each call, and a member whose socket was lost stays in the call for 30 seconds while their browser resumes. `hears` decides which tracks a member is told of; the media itself goes between the browsers, which Protobase cannot stop.
|
|
100
|
+
|
|
101
|
+
## Contract test
|
|
102
|
+
|
|
103
|
+
The repository's contract test runs members in Chromium through both plugins, against a real LiveKit server: `bun run calls:up`, then `bun run test:calls`. `LIVEKIT_IMAGE` in the environment of `calls:up` tries another LiveKit version.
|
|
@@ -160,6 +160,19 @@ How [Supabase Realtime](../supabase-realtime.md) is served. With `'one'`, one pr
|
|
|
160
160
|
export default defineConfig({ realtime: { processes: 'many' } })
|
|
161
161
|
```
|
|
162
162
|
|
|
163
|
+
## calls
|
|
164
|
+
|
|
165
|
+
- **Type:** `{ backend: { kind: 'livekit', url: string, apiKey: string, apiSecret: string } | { kind: 'peer', iceServers?: { urls: string[], username?: string, credential?: string }[] } }`
|
|
166
|
+
- **Default:** none: no calls
|
|
167
|
+
|
|
168
|
+
The media plugin that carries the audio and video of the calls API functions admit members to with `calls.join`: a LiveKit server, or the members' browsers peer to peer. Without it, `calls.join` rejects and the app loads no calls code. See [Calls](../calls.md).
|
|
169
|
+
|
|
170
|
+
```ts
|
|
171
|
+
export default defineConfig(({ env }) => ({
|
|
172
|
+
calls: { backend: { kind: 'livekit', url: env.LIVEKIT_URL!, apiKey: env.LIVEKIT_API_KEY!, apiSecret: env.LIVEKIT_API_SECRET! } },
|
|
173
|
+
}))
|
|
174
|
+
```
|
|
175
|
+
|
|
163
176
|
## Code of the API
|
|
164
177
|
|
|
165
178
|
Two files of the project's own change what the API does, each its default export, with no key in the config:
|
|
@@ -211,10 +211,10 @@ export default defineConfig({ auth: { accountDeletion: false } })
|
|
|
211
211
|
|
|
212
212
|
## auth.users
|
|
213
213
|
|
|
214
|
-
- **Type:** `{ table?: string; columns?: Record<string, string>; metadata?: string }`
|
|
214
|
+
- **Type:** `{ table?: string; columns?: Record<string, string>; metadata?: string; keyTable?: { schema: string; table: string } }`
|
|
215
215
|
- **Default:** the table `protobase auth migration` makes
|
|
216
216
|
|
|
217
|
-
The user table, when another system made it, such as Supabase's `auth.users`: its name, the columns named otherwise than Protobase names them, and a JSON column for each user's metadata. See [An existing users table](../auth.md#an-existing-users-table).
|
|
217
|
+
The user table, when another system made it, such as Supabase's `auth.users`: its name, the columns named otherwise than Protobase names them, and a JSON column for each user's metadata. See [An existing users table](../auth.md#an-existing-users-table). `keyTable` makes the user table a view of the app's own over another system's, the table it names, which holds the user ids: the store's migrations leave the view to the app and point their foreign keys at that table. See [A view over another system's users](../auth.md#a-view-over-another-systems-users).
|
|
218
218
|
|
|
219
219
|
```ts
|
|
220
220
|
export default defineConfig({
|
|
@@ -28,7 +28,7 @@ Each key is described with its type and default in the option pages:
|
|
|
28
28
|
| --- | --- |
|
|
29
29
|
| [App options](config/app.md) | `name`, `url`, `secret`, `previousSecrets`, `locale`, `timezone`, `themeColor`, `backgroundColor`, `mobile` |
|
|
30
30
|
| [Sign-in options](config/sign-in.md) | `auth`, `authenticate`, `signingKeyDays`, `signingKeyGraceDays` |
|
|
31
|
-
| [API options](config/api.md) | `apiPath`, `apiKeys`, `cors`, `defaultAccess`, `rowPermissions`, `statementTimeoutMs`, `scanGuard`, `errorReporting`, `writeHooks`, `mcpEndpoint`, `remoteResources`, `runtimeUpdates`, `realtime` |
|
|
31
|
+
| [API options](config/api.md) | `apiPath`, `apiKeys`, `cors`, `defaultAccess`, `rowPermissions`, `statementTimeoutMs`, `scanGuard`, `errorReporting`, `writeHooks`, `mcpEndpoint`, `remoteResources`, `runtimeUpdates`, `realtime`, `calls` |
|
|
32
32
|
| [Admin app options](config/admin-app.md) | `assistant`, `maps`, `plugins` |
|
|
33
33
|
| [Jobs and events options](config/jobs-and-events.md) | `jobs`, `events`, `history`, `webhooks`, `notifications` |
|
|
34
34
|
| [Files options](config/files.md) | `files` |
|