@protobase/cli 0.129.0 → 0.130.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/auth/config-organizations.js +15 -0
- package/dist/auth/register.js +8 -2
- package/dist/auth/write-migration.js +34 -12
- package/dist/cli/package.js +1 -1
- package/dist/config/build-project.js +1 -0
- package/dist/config/project-modules.js +64 -0
- package/dist/config/read-only-queries.js +9 -0
- package/dist/config/user-tables-config.js +1 -1
- package/dist/dev/dev-jobs.js +12 -6
- package/dist/dev/entry.js +12 -19
- package/dist/doctor/capture-files.js +3 -3
- package/dist/doctor/startup.js +2 -4
- package/dist/migration/apply-migrations.js +9 -6
- package/dist/migration/baseline/read-live-modules.js +31 -0
- package/dist/migration/baseline/read-live-store.js +50 -0
- package/dist/migration/baseline/write-baseline.js +80 -0
- package/dist/migration/migrate-project.js +3 -3
- package/dist/migration/migration-project.js +29 -15
- package/dist/migration/older-code/catalog.js +34 -0
- package/dist/migration/older-code/contractions.js +86 -0
- package/dist/migration/older-code/lint-files.js +55 -0
- package/dist/migration/older-code/refusal.js +9 -0
- package/dist/migration/older-code/trial.js +58 -0
- package/dist/migration/parts.js +8 -104
- package/dist/migration/record/after-file.js +20 -2
- package/dist/migration/register.js +56 -15
- package/dist/migration/release/release-record.js +9 -7
- package/dist/migration/release/release-steps.js +15 -3
- package/dist/migration/snapshot/auth-difference.js +111 -12
- package/dist/migration/snapshot/auth-target.js +9 -3
- package/dist/migration/snapshot/check.js +26 -9
- package/dist/migration/snapshot/custom.js +6 -3
- package/dist/migration/snapshot/drop.js +5 -1
- package/dist/migration/snapshot/header.js +11 -4
- package/dist/migration/snapshot/module-changes.js +22 -0
- package/dist/migration/snapshot/module-prompts.js +28 -0
- package/dist/migration/snapshot/module-sections.js +38 -0
- package/dist/migration/snapshot/next-snapshot.js +24 -8
- package/dist/migration/snapshot/off-choice.js +11 -0
- package/dist/migration/snapshot/organizations-off-facts.js +49 -0
- package/dist/migration/snapshot/revival-rows.js +34 -0
- package/dist/migration/snapshot/run-migration.js +82 -16
- package/dist/migration/snapshot/snapshot-file.js +7 -0
- package/dist/migration/snapshot/terminal-prompts.js +21 -0
- package/dist/migration/snapshot/write-file.js +1 -1
- package/dist/migration/summary.js +3 -2
- package/dist/organizations/api.js +4 -2
- package/dist/organizations/commands.js +27 -10
- package/dist/organizations/pin-source.js +20 -0
- package/dist/organizations/pin.js +40 -0
- package/dist/organizations/register.js +20 -12
- package/dist/scaffold/protobase-tables.js +2 -2
- package/dist/serve/create-admin.js +6 -3
- package/dist/serve/lifecycle.js +2 -2
- package/dist/serve/migrate-release.js +1 -1
- package/dist/serve/relay-check.js +7 -8
- package/dist/serve/startup-checks.js +12 -22
- package/dist/supabase/load-phase.js +3 -1
- package/dist/supabase/project-users.js +4 -1
- package/dist/users/commands.js +44 -6
- package/dist/users/load-auth.js +9 -3
- package/dist/users/manage.js +16 -1
- package/dist/users/register.js +28 -25
- package/dist/users/set-disabled.js +3 -2
- package/dist/users/users-api.js +9 -3
- package/dist/worker/start-worker.js +7 -4
- package/package.json +8 -8
- package/skills/protobase/references/features/api-functions.md +1 -0
- package/skills/protobase/references/features/build-and-run.md +3 -2
- package/skills/protobase/references/features/sign-in-and-accounts.md +2 -1
- package/skills/protobase/references/guides/api-functions.md +27 -2
- package/skills/protobase/references/guides/deploy.md +2 -2
- package/skills/protobase/references/reference/assistant.md +1 -1
- package/skills/protobase/references/reference/auth.md +52 -17
- package/skills/protobase/references/reference/calls.md +1 -1
- package/skills/protobase/references/reference/cli.md +41 -27
- package/skills/protobase/references/reference/comments.md +1 -1
- package/skills/protobase/references/reference/config/api.md +1 -1
- package/skills/protobase/references/reference/config/jobs-and-events.md +1 -1
- package/skills/protobase/references/reference/config/sign-in.md +22 -4
- package/skills/protobase/references/reference/config.md +1 -1
- package/skills/protobase/references/reference/data-config.md +9 -9
- package/skills/protobase/references/reference/derived.md +1 -1
- package/skills/protobase/references/reference/email.md +2 -2
- package/skills/protobase/references/reference/events.md +2 -2
- package/skills/protobase/references/reference/history.md +1 -1
- package/skills/protobase/references/reference/jobs.md +5 -5
- package/skills/protobase/references/reference/live.md +2 -2
- package/skills/protobase/references/reference/notifications.md +4 -4
- package/skills/protobase/references/reference/personal-access-tokens.md +2 -2
- package/skills/protobase/references/reference/realtime-relay.md +1 -1
- package/skills/protobase/references/reference/status.md +2 -2
- package/skills/protobase/references/reference/supabase-rest.md +1 -1
- package/skills/protobase/references/reference/user-tables.md +1 -1
- package/skills/protobase/references/reference/webhooks.md +1 -1
- package/dist/migration/snapshot/lint-custom.js +0 -23
|
@@ -1,51 +1,117 @@
|
|
|
1
|
+
import { organizationsNow } from "./auth-target.js";
|
|
2
|
+
import { moduleChanges } from "./module-changes.js";
|
|
1
3
|
import { readSnapshot, snapshotFile } from "./snapshot-file.js";
|
|
2
4
|
import { authDifference } from "./auth-difference.js";
|
|
3
5
|
import { readMigrationFiles } from "./migration-files.js";
|
|
4
6
|
import { refuseInconsistent } from "./consistency.js";
|
|
5
7
|
import { authMigrationTitle } from "../../auth/migration-file.js";
|
|
6
8
|
import { writeMigrationFile } from "./write-file.js";
|
|
9
|
+
import { defaultChosen, revivalRefused } from "./module-prompts.js";
|
|
10
|
+
import { organizationsOffFacts } from "./organizations-off-facts.js";
|
|
11
|
+
import { revivedRows } from "./revival-rows.js";
|
|
12
|
+
import { breaksOlderCodeNote, olderCodeRefusal } from "../older-code/refusal.js";
|
|
13
|
+
import { moduleSections } from "./module-sections.js";
|
|
7
14
|
import { runPreconditions } from "./preconditions.js";
|
|
15
|
+
import { schemaModules } from "@protobase/server/internal";
|
|
8
16
|
//#region src/migration/snapshot/run-migration.ts
|
|
17
|
+
const checkRevivals = async (url, run, revived) => {
|
|
18
|
+
if (revived.length === 0 || run.force) return;
|
|
19
|
+
for (const rows of await revivedRows(url, run.auth.names, revived)) if (!(run.confirmRevival && await run.confirmRevival(rows))) throw new Error(revivalRefused(rows));
|
|
20
|
+
};
|
|
21
|
+
const refuseUnrecorded = async (read, snapshot, sections, targets) => {
|
|
22
|
+
for (const { name } of sections) {
|
|
23
|
+
if (snapshot?.model.modules?.[name] || !await read(name, targets[name])) continue;
|
|
24
|
+
throw new Error(`The database has ${schemaModules[name].label}, which ${snapshotFile} does not record: describe it with \`protobase migration baseline\`, run against the database with the project's migrations applied, then run \`protobase migration\` again`);
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
const offFacts = async (run, turnedOff) => {
|
|
28
|
+
const defaultId = run.auth?.organizations?.default.id;
|
|
29
|
+
if (!run.database || defaultId === void 0 || !turnedOff.some(({ module }) => module === "organizations")) return;
|
|
30
|
+
const facts = await organizationsOffFacts(run.database.url, run.auth.names, defaultId);
|
|
31
|
+
if (facts.only && run.offerDefault && await run.offerDefault(facts.only)) throw new Error(defaultChosen(facts.only));
|
|
32
|
+
return facts;
|
|
33
|
+
};
|
|
9
34
|
const section = (title, sql) => `-- ${title}.\n${sql}\n`;
|
|
10
35
|
/** The line `protobase migration`'s files open with, under their header. */
|
|
11
36
|
const intro = `-- Written by \`protobase migration\` from the config and ${snapshotFile}; applied with the project's other migrations.\n`;
|
|
12
37
|
/**
|
|
13
38
|
* `protobase migration`: writes what the config needs as the project's next migration, one file, and rewrites the
|
|
14
|
-
* snapshot to end at it. The auth store's steps come from the snapshot alone; with a database,
|
|
15
|
-
* its rows, and the other parts are compared with it. Every part is compared before anything is written. Returns the
|
|
39
|
+
* snapshot to end at it. The auth store's steps and the schema modules' come from the snapshot alone; with a database,
|
|
40
|
+
* the steps' checks run against its rows, and the other parts are compared with it. Every part is compared before anything is written. Returns the
|
|
16
41
|
* file's path, `undefined` when nothing differs.
|
|
17
42
|
*/
|
|
18
|
-
const runMigration = async (
|
|
43
|
+
const runMigration = async (run) => {
|
|
44
|
+
const { projectDir, dir, auth, modules, database, protobaseVersion, newId } = run;
|
|
19
45
|
const snapshot = await readSnapshot(projectDir);
|
|
20
46
|
const files = await readMigrationFiles(dir);
|
|
21
47
|
refuseInconsistent(snapshot, files);
|
|
22
|
-
if (!snapshot && auth && files.some(({ text }) => text.includes("The auth schema changes this version of Protobase needs"))) throw new Error(`The project has auth migrations from before ${snapshotFile}: start it with \`protobase
|
|
23
|
-
const
|
|
48
|
+
if (!snapshot && auth && files.some(({ text }) => text.includes("The auth schema changes this version of Protobase needs"))) throw new Error(`The project has auth migrations from before ${snapshotFile}: start it with \`protobase migration baseline\`, run against the database with the project's migrations applied, then run \`protobase migration\` again`);
|
|
49
|
+
const { off: turnedOff } = moduleChanges(snapshot, auth);
|
|
50
|
+
const off = run.off ?? (turnedOff.length > 0 && run.chooseOff ? await run.chooseOff(turnedOff, await offFacts(run, turnedOff)) : void 0);
|
|
51
|
+
const difference = authDifference(snapshot, auth, off);
|
|
52
|
+
if (database) await checkRevivals(database.url, run, difference.changes.revived);
|
|
24
53
|
if (database && difference.migration && difference.migration.checks.length > 0) await runPreconditions(database.url, difference.migration.checks);
|
|
54
|
+
const written = moduleSections(snapshot, modules);
|
|
55
|
+
if (database) await refuseUnrecorded(database.readModule, snapshot, written.sections, modules);
|
|
25
56
|
const compared = [];
|
|
26
57
|
for (const part of database?.parts ?? []) {
|
|
27
|
-
const sql = await part.sql(
|
|
58
|
+
const sql = await part.sql();
|
|
28
59
|
if (sql !== void 0) compared.push({
|
|
29
60
|
name: part.name,
|
|
30
61
|
text: section(part.title, sql)
|
|
31
62
|
});
|
|
32
63
|
}
|
|
33
|
-
const sections = [
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
64
|
+
const sections = [
|
|
65
|
+
...difference.migration ? [{
|
|
66
|
+
name: "auth",
|
|
67
|
+
text: section(authMigrationTitle, difference.migration.sql)
|
|
68
|
+
}] : [],
|
|
69
|
+
...written.sections.map(({ name, title, sql }) => ({
|
|
70
|
+
name,
|
|
71
|
+
text: section(title, sql)
|
|
72
|
+
})),
|
|
73
|
+
...compared
|
|
74
|
+
];
|
|
37
75
|
if (sections.length === 0) return;
|
|
76
|
+
const own = /* @__PURE__ */ new Set(["auth", ...written.sections.map(({ name }) => name)]);
|
|
77
|
+
const found = database ? await database.contractions(sections) : [];
|
|
78
|
+
const refused = found.filter(({ name }) => !own.has(name));
|
|
79
|
+
if (refused.length > 0) throw new Error(olderCodeRefusal(refused));
|
|
80
|
+
const label = (name) => name === "auth" ? "The sign-in modules' steps" : schemaModules[name].title;
|
|
81
|
+
const breaking = [...found.flatMap(({ name, found: lines }) => lines.map((line) => `${label(name)}: ${line}`)), ...written.sections.flatMap(({ title, breaks }) => breaks.map((line) => `${title}: ${line}`))];
|
|
82
|
+
const afterParts = [...difference.migration?.after ? [difference.migration.after.trimEnd()] : [], ...written.sections.flatMap(({ title, after }) => after === void 0 ? [] : [section(title, after).trimEnd()])];
|
|
83
|
+
const after = afterParts.length > 0 ? `${afterParts.join("\n\n")}\n` : void 0;
|
|
38
84
|
const content = {
|
|
39
85
|
name: sections.map(({ name }) => name).join("_"),
|
|
40
|
-
body: [
|
|
41
|
-
|
|
86
|
+
body: [
|
|
87
|
+
intro,
|
|
88
|
+
...breaking.length > 0 ? [breaksOlderCodeNote(breaking)] : [],
|
|
89
|
+
...sections.map(({ text }) => text)
|
|
90
|
+
].join("\n"),
|
|
91
|
+
additive: breaking.length === 0,
|
|
92
|
+
...breaking.length > 0 && { kind: {
|
|
93
|
+
custom: false,
|
|
94
|
+
additive: false,
|
|
95
|
+
breaksOlderCode: true
|
|
96
|
+
} },
|
|
97
|
+
...after && { after }
|
|
98
|
+
};
|
|
99
|
+
const decisions = snapshot && {
|
|
100
|
+
...snapshot.decisions,
|
|
101
|
+
modules: {
|
|
102
|
+
...snapshot.decisions.modules,
|
|
103
|
+
kept: difference.kept
|
|
104
|
+
}
|
|
42
105
|
};
|
|
43
|
-
|
|
106
|
+
const draft = {
|
|
44
107
|
previous: snapshot,
|
|
45
108
|
auth: difference.model,
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
109
|
+
modules: written.model,
|
|
110
|
+
organizations: organizationsNow(auth),
|
|
111
|
+
protobaseVersion,
|
|
112
|
+
...decisions && { decisions }
|
|
113
|
+
};
|
|
114
|
+
return writeMigrationFile(projectDir, dir, content, draft, newId());
|
|
49
115
|
};
|
|
50
116
|
//#endregion
|
|
51
117
|
export { intro, runMigration };
|
|
@@ -21,11 +21,18 @@ const checkFormat = (format) => {
|
|
|
21
21
|
if (format > 1) throw new Error(`${snapshotFile} is format ${format}, which a newer Protobase wrote; this one reads format 1: upgrade Protobase`);
|
|
22
22
|
if (format < 1) throw new Error(`${snapshotFile} is format ${format}; this Protobase reads format 1: run \`protobase migration up\``);
|
|
23
23
|
};
|
|
24
|
+
/** Refuses kept modules recorded without their step and tables, which `protobase migration baseline` writes again. */
|
|
25
|
+
const checkKept = (snapshot) => {
|
|
26
|
+
const named = snapshot.decisions.modules.kept.filter((kept) => typeof kept !== "object" || kept === null || typeof kept.step !== "number" || typeof kept.tables !== "object");
|
|
27
|
+
if (named.length === 0) return;
|
|
28
|
+
throw new Error(`${snapshotFile} keeps ${named.map(String).join(", ")} without the step and tables it had: start the snapshot again with \`protobase migration baseline\``);
|
|
29
|
+
};
|
|
24
30
|
/** The project's snapshot; `undefined` when it has none. */
|
|
25
31
|
const readSnapshot = async (projectDir) => {
|
|
26
32
|
const json = await readSnapshotJson(projectDir);
|
|
27
33
|
if (!json) return;
|
|
28
34
|
checkFormat(json.format);
|
|
35
|
+
checkKept(json);
|
|
29
36
|
return json;
|
|
30
37
|
};
|
|
31
38
|
const writeSnapshot = (projectDir, snapshot) => writeFile(path.join(projectDir, snapshotFile), snapshotText(snapshot));
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { chooseOff, confirmRevival, offerDefault } from "./module-prompts.js";
|
|
2
|
+
import { createInterface } from "node:readline/promises";
|
|
3
|
+
//#region src/migration/snapshot/terminal-prompts.ts
|
|
4
|
+
/** The questions of `protobase migration` asked on the terminal, and what closes it once answered. */
|
|
5
|
+
const terminalPrompts = () => {
|
|
6
|
+
const rl = createInterface({
|
|
7
|
+
input: process.stdin,
|
|
8
|
+
output: process.stdout
|
|
9
|
+
});
|
|
10
|
+
const ask = (question) => rl.question(question);
|
|
11
|
+
return {
|
|
12
|
+
prompts: {
|
|
13
|
+
chooseOff: chooseOff(ask),
|
|
14
|
+
confirmRevival: confirmRevival(ask),
|
|
15
|
+
offerDefault: offerDefault(ask)
|
|
16
|
+
},
|
|
17
|
+
close: () => rl.close()
|
|
18
|
+
};
|
|
19
|
+
};
|
|
20
|
+
//#endregion
|
|
21
|
+
export { terminalPrompts };
|
|
@@ -14,7 +14,7 @@ import { mkdir, readdir, writeFile } from "node:fs/promises";
|
|
|
14
14
|
const writeMigrationFile = async (projectDir, dir, content, draft, id) => {
|
|
15
15
|
await mkdir(dir, { recursive: true });
|
|
16
16
|
const file = nextMigrationName(await readdir(dir), content.name);
|
|
17
|
-
const snapshot = nextSnapshot(draft.previous, draft.auth, draft.
|
|
17
|
+
const snapshot = nextSnapshot(draft.decisions ?? draft.previous?.decisions, draft.auth, draft.modules, draft.organizations, {
|
|
18
18
|
file,
|
|
19
19
|
id
|
|
20
20
|
}, draft.protobaseVersion);
|
|
@@ -5,11 +5,12 @@ import path from "node:path";
|
|
|
5
5
|
const signInGuide = "https://docs.protobase.net/guides/existing-database/";
|
|
6
6
|
/**
|
|
7
7
|
* What `protobase migration` prints: the file it wrote, relative to `cwd`, or that the migrations already make what
|
|
8
|
-
* the config needs. Without a database (`compared` false), the features besides the auth store
|
|
8
|
+
* the config needs. Without a database (`compared` false), the features besides the auth store and the schema modules,
|
|
9
|
+
* which the snapshot holds, were not compared. A
|
|
9
10
|
* config with sign-in off (`auth: false`) has no auth store, so the migrations being current says nothing about it.
|
|
10
11
|
*/
|
|
11
12
|
const migrationSummary = (file, cwd, { hasAuth, compared }) => {
|
|
12
|
-
return `${file ? `wrote ${path.relative(cwd, file)} and ${snapshotFile}\napply it with the project's migrations\n` : "the migrations make what the config needs; nothing to write\n"}${compared ? "" : "DATABASE_URL is not set, so only the auth store
|
|
13
|
+
return `${file ? `wrote ${path.relative(cwd, file)} and ${snapshotFile}\napply it with the project's migrations\n` : "the migrations make what the config needs; nothing to write\n"}${compared ? "" : "DATABASE_URL is not set, so only the auth store and the jobs schema were compared, with the snapshot: set it to compare the other features with the database\n"}${hasAuth ? "" : `sign-in is off, so nothing was written for it: see ${signInGuide}\n`}`;
|
|
13
14
|
};
|
|
14
15
|
//#endregion
|
|
15
16
|
export { migrationSummary, signInGuide };
|
|
@@ -1,12 +1,14 @@
|
|
|
1
|
+
import { pinSource } from "./pin-source.js";
|
|
1
2
|
import { addAppRoleToOwners, addEveryUser, addMember, createOrganization, listOrganizations, removeMember, setMemberRoles } from "@protobase/server";
|
|
2
3
|
//#region src/organizations/api.ts
|
|
3
4
|
const organizationsApi = (auth) => ({
|
|
4
|
-
|
|
5
|
+
...pinSource(auth),
|
|
6
|
+
listOrganizations: (scope, after) => listOrganizations(auth, scope, after && { after }),
|
|
5
7
|
createOrganization: (input) => createOrganization(auth, input),
|
|
6
8
|
addMember: (input) => addMember(auth, input),
|
|
7
9
|
setMemberRoles: (input) => setMemberRoles(auth, input),
|
|
8
10
|
removeMember: (input) => removeMember(auth, input),
|
|
9
|
-
addAppRoleToOwners: (appRole) => addAppRoleToOwners(auth, appRole),
|
|
11
|
+
addAppRoleToOwners: (scope, appRole) => addAppRoleToOwners(auth, scope, appRole),
|
|
10
12
|
addEveryUser: (organization) => addEveryUser(auth, organization)
|
|
11
13
|
});
|
|
12
14
|
//#endregion
|
|
@@ -1,10 +1,14 @@
|
|
|
1
|
+
import { pinLine, resolvePin, scopeOf } from "./pin.js";
|
|
2
|
+
import { everyOrganization } from "@protobase/query";
|
|
1
3
|
//#region src/organizations/commands.ts
|
|
2
4
|
/** A slug from a name: lowercase ASCII words joined by dashes; diacritics are dropped, so Müller becomes muller. */
|
|
3
5
|
const slugOf = (name) => name.normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 63);
|
|
4
6
|
/** `a,b` as a list of roles; an empty text is none. */
|
|
5
7
|
const parseRoleList = (text) => text === void 0 ? void 0 : text.split(",").map((name) => name.trim()).filter(Boolean);
|
|
6
|
-
const listOrganizationsCommand = async (api, out) => {
|
|
7
|
-
|
|
8
|
+
const listOrganizationsCommand = async (api, options, out) => {
|
|
9
|
+
const pin = await resolvePin(api, options, "organizations list", () => everyOrganization("protobase organizations list: --all-organizations"));
|
|
10
|
+
out(pinLine(pin));
|
|
11
|
+
let page = await api.listOrganizations(scopeOf(pin));
|
|
8
12
|
if (page.organizations.length === 0) {
|
|
9
13
|
out("No organizations yet. Create one with: protobase organizations create \"Acme\" --owner you@example.com\n");
|
|
10
14
|
return;
|
|
@@ -15,7 +19,7 @@ const listOrganizationsCommand = async (api, out) => {
|
|
|
15
19
|
for (const member of organization.members) out(` ${member.email} ${member.role}${member.appRoles.length > 0 ? ` ${member.appRoles.join(",")}` : ""}\n`);
|
|
16
20
|
}
|
|
17
21
|
if (!page.next) return;
|
|
18
|
-
page = await api.listOrganizations(page.next);
|
|
22
|
+
page = await api.listOrganizations(scopeOf(pin), page.next);
|
|
19
23
|
}
|
|
20
24
|
};
|
|
21
25
|
/**
|
|
@@ -37,34 +41,47 @@ const createOrganizationCommand = async (api, options, out) => {
|
|
|
37
41
|
for (const user of await api.addEveryUser(organization.id)) if (user.role === "owner") out(` ${user.email}: owner, with every app role\n`);
|
|
38
42
|
else out(` ${user.email}: member${user.appRoles.length > 0 ? `, with ${user.appRoles.join(",")}` : ""}\n`);
|
|
39
43
|
};
|
|
44
|
+
const memberPin = async (api, options, command) => {
|
|
45
|
+
const pin = await resolvePin(api, options, command);
|
|
46
|
+
if ("every" in pin) throw new Error(`protobase ${command} acts on one organization`);
|
|
47
|
+
return pin.organization;
|
|
48
|
+
};
|
|
40
49
|
const addMemberCommand = async (api, options, out) => {
|
|
41
50
|
const appRoles = parseRoleList(options.appRoles);
|
|
51
|
+
const organization = await memberPin(api, options, "organizations add-member");
|
|
42
52
|
await api.addMember({
|
|
43
|
-
organization:
|
|
53
|
+
organization: organization.id,
|
|
44
54
|
email: options.email,
|
|
45
55
|
...options.orgRole && { role: options.orgRole },
|
|
46
56
|
...appRoles && { appRoles }
|
|
47
57
|
});
|
|
48
|
-
out(`Added ${options.email} to ${
|
|
58
|
+
out(`Added ${options.email} to ${organization.slug}\n`);
|
|
49
59
|
};
|
|
50
60
|
const setMemberRolesCommand = async (api, options, out) => {
|
|
51
61
|
const appRoles = parseRoleList(options.appRoles);
|
|
52
62
|
if (options.orgRole === void 0 && appRoles === void 0) throw new Error("Pass --org-role, --app-roles or both");
|
|
63
|
+
const organization = await memberPin(api, options, "organizations set-roles");
|
|
53
64
|
await api.setMemberRoles({
|
|
54
|
-
organization:
|
|
65
|
+
organization: organization.id,
|
|
55
66
|
email: options.email,
|
|
56
67
|
...options.orgRole && { role: options.orgRole },
|
|
57
68
|
...appRoles && { appRoles }
|
|
58
69
|
});
|
|
59
|
-
out(`Changed the roles of ${options.email} in ${
|
|
70
|
+
out(`Changed the roles of ${options.email} in ${organization.slug}\n`);
|
|
60
71
|
};
|
|
61
72
|
const removeMemberCommand = async (api, options, out) => {
|
|
62
|
-
await api
|
|
63
|
-
|
|
73
|
+
const organization = await memberPin(api, options, "organizations remove-member");
|
|
74
|
+
await api.removeMember({
|
|
75
|
+
organization: organization.id,
|
|
76
|
+
email: options.email
|
|
77
|
+
});
|
|
78
|
+
out(`Removed ${options.email} from ${organization.slug}\n`);
|
|
64
79
|
};
|
|
65
80
|
const addAppRoleCommand = async (api, options, out) => {
|
|
66
81
|
if (options.to !== "owners") throw new Error(`--to takes "owners", not "${options.to}"`);
|
|
67
|
-
const
|
|
82
|
+
const pin = await resolvePin(api, options, "organizations add-app-role", () => everyOrganization("protobase organizations add-app-role: --all-organizations"));
|
|
83
|
+
out(pinLine(pin));
|
|
84
|
+
const changed = await api.addAppRoleToOwners(scopeOf(pin), options.role);
|
|
68
85
|
out(`Gave ${options.role} to ${changed} owner${changed === 1 ? "" : "s"}\n`);
|
|
69
86
|
};
|
|
70
87
|
//#endregion
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { isMemberByEmail, organizationByKey } from "@protobase/server";
|
|
2
|
+
//#region src/organizations/pin-source.ts
|
|
3
|
+
const pinSource = (auth) => {
|
|
4
|
+
const pinned = auth.organizations?.options.default;
|
|
5
|
+
return {
|
|
6
|
+
organizationsOn: auth.organizations !== void 0,
|
|
7
|
+
...pinned && { defaultOrganization: pinned },
|
|
8
|
+
organizationByKey: async (key) => {
|
|
9
|
+
const found = await organizationByKey(auth, key);
|
|
10
|
+
return found && {
|
|
11
|
+
id: found.id,
|
|
12
|
+
slug: found.slug,
|
|
13
|
+
name: found.name
|
|
14
|
+
};
|
|
15
|
+
},
|
|
16
|
+
isMember: (organizationId, email) => isMemberByEmail(auth, organizationId, email)
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
//#endregion
|
|
20
|
+
export { pinSource };
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
//#region src/organizations/pin.ts
|
|
2
|
+
/**
|
|
3
|
+
* The pin of a command named `command` with organizations on. `wide` is the command's reviewed way out, as
|
|
4
|
+
* `everyOrganization('<command>: --all-organizations')`; a command without one refuses `--all-organizations`.
|
|
5
|
+
*/
|
|
6
|
+
const resolvePin = async (source, options, command, wide) => {
|
|
7
|
+
if (!source.organizationsOn) throw new Error(`protobase ${command} needs organizations: turn on auth.organizations in the config`);
|
|
8
|
+
if (options.allOrganizations && options.organization !== void 0) throw new Error("Pass --organization or --all-organizations, not both");
|
|
9
|
+
if (options.allOrganizations) {
|
|
10
|
+
if (!wide) throw new Error(`protobase ${command} acts on one organization: pass --organization <slug> instead of --all-organizations`);
|
|
11
|
+
return { every: wide() };
|
|
12
|
+
}
|
|
13
|
+
if (options.organization !== void 0) {
|
|
14
|
+
const found = await source.organizationByKey(options.organization);
|
|
15
|
+
if (!found) throw new Error(`No organization "${options.organization}"`);
|
|
16
|
+
return { organization: found };
|
|
17
|
+
}
|
|
18
|
+
const pinned = source.defaultOrganization;
|
|
19
|
+
if (!pinned) throw new Error("No organization is pinned: set auth.organizations.default in the config, or pass --organization <slug> or --all-organizations");
|
|
20
|
+
const found = await source.organizationByKey(pinned.id);
|
|
21
|
+
if (!found) throw new Error(`The config's auth.organizations.default names organization "${pinned.slug}" (${pinned.id}), which the database does not have: pass --organization <slug> or --all-organizations`);
|
|
22
|
+
return { organization: found };
|
|
23
|
+
};
|
|
24
|
+
/** The pin of a command that works without organizations too: none while they are off, which refuses the pin's flags. */
|
|
25
|
+
const resolveOptionalPin = async (source, options, command, wide) => {
|
|
26
|
+
if (source.organizationsOn) return resolvePin(source, options, command, wide);
|
|
27
|
+
if (options.organization !== void 0 || options.allOrganizations) throw new Error("--organization and --all-organizations need organizations: turn on auth.organizations in the config");
|
|
28
|
+
};
|
|
29
|
+
/** What the scope of `@protobase/server`'s host functions takes: the organization's id, or every organization. */
|
|
30
|
+
const scopeOf = (pin) => "every" in pin ? pin.every : pin.organization.id;
|
|
31
|
+
/** The line a command prints first, naming what it acts on. */
|
|
32
|
+
const pinLine = (pin) => "every" in pin ? "Every organization\n" : `Organization: ${pin.organization.slug} (${pin.organization.name})\n`;
|
|
33
|
+
/** Refuses a user outside the pinned organization, for a command that changes their whole account. */
|
|
34
|
+
const checkPinnedUser = async (source, pin, email) => {
|
|
35
|
+
if ("every" in pin) return;
|
|
36
|
+
if (await source.isMember(pin.organization.id, email)) return;
|
|
37
|
+
throw new Error(`${email} is not a member of ${pin.organization.slug}: pass --organization <slug> for theirs, or --all-organizations to reach any user`);
|
|
38
|
+
};
|
|
39
|
+
//#endregion
|
|
40
|
+
export { checkPinnedUser, pinLine, resolveOptionalPin, resolvePin, scopeOf };
|
|
@@ -5,12 +5,18 @@ const projectApi = async () => {
|
|
|
5
5
|
return organizationsApi(await loadProjectAuth(process.cwd()));
|
|
6
6
|
};
|
|
7
7
|
const finish = (code) => process.exit(code);
|
|
8
|
-
const
|
|
8
|
+
const organizationOption = (command) => command.option("--organization <organization>", "its slug or id (default: auth.organizations.default of the config)");
|
|
9
|
+
/** `--organization`, and `--all-organizations` for a command that can reach every organization. */
|
|
10
|
+
const pinOptions = (command) => organizationOption(command).option("--all-organizations", "act on every organization", false);
|
|
11
|
+
const memberOptions = (command) => organizationOption(command).argument("<email>").option("--org-role <role>", "owner, admin or member: who manages the organization").option("--app-roles <roles>", "app roles in this organization, comma separated (see `users roles`)");
|
|
9
12
|
const registerOrganizations = (program) => {
|
|
10
13
|
const organizations = program.command("organizations").description("Manage the organizations of the project in the current directory (with `auth.organizations` in protobase.config.ts)");
|
|
11
|
-
organizations.command("list").description("List
|
|
14
|
+
pinOptions(organizations.command("list").description("List the organization with its members and roles")).action(async (opts) => {
|
|
12
15
|
const { listOrganizationsCommand } = await import("./commands.js");
|
|
13
|
-
await listOrganizationsCommand(await projectApi(),
|
|
16
|
+
await listOrganizationsCommand(await projectApi(), {
|
|
17
|
+
organization: opts.organization,
|
|
18
|
+
allOrganizations: opts.allOrganizations
|
|
19
|
+
}, out);
|
|
14
20
|
finish(0);
|
|
15
21
|
});
|
|
16
22
|
organizations.command("create").description("Create an organization; its owner holds every app role").argument("<name>").requiredOption("--owner <email>", "the user who owns it").option("--slug <slug>", "default: from the name").option("--id <id>", "keep an existing tenant value, for an app that ran as one organization").option("--members <all>", "\"all\": every other user joins; their global roles move here, superusers become owners").action(async (name, opts) => {
|
|
@@ -24,42 +30,44 @@ const registerOrganizations = (program) => {
|
|
|
24
30
|
}, out);
|
|
25
31
|
finish(0);
|
|
26
32
|
});
|
|
27
|
-
memberOptions(organizations.command("add-member").description("Add a user to
|
|
33
|
+
memberOptions(organizations.command("add-member").description("Add a user to the organization (organization role member unless given)")).action(async (email, opts) => {
|
|
28
34
|
const { addMemberCommand } = await import("./commands.js");
|
|
29
35
|
await addMemberCommand(await projectApi(), {
|
|
30
|
-
organization,
|
|
36
|
+
organization: opts.organization,
|
|
31
37
|
email,
|
|
32
38
|
orgRole: opts.orgRole,
|
|
33
39
|
appRoles: opts.appRoles
|
|
34
40
|
}, out);
|
|
35
41
|
finish(0);
|
|
36
42
|
});
|
|
37
|
-
memberOptions(organizations.command("set-roles").description("Change a member's organization role, app roles, or both")).action(async (
|
|
43
|
+
memberOptions(organizations.command("set-roles").description("Change a member's organization role, app roles, or both")).action(async (email, opts) => {
|
|
38
44
|
const { setMemberRolesCommand } = await import("./commands.js");
|
|
39
45
|
await setMemberRolesCommand(await projectApi(), {
|
|
40
|
-
organization,
|
|
46
|
+
organization: opts.organization,
|
|
41
47
|
email,
|
|
42
48
|
orgRole: opts.orgRole,
|
|
43
49
|
appRoles: opts.appRoles
|
|
44
50
|
}, out);
|
|
45
51
|
finish(0);
|
|
46
52
|
});
|
|
47
|
-
organizations.command("remove-member").description("Remove a member (refuses the last owner)")
|
|
53
|
+
organizationOption(organizations.command("remove-member").description("Remove a member (refuses the last owner)")).argument("<email>").action(async (email, opts) => {
|
|
48
54
|
const { removeMemberCommand } = await import("./commands.js");
|
|
49
55
|
await removeMemberCommand(await projectApi(), {
|
|
50
|
-
organization,
|
|
56
|
+
organization: opts.organization,
|
|
51
57
|
email
|
|
52
58
|
}, out);
|
|
53
59
|
finish(0);
|
|
54
60
|
});
|
|
55
|
-
organizations.command("add-app-role").description("Give an app role to
|
|
61
|
+
pinOptions(organizations.command("add-app-role").description("Give an app role to the organization's owners, for a role added after they were made")).argument("<role>").requiredOption("--to <owners>", "\"owners\"").action(async (role, opts) => {
|
|
56
62
|
const { addAppRoleCommand } = await import("./commands.js");
|
|
57
63
|
await addAppRoleCommand(await projectApi(), {
|
|
58
64
|
role,
|
|
59
|
-
to: opts.to
|
|
65
|
+
to: opts.to,
|
|
66
|
+
organization: opts.organization,
|
|
67
|
+
allOrganizations: opts.allOrganizations
|
|
60
68
|
}, out);
|
|
61
69
|
finish(0);
|
|
62
70
|
});
|
|
63
71
|
};
|
|
64
72
|
//#endregion
|
|
65
|
-
export { registerOrganizations };
|
|
73
|
+
export { pinOptions, registerOrganizations };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { tableKey } from "../db/model.js";
|
|
2
|
-
import {
|
|
2
|
+
import { storeRecordNames, storeTableNames } from "@protobase/server/auth-store";
|
|
3
3
|
import { definitionsSchema, userTablesSchema } from "@protobase/server/config-exports";
|
|
4
4
|
//#region src/scaffold/protobase-tables.ts
|
|
5
5
|
const storeCore = [
|
|
@@ -17,7 +17,7 @@ const authStore = (schema, tables) => {
|
|
|
17
17
|
if (schema === "auth") return tables;
|
|
18
18
|
const has = (name) => tables.some((table) => table.name === name);
|
|
19
19
|
const user = userTableOf(schema, tables);
|
|
20
|
-
if (!has
|
|
20
|
+
if (!storeRecordNames.some(has) && !(storeCore.every(has) && user !== void 0)) return [];
|
|
21
21
|
if (schema !== "public") return tables;
|
|
22
22
|
return tables.filter((table) => storeTableNames.includes(table.name) || table.name === user);
|
|
23
23
|
};
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { protobaseVersion } from "../version/version.js";
|
|
2
|
-
import {
|
|
2
|
+
import { buildProject } from "../config/build-project.js";
|
|
3
|
+
import { builtRuntimeModel } from "../config/project-modules.js";
|
|
3
4
|
import { openAppDatabase } from "../project/pg-db.js";
|
|
4
5
|
import { readHidden } from "../users/password.js";
|
|
5
6
|
import { createUserCommand } from "../users/commands.js";
|
|
@@ -16,8 +17,10 @@ const createAdminInBundle = async (bundle, email, options, out) => {
|
|
|
16
17
|
const config = await loadBundle(file);
|
|
17
18
|
if (!config.auth) throw new Error("Sign-in is off in the bundle's config (`auth: false`), so the app has no users to manage");
|
|
18
19
|
if (!process.env.DATABASE_URL) throw new Error("No database: set DATABASE_URL");
|
|
19
|
-
const
|
|
20
|
-
await
|
|
20
|
+
const database = openAppDatabase(pg, process.env.DATABASE_URL);
|
|
21
|
+
const project = await buildProject(config, database);
|
|
22
|
+
await checkMigrationRecord(database.db, builtRuntimeModel(project), protobaseVersion);
|
|
23
|
+
const auth = project.auth;
|
|
21
24
|
await createUserCommand(usersApi(auth), {
|
|
22
25
|
email,
|
|
23
26
|
role: "admin",
|
package/dist/serve/lifecycle.js
CHANGED
|
@@ -11,7 +11,7 @@ import { checkStartup } from "./startup-checks.js";
|
|
|
11
11
|
import { closeSockets } from "./close-sockets.js";
|
|
12
12
|
import { servedRelease } from "./mobile-release.js";
|
|
13
13
|
import pg from "pg";
|
|
14
|
-
import { backgroundSettled, checkAi,
|
|
14
|
+
import { backgroundSettled, checkAi, configExports, createFileCleanup, startJobs } from "@protobase/server";
|
|
15
15
|
import { createAdaptorServer, upgradeWebSocket } from "@hono/node-server";
|
|
16
16
|
//#region src/serve/lifecycle.ts
|
|
17
17
|
const listen = (server, port, host) => new Promise((resolve, reject) => {
|
|
@@ -38,9 +38,9 @@ const startServe = async ({ config, env, openDb = (url) => openAppDatabase(pg, u
|
|
|
38
38
|
env: process.env
|
|
39
39
|
});
|
|
40
40
|
const { admin, jobs: definitions } = await servedAdmin(project, db, ui, reporter, upgradeWebSocket);
|
|
41
|
-
if (env.startupChecks && definitions.length > 0) await checkJobsSchema(db);
|
|
42
41
|
const jobs = definitions.length > 0 ? await startJobs({
|
|
43
42
|
db,
|
|
43
|
+
scope: await admin.organizationScope(),
|
|
44
44
|
jobs: definitions,
|
|
45
45
|
work: env.runJobs,
|
|
46
46
|
decryptField: admin.decryptField,
|
|
@@ -35,7 +35,7 @@ const migrateRelease = async (bundle, env, out, plan) => {
|
|
|
35
35
|
const pending = migrations ? await pendingIn(tx, await readMigrationDir(path.join(dir, migrations))) : [];
|
|
36
36
|
if (pending.length > 0) throw new Error(`The database lacks the bundle's migrations ${pending.map(({ file }) => file).join(", ")}: apply them first with \`protobase-serve migrate\``);
|
|
37
37
|
const steps = await releaseSteps(project);
|
|
38
|
-
const record =
|
|
38
|
+
const record = await releaseRecord(project, steps, protobaseVersion, randomUUID());
|
|
39
39
|
return record ? [...steps, record] : steps;
|
|
40
40
|
};
|
|
41
41
|
await (plan ? planReleaseSteps(sql, find, out) : applyReleaseSteps(sql, find, out));
|
|
@@ -1,19 +1,18 @@
|
|
|
1
|
-
import { appRelayChannels,
|
|
1
|
+
import { appRelayChannels, readRelaySwitch } from "@protobase/server";
|
|
2
2
|
//#region src/serve/relay-check.ts
|
|
3
3
|
/**
|
|
4
|
-
* Refuses to start while the
|
|
5
|
-
*
|
|
6
|
-
*
|
|
4
|
+
* Refuses to start while the platform's switch is neither true nor false, or the relay is on, by the config's
|
|
5
|
+
* `realtime.relay` or the switch, and its channels do not fit the views. What the channels need of the database is
|
|
6
|
+
* the relay module, which the record of migrations holds. A switch with no channels to derive is left to the server,
|
|
7
|
+
* which stops naming it.
|
|
7
8
|
*/
|
|
8
|
-
const checkProjectRelay =
|
|
9
|
+
const checkProjectRelay = ({ realtime, auth, models, views }, env) => {
|
|
9
10
|
if (!realtime?.relay && !readRelaySwitch(env)) return;
|
|
10
|
-
|
|
11
|
+
appRelayChannels(realtime?.relay, {
|
|
11
12
|
views,
|
|
12
13
|
models,
|
|
13
14
|
signIn: Boolean(auth)
|
|
14
15
|
});
|
|
15
|
-
if (!channels) return;
|
|
16
|
-
await checkRelaySchema(db, auth, channels, models);
|
|
17
16
|
};
|
|
18
17
|
//#endregion
|
|
19
18
|
export { checkProjectRelay };
|
|
@@ -1,42 +1,32 @@
|
|
|
1
1
|
import { protobaseVersion } from "../version/version.js";
|
|
2
|
+
import { readOnlyQueriesOn } from "../config/read-only-queries.js";
|
|
3
|
+
import { builtRuntimeModel } from "../config/project-modules.js";
|
|
2
4
|
import { checkProjectRelay } from "./relay-check.js";
|
|
3
|
-
import {
|
|
5
|
+
import { authStoreTables, checkMigrationRecord, checkQueryRoleSafety, checkResourcesOutsideAuthStore, configExports } from "@protobase/server";
|
|
4
6
|
//#region src/serve/startup-checks.ts
|
|
5
7
|
/**
|
|
6
|
-
* The server's startup checks of the database: the record of its migrations (`checkMigrationRecord`),
|
|
7
|
-
*
|
|
8
|
-
*
|
|
8
|
+
* The server's startup checks of the database: the record of its migrations (`checkMigrationRecord`), which holds the
|
|
9
|
+
* auth store and the schema modules, such as the jobs schema, the rollups and formulas, the change capture, the derived schema, the schemas of user tables, webhooks, workflows, status, calls, the relay, comments, mail feedback, unsubscribe and the assistant's query role, the organization pinned while organizations are off
|
|
10
|
+
* after being on (`pinnedOrganization`), the resources over the auth store's tables, and what the live database gave the
|
|
11
|
+
* query role (`checkQueryRoleSafety`); each throws, with what to write as a migration, while a schema the project's
|
|
12
|
+
* features need is missing or behind. They only read. `serve` runs them before it builds the admin, and
|
|
9
13
|
* `protobase doctor` runs them too, so a change that would not start fails wherever doctor runs.
|
|
10
14
|
*/
|
|
11
15
|
const checkStartup = async (project, db) => {
|
|
12
16
|
const exported = configExports(project.config);
|
|
13
17
|
const models = exported.resources.map((resource) => resource.toModel());
|
|
14
|
-
|
|
15
|
-
await
|
|
18
|
+
await checkMigrationRecord(db, builtRuntimeModel(project), protobaseVersion);
|
|
19
|
+
await project.auth?.pinnedOrganization();
|
|
16
20
|
if (project.auth) await checkResourcesOutsideAuthStore(db, models, project.auth);
|
|
17
|
-
if (project.
|
|
18
|
-
await checkChanges(db, captured, project.events);
|
|
19
|
-
await checkComments(db, models);
|
|
20
|
-
await checkDerived(db, models);
|
|
21
|
-
await checkCalls(db, project.calls, project.events);
|
|
22
|
-
await checkComputed(db, models);
|
|
23
|
-
if (assistantSettings(project.options?.assistant, process.env)?.kind === "built-in") await checkQueryRunner(db, project.auth ? authStoreTables(project.auth) : {
|
|
21
|
+
if (readOnlyQueriesOn(project.options?.assistant, process.env)) await checkQueryRoleSafety(db, project.auth ? authStoreTables(project.auth) : {
|
|
24
22
|
tables: [],
|
|
25
23
|
schemas: []
|
|
26
24
|
});
|
|
27
|
-
|
|
28
|
-
if (project.workflows) await checkWorkflowsSchema(db, project.workflows);
|
|
29
|
-
if (relayed(project.realtime)) await checkRealtimeRelay(db);
|
|
30
|
-
if (sqlSends(project.realtime)) await checkChannelSends(db);
|
|
31
|
-
await checkProjectRelay(db, {
|
|
25
|
+
checkProjectRelay({
|
|
32
26
|
...project,
|
|
33
27
|
models,
|
|
34
28
|
views: exported.views.map((view) => view.toModel())
|
|
35
29
|
}, process.env);
|
|
36
|
-
if (project.notifications) await checkNotificationsSchema(db, project.notifications, project.auth);
|
|
37
|
-
if (project.status) await checkStatusSchema(db, project.status, project.auth);
|
|
38
|
-
if (project.unsubscribe) await checkUnsubscribesSchema(db);
|
|
39
|
-
if (project.userTables) await checkUserTablesSchema(db);
|
|
40
30
|
};
|
|
41
31
|
//#endregion
|
|
42
32
|
export { checkStartup };
|
|
@@ -2,6 +2,7 @@ import { loadProjectAuth } from "../users/load-auth.js";
|
|
|
2
2
|
import { connect } from "../db/connect.js";
|
|
3
3
|
import { authStorageSchemas } from "./platform-schemas.js";
|
|
4
4
|
import { runScaffold } from "../scaffold/run.js";
|
|
5
|
+
import { loadConfigOrganizations } from "../auth/config-organizations.js";
|
|
5
6
|
import { readSnapshot } from "../migration/snapshot/snapshot-file.js";
|
|
6
7
|
import { readMigrationFiles } from "../migration/snapshot/migration-files.js";
|
|
7
8
|
import { refuseInconsistent } from "../migration/snapshot/consistency.js";
|
|
@@ -104,7 +105,8 @@ const runLoadPhase = async (options, out) => {
|
|
|
104
105
|
auth,
|
|
105
106
|
projectDir: options.projectDir,
|
|
106
107
|
dir: options.migrationsDir,
|
|
107
|
-
name: "auth"
|
|
108
|
+
name: "auth",
|
|
109
|
+
organizations: await loadConfigOrganizations(options.projectDir)
|
|
108
110
|
});
|
|
109
111
|
if (authFile) out(`wrote ${path.relative(options.projectDir, authFile)}, Better Auth's tables next to auth.users\n`);
|
|
110
112
|
const accountsFile = await writeMigration(options.migrationsDir, "supabase_accounts", accountsMigration());
|