@protobase/cli 0.33.4 → 0.34.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/build/bundle-migrations.js +17 -0
- package/dist/build/deploy-bundle.js +13 -6
- package/dist/bundle/manifest.js +8 -5
- package/dist/cli/package.js +1 -1
- package/dist/dev/run.js +3 -1
- package/dist/encryption/print-apply.js +22 -0
- package/dist/encryption/print-status.js +32 -0
- package/dist/encryption/rebind-option.js +22 -0
- package/dist/encryption/register.js +34 -0
- package/dist/files/register.js +2 -2
- package/dist/main.js +2 -0
- package/dist/migration/apply-migrations.js +30 -0
- package/dist/{files/load-project.js → project/load-bundle-project.js} +8 -7
- package/dist/serve/bundle-site.js +9 -0
- package/dist/serve/create-admin.js +25 -0
- package/dist/serve/main.js +15 -4
- package/dist/serve/migrate-bundle.js +31 -0
- package/dist/serve/runtime-program.js +23 -0
- package/dist/serve/serve-bundle-path.js +13 -0
- package/dist/serve/serve-dir.js +2 -3
- package/dist/serve/static-site.js +11 -2
- package/dist/users/password.js +8 -6
- package/dist/users/register.js +3 -14
- package/dist/users/users-api.js +16 -0
- package/package.json +8 -8
- package/skills/protobase/references/guides/deploy.md +121 -3
- package/skills/protobase/references/reference/api.md +1 -1
- package/skills/protobase/references/reference/auth.md +20 -1
- package/skills/protobase/references/reference/cli.md +44 -9
- package/skills/protobase/references/reference/data-config.md +61 -0
- package/skills/protobase/references/reference/forms.md +3 -1
- package/skills/protobase/references/reference/supabase-rest.md +4 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { bundleMigrations } from "../bundle/manifest.js";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { copyFile, mkdir, readdir } from "node:fs/promises";
|
|
5
|
+
//#region src/build/bundle-migrations.ts
|
|
6
|
+
const projectMigrations = "db/migrations";
|
|
7
|
+
const copyMigrations = async ({ projectDir, outDir }) => {
|
|
8
|
+
const source = path.join(projectDir, projectMigrations);
|
|
9
|
+
if (!existsSync(source)) return void 0;
|
|
10
|
+
const target = path.join(outDir, bundleMigrations);
|
|
11
|
+
await mkdir(target, { recursive: true });
|
|
12
|
+
const files = (await readdir(source, { withFileTypes: true })).filter((entry) => entry.isFile() && entry.name.endsWith(".sql"));
|
|
13
|
+
for (const file of files) await copyFile(path.join(source, file.name), path.join(target, file.name));
|
|
14
|
+
return bundleMigrations;
|
|
15
|
+
};
|
|
16
|
+
//#endregion
|
|
17
|
+
export { copyMigrations, projectMigrations };
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { bundleLayout, bundleNodeModules, manifestFile } from "../bundle/manifest.js";
|
|
1
|
+
import { bundleLayout, bundleMigrations, bundleNodeModules, manifestFile } from "../bundle/manifest.js";
|
|
2
2
|
import { buildBundlePlugins } from "./bundle-plugins.js";
|
|
3
|
+
import { copyMigrations } from "./bundle-migrations.js";
|
|
3
4
|
import { buildConfigBundle } from "./config-bundle.js";
|
|
4
5
|
import { protobaseVersion } from "../version/version.js";
|
|
5
6
|
import { copyPackages } from "./packages/copy-packages.js";
|
|
@@ -13,11 +14,11 @@ import { existsSync } from "node:fs";
|
|
|
13
14
|
import path from "node:path";
|
|
14
15
|
import { cp, readFile, rm, writeFile } from "node:fs/promises";
|
|
15
16
|
//#region src/build/deploy-bundle.ts
|
|
16
|
-
const
|
|
17
|
-
const dir = path.join(outDir,
|
|
17
|
+
const removeOwnFolder = async (outDir, name, key) => {
|
|
18
|
+
const dir = path.join(outDir, name);
|
|
18
19
|
if (!existsSync(dir)) return;
|
|
19
20
|
const manifest = path.join(outDir, manifestFile);
|
|
20
|
-
if ((existsSync(manifest) ? JSON.parse(await readFile(manifest, "utf8")) : void 0)?.
|
|
21
|
+
if ((existsSync(manifest) ? JSON.parse(await readFile(manifest, "utf8")) : void 0)?.[key] !== name) throw new Error(`${dir} was not written by \`protobase build\`; build into another folder (--out)`);
|
|
21
22
|
await rm(dir, {
|
|
22
23
|
recursive: true,
|
|
23
24
|
force: true
|
|
@@ -44,7 +45,8 @@ const copyShell = async (publicDir, sourceMaps) => {
|
|
|
44
45
|
return shell;
|
|
45
46
|
};
|
|
46
47
|
const buildDeployBundle = async ({ projectDir, outDir, bun, extensions = [], sourceMaps = false, onWarning }) => {
|
|
47
|
-
await
|
|
48
|
+
await removeOwnFolder(outDir, bundleNodeModules, "nodeModules");
|
|
49
|
+
await removeOwnFolder(outDir, bundleMigrations, "migrations");
|
|
48
50
|
const components = /* @__PURE__ */ new Set();
|
|
49
51
|
const native = await buildConfigBundle({
|
|
50
52
|
projectDir,
|
|
@@ -58,6 +60,10 @@ const buildDeployBundle = async ({ projectDir, outDir, bun, extensions = [], sou
|
|
|
58
60
|
const packages = native.length > 0 ? await copyPackages(native, path.join(outDir, bundleNodeModules)) : [];
|
|
59
61
|
const publicDir = path.join(outDir, bundleLayout.public);
|
|
60
62
|
const shell = await copyShell(publicDir, sourceMaps);
|
|
63
|
+
const migrations = await copyMigrations({
|
|
64
|
+
projectDir,
|
|
65
|
+
outDir
|
|
66
|
+
});
|
|
61
67
|
const plugins = await buildBundlePlugins({
|
|
62
68
|
projectDir,
|
|
63
69
|
publicDir,
|
|
@@ -81,7 +87,8 @@ const buildDeployBundle = async ({ projectDir, outDir, bun, extensions = [], sou
|
|
|
81
87
|
plugins,
|
|
82
88
|
shell,
|
|
83
89
|
icons,
|
|
84
|
-
...packages.length > 0 ? { nodeModules: bundleNodeModules } : {}
|
|
90
|
+
...packages.length > 0 ? { nodeModules: bundleNodeModules } : {},
|
|
91
|
+
...migrations ? { migrations } : {}
|
|
85
92
|
};
|
|
86
93
|
await writeFile(path.join(outDir, manifestFile), `${JSON.stringify(manifest, null, 2)}\n`);
|
|
87
94
|
return manifest;
|
package/dist/bundle/manifest.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
2
|
import { readFile } from "node:fs/promises";
|
|
3
|
-
import { pngIcons } from "@protobase/server";
|
|
3
|
+
import { oauthWellKnownPaths, pngIcons } from "@protobase/server";
|
|
4
4
|
//#region src/bundle/manifest.ts
|
|
5
5
|
const manifestFile = "protobase.bundle.json";
|
|
6
6
|
const isApiPath = (api, pathname) => api.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`));
|
|
@@ -9,10 +9,11 @@ const bundleLayout = {
|
|
|
9
9
|
server: "protobase.config.js",
|
|
10
10
|
public: "public",
|
|
11
11
|
spa: "index.html",
|
|
12
|
-
api: ["/api"],
|
|
12
|
+
api: ["/api", ...oauthWellKnownPaths],
|
|
13
13
|
theme: "protobase.theme.css"
|
|
14
14
|
};
|
|
15
15
|
const bundleNodeModules = "node_modules";
|
|
16
|
+
const bundleMigrations = "migrations";
|
|
16
17
|
const isStringList = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
|
|
17
18
|
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
18
19
|
const isFieldTypes = (value) => isObject(value) && Object.values(value).every(isStringList);
|
|
@@ -22,12 +23,13 @@ const isIcons = (value) => isObject(value) && typeof value.favicon === "boolean"
|
|
|
22
23
|
const parseManifest = (value, file) => {
|
|
23
24
|
const manifest = value;
|
|
24
25
|
if (manifest?.version !== 3) throw new Error(`${file} is not a version 3 bundle manifest; rebuild it with \`protobase build\``);
|
|
25
|
-
const { server, public: publicDir, api, spa, plugins, theme, shell, icons, nodeModules } = manifest;
|
|
26
|
+
const { server, public: publicDir, api, spa, plugins, theme, shell, icons, nodeModules, migrations } = manifest;
|
|
26
27
|
if (typeof server !== "string" || typeof publicDir !== "string" || typeof spa !== "string" || typeof theme !== "string" || !isStringList(api)) throw new Error(`${file} needs server, public, spa and theme paths and an api list`);
|
|
27
28
|
if (!Array.isArray(plugins) || !plugins.every(isPlugin)) throw new Error(`${file} needs a plugins list, each with a name, path, api and protobase`);
|
|
28
29
|
if (!isShell(shell)) throw new Error(`${file} needs a shell with its protobase version, pluginApi and paths`);
|
|
29
30
|
if (icons !== void 0 && !isIcons(icons)) throw new Error(`${file} has icons that are not a favicon flag and a list of PNG icons`);
|
|
30
31
|
if (nodeModules !== void 0 && typeof nodeModules !== "string") throw new Error(`${file} has a nodeModules that is no path`);
|
|
32
|
+
if (migrations !== void 0 && typeof migrations !== "string") throw new Error(`${file} has a migrations that is no path`);
|
|
31
33
|
return {
|
|
32
34
|
version: 3,
|
|
33
35
|
server,
|
|
@@ -38,7 +40,8 @@ const parseManifest = (value, file) => {
|
|
|
38
40
|
theme,
|
|
39
41
|
shell,
|
|
40
42
|
...icons && { icons },
|
|
41
|
-
...nodeModules === void 0 ? {} : { nodeModules }
|
|
43
|
+
...nodeModules === void 0 ? {} : { nodeModules },
|
|
44
|
+
...migrations === void 0 ? {} : { migrations }
|
|
42
45
|
};
|
|
43
46
|
};
|
|
44
47
|
const readManifest = async (bundleDir) => {
|
|
@@ -46,4 +49,4 @@ const readManifest = async (bundleDir) => {
|
|
|
46
49
|
return parseManifest(JSON.parse(await readFile(file, "utf8")), file);
|
|
47
50
|
};
|
|
48
51
|
//#endregion
|
|
49
|
-
export { bundleBasePath, bundleLayout, bundleNodeModules, isApiPath, manifestFile, parseManifest, readManifest };
|
|
52
|
+
export { bundleBasePath, bundleLayout, bundleMigrations, bundleNodeModules, isApiPath, manifestFile, parseManifest, readManifest };
|
package/dist/cli/package.js
CHANGED
package/dist/dev/run.js
CHANGED
|
@@ -11,6 +11,7 @@ import { checkDatabase } from "./check-database.js";
|
|
|
11
11
|
import { stopDevJobs } from "./dev-jobs.js";
|
|
12
12
|
import { isProjectFile } from "./project-files.js";
|
|
13
13
|
import { apiWebSockets } from "./api-websockets.js";
|
|
14
|
+
import { frameHeaders } from "../serve/static-site.js";
|
|
14
15
|
import { existsSync } from "node:fs";
|
|
15
16
|
import path from "node:path";
|
|
16
17
|
import { createServer, searchForWorkspaceRoot } from "vite";
|
|
@@ -71,6 +72,7 @@ const runDev = async (options, out) => {
|
|
|
71
72
|
exclude: ["@protobase/ui"]
|
|
72
73
|
},
|
|
73
74
|
server: {
|
|
75
|
+
headers: frameHeaders,
|
|
74
76
|
port: options.port,
|
|
75
77
|
strictPort: true,
|
|
76
78
|
...options.allowedHosts.length > 0 && { allowedHosts: options.allowedHosts },
|
|
@@ -96,7 +98,7 @@ const runDev = async (options, out) => {
|
|
|
96
98
|
tailwindcss(),
|
|
97
99
|
devServer({
|
|
98
100
|
entry,
|
|
99
|
-
exclude: [/^(?!\/api(\/|\?|$)|\/\.well-known\/webauthn(\?|$)).*/],
|
|
101
|
+
exclude: [/^(?!\/api(\/|\?|$)|\/\.well-known\/webauthn(\?|$)|\/\.well-known\/oauth-(authorization-server|protected-resource)(\/|\?|$)).*/],
|
|
100
102
|
injectClientScript: false
|
|
101
103
|
})
|
|
102
104
|
]
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { failedAuthenticationHint, unreadableLine } from "./print-status.js";
|
|
2
|
+
//#region src/encryption/print-apply.ts
|
|
3
|
+
/** Prints what apply did per field, and tells whether values that do not open remain. */
|
|
4
|
+
const printApply = (result, out) => {
|
|
5
|
+
for (const field of result.fields) {
|
|
6
|
+
const counts = [
|
|
7
|
+
`${field.encrypted} encrypted`,
|
|
8
|
+
`${field.reencrypted} re-encrypted`,
|
|
9
|
+
`${field.rebound} rebound`,
|
|
10
|
+
`${field.skipped} skipped`,
|
|
11
|
+
`${field.unreadable.length} unreadable`
|
|
12
|
+
];
|
|
13
|
+
out(`${field.resource}.${field.field}: ${counts.join(", ")}; old values removed from ${field.historyScrubbed} history rows and ${field.outboxScrubbed} undispatched changes\n`);
|
|
14
|
+
for (const entry of field.unreadable) out(unreadableLine(field.resource, field.field, entry));
|
|
15
|
+
}
|
|
16
|
+
for (const key of result.warnings) out(`warning: ${key.resource}'s key changes with another record's through foreign key ${key.constraint}, which makes its encrypted values unreadable\n`);
|
|
17
|
+
const unreadable = result.fields.some((field) => field.unreadable.length > 0);
|
|
18
|
+
if (result.fields.some((field) => field.unreadable.some((entry) => entry.kind === "failed-authentication"))) out(failedAuthenticationHint);
|
|
19
|
+
return unreadable;
|
|
20
|
+
};
|
|
21
|
+
//#endregion
|
|
22
|
+
export { printApply };
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
//#region src/encryption/print-status.ts
|
|
2
|
+
const plural = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
|
|
3
|
+
/** One line per value that does not open: never the value. */
|
|
4
|
+
const unreadableLine = (resource, field, entry) => ` ${resource}.${field} ${JSON.stringify(entry.key)}: ${entry.kind}${entry.kid ? ` [key ${entry.kid}]` : ""}\n`;
|
|
5
|
+
/** What causes values that fail authentication, printed once when there are any. */
|
|
6
|
+
const failedAuthenticationHint = "Values fail authentication when their table or column was renamed or moved (protobase encryption apply --rebind), the resource's key or tenant field changed, their record's key changed in the database, or they were copied there by SQL.\n";
|
|
7
|
+
/**
|
|
8
|
+
* Prints the status and tells whether anything needs work: plaintext, values under a previous key, values that do not
|
|
9
|
+
* open, old values in history or the outbox, or envelopes in fields that are not encrypted.
|
|
10
|
+
*/
|
|
11
|
+
const printStatus = (status, out) => {
|
|
12
|
+
let dirty = false;
|
|
13
|
+
out(`Current key ${status.kid}\n`);
|
|
14
|
+
for (const field of status.fields) {
|
|
15
|
+
const keys = Object.entries(field.byKey).map(([kid, count]) => `${count} under ${kid === status.kid ? `key ${kid} (current)` : `key ${kid}`}`);
|
|
16
|
+
const parts = [
|
|
17
|
+
...keys,
|
|
18
|
+
`${field.plaintext} plaintext`,
|
|
19
|
+
`${field.unreadable.length} unreadable`
|
|
20
|
+
];
|
|
21
|
+
out(`${field.resource}.${field.field}: ${parts.join(", ")}\n`);
|
|
22
|
+
for (const entry of field.unreadable) out(unreadableLine(field.resource, field.field, entry));
|
|
23
|
+
if (field.history > 0 || field.outbox > 0) out(` old values left in ${plural(field.history, "history row")} and ${plural(field.outbox, "undispatched change")}\n`);
|
|
24
|
+
dirty ||= field.plaintext > 0 || field.unreadable.length > 0 || keys.length > (field.byKey[status.kid] ? 1 : 0) || field.history > 0 || field.outbox > 0;
|
|
25
|
+
}
|
|
26
|
+
for (const stray of status.stray) out(`${stray.resource}.${stray.field} is not encrypted but holds ${plural(stray.count, "encrypted value")}\n`);
|
|
27
|
+
for (const key of status.cascading) out(`warning: ${key.resource}'s key changes with another record's through foreign key ${key.constraint}, which makes its encrypted values unreadable\n`);
|
|
28
|
+
if (status.fields.some((field) => field.unreadable.some((entry) => entry.kind === "failed-authentication"))) out(failedAuthenticationHint);
|
|
29
|
+
return dirty || status.stray.length > 0;
|
|
30
|
+
};
|
|
31
|
+
//#endregion
|
|
32
|
+
export { failedAuthenticationHint, printStatus, unreadableLine };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
//#region src/encryption/rebind-option.ts
|
|
2
|
+
/** `--rebind <resource>[.<field>]` with `--from-table` or `--from-column`, checked before anything is written. */
|
|
3
|
+
const rebindOption = ({ rebind, fromTable, fromColumn }) => {
|
|
4
|
+
if (rebind === void 0) {
|
|
5
|
+
if (fromTable !== void 0 || fromColumn !== void 0) throw new Error("--from-table and --from-column go with --rebind <resource>[.<field>]");
|
|
6
|
+
return;
|
|
7
|
+
}
|
|
8
|
+
const [resource, field, ...rest] = rebind.split(".");
|
|
9
|
+
if (!resource || field === "" || rest.length > 0) throw new Error(`--rebind takes <resource> or <resource>.<field>, not "${rebind}"`);
|
|
10
|
+
if (fromTable === void 0 && fromColumn === void 0) throw new Error("--rebind needs --from-table <table> or --from-column <column>: where the values were before");
|
|
11
|
+
if (fromColumn !== void 0 && field === void 0) throw new Error("--from-column needs the field whose column was renamed: --rebind <resource>.<field>");
|
|
12
|
+
return {
|
|
13
|
+
resource,
|
|
14
|
+
...field !== void 0 && { field },
|
|
15
|
+
from: {
|
|
16
|
+
...fromTable !== void 0 && { table: fromTable },
|
|
17
|
+
...fromColumn !== void 0 && { column: fromColumn }
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
//#endregion
|
|
22
|
+
export { rebindOption };
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { loadBundleProject } from "../project/load-bundle-project.js";
|
|
2
|
+
import { printStatus } from "./print-status.js";
|
|
3
|
+
import { printApply } from "./print-apply.js";
|
|
4
|
+
import { rebindOption } from "./rebind-option.js";
|
|
5
|
+
import { createEncryptionTools } from "@protobase/server";
|
|
6
|
+
//#region src/encryption/register.ts
|
|
7
|
+
const out = (text) => void process.stdout.write(text);
|
|
8
|
+
const bundleArgument = ["[bundle]", "a bundle from `protobase build` (its folder or config module); default: the project in the current directory"];
|
|
9
|
+
const withTools = async (bundle, work) => {
|
|
10
|
+
const project = await loadBundleProject(bundle, process.cwd());
|
|
11
|
+
try {
|
|
12
|
+
const tools = createEncryptionTools({
|
|
13
|
+
...project,
|
|
14
|
+
env: process.env
|
|
15
|
+
});
|
|
16
|
+
if (!tools) return out("The project has no encrypted fields\n");
|
|
17
|
+
if (await work(tools)) process.exitCode = 1;
|
|
18
|
+
} finally {
|
|
19
|
+
await project.close();
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
const registerEncryption = (program) => {
|
|
23
|
+
const encryption = program.command("encryption").description("Check and update the stored values of encrypted fields");
|
|
24
|
+
encryption.command("status").description("Count each encrypted field's values by key, list plaintext and unreadable ones and old values left in history; exits 1 when any need work").argument(...bundleArgument).action((bundle) => withTools(bundle, async (tools) => printStatus(await tools.status(), out)));
|
|
25
|
+
encryption.command("apply").description("Encrypt plaintext values, move values to the current key, rebind renamed ones and remove old values from history; exits 1 when unreadable values remain").argument(...bundleArgument).option("--rebind <resource[.field]>", "rebind the values of a resource, or one field, sealed before a rename").option("--from-table <table>", "the table, as .table() named it, the values were in before").option("--from-column <column>", "the column the field's values were in before").action((bundle, flags) => {
|
|
26
|
+
const rebind = rebindOption(flags);
|
|
27
|
+
return withTools(bundle, async (tools) => {
|
|
28
|
+
out(`Encrypting with key ${tools.kid}\n`);
|
|
29
|
+
return printApply(await tools.apply(rebind ? { rebind } : {}), out);
|
|
30
|
+
});
|
|
31
|
+
});
|
|
32
|
+
};
|
|
33
|
+
//#endregion
|
|
34
|
+
export { registerEncryption };
|
package/dist/files/register.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { cleanupCommand } from "./cleanup-command.js";
|
|
2
|
-
import {
|
|
2
|
+
import { loadBundleProject } from "../project/load-bundle-project.js";
|
|
3
3
|
import { createFileCleanup } from "@protobase/server";
|
|
4
4
|
//#region src/files/register.ts
|
|
5
5
|
const out = (text) => process.stdout.write(text);
|
|
6
6
|
const registerFiles = (program) => {
|
|
7
7
|
program.command("files").description("Manage the stored files of the project in the current directory").command("cleanup").description("Delete the files whose scheduled delete is due and that no row references, such as replaced files and unused uploads").argument("[bundle]", "a bundle from `protobase build` (its folder or config module); default: the project in the current directory").action(async (bundle) => {
|
|
8
|
-
const project = await
|
|
8
|
+
const project = await loadBundleProject(bundle, process.cwd());
|
|
9
9
|
try {
|
|
10
10
|
const cleanup = createFileCleanup(project);
|
|
11
11
|
if (cleanup) await cleanupCommand(cleanup.run, out);
|
package/dist/main.js
CHANGED
|
@@ -19,6 +19,7 @@ import { serveBundleDir } from "./serve/serve-dir.js";
|
|
|
19
19
|
import { loadWorkerBundle, startWorker } from "./worker/start-worker.js";
|
|
20
20
|
import { registerOrganizations } from "./organizations/register.js";
|
|
21
21
|
import { registerFiles } from "./files/register.js";
|
|
22
|
+
import { registerEncryption } from "./encryption/register.js";
|
|
22
23
|
import { registerMigration } from "./migration/register.js";
|
|
23
24
|
import { registerMobile } from "./mobile/register.js";
|
|
24
25
|
import { registerSkill } from "./skill/register.js";
|
|
@@ -133,6 +134,7 @@ registerToken(program);
|
|
|
133
134
|
registerAuth(program);
|
|
134
135
|
registerMigration(program);
|
|
135
136
|
registerFiles(program);
|
|
137
|
+
registerEncryption(program);
|
|
136
138
|
registerSkill(program);
|
|
137
139
|
registerImport(program);
|
|
138
140
|
registerMobile(program);
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { readFile, readdir } from "node:fs/promises";
|
|
3
|
+
//#region src/migration/apply-migrations.ts
|
|
4
|
+
const lockKey = 7311946202;
|
|
5
|
+
const executeFile = "do $migration$ begin execute current_setting('migrations.file'); end $migration$";
|
|
6
|
+
/**
|
|
7
|
+
* Applies the `*.sql` files of `dir` not yet recorded in `public.schema_migrations`, in file name order and in one
|
|
8
|
+
* transaction behind an advisory lock: when one fails, none is applied. Run it before a new version serves, while
|
|
9
|
+
* nothing else writes. Returns the names it applied.
|
|
10
|
+
*/
|
|
11
|
+
const applyMigrations = async (sql, dir, out) => {
|
|
12
|
+
const files = (await readdir(dir)).filter((file) => file.endsWith(".sql")).sort();
|
|
13
|
+
const applied = await sql.begin(async (tx) => {
|
|
14
|
+
await tx`select pg_advisory_xact_lock(${lockKey})`;
|
|
15
|
+
await tx`create table if not exists public.schema_migrations (name text primary key, applied_at timestamptz not null default now())`;
|
|
16
|
+
const done = new Set((await tx`select name from public.schema_migrations`).map((row) => row.name));
|
|
17
|
+
const pending = files.filter((file) => !done.has(file));
|
|
18
|
+
for (const file of pending) {
|
|
19
|
+
out(`applying ${file}\n`);
|
|
20
|
+
await tx`select set_config('migrations.file', ${await readFile(path.join(dir, file), "utf8")}, true)`;
|
|
21
|
+
await tx.unsafe(executeFile);
|
|
22
|
+
await tx`insert into public.schema_migrations (name) values (${file})`;
|
|
23
|
+
}
|
|
24
|
+
return pending;
|
|
25
|
+
});
|
|
26
|
+
out(applied.length > 0 ? `applied ${applied.length} migrations\n` : "the database is up to date\n");
|
|
27
|
+
return applied;
|
|
28
|
+
};
|
|
29
|
+
//#endregion
|
|
30
|
+
export { applyMigrations };
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { loadNearestEnvFile } from "../dev/env.js";
|
|
2
|
-
import { importProjectFile } from "
|
|
2
|
+
import { importProjectFile } from "./import-project-file.js";
|
|
3
3
|
import { readManifest } from "../bundle/manifest.js";
|
|
4
|
-
import { createPgDb } from "
|
|
4
|
+
import { createPgDb } from "./pg-db.js";
|
|
5
5
|
import { loadBundle } from "../serve/load-bundle.js";
|
|
6
6
|
import { existsSync, statSync } from "node:fs";
|
|
7
7
|
import path from "node:path";
|
|
8
8
|
import { configExports } from "@protobase/server";
|
|
9
9
|
import pg from "pg";
|
|
10
|
-
//#region src/
|
|
10
|
+
//#region src/project/load-bundle-project.ts
|
|
11
11
|
const bundleProject = async (bundle) => {
|
|
12
12
|
if (!statSync(bundle).isDirectory()) return loadBundle(bundle);
|
|
13
13
|
const manifest = await readManifest(bundle);
|
|
@@ -25,10 +25,10 @@ const sourceProject = async (dir) => {
|
|
|
25
25
|
};
|
|
26
26
|
};
|
|
27
27
|
/**
|
|
28
|
-
* What a command over a project's
|
|
29
|
-
* the project in `dir`. `close` ends the pool it opened; a `db` the project exports stays the project's.
|
|
28
|
+
* What a command over a project's data needs: its resources, its files and events options and a database, from a bundle
|
|
29
|
+
* or from the project in `dir`. `close` ends the pool it opened; a `db` the project exports stays the project's.
|
|
30
30
|
*/
|
|
31
|
-
const
|
|
31
|
+
const loadBundleProject = async (bundle, dir) => {
|
|
32
32
|
loadNearestEnvFile(dir);
|
|
33
33
|
const project = bundle ? await bundleProject(bundle) : await sourceProject(dir);
|
|
34
34
|
const url = process.env.DATABASE_URL;
|
|
@@ -38,10 +38,11 @@ const loadFilesProject = async (bundle, dir) => {
|
|
|
38
38
|
resources: configExports(project.config ?? {}).resources,
|
|
39
39
|
db: project.db ?? ownDb,
|
|
40
40
|
...project.files && { files: project.files },
|
|
41
|
+
...project.events && { events: project.events },
|
|
41
42
|
close: async () => {
|
|
42
43
|
await ownDb?.destroy();
|
|
43
44
|
}
|
|
44
45
|
};
|
|
45
46
|
};
|
|
46
47
|
//#endregion
|
|
47
|
-
export {
|
|
48
|
+
export { loadBundleProject };
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { checkBundleVersion } from "./bundle-version.js";
|
|
2
|
+
import { loadBundle } from "./load-bundle.js";
|
|
3
|
+
import { bundleConfigFile } from "../worker/start-worker.js";
|
|
4
|
+
import { readHidden } from "../users/password.js";
|
|
5
|
+
import { createUserCommand } from "../users/commands.js";
|
|
6
|
+
import { usersApi } from "../users/users-api.js";
|
|
7
|
+
import { checkAuthSchema } from "@protobase/server";
|
|
8
|
+
//#region src/serve/create-admin.ts
|
|
9
|
+
const createAdminInBundle = async (bundle, email, options, out) => {
|
|
10
|
+
const file = await bundleConfigFile(bundle);
|
|
11
|
+
await checkBundleVersion(file);
|
|
12
|
+
const project = await loadBundle(file);
|
|
13
|
+
if (!project.auth) throw new Error("The bundle exports no `auth`: users are managed by Better Auth");
|
|
14
|
+
await checkAuthSchema(project.auth);
|
|
15
|
+
await createUserCommand(usersApi(project.auth), {
|
|
16
|
+
email,
|
|
17
|
+
role: "admin",
|
|
18
|
+
...options
|
|
19
|
+
}, {
|
|
20
|
+
stdin: process.stdin,
|
|
21
|
+
prompt: readHidden
|
|
22
|
+
}, out);
|
|
23
|
+
};
|
|
24
|
+
//#endregion
|
|
25
|
+
export { createAdminInBundle };
|
package/dist/serve/main.js
CHANGED
|
@@ -1,13 +1,24 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createAdminInBundle } from "./create-admin.js";
|
|
2
2
|
import { provideHostModules } from "./host-modules.js";
|
|
3
|
+
import { migrateBundle } from "./migrate-bundle.js";
|
|
4
|
+
import { runtimeProgram } from "./runtime-program.js";
|
|
5
|
+
import { serveBundlePath } from "./serve-bundle-path.js";
|
|
3
6
|
//#region src/serve/main.ts
|
|
4
7
|
const fail = (message) => {
|
|
5
8
|
process.stderr.write(`error: ${message}\n`);
|
|
6
9
|
process.exit(1);
|
|
7
10
|
};
|
|
11
|
+
const out = (text) => process.stdout.write(text);
|
|
8
12
|
provideHostModules();
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
await
|
|
13
|
+
await runtimeProgram({
|
|
14
|
+
serve: async (bundle) => {
|
|
15
|
+
await serveBundlePath(bundle, process.env, out);
|
|
16
|
+
},
|
|
17
|
+
migrate: (bundle) => migrateBundle(bundle, process.env, out),
|
|
18
|
+
createAdmin: async (bundle, email, options) => {
|
|
19
|
+
await createAdminInBundle(bundle, email, options, out);
|
|
20
|
+
process.exit(0);
|
|
21
|
+
}
|
|
22
|
+
}).parseAsync(process.argv).catch((error) => fail(error.message));
|
|
12
23
|
//#endregion
|
|
13
24
|
export {};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { readManifest } from "../bundle/manifest.js";
|
|
2
|
+
import { checkBundleVersion } from "./bundle-version.js";
|
|
3
|
+
import { bundleConfigFile } from "../worker/start-worker.js";
|
|
4
|
+
import { applyMigrations } from "../migration/apply-migrations.js";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import postgres from "postgres";
|
|
7
|
+
//#region src/serve/migrate-bundle.ts
|
|
8
|
+
/**
|
|
9
|
+
* The runtime's `migrate`: applies the migrations the bundle carries to DATABASE_URL (see applyMigrations). It never
|
|
10
|
+
* imports the config module, so it runs no code of the app and needs none of its settings. On a failure the error
|
|
11
|
+
* ends the process, which closes the connection.
|
|
12
|
+
*/
|
|
13
|
+
const migrateBundle = async (bundle, env, out) => {
|
|
14
|
+
const file = await bundleConfigFile(bundle);
|
|
15
|
+
await checkBundleVersion(file);
|
|
16
|
+
const dir = path.dirname(file);
|
|
17
|
+
const manifest = await readManifest(dir);
|
|
18
|
+
if (!manifest.migrations) {
|
|
19
|
+
out("the bundle has no migrations\n");
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
if (!env.DATABASE_URL) throw new Error("No database: set DATABASE_URL");
|
|
23
|
+
const sql = postgres(env.DATABASE_URL, {
|
|
24
|
+
max: 1,
|
|
25
|
+
onnotice: () => {}
|
|
26
|
+
});
|
|
27
|
+
await applyMigrations(sql, path.join(dir, manifest.migrations), out);
|
|
28
|
+
await sql.end();
|
|
29
|
+
};
|
|
30
|
+
//#endregion
|
|
31
|
+
export { migrateBundle };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { rejectPasswordArgument } from "../users/password.js";
|
|
2
|
+
import { Command, Option } from "commander";
|
|
3
|
+
//#region src/serve/runtime-program.ts
|
|
4
|
+
/**
|
|
5
|
+
* The serve runtime's commands. `serve` is the default, so `protobase-serve <config module>`, which hosts run, keeps
|
|
6
|
+
* serving that module's API alone; given the bundle folder it serves the app too.
|
|
7
|
+
*/
|
|
8
|
+
const runtimeProgram = (actions) => {
|
|
9
|
+
const program = new Command("protobase-serve").description("Protobase's serve runtime for a bundle from `protobase build`");
|
|
10
|
+
program.command("serve", { isDefault: true }).description("Serve a bundle: its folder serves the app and the API, its config module the API alone").argument("<bundle>").action((bundle) => actions.serve(bundle));
|
|
11
|
+
program.command("migrate").description("Apply the bundle's pending migrations in one transaction, before a new version serves (DATABASE_URL)").argument("<bundle>").action((bundle) => actions.migrate(bundle));
|
|
12
|
+
program.command("create-admin").description("Create an admin user of the bundle's app").argument("<bundle>").argument("<email>").option("--name <name>", "display name").option("--password-stdin", "read the password from stdin", false).option("--generate-password", "generate a strong password and print it once", false).addOption(new Option("--password <value>").hideHelp()).action((bundle, email, opts) => {
|
|
13
|
+
rejectPasswordArgument(opts.password);
|
|
14
|
+
return actions.createAdmin(bundle, email, {
|
|
15
|
+
name: opts.name,
|
|
16
|
+
passwordStdin: opts.passwordStdin,
|
|
17
|
+
generatePassword: opts.generatePassword
|
|
18
|
+
});
|
|
19
|
+
});
|
|
20
|
+
return program;
|
|
21
|
+
};
|
|
22
|
+
//#endregion
|
|
23
|
+
export { runtimeProgram };
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { readManifest } from "../bundle/manifest.js";
|
|
2
|
+
import { serveBundle } from "./serve-bundle.js";
|
|
3
|
+
import { bundleSite } from "./bundle-site.js";
|
|
4
|
+
import { statSync } from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
//#region src/serve/serve-bundle-path.ts
|
|
7
|
+
const serveBundlePath = async (bundle, env, out) => {
|
|
8
|
+
if (!statSync(bundle).isDirectory()) return serveBundle(bundle, env, out);
|
|
9
|
+
const manifest = await readManifest(bundle);
|
|
10
|
+
return serveBundle(path.join(bundle, manifest.server), env, out, bundleSite(bundle, manifest));
|
|
11
|
+
};
|
|
12
|
+
//#endregion
|
|
13
|
+
export { serveBundlePath };
|
package/dist/serve/serve-dir.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { readManifest } from "../bundle/manifest.js";
|
|
2
2
|
import { installedShellDir } from "../build/shell.js";
|
|
3
3
|
import { serveBundle } from "./serve-bundle.js";
|
|
4
|
+
import { bundleSite } from "./bundle-site.js";
|
|
4
5
|
import { servedShell, shellVariable } from "./served-shell.js";
|
|
5
6
|
import path from "node:path";
|
|
6
7
|
//#region src/serve/serve-dir.ts
|
|
@@ -9,9 +10,7 @@ const serveBundleDir = async (dir, env, out) => {
|
|
|
9
10
|
const own = env["PROTOBASE_SHELL"] ? path.resolve(env[shellVariable]) : installedShellDir;
|
|
10
11
|
const { shell, note } = await servedShell(manifest, own);
|
|
11
12
|
const site = {
|
|
12
|
-
|
|
13
|
-
spa: manifest.spa,
|
|
14
|
-
api: manifest.api,
|
|
13
|
+
...bundleSite(dir, manifest),
|
|
15
14
|
...shell && { shell }
|
|
16
15
|
};
|
|
17
16
|
const server = await serveBundle(path.join(dir, manifest.server), env, out, site);
|
|
@@ -27,9 +27,18 @@ const fileFor = async (publicDir, pathname) => {
|
|
|
27
27
|
return (await statOrUndefined(index))?.isFile() ? index : void 0;
|
|
28
28
|
};
|
|
29
29
|
const cacheControl = (root, file) => path.relative(root, file).split(path.sep).slice(0, -1).includes("assets") ? "public, max-age=31536000, immutable" : "no-cache";
|
|
30
|
+
/**
|
|
31
|
+
* Headers that keep every page of the UI out of other sites' frames, so none can put a click on a page of the app,
|
|
32
|
+
* such as Allow on the connect page, under its own. A host that serves `public/` itself should send them too.
|
|
33
|
+
*/
|
|
34
|
+
const frameHeaders = {
|
|
35
|
+
"x-frame-options": "DENY",
|
|
36
|
+
"content-security-policy": "frame-ancestors 'none'"
|
|
37
|
+
};
|
|
30
38
|
const fileResponse = async (root, file) => new Response(await readFile(file), { headers: {
|
|
31
39
|
"content-type": getMimeType(file) ?? "application/octet-stream",
|
|
32
|
-
"cache-control": cacheControl(root, file)
|
|
40
|
+
"cache-control": cacheControl(root, file),
|
|
41
|
+
...frameHeaders
|
|
33
42
|
} });
|
|
34
43
|
const isNavigation = (request) => (request.headers.get("accept") ?? "").includes("text/html");
|
|
35
44
|
const isUnder = (paths, pathname) => paths.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`));
|
|
@@ -47,4 +56,4 @@ const serveStaticSite = async ({ publicDir, spa, shell }, request) => {
|
|
|
47
56
|
return new Response("Not Found", { status: 404 });
|
|
48
57
|
};
|
|
49
58
|
//#endregion
|
|
50
|
-
export { serveStaticSite };
|
|
59
|
+
export { frameHeaders, serveStaticSite };
|
package/dist/users/password.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { passwordLength } from "@protobase/server";
|
|
1
2
|
import { randomBytes } from "node:crypto";
|
|
2
3
|
//#region src/users/password.ts
|
|
3
4
|
const rejectPasswordArgument = (value) => {
|
|
@@ -43,6 +44,10 @@ const readHidden = (question) => new Promise((resolve, reject) => {
|
|
|
43
44
|
};
|
|
44
45
|
stdin.on("data", onData);
|
|
45
46
|
});
|
|
47
|
+
const checkPasswordLength = (password) => {
|
|
48
|
+
const { min, max } = passwordLength;
|
|
49
|
+
if (password.length < min || password.length > max) throw new Error(`Choose a password of ${min} to ${max} characters`);
|
|
50
|
+
};
|
|
46
51
|
const resolvePassword = async (options, deps) => {
|
|
47
52
|
if ([
|
|
48
53
|
options.passwordStdin,
|
|
@@ -54,12 +59,9 @@ const resolvePassword = async (options, deps) => {
|
|
|
54
59
|
password: generatePassword(),
|
|
55
60
|
generated: true
|
|
56
61
|
};
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
};
|
|
61
|
-
const password = await deps.prompt("Password: ");
|
|
62
|
-
if (password !== await deps.prompt("Repeat password: ")) throw new Error("The passwords do not match");
|
|
62
|
+
const password = options.passwordStdin ? await readPasswordFromStream(deps.stdin) : await deps.prompt("Password: ");
|
|
63
|
+
if (!options.passwordStdin && password !== await deps.prompt("Repeat password: ")) throw new Error("The passwords do not match");
|
|
64
|
+
checkPasswordLength(password);
|
|
63
65
|
return {
|
|
64
66
|
password,
|
|
65
67
|
generated: false
|
package/dist/users/register.js
CHANGED
|
@@ -5,23 +5,12 @@ import { readHidden, rejectPasswordArgument } from "./password.js";
|
|
|
5
5
|
import { createUserCommand, listRolesCommand, listUsersCommand } from "./commands.js";
|
|
6
6
|
import { deleteUserCommand, setDisabledCommand, setRoleCommand } from "./manage.js";
|
|
7
7
|
import { parseTtl } from "./ttl.js";
|
|
8
|
+
import { usersApi } from "./users-api.js";
|
|
8
9
|
import { Option } from "commander";
|
|
9
|
-
import {
|
|
10
|
+
import { issueToken } from "@protobase/server";
|
|
10
11
|
import { createInterface } from "node:readline/promises";
|
|
11
12
|
//#region src/users/register.ts
|
|
12
13
|
const out = (text) => process.stdout.write(text);
|
|
13
|
-
const usersApi = (auth) => ({
|
|
14
|
-
hasUsers: () => hasUsers(auth),
|
|
15
|
-
roles: async () => ({
|
|
16
|
-
roles: roleChoices(auth),
|
|
17
|
-
defaultRole: auth.defaultRole
|
|
18
|
-
}),
|
|
19
|
-
createUser: (input) => createUser(auth, input),
|
|
20
|
-
listUsers: () => listUsers(auth),
|
|
21
|
-
deleteUser: (email) => deleteUser(auth, email),
|
|
22
|
-
setUserRole: (input) => setUserRole(auth, input),
|
|
23
|
-
setUserBanned: (input) => setUserBanned(auth, input)
|
|
24
|
-
});
|
|
25
14
|
const projectApi = async () => usersApi(await loadProjectAuth(process.cwd()));
|
|
26
15
|
const ask = async (question) => {
|
|
27
16
|
if (!process.stdin.isTTY) throw new Error("Confirmation needs a terminal; pass --yes to skip it");
|
|
@@ -102,4 +91,4 @@ const registerToken = (program) => {
|
|
|
102
91
|
});
|
|
103
92
|
};
|
|
104
93
|
//#endregion
|
|
105
|
-
export { registerToken, registerUsers
|
|
94
|
+
export { registerToken, registerUsers };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { createUser, deleteUser, hasUsers, listUsers, roleChoices, setUserBanned, setUserRole } from "@protobase/server";
|
|
2
|
+
//#region src/users/users-api.ts
|
|
3
|
+
const usersApi = (auth) => ({
|
|
4
|
+
hasUsers: () => hasUsers(auth),
|
|
5
|
+
roles: async () => ({
|
|
6
|
+
roles: roleChoices(auth),
|
|
7
|
+
defaultRole: auth.defaultRole
|
|
8
|
+
}),
|
|
9
|
+
createUser: (input) => createUser(auth, input),
|
|
10
|
+
listUsers: () => listUsers(auth),
|
|
11
|
+
deleteUser: (email) => deleteUser(auth, email),
|
|
12
|
+
setUserRole: (input) => setUserRole(auth, input),
|
|
13
|
+
setUserBanned: (input) => setUserBanned(auth, input)
|
|
14
|
+
});
|
|
15
|
+
//#endregion
|
|
16
|
+
export { usersApi };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@protobase/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.34.1",
|
|
4
4
|
"description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -33,20 +33,20 @@
|
|
|
33
33
|
"access": "public"
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
|
-
"@better-auth/core": "^1.7.
|
|
36
|
+
"@better-auth/core": "^1.7.12",
|
|
37
37
|
"@hono/node-server": "^2.1.3",
|
|
38
38
|
"@hono/vite-dev-server": "^0.26.1",
|
|
39
|
-
"@protobase/layout": "0.
|
|
40
|
-
"@protobase/query": "0.
|
|
41
|
-
"@protobase/schema": "0.
|
|
42
|
-
"@protobase/server": "0.
|
|
43
|
-
"@protobase/ui": "0.
|
|
39
|
+
"@protobase/layout": "0.34.1",
|
|
40
|
+
"@protobase/query": "0.34.1",
|
|
41
|
+
"@protobase/schema": "0.34.1",
|
|
42
|
+
"@protobase/server": "0.34.1",
|
|
43
|
+
"@protobase/ui": "0.34.1",
|
|
44
44
|
"@react-email/render": "^2.1.0",
|
|
45
45
|
"@scalar/hono-api-reference": "^0.12.10",
|
|
46
46
|
"@tailwindcss/vite": "^4.3.3",
|
|
47
47
|
"@vitejs/plugin-react": "^6.1.2",
|
|
48
48
|
"aip-parsers": "^1.0.0",
|
|
49
|
-
"better-auth": "^1.7.
|
|
49
|
+
"better-auth": "^1.7.12",
|
|
50
50
|
"commander": "^15.0.0",
|
|
51
51
|
"diff": "^9.0.0",
|
|
52
52
|
"hono": "^4.13.13",
|
|
@@ -14,11 +14,12 @@ bun --no-install /opt/protobase/protobase-serve.js /app/protobase.config.js #
|
|
|
14
14
|
|
|
15
15
|
Both builds write plain JavaScript that Node and Bun load as it is. For a host that runs Bun, as the images below do, add `--bun` to either: Bun's bundler then writes the final file, the form Bun loads without transpiling, and the build needs `bun` on `PATH` ([details](../reference/cli.md#the-config-module))).
|
|
16
16
|
|
|
17
|
-
The bundle holds three things,
|
|
17
|
+
The bundle holds three things, more when the project has migrations or the config uses native add-ons:
|
|
18
18
|
|
|
19
19
|
```
|
|
20
20
|
dist/
|
|
21
21
|
protobase.config.js the config module, run by the serve runtime
|
|
22
|
+
migrations/ only with migrations: the project's db/migrations/*.sql, which `migrate` applies
|
|
22
23
|
node_modules/ only with native add-ons: those packages, with linux x64 and arm64 binaries
|
|
23
24
|
public/ the admin app (index.html and content-hashed assets/), the project's UI as plugins in
|
|
24
25
|
plugins/, its theme, protobase.theme.css, and its icons, protobase.favicon.svg
|
|
@@ -27,7 +28,7 @@ dist/
|
|
|
27
28
|
plugins and the app's version
|
|
28
29
|
```
|
|
29
30
|
|
|
30
|
-
The host serves `public/` itself and sends only the manifest's `api` paths to the runtime (and `/.well-known/webauthn`, for an app on [several origins](../reference/auth.md#several-origins))), so loading the UI never needs a running container. The runtime serves the API alone; `protobase serve dist` serves the whole folder the same way, to check a bundle locally. The host passes `DATABASE_URL`, `PORT` (default 8787) and optionally `PROTOBASE_DB_CONNECTIONS` (the connections the app may open, so its functions and jobs leave one to requests, see [`serve`](../reference/cli.md#serve))), `REQUEST_LOG`, `PROTOBASE_SMTP_URL` and `PROTOBASE_MAIL_FROM` (the mail server and sender for [password reset](../reference/auth.md#password-reset)) and emailed sign-in codes) `PROTOBASE_APP_NAME` (the app's name in that mail, see [`appName`](../reference/auth.md#configuration))) `PROTOBASE_SIGN_IN_*` (a provider people with an account sign in with, the [platform sign-in provider](../reference/auth.md#platform-sign-in-provider))) `PROTOBASE_OPERATOR_*` (the provider its staff sign in with for [staff sign-in](../reference/auth.md#staff-sign-in))), `PROTOBASE_ORIGINS` and `PROTOBASE_PASSKEY_DOMAIN` (the app's [other origins](../reference/auth.md#several-origins)) and its passkey domain) `PROTOBASE_CORS_ORIGINS` (the websites that may call its API, see [CORS](../reference/api.md#cors))), `PROTOBASE_TRUSTED_PROXIES` (the proxies in front of the runtime, whose `X-Forwarded-For` names the client the sign-in limits count, see [Client addresses](../reference/auth.md#client-addresses))) and `PROTOBASE_SENTRY_DSN` (the app's [error tracker](../reference/api.md#error-reporting))), plus the project's own settings (`BETTER_AUTH_SECRET`, ...). The runtime and the config module are plain JavaScript for Bun: no install, no TypeScript, no writes. The runtime supplies protobase and the dependencies it runs on the server (`pg`, `postgres`, `kysely`, `better-auth`, ...), so the config module carries only the project's code and the other packages it uses. The runtime serves only bundles built by a compatible Protobase version, below 1.0 the same minor (see [Versioning](../reference/versioning.md#bundles-and-runtimes))), so rebuild the bundle when the host's runtime moves to another one.
|
|
31
|
+
The host serves `public/` itself and sends only the manifest's `api` paths to the runtime (`/api` and the two OAuth discovery documents of [MCP clients](../reference/auth.md#oauth-for-mcp-clients)), and `/.well-known/webauthn`, for an app on [several origins](../reference/auth.md#several-origins))), so loading the UI never needs a running container. With the UI it sends `X-Frame-Options: DENY` and `Content-Security-Policy: frame-ancestors 'none'`, as `protobase serve` does, so no other site frames the app's pages. The runtime serves the API alone; `protobase serve dist` serves the whole folder the same way, to check a bundle locally. The host passes `DATABASE_URL`, `PORT` (default 8787) and optionally `PROTOBASE_DB_CONNECTIONS` (the connections the app may open, so its functions and jobs leave one to requests, see [`serve`](../reference/cli.md#serve))), `REQUEST_LOG`, `PROTOBASE_SMTP_URL` and `PROTOBASE_MAIL_FROM` (the mail server and sender for [password reset](../reference/auth.md#password-reset)) and emailed sign-in codes) `PROTOBASE_APP_NAME` (the app's name in that mail, see [`appName`](../reference/auth.md#configuration))) `PROTOBASE_SIGN_IN_*` (a provider people with an account sign in with, the [platform sign-in provider](../reference/auth.md#platform-sign-in-provider))) `PROTOBASE_OPERATOR_*` (the provider its staff sign in with for [staff sign-in](../reference/auth.md#staff-sign-in))), `PROTOBASE_ORIGINS` and `PROTOBASE_PASSKEY_DOMAIN` (the app's [other origins](../reference/auth.md#several-origins)) and its passkey domain) `PROTOBASE_CORS_ORIGINS` (the websites that may call its API, see [CORS](../reference/api.md#cors))), `PROTOBASE_TRUSTED_PROXIES` (the proxies in front of the runtime, whose `X-Forwarded-For` names the client the sign-in limits count, see [Client addresses](../reference/auth.md#client-addresses))) and `PROTOBASE_SENTRY_DSN` (the app's [error tracker](../reference/api.md#error-reporting))), plus the project's own settings (`BETTER_AUTH_SECRET`, ...). The runtime and the config module are plain JavaScript for Bun: no install, no TypeScript, no writes. The runtime supplies protobase and the dependencies it runs on the server (`pg`, `postgres`, `kysely`, `better-auth`, ...), so the config module carries only the project's code and the other packages it uses. The runtime serves only bundles built by a compatible Protobase version, below 1.0 the same minor (see [Versioning](../reference/versioning.md#bundles-and-runtimes))), so rebuild the bundle when the host's runtime moves to another one. Serving never changes the database: the bundle carries the project's `db/migrations` as `migrations/`, and the runtime's `migrate <bundle>` applies the pending ones, the app's and the auth schema's, before a new version serves, with no other writes while it runs. It applies them in one transaction behind a lock, recorded in `public.schema_migrations` as the presets' `db:migrate` does, so a database either script migrated is current for the other. A file that would end that transaction (`BEGIN`, `COMMIT`, `ROLLBACK`) or cannot run in one (`create index concurrently`) is refused, and a refused or failing file leaves the database unchanged. The runtime refuses to start while the auth schema lacks a table or column the new version needs (see [migrations](../reference/auth.md#migrations))). The manifest format and the routing rules are in the CLI reference: [`build`](../reference/cli.md#build)), [`build-serve`](../reference/cli.md#build-serve)) and [`serve`](../reference/cli.md#serve)).
|
|
31
32
|
|
|
32
33
|
## Images
|
|
33
34
|
|
|
@@ -35,7 +36,7 @@ Every release pushes two public images to GitHub's registry, for `linux/amd64` a
|
|
|
35
36
|
|
|
36
37
|
| Image | What it holds |
|
|
37
38
|
| --- | --- |
|
|
38
|
-
| `ghcr.io/prototeamhq/protobase:<version>` | the serve runtime, compiled with Bun into `/opt/protobase/protobase-serve`, which serves the API of the bundle mounted at `/app
|
|
39
|
+
| `ghcr.io/prototeamhq/protobase:<version>` | the serve runtime, compiled with Bun into `/opt/protobase/protobase-serve`, which serves the API of the bundle mounted at `/app` (and, given the folder, its app too, see [a self-hosted image](#a-self-hosted-image)); the release's prebuilt admin app at `/opt/protobase/shell`, which a host may serve for the bundle's [shell paths](../reference/plugins.md#the-shell)) instead of the bundle's copy; Bun for its healthcheck on `/health`, and the C++ runtime native add-ons link. It runs as `nonroot` (65532) and writes nothing, so it runs with a read-only root filesystem |
|
|
39
40
|
| `ghcr.io/prototeamhq/protobase-dev:<version>` | Bun and the presets at `/opt/protobase/presets/<name>` (`erp`, `real-estate`, `scratch`), with the dependencies they share installed in `/workspace` and Bun's cache in `/opt/bun-cache`. It has no Node: the presets' scripts and the `protobase` command run on Bun. It runs as `bun` (1000) |
|
|
40
41
|
|
|
41
42
|
```sh
|
|
@@ -51,3 +52,120 @@ bun run images:context # dist/images/protobase and dist/images/protobase-dev
|
|
|
51
52
|
docker build -f docker/protobase/Dockerfile -t protobase dist/images/protobase
|
|
52
53
|
docker build -f docker/protobase-dev/Dockerfile -t protobase-dev dist/images/protobase-dev
|
|
53
54
|
```
|
|
55
|
+
|
|
56
|
+
## A self-hosted image
|
|
57
|
+
|
|
58
|
+
A product built on Protobase ships to self-hosters as one image: the runtime image with the bundle inside. Build the bundle with `protobase build --bun`, then:
|
|
59
|
+
|
|
60
|
+
```dockerfile
|
|
61
|
+
# The runtime of the @protobase/cli version that built dist/.
|
|
62
|
+
FROM ghcr.io/prototeamhq/protobase:0.2.0
|
|
63
|
+
COPY dist /app
|
|
64
|
+
CMD ["/app"]
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
The image runs three commands:
|
|
68
|
+
|
|
69
|
+
- `/app` serves the admin app and its API.
|
|
70
|
+
- `migrate /app` applies the bundle's pending migrations with `DATABASE_URL` alone. It runs none of the app's code.
|
|
71
|
+
- `create-admin /app <email>` creates an admin, with `--generate-password` (printed once) or `--password-stdin`. It refuses a schema that is behind.
|
|
72
|
+
|
|
73
|
+
### Compose template
|
|
74
|
+
|
|
75
|
+
Two files next to `compose.yaml` hold the settings. `.env`, which compose reads itself:
|
|
76
|
+
|
|
77
|
+
```sh
|
|
78
|
+
APP_VERSION=1.0.0
|
|
79
|
+
POSTGRES_PASSWORD=... # openssl rand -hex 24
|
|
80
|
+
APP_DB_PASSWORD=... # openssl rand -hex 24
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
`app.env`, the app's own settings:
|
|
84
|
+
|
|
85
|
+
```sh
|
|
86
|
+
BETTER_AUTH_SECRET=... # openssl rand -base64 32
|
|
87
|
+
BETTER_AUTH_URL=http://localhost:8787
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
`BETTER_AUTH_URL` is the address the browser opens, exactly: sign-in from `http://127.0.0.1:8787` is refused as another origin. Add the app's other variables to `app.env` too.
|
|
91
|
+
|
|
92
|
+
```yaml
|
|
93
|
+
services:
|
|
94
|
+
postgres:
|
|
95
|
+
image: postgres:18
|
|
96
|
+
restart: unless-stopped
|
|
97
|
+
environment:
|
|
98
|
+
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set it in .env}
|
|
99
|
+
APP_DB_PASSWORD: ${APP_DB_PASSWORD:?set it in .env}
|
|
100
|
+
configs:
|
|
101
|
+
- source: app-database
|
|
102
|
+
target: /docker-entrypoint-initdb.d/app-database.sql
|
|
103
|
+
volumes:
|
|
104
|
+
- db:/var/lib/postgresql
|
|
105
|
+
healthcheck:
|
|
106
|
+
test: ["CMD", "pg_isready", "-h", "127.0.0.1", "-U", "app", "-d", "app"]
|
|
107
|
+
interval: 2s
|
|
108
|
+
retries: 30
|
|
109
|
+
|
|
110
|
+
migrate:
|
|
111
|
+
image: ghcr.io/example/my-app:${APP_VERSION:?set it in .env}
|
|
112
|
+
command: ["migrate", "/app"]
|
|
113
|
+
environment:
|
|
114
|
+
DATABASE_URL: postgres://app:${APP_DB_PASSWORD:?set it in .env}@postgres:5432/app
|
|
115
|
+
depends_on:
|
|
116
|
+
postgres:
|
|
117
|
+
condition: service_healthy
|
|
118
|
+
|
|
119
|
+
app:
|
|
120
|
+
image: ghcr.io/example/my-app:${APP_VERSION:?set it in .env}
|
|
121
|
+
restart: unless-stopped
|
|
122
|
+
env_file: app.env
|
|
123
|
+
environment:
|
|
124
|
+
DATABASE_URL: postgres://app:${APP_DB_PASSWORD:?set it in .env}@postgres:5432/app
|
|
125
|
+
ports:
|
|
126
|
+
- "127.0.0.1:8787:8787"
|
|
127
|
+
depends_on:
|
|
128
|
+
migrate:
|
|
129
|
+
condition: service_completed_successfully
|
|
130
|
+
|
|
131
|
+
configs:
|
|
132
|
+
app-database:
|
|
133
|
+
content: |
|
|
134
|
+
\getenv app_password APP_DB_PASSWORD
|
|
135
|
+
create role app login password :'app_password';
|
|
136
|
+
create database app owner app;
|
|
137
|
+
|
|
138
|
+
volumes:
|
|
139
|
+
db:
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
`docker compose up -d` starts Postgres, runs `migrate` once and starts the app only when it succeeded. The app and `migrate` connect as `app`, which owns its database but is no superuser (see the [assistant](../reference/assistant.md)) on why that matters); the superuser's password stays in `.env` and the `postgres` service. Postgres runs the init file only on an empty volume. `configs` with `content` needs a recent Compose v2 (tested with 2.39.4).
|
|
143
|
+
|
|
144
|
+
### Local only by default
|
|
145
|
+
|
|
146
|
+
The template publishes the app on `127.0.0.1:8787` only, so only the machine running it can open `http://localhost:8787`, and it speaks plain HTTP. To try it on a remote server, tunnel it with `ssh -L 8787:localhost:8787 <server>` and open `http://localhost:8787` on your own machine.
|
|
147
|
+
|
|
148
|
+
Before other machines may reach it, put HTTPS in front: a reverse proxy on the host that forwards to `127.0.0.1:8787`, with `BETTER_AUTH_URL` set to the `https://` address. Only then are the session cookies `Secure` and passwords and codes encrypted on the way. Do not change the port to `8787:8787`: that publishes plain HTTP on every interface, ahead of host firewall rules such as ufw. On Docker Engine older than 28.0, hosts on the same local network can still reach a port published to `127.0.0.1`, so use 28.0 or newer.
|
|
149
|
+
|
|
150
|
+
### First admin
|
|
151
|
+
|
|
152
|
+
```sh
|
|
153
|
+
docker compose run --rm --no-deps app create-admin /app you@example.com --generate-password
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
Then open `http://localhost:8787` and sign in with that email and the printed password. `--no-deps` keeps compose from running `migrate` first, which during an upgrade would migrate under the old version while it serves; use it with every `docker compose run … app`. Where container logs leave the host, pass the password on stdin instead: `docker compose run --rm --no-deps -T app create-admin /app you@example.com --password-stdin < password.txt`.
|
|
157
|
+
|
|
158
|
+
### Upgrade
|
|
159
|
+
|
|
160
|
+
```sh
|
|
161
|
+
docker compose exec -T postgres pg_dump -U app app > backup.sql
|
|
162
|
+
# set APP_VERSION in .env to the new version
|
|
163
|
+
docker compose pull
|
|
164
|
+
docker compose stop app # the old version stops, so nothing writes
|
|
165
|
+
docker compose run --rm migrate
|
|
166
|
+
docker compose up -d
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
Stop any `protobase worker` processes before `migrate` too.
|
|
170
|
+
|
|
171
|
+
When a migration fails, `migrate` exits with an error and its transaction is rolled back, so the schema is unchanged. Set `APP_VERSION` back and `docker compose start app` brings the old version back on it. A plain `docker compose up -d` with the new version also stops the old one before `migrate`, but after a failure nothing serves until `APP_VERSION` is set back and `up -d` runs again. Going back after a migration that succeeded needs the backup.
|
|
@@ -112,7 +112,7 @@ Get responses carry `permissions: { update, delete, fields }`, where `fields` ma
|
|
|
112
112
|
|
|
113
113
|
## Sensitive fields and audit
|
|
114
114
|
|
|
115
|
-
A field declared [`.sensitive()`](data-config.md#sensitive-fields)) is in `/meta` (marked `sensitive: true`), in record `permissions.fields` and in create and update bodies, but in no list, get, `:search`, `:seek`, write or batch response, and `filter`, `order_by`, `fields` and the aggregates refuse it like an unknown field. `POST /{resource}/{key}:reveal` with `{ "field": "<name>" }` returns one record's value. It needs read access to the record and the field: another tenant's record, a row outside the caller's row filter or a key that does not exist is a `404`, a field the caller cannot read or that is not sensitive a `400`.
|
|
115
|
+
A field declared [`.sensitive()`](data-config.md#sensitive-fields)) is in `/meta` (marked `sensitive: true`), in record `permissions.fields` and in create and update bodies, but in no list, get, `:search`, `:seek`, write or batch response, and `filter`, `order_by`, `fields` and the aggregates refuse it like an unknown field. `POST /{resource}/{key}:reveal` with `{ "field": "<name>" }` returns one record's value. It needs read access to the record and the field: another tenant's record, a row outside the caller's row filter or a key that does not exist is a `404`, a field the caller cannot read or that is not sensitive a `400`. An [encrypted field](data-config.md#encrypted-fields))'s reveal decrypts its value, and an empty one reveals `null`; a value that does not decrypt is a `500` reported to the operator, without an audit event. An update that changes the key of a record with encrypted fields is a `400` `key-change-unsupported`.
|
|
116
116
|
|
|
117
117
|
Before answering, the server publishes an audit event to `options.audit`, and when publishing fails the reveal fails (`500`), so no value leaves without its event. The event never holds the value:
|
|
118
118
|
|
|
@@ -507,6 +507,25 @@ const { token, expiresAt } = await issueToken(auth, { email: 'you@example.com',
|
|
|
507
507
|
|
|
508
508
|
It is signed with the same keys and carries the same claims as a token from `/api/auth/token`, with the role the user last chose, else their first, so the API treats it as any other, and a ban, a role taken away or the user deleted ends it before it expires. Banned and unknown users get an error. There is no HTTP route for this.
|
|
509
509
|
|
|
510
|
+
## OAuth for MCP clients
|
|
511
|
+
|
|
512
|
+
With `mcp`, the app is an OAuth provider for MCP clients, such as AI assistants and code editors that speak MCP: a person adds the app's MCP address to the client, the client registers itself, the person signs in on the app's own pages and allows it on the connect page, and the client gets tokens that act as that person.
|
|
513
|
+
|
|
514
|
+
```ts
|
|
515
|
+
createAuth({ ..., mcp: true })
|
|
516
|
+
createAuth({ ..., mcp: { path: '/api/mcp', connectPage: '/-/connect' } })
|
|
517
|
+
```
|
|
518
|
+
|
|
519
|
+
- `path` is the MCP endpoint's path on the origin of `baseURL`, its OAuth resource (default `/api/mcp`); `connectPage` is the connect page's path (default `/-/connect`, for a UI at the root); `fetchClientMetadata` replaces how a client's metadata document is fetched (default a transport that refuses private and reserved addresses). `auth.mcp` is `{ resource, path, scope }`, for the endpoint.
|
|
520
|
+
- It needs an https `baseURL`, or localhost, and the OAuth tables: run `protobase auth migration` after turning it on (see [migrations](#migrations)). Clients connect through `baseURL`'s origin only, whatever [other origins](#several-origins) the app has. Changing `path` makes every client connect again.
|
|
521
|
+
- Clients find the provider at `/.well-known/oauth-protected-resource` and `/.well-known/oauth-authorization-server`, register at `/api/auth/oauth2/register` (dynamic registration) or are known by an https client id that names their metadata document (CIMD), and are asked for nothing per client. Back-channel logout, a key set URL at registration (`jwks_uri`) and the client credentials grant are refused, though a client with a metadata document may publish its keys on its own origin, and the provider's client management, userinfo, logout and consent endpoints are closed.
|
|
522
|
+
- The scopes are `mcp` and `offline_access`, which is added when a client leaves it out. Access tokens last 15 minutes, carry the MCP resource as their audience and `typ: at+jwt`, and work for MCP only: the app's API refuses them, and the MCP endpoint refuses the app's own tokens. Refresh tokens roll for 30 days. `betterAuthAuthenticator(...).forAudience(auth.mcp.resource)` verifies them; a client that binds its tokens to a key (DPoP) sends a proof with each, checked against the resource's URL.
|
|
523
|
+
- A grant keeps the role and organization the person worked in when they allowed the client. A refresh is refused once they no longer hold that role or may no longer enter that organization, once the [sign-in policy](#sign-in-policy) requires something they have not set up, and while they are banned; access tokens already issued last out their 15 minutes. A grant made without a role is refused.
|
|
524
|
+
- Someone who has not set up what the sign-in policy requires is sent to the setup page first. Staff signed in as a person cannot allow a client, nor disconnect one. An account whose address is not verified cannot connect a client until it signs in once with an emailed code: a provider sign-up whose provider did not vouch for the address, or a password account created before Protobase created accounts verified. With password-only sign-in, or without mail, it cannot.
|
|
525
|
+
- The connect page shows the client's name as the client's own claim, who published it for a client with an https id, where the code goes (a website by its host, an app on this computer by its port, or an app on the device by its whole address), and the signed-in address. It cannot be used inside another site's frame, and Allow takes a click only once the page has been in front for half a second. `protobase serve` and `protobase dev` send `X-Frame-Options: DENY` and `Content-Security-Policy: frame-ancestors 'none'` with every page of the UI; a host that serves `public/` itself should send them too.
|
|
526
|
+
- The account page lists the clients a person allowed, under Connected apps, and disconnects any one: its consent is forgotten and its tokens revoked, so it has to ask again. A client published at a URL has one id for everyone, so two copies of it allowed on one account with the same role show as one entry, and disconnecting it disconnects both.
|
|
527
|
+
- Signing out everywhere, signing out the other devices, a password change that signs out the other devices, a password reset, an admin ending the person's sessions, banning them, setting their password or marking their address unverified, and `protobase users disable` disconnect every client and forget which were allowed, so each has to ask again; enabling a disabled user brings none back. Through the [endpoints for supabase-js](#supabase-js-and-supabasessr) the same holds for signing out with the `global` or `others` scope and for every new password set with `PUT /user`, since a password reset ends there too. Signing out of one browser, or a session expiring, disconnects nothing.
|
|
528
|
+
|
|
510
529
|
## Several origins
|
|
511
530
|
|
|
512
531
|
An app can be served on more than one origin, such as its platform address and the customer's own domain. `origins` lists the others; it defaults to `PROTOBASE_ORIGINS`, which a platform sets:
|
|
@@ -524,7 +543,7 @@ createAuth({ ..., baseURL: 'https://erp-x1.protobase.net', origins: ['https://ad
|
|
|
524
543
|
|
|
525
544
|
## Public endpoints
|
|
526
545
|
|
|
527
|
-
Only the Better Auth routes under `/api/auth/*` (sign-in, password reset, [open sign-up](#open-sign-up), the start and callback of a [staff sign-in](#staff-sign-in) and the like), `GET /api/auth/status
|
|
546
|
+
Only the Better Auth routes under `/api/auth/*` (sign-in, password reset, [open sign-up](#open-sign-up), the start and callback of a [staff sign-in](#staff-sign-in), and with [MCP](#oauth-for-mcp-clients) the OAuth provider's register, token and authorize, and the like), `GET /api/auth/status`, with MCP the two OAuth discovery documents under `/.well-known/`, and, with [several origins](#several-origins), `GET /.well-known/webauthn` are reachable without a token; the account, policy and staff session endpoints there need a session. The API (`/api/v1/*`) and the system endpoints (`/api/meta`, `/api/openapi.json`, `/api/docs`) all answer `401` without one, but for what an [anonymous role](access.md#anonymous-access)) reads in `/api/v1` and `/api/meta`, when the project defines one. [Public forms](forms.md#routes)) (`/api/forms/*`) need no token either.
|
|
528
547
|
|
|
529
548
|
## Roles and access in the API
|
|
530
549
|
|
|
@@ -175,6 +175,7 @@ Writes the project's deploy bundle, the folder a deployment ships:
|
|
|
175
175
|
```
|
|
176
176
|
dist/
|
|
177
177
|
protobase.config.js the config module for serve
|
|
178
|
+
migrations/ the project's db/migrations/*.sql, which the runtime's migrate applies; only with some
|
|
178
179
|
node_modules/ the packages it loads from disk, only when it imports native add-ons
|
|
179
180
|
public/
|
|
180
181
|
index.html, assets/ the admin app: the shell, the same for every project
|
|
@@ -187,7 +188,7 @@ dist/
|
|
|
187
188
|
protobase.bundle.json the manifest
|
|
188
189
|
```
|
|
189
190
|
|
|
190
|
-
The output folder is not emptied; `public/` and `node_modules/` are replaced on every build. `node_modules/`
|
|
191
|
+
The output folder is not emptied; `public/`, `migrations/` and `node_modules/` are replaced on every build. `migrations/` and `node_modules/` are deleted only when the previous build's manifest names them, so a build into a folder with a project's own `node_modules` fails instead. Of the project's server config only the config folder runs at build time, `config/index.ts` and `config/*/ui.ts` with what they import, never `protobase.config.ts`, so the build needs no secrets and no database. It is loaded once in Node to check each view against its resource: a filter widget or the chart on a field that is not `.filterable()`, a list sorted by one that is not `.sortable()`, or a list search on a field outside the resource's `.search(...)` fails the build, naming the view and the field, since the API would refuse it once a page asked. Whether an index serves those reads needs the database, which [`doctor`](#doctor) checks. Its browser code is loaded once in Node too: to check its component names (see [The UI](#the-ui)) and to read the field types each plugin registers.
|
|
191
192
|
|
|
192
193
|
A token the [theme](theme.md)) sets that the app does not read prints a `warning:` line, a likely typo; the build still succeeds.
|
|
193
194
|
|
|
@@ -214,23 +215,25 @@ By default the bundle runs on Node and on Bun. `--bun` makes it a bundle for Bun
|
|
|
214
215
|
"server": "protobase.config.js",
|
|
215
216
|
"public": "public",
|
|
216
217
|
"spa": "index.html",
|
|
217
|
-
"api": ["/api"],
|
|
218
|
+
"api": ["/api", "/.well-known/oauth-authorization-server", "/.well-known/oauth-protected-resource"],
|
|
218
219
|
"theme": "protobase.theme.css",
|
|
219
220
|
"plugins": [
|
|
220
221
|
{ "name": "app", "path": "plugins/app/plugin.json", "api": 1, "protobase": ">=0.12.0", "fields": { "steps": ["enum"] } }
|
|
221
222
|
],
|
|
222
223
|
"shell": { "protobase": "0.12.0", "pluginApi": 1, "paths": ["/index.html", "/assets", "/protobase.sw.js"] },
|
|
223
|
-
"nodeModules": "node_modules"
|
|
224
|
+
"nodeModules": "node_modules",
|
|
225
|
+
"migrations": "migrations"
|
|
224
226
|
}
|
|
225
227
|
```
|
|
226
228
|
|
|
227
229
|
- `protobase` is the Protobase version that built the bundle. The serve runtime serves only bundles of a compatible version: below 1.0 the same minor, from 1.0 the same major and the runtime's minor or an older one (see [Versioning](versioning.md#bundles-and-runtimes))).
|
|
228
|
-
- `server`, `public` and `
|
|
230
|
+
- `server`, `public`, `nodeModules` and `migrations` are relative to the bundle folder; `spa`, `theme` and each plugin's `path` to `public`.
|
|
229
231
|
- `plugins` are the bundle's own plugins, in the order the app merges them: the extensions', then the project's (`app`). Each names its `plugin.json`, the plugin API and Protobase versions it is built for, and the [field types](plugins.md#field-types)) it registers with the storage types each shows, which the serve runtime checks the views against at startup. `/api/meta` names them to everyone, before any other plugin.
|
|
230
232
|
- `shell` is the admin app `public/` holds a copy of: its Protobase version and plugin API, and its files as URL paths. A host with a shell of its own, of a release every plugin of the bundle loads in, may serve its own for those paths instead (see [The UI](#the-ui)), so the app gets that release's fixes without a rebuild.
|
|
231
233
|
- `theme` is the project's [theme](theme.md)), which the app links at `/protobase.theme.css`. It is always there, empty when the project has none.
|
|
232
234
|
- `nodeModules` is present only when the config module imports [native packages](#native-packages). It is always the `node_modules` folder beside `server`, where Bun and Node resolve the module's imports from, and holds plain packages: JavaScript, `package.json` files and native binaries for linux x64 and arm64 (glibc), which the runtime loads with `dlopen`. A host keeps it next to the server module and must not mount it `noexec` (an add-on there then fails with `failed to map segment from shared object`). Its binaries link nothing but glibc, `libstdc++.so.6`, `libgcc_s.so.1` and libraries in the bundle itself, so the run image must have those three. Without `nodeModules`, the server module is the only file the runtime reads.
|
|
233
|
-
- `
|
|
235
|
+
- `migrations` is present only when the project has a `db/migrations` folder: its `.sql` files, which the runtime's `migrate` applies (see [Deploy](../guides/deploy.md))). A host never serves it.
|
|
236
|
+
- `api` lists the path prefixes the server answers. A path is under a prefix when it equals it or continues it with `/` (`/api` covers `/api/meta` and `/api/v1:batchWrite`, not `/apiary`). It is always `/api` and the two OAuth discovery documents [MCP clients](auth.md#oauth-for-mcp-clients)) read, which answer 404 without MCP: a bundle assumes the API lives under `/api`, with the resources at the default `basePath` `/api/v1`, `/api/meta`, the docs, the API functions and the built-in assistant beside them and Better Auth at `/api/auth`. A bundle built before them sends them to the UI: rebuild it. The serve runtime refuses a config that sets another `options.basePath`.
|
|
234
237
|
- Every other path is the UI's. A `GET` or `HEAD` for a file in `public` gets that file; a folder gets its `index.html`. Otherwise a request whose `Accept` header contains `text/html` (a navigation) gets `spa` with status 200, so deep links such as `/orders/42` load the app; anything else gets 404. Other methods get 405.
|
|
235
238
|
- Files under an `assets/` folder, `public/assets/` and each plugin's, are named by their content hash and never change: serve them with `Cache-Control: public, max-age=31536000, immutable`, and everything else, `index.html`, each `plugin.json` and the theme, with `no-cache`.
|
|
236
239
|
- `version` is the format of the manifest, not a Protobase version. A host that does not know it must refuse the bundle. Version 3 replaced version 2 when the project's UI became a plugin beside a prebuilt app, and gained `plugins`, `theme` and `shell`; version 2 replaced version 1 when the config module started to import [every module the runtime supplies](#the-config-module), and gained `nodeModules`. `protobase serve` refuses an older bundle; rebuild it with `protobase build`.
|
|
@@ -345,6 +348,14 @@ protobase build-serve [--out dist/protobase-serve.js] [--bun] # or, in this re
|
|
|
345
348
|
|
|
346
349
|
Bundles the serve runtime (`@protobase/cli`'s `src/serve/main.ts`) and all its dependencies into one file, about 3 MB. A host needs Bun and this file, nothing else. `--bun` has Bun's bundler write the file, as for [`build`](#build), and needs `bun` on `PATH`; the `protobase` image is built from such a file. The file carries the Protobase version it was built from, which decides [the bundles it serves](versioning.md#bundles-and-runtimes)).
|
|
347
350
|
|
|
351
|
+
```sh
|
|
352
|
+
bun --no-install protobase-serve.js [serve] <bundle> # the folder: the app and the API; the config module: the API
|
|
353
|
+
bun --no-install protobase-serve.js migrate <bundle> # apply the bundle's migrations to DATABASE_URL
|
|
354
|
+
bun --no-install protobase-serve.js create-admin <bundle> <email> # --generate-password or --password-stdin
|
|
355
|
+
```
|
|
356
|
+
|
|
357
|
+
`migrate` runs none of the app's code and needs only `DATABASE_URL`; `create-admin` loads the app with its settings and refuses an auth schema that is behind. Given the folder, the runtime serves the bundle's own copy of the app. [Deploy](../guides/deploy.md#a-self-hosted-image)) puts the three in a self-hosted image.
|
|
358
|
+
|
|
348
359
|
## `serve`
|
|
349
360
|
|
|
350
361
|
```sh
|
|
@@ -377,6 +388,7 @@ Serves the API of a bundle from `protobase build` and owns the process around it
|
|
|
377
388
|
| `PROTOBASE_SOURCES` | other Protobase APIs whose resources the app draws as its own, a JSON list of `{ "url", "label", "resources", "roles"? }` after `options.sources` ([Remote resources](remote-resources.md#declaring-a-source))) |
|
|
378
389
|
| `PROTOBASE_FILES_<NAME>`, `PROTOBASE_FILES_RETENTION`, `PROTOBASE_FILES_SECRET` | [file providers](files.md#providers)) and their settings, over `files` in the config; a bucket's credentials in `PROTOBASE_FILES_<NAME>_ACCESS_KEY_ID` and `_SECRET_ACCESS_KEY` |
|
|
379
390
|
| `PROTOBASE_FILES_CLEANUP_MINUTES` | minutes between runs of the [scheduled file deletes](files.md#deleting-files)), default 60; 0 leaves them to `protobase files cleanup` or the platform |
|
|
391
|
+
| `PROTOBASE_ENCRYPTION_KEY`, `PROTOBASE_ENCRYPTION_PREVIOUS_KEYS` | the key [encrypted fields](data-config.md#encrypted-fields)) are sealed with, 32 random bytes in base64 (`openssl rand -base64 32`), and the comma separated keys they were sealed with before, which still open them |
|
|
380
392
|
| `PROTOBASE_JOBS` | `false` runs none of the app's [jobs](jobs.md)) in this process, which still enqueues them; default `true` |
|
|
381
393
|
| `PROTOBASE_STARTUP_CHECKS` | `false` skips the startup reads of the auth, changes, computed columns, webhooks and jobs schemas, which make a start slower; default `true`. Set it only to restart a bundle that already started on this database, such as when a platform wakes a sleeping app, never for a new bundle or after its migrations ran |
|
|
382
394
|
| `PROTOBASE_SHELL` | `protobase serve <bundle>` only: a shell folder, such as the `/opt/protobase/shell` of a protobase image or `@protobase/ui`'s `dist/shell`, to serve the bundle's app from (see [its own shell](#serve)) |
|
|
@@ -385,10 +397,10 @@ Serves the API of a bundle from `protobase build` and owns the process around it
|
|
|
385
397
|
|
|
386
398
|
Better Auth and other settings are the project's own variables (`BETTER_AUTH_SECRET`, `BETTER_AUTH_URL`, ...), read by its config. `protobase serve` also loads the nearest `.env`, like `dev`; the runtime takes the environment as it is.
|
|
387
399
|
|
|
388
|
-
- **Routes:** `createAdmin` (`/api/v1`, `/api/meta`, `/api/functions/*`, `/api/auth/*`, ...) and `GET /health`, which answers `{"status":"ok"}` without a token and without touching the database. The runtime never serves the UI; `protobase serve <bundle>` serves `public/` for every path outside the manifest's `api` and `/.well-known/webauthn`, after `/health
|
|
400
|
+
- **Routes:** `createAdmin` (`/api/v1`, `/api/meta`, `/api/functions/*`, `/api/auth/*`, ...) and `GET /health`, which answers `{"status":"ok"}` without a token and without touching the database. The runtime never serves the UI; `protobase serve <bundle>` serves `public/` for every path outside the manifest's `api` and `/.well-known/webauthn`, after `/health`, with `X-Frame-Options: DENY` and `Content-Security-Policy: frame-ancestors 'none'`, so no other site frames its pages.
|
|
389
401
|
- **Plugins:** the runtime reads the manifest's `plugins`: `/api/meta` names them, and a view that shows a field with one of their [field types](plugins.md#field-types)) that does not show the field's storage type stops startup, naming the view, the field and what the field type shows.
|
|
390
402
|
- **Version:** before loading the config module, the runtime reads `protobase.bundle.json` beside it and refuses a bundle built by a Protobase version it does not serve, or one without a version, with an error naming both versions (see [Versioning](versioning.md#bundles-and-runtimes))). A config module needs its manifest beside it.
|
|
391
|
-
- **Startup:** a bundle without a default export, `config` or `authenticate`, or with an `options.basePath` other than `/api/v1`, stops startup with a one-line error and exit code 1, as does a missing `DATABASE_URL`, an auth schema that lacks a table or column (see [`auth migration`](#auth-migration)), a resource whose [events](events.md)) or [history](history.md)) lack their triggers or have out-of-date ones, or a missing history or [comments](comments.md#the-table)) table, a [rollup or formula field](data-config.md#rollups-and-formulas)) whose column or trigger is missing or out of date, a jobs schema that is missing or behind for a config with [jobs](jobs.md#the-jobs-schema)) (see [`migration`](#migration)), an [AI field or action](ai.md#the-model)) without a model key, or a taken port; `PROTOBASE_STARTUP_CHECKS=false` skips the checks of those schemas and the key. `protobase serve listening on port <port>` means it is ready.
|
|
403
|
+
- **Startup:** a bundle without a default export, `config` or `authenticate`, or with an `options.basePath` other than `/api/v1`, stops startup with a one-line error and exit code 1, as does a missing `DATABASE_URL`, an auth schema that lacks a table or column (see [`auth migration`](#auth-migration)), a resource whose [events](events.md)) or [history](history.md)) lack their triggers or have out-of-date ones, or a missing history or [comments](comments.md#the-table)) table, a [rollup or formula field](data-config.md#rollups-and-formulas)) whose column or trigger is missing or out of date, a jobs schema that is missing or behind for a config with [jobs](jobs.md#the-jobs-schema)) (see [`migration`](#migration)), an [AI field or action](ai.md#the-model)) without a model key, [encrypted fields](data-config.md#encrypted-fields)) without a key, or another resource over their column, or a taken port; `PROTOBASE_STARTUP_CHECKS=false` skips the checks of those schemas and the key. `protobase serve listening on port <port>` means it is ready.
|
|
392
404
|
- **Jobs:** with [jobs](jobs.md)) in the config it runs them beside the API, unless `PROTOBASE_JOBS=false`, and with `PROTOBASE_JOBS_DRAIN_TOKEN` it answers `POST /api/jobs/drain` for the operator.
|
|
393
405
|
- **Shutdown:** the first SIGTERM or SIGINT stops accepting connections, closes open WebSockets with 1001 (dropping any still open after 5 seconds), waits for open requests, gives running jobs 30 seconds to finish, drains the pool `serve` created (a `db` the config exports is the project's to close) and exits with 0.
|
|
394
406
|
- **Host modules:** under Bun, the runtime registers [the modules it supplies](#the-config-module) as virtual modules, so the bundle needs no `node_modules` for them. `protobase serve`, on Node or Bun, resolves them from the `node_modules` next to the bundle, so keep the bundle inside the project. Native packages load from the bundle's own `node_modules/` under both.
|
|
@@ -411,6 +423,29 @@ protobase files cleanup <bundle> # a bundle from `protobase build`: its folder
|
|
|
411
423
|
|
|
412
424
|
Runs the [scheduled file deletes](files.md#deleting-files)) that are due: replaced and cleared files past their retention, and uploads nobody saved. A file a row references again is kept. It prints each file it deleted or kept. It reads the `.env` nearest the current directory and needs `DATABASE_URL` unless the config exports `db`. `protobase serve` runs the same every hour; this is for cron, or a host that turns that off.
|
|
413
425
|
|
|
426
|
+
## `encryption status`
|
|
427
|
+
|
|
428
|
+
```sh
|
|
429
|
+
protobase encryption status # the project in the current directory
|
|
430
|
+
protobase encryption status <bundle> # a bundle from `protobase build`: its folder or its protobase.config.js
|
|
431
|
+
```
|
|
432
|
+
|
|
433
|
+
Reads every [encrypted field](data-config.md#encrypted-fields))'s column and prints its values per key id, the current one marked, its plaintext values, and each value that does not decrypt by record key, with why (`not-encrypted`, `malformed`, `unknown-key`, `failed-authentication`) and never the value. It also prints the history rows and undispatched changes that still hold a field's old values, encrypted values in fields that are not encrypted, and foreign keys `on update cascade` that change a record's key. It writes nothing, so it shows what `apply` would do. It exits with 1 when anything is plaintext, under a previous key, unreadable, misplaced or left in history, so a script can gate on it. It takes the keys from the environment and the `.env` nearest the current directory, like `serve`, and needs `DATABASE_URL` unless the config exports `db`.
|
|
434
|
+
|
|
435
|
+
## `encryption apply`
|
|
436
|
+
|
|
437
|
+
```sh
|
|
438
|
+
protobase encryption apply [bundle]
|
|
439
|
+
protobase encryption apply --rebind people --from-table persons # after a table rename
|
|
440
|
+
protobase encryption apply --rebind people.iban --from-column bank_iban # after a column rename
|
|
441
|
+
```
|
|
442
|
+
|
|
443
|
+
Encrypts every plaintext value of the encrypted fields with the current key, encrypts values under a previous key again with it, and removes the fields' old values from the [history](history.md)) and the changes not yet dispatched. Values that do not decrypt are listed and left as they are; it exits with 1 when any remain. Its writes are captured by no event, history or webhook, and a value a write changes while it runs is left to that write. It refuses to run when a column holds values under none of its keys, such as with another key than the app's.
|
|
444
|
+
|
|
445
|
+
`--rebind <resource>[.<field>]` with `--from-table <table>` (as `.table()` wrote it) or `--from-column <column>` also takes values sealed where the field was before a rename, and seals them where it is now; running it again rebinds nothing more. It refuses a former place another resource still encrypts.
|
|
446
|
+
|
|
447
|
+
Run it at update time, after the migrations and before the new version serves, and again once an old version that wrote plaintext has stopped. It works over one database connection, so a project's own `db` with a pool of one is enough.
|
|
448
|
+
|
|
414
449
|
## `users`
|
|
415
450
|
|
|
416
451
|
```sh
|
|
@@ -425,9 +460,9 @@ protobase users delete <email> [--yes]
|
|
|
425
460
|
|
|
426
461
|
Run inside a project whose `protobase.config.ts` exports `auth` (Better Auth). There is no web setup page, and [open sign-up](auth.md#open-sign-up)), when a project turns it on, waits for the first admin: the first admin is created here. The first user is always an admin, whatever `--role` says; later users get `--role`, or the project's default role (`createAuth({ roles, defaultRole })`). `protobase users roles` lists the roles of the project; anything else is refused with that list. `set-role` also takes comma separated roles (`sales,accountant`). `--github-id` links the new user to a GitHub user id (the number, not the login), so signing in with GitHub, the app's own provider or the [platform's](auth.md#platform-sign-in-provider)), finds them whatever address GitHub reports; an id that signs in another user already is refused. `createUser(auth, { ..., accounts: [{ providerId, accountId }] })` does the same from code.
|
|
427
462
|
|
|
428
|
-
The password is typed at a hidden prompt with confirmation, read from stdin with `--password-stdin` (for scripts, e.g. `pass show erp | protobase users create me@example.com --password-stdin`), or generated with `--generate-password` and printed once. `--no-password` makes an account without one, which signs in by [emailed code](auth.md#emailed-sign-in-codes)), passkey or a sign-in provider, as with an app whose [sign-in policy](auth.md#sign-in-policy)) turns passwords off. A password is never accepted as an argument, since it would end up in shell history. `users list` prints email, role and creation date (and `disabled` for banned users), never credentials.
|
|
463
|
+
The password is typed at a hidden prompt with confirmation, read from stdin with `--password-stdin` (for scripts, e.g. `pass show erp | protobase users create me@example.com --password-stdin`), or generated with `--generate-password` and printed once; it must be 12 to 128 characters, the length the app requires of every new password. `--no-password` makes an account without one, which signs in by [emailed code](auth.md#emailed-sign-in-codes)), passkey or a sign-in provider, as with an app whose [sign-in policy](auth.md#sign-in-policy)) turns passwords off. A password is never accepted as an argument, since it would end up in shell history. `users list` prints email, role and creation date (and `disabled` for banned users), never credentials.
|
|
429
464
|
|
|
430
|
-
`delete` asks you to type the email back (or pass `--yes`), and needs a terminal otherwise. `delete`, `set-role` and `disable` refuse to touch the last admin, so the project cannot lock itself out. `disable` bans the user and revokes their sessions; tokens already issued stop working on their next request, and `protobase token` refuses disabled users. `enable` lifts the ban. `protobase dev` prints "No users yet. Create the first admin with: protobase users create you@example.com" at startup while the user table is empty.
|
|
465
|
+
`delete` asks you to type the email back (or pass `--yes`), and needs a terminal otherwise. `delete`, `set-role` and `disable` refuse to touch the last admin, so the project cannot lock itself out. `disable` bans the user and revokes their sessions; tokens already issued stop working on their next request, and `protobase token` refuses disabled users. With [MCP](auth.md#oauth-for-mcp-clients)) on, it also disconnects their MCP clients. `enable` lifts the ban; the clients have to be allowed again. `protobase dev` prints "No users yet. Create the first admin with: protobase users create you@example.com" at startup while the user table is empty.
|
|
431
466
|
|
|
432
467
|
With [organizations](auth.md#organizations)), `--role` is the user's global role (none by default) and `--organization` adds the new user to an organization, with `--org-role` (`owner`, `admin`, or `member`, the default) and `--app-roles` there.
|
|
433
468
|
|
|
@@ -109,6 +109,7 @@ Every option returns a new [field](https://docs.protobase.net/api/schema/interfa
|
|
|
109
109
|
| `.column('name')` | The column, when it is not the snake_case of the field name (`'EMP_NAME'`). |
|
|
110
110
|
| `.access({ read, create, update })` | Role rules for this column. See [Access](#access). |
|
|
111
111
|
| `.sensitive()` | Hidden like a password: no response carries it, and a caller who may read it reveals one record's value at a time. See [Sensitive fields](#sensitive-fields). |
|
|
112
|
+
| `.encrypted()` | Sensitive, and stored encrypted with the app's own key, so the database only ever holds ciphertext. Text only. See [Encrypted fields](#encrypted-fields). |
|
|
112
113
|
| `.ai({ prompt })` | A job fills the field from `prompt`, `{field}` replaced by the record's values, after a create and after an update of a field the prompt reads, as the user who wrote. Text or enum, optional. See [AI fields and actions](ai.md)). |
|
|
113
114
|
| `.rollup({ from, via, fn, field })` | The database keeps the field from the records of another resource: their count, sum, average, least or greatest value. Read-only. See [Rollups and formulas](#rollups-and-formulas). |
|
|
114
115
|
| `.formula(expression)` | The database computes the field from the record's other number fields, as a generated column. Read-only. See [Rollups and formulas](#rollups-and-formulas). |
|
|
@@ -205,6 +206,66 @@ iban: f.text().sensitive().access({ read: roles.can('screening.read') }),
|
|
|
205
206
|
|
|
206
207
|
A sensitive field cannot be `.filterable()`, `.sortable()`, aliased, searched, or the key, tenant, owner or soft delete field, and a view may only put it in a record page section: in a list, filter, chart, sidebar, title, recent-record group or action it would always be empty, so the config fails to load.
|
|
207
208
|
|
|
209
|
+
## Encrypted fields
|
|
210
|
+
|
|
211
|
+
An encrypted field is a [sensitive field](#sensitive-fields) whose value the server encrypts before it reaches the database, so a dump, a backup, a replica, a realtime subscriber or anyone running SQL sees only ciphertext. Only its reveal decrypts it, for a caller who may read the record and the field, and every reveal is audited. Every API write encrypts it: the record form, REST, batches, imports, [public forms](forms.md)) and `records` in [API functions](../guides/api-functions.md)). The [Supabase-compatible REST API](supabase-rest.md#encrypted-fields)) refuses to write or filter it.
|
|
212
|
+
|
|
213
|
+
```ts
|
|
214
|
+
api_key: f.text().encrypted().access({ read: roles.can('keys.read') }),
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
It takes `f.text()` only, and cannot be `.readOnly()` or have a `.dbDefault()`. Its column must be `text`, with no length, pattern or unique constraint, index, default, trigger or generated column reading it: the database only ever sees ciphertext.
|
|
218
|
+
|
|
219
|
+
**Write it only through the API.** SQL of your own, in an API function's `db`, a write hook's transaction or the assistant's approved changes, stores the value unencrypted, and its reveal then fails until [`protobase encryption apply`](cli.md#encryption-apply)) encrypts it.
|
|
220
|
+
|
|
221
|
+
**Your code never sees the stored value, only whether it is set.** Access rules cannot filter on it: a rule that returns a filter on it fails the request. Record rules, validators and write hooks get a stored record with a set value as `encrypted` (exported from `@protobase/schema`) and an empty one as `null`. Check whether it is set with `== null`; the marker is never equal to anything, so a rule comparing it with a constant decides as if it held another value, and reading it as text throws. One check cannot know whether it is set: the read rule a [webhook subscription](webhooks.md)) delivering `as` a role runs on a captured change, which holds no encrypted field, so a rule that reads one there throws and the change is kept as failed instead of delivered. Rules and validators see the plaintext only where a write gives it, so a validator written this way checks each value written and leaves a stored one alone:
|
|
222
|
+
|
|
223
|
+
```ts
|
|
224
|
+
.validate((r) => (typeof r.iban === 'string' && !r.iban.startsWith('NL') ? [{ field: 'iban', message: 'A Dutch IBAN' }] : undefined))
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
When you change a `.sensitive()` field to `.encrypted()`, change every rule, validator and hook that reads its stored value: from then on it gets `encrypted`, and TypeScript flags reading it as text.
|
|
228
|
+
|
|
229
|
+
No other field of the resource may be over the column, as its own or as a relation's column, and another resource over the same table must leave the column out, or declare it `.encrypted()` too with the same `.table()`, tenant and key; the server does not start otherwise. A resource over a view of the table cannot be checked, so leave the column out of the view itself, not only out of the resource.
|
|
230
|
+
|
|
231
|
+
### The key
|
|
232
|
+
|
|
233
|
+
The app's key is `PROTOBASE_ENCRYPTION_KEY`: 32 random bytes in base64, such as the output of `openssl rand -base64 32`. It is its own: never `BETTER_AUTH_SECRET` or an API key, nor derived from one, so rotating those loses nothing. Keep it apart from the database's backups, since whoever holds both reads every value. The server does not start with an encrypted field and no key, or a key that is not 32 bytes in base64.
|
|
234
|
+
|
|
235
|
+
To rotate it on several instances:
|
|
236
|
+
|
|
237
|
+
1. Add the new key to `PROTOBASE_ENCRYPTION_PREVIOUS_KEYS` (comma separated) everywhere, so every instance can read what it seals.
|
|
238
|
+
2. Make the new key `PROTOBASE_ENCRYPTION_KEY`, with the old one in `PROTOBASE_ENCRYPTION_PREVIOUS_KEYS`.
|
|
239
|
+
3. Run `protobase encryption apply`, which encrypts the old key's values with the new one.
|
|
240
|
+
4. Drop the old key once `protobase encryption status` shows none of its values. Keep retired keys as long as you keep backups made under them.
|
|
241
|
+
|
|
242
|
+
**A lost key loses its values.** Nothing can decrypt them; `status` lists them as `unknown-key`, and writing a new value replaces one. `apply` refuses to run while a column holds values under none of its keys, so a wrong key in a local `.env` does not seal values the app cannot read; clear values whose key is lost (set them to `null` with SQL) to go on.
|
|
243
|
+
|
|
244
|
+
There is no command that decrypts a field, so keep `.encrypted()` on a field while its column holds encrypted values; `status` reports encrypted values in a field that is not encrypted.
|
|
245
|
+
|
|
246
|
+
### What a value is bound to
|
|
247
|
+
|
|
248
|
+
A value opens only where it was sealed: its table as `.table()` names it (with or without the schema), its column, its record's tenant and its record's key. Copying it to another row, column or tenant makes it unreadable rather than readable there.
|
|
249
|
+
|
|
250
|
+
- Renaming the resource or the field in the config changes nothing.
|
|
251
|
+
- Renaming the table or the column, moving the table to another schema, or adding or changing the schema in `.table()` makes the field's values unreadable until `protobase encryption apply --rebind people --from-table <old table>` (or `--rebind people.iban --from-column <old column>`) runs. Run it at update time, like a migration; reveals fail until then.
|
|
252
|
+
- Changing a resource's declared key or tenant field makes its values unreadable, and no command rebinds them: make such a change before encrypting.
|
|
253
|
+
- The record key must be unique in its table, as [`protobase doctor`](cli.md#doctor)) checks, or at least within each tenant. A key changed in the database, by SQL, a trigger or a foreign key `on update cascade` (which `status` warns about), makes that row's values unreadable; the API refuses to change the key of a record with encrypted fields.
|
|
254
|
+
|
|
255
|
+
### Encrypting an existing column
|
|
256
|
+
|
|
257
|
+
1. With [events](events.md)), [history](history.md)) or live updates on the resource, [`protobase migration`](cli.md#migration)) writes the change of its capture trigger; apply it with your other migrations.
|
|
258
|
+
2. At update time, before the new version serves, run `protobase encryption apply`. It encrypts every plaintext value and removes the field's old values from the history and from the changes not yet dispatched.
|
|
259
|
+
3. With a rolling deploy, the old version writes plaintext until it stops: run `apply` again once the new version serves alone, and gate on `protobase encryption status`, which exits with 1 while anything is left. Until then, reveals of plaintext values fail.
|
|
260
|
+
|
|
261
|
+
Do not import ciphertext from elsewhere, such as another database's column encryption, into the column: `apply` would encrypt it as if it were plaintext. Export it decrypted instead.
|
|
262
|
+
|
|
263
|
+
What a move leaves behind: webhooks already sent carried the old values to their receivers, and webhook jobs keep their event, with the old values, in the jobs schema, a finished one for 7 days and a waiting one up to 14 days, so a backup made within a week of the move still holds them. Assistant conversations that showed the column keep what they showed. Older backups, the write-ahead log, replicas and the Postgres logs keep the old plaintext.
|
|
264
|
+
|
|
265
|
+
### What it protects against
|
|
266
|
+
|
|
267
|
+
It protects the values from database dumps, backups, replicas, and readers of raw SQL and realtime changes, who see only ciphertext. It does not protect them from whoever holds the key or the app's environment, or can run code in the server. Someone who can write to the database can change a row's tenant or roles, or put back an older value of the same record and field, from a backup say, which still opens. The ciphertext shows whether a value is empty, its length and when it changed. A key seals at most about 2³² values safely, as each gets a random IV; rotating starts a new key's count.
|
|
268
|
+
|
|
208
269
|
## Keys and relations
|
|
209
270
|
|
|
210
271
|
A key of several columns is a list, and a record's address joins its parts with a comma (`/stock/CHAIN-11,L`). A relation to such a resource names its columns, in the order of that key:
|
|
@@ -72,11 +72,13 @@ A form takes plain fields: text, numbers, booleans, dates, enums, currencies and
|
|
|
72
72
|
|
|
73
73
|
- a relation, since a visitor cannot read the records to pick one;
|
|
74
74
|
- a file field, since a visitor cannot upload;
|
|
75
|
-
- a sensitive, read-only or generated field;
|
|
75
|
+
- a sensitive field that is not encrypted, a read-only or a generated field;
|
|
76
76
|
- a field the anonymous role's `<resource>.create` does not list; the error names the entry to add;
|
|
77
77
|
- a field the resource does not have, or two forms of the same name;
|
|
78
78
|
- a field every create must give left out, since no submission could then be saved.
|
|
79
79
|
|
|
80
|
+
An [encrypted field](data-config.md#encrypted-fields)) is written blind, masked as the visitor types, and stored encrypted.
|
|
81
|
+
|
|
80
82
|
## The record
|
|
81
83
|
|
|
82
84
|
A submission is a create like any other, made by the anonymous role and limited to the form's fields: the resource's `.validate()` rules, record rules and write hooks run, and [events](events.md)), [webhooks](webhooks.md)) and [history](history.md)) see it. History names its maker **Visitor**.
|
|
@@ -44,6 +44,10 @@ Not yet: many-to-many embeds through a junction table, spreads (`...profiles(nam
|
|
|
44
44
|
|
|
45
45
|
As on the [REST API](api.md#safety)), a filter or a sort reads only columns an index serves: a btree index for comparisons, `in`, `is` and sorts, a pg_trgm index for patterns and regular expressions, a GIN index for text search and `cs`, `cd` and `ov` (or GiST), and a GiST index for the range operators. A JSON path needs an index on that expression. An embed's filters and order are judged on the embedded table, and so are the columns it joins on, so a one-to-many embed needs an index on the foreign key's columns. Any other read is `400` with code `expensive-query` and the statement that adds the index as its `hint`. Functions are not judged.
|
|
46
46
|
|
|
47
|
+
## Encrypted fields
|
|
48
|
+
|
|
49
|
+
The column of an [encrypted field](data-config.md#encrypted-fields)) holds ciphertext, which this API can neither write nor compare. A read returns it as stored. Writing the column, an `on_conflict` on it, a filter, sort or embed join on it, and, on a table with encrypted fields, a write that changes a row's key or tenant are `400` with code `encrypted-column`, writing nothing, whichever resource over the table declares the field. A view this API serves cannot be checked, so it must not show an encrypted column. Write such fields and reveal them through the [REST API](api.md)).
|
|
50
|
+
|
|
47
51
|
## Errors
|
|
48
52
|
|
|
49
53
|
Errors come back as PostgREST sends them, `{ code, details, hint, message }`. A database error keeps its Postgres code, message, detail and hint, with PostgREST's status: an RLS refusal (`42501`) is `401` for `anon` and `403` for others, a duplicate (`23505`) `409`, a function that writes called by GET (`25006`) `405`. `.single()` on no or several rows is `406` `PGRST116`, an unknown table `404` `PGRST205`, an unknown function `404` `PGRST202`, an embed without a relationship `400` `PGRST200` and one with several `300` `PGRST201`, and a missing or wrong key or token `401` `PGRST301`.
|