@protobase/cli 0.33.3 → 0.34.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundle/manifest.js +2 -2
- package/dist/cli/package.js +1 -1
- package/dist/dev/allowed-host.js +29 -0
- package/dist/dev/api-websockets.js +13 -5
- 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/{files/load-project.js → project/load-bundle-project.js} +8 -7
- package/dist/serve/close-sockets.js +15 -0
- package/dist/serve/lifecycle.js +8 -3
- package/dist/serve/static-site.js +11 -2
- package/package.json +8 -8
- package/skills/protobase/references/guides/api-functions.md +132 -1
- package/skills/protobase/references/guides/deploy.md +1 -1
- 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 +30 -6
- 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
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,7 +9,7 @@ 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";
|
package/dist/cli/package.js
CHANGED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { isIP } from "node:net";
|
|
2
|
+
//#region src/dev/allowed-host.ts
|
|
3
|
+
const fileOrExtension = /^(?:file|.+-extension):/i;
|
|
4
|
+
const hostNameOf = (host) => {
|
|
5
|
+
const trimmed = host.trim();
|
|
6
|
+
if (trimmed.startsWith("[")) {
|
|
7
|
+
const end = trimmed.indexOf("]");
|
|
8
|
+
return end >= 0 && isIP(trimmed.slice(1, end)) === 6 ? { ip: true } : { invalid: true };
|
|
9
|
+
}
|
|
10
|
+
const colon = trimmed.indexOf(":");
|
|
11
|
+
const name = colon === -1 ? trimmed : trimmed.slice(0, colon);
|
|
12
|
+
return isIP(name) === 4 ? { ip: true } : { name };
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Whether Vite's dev server would serve a request with this Host header under `server.allowedHosts`, by Vite's own
|
|
16
|
+
* rules, which it does not export: no Host, an IP literal, `localhost` and its subdomains pass; otherwise the name must
|
|
17
|
+
* be listed, or be or end in an entry starting with `.`. It keeps a DNS-rebinding page off the API's sockets.
|
|
18
|
+
*/
|
|
19
|
+
const isAllowedHost = (host, allowedHosts) => {
|
|
20
|
+
if (host === void 0 || allowedHosts === true || fileOrExtension.test(host)) return true;
|
|
21
|
+
const parsed = hostNameOf(host);
|
|
22
|
+
if ("invalid" in parsed) return false;
|
|
23
|
+
if ("ip" in parsed) return true;
|
|
24
|
+
const { name } = parsed;
|
|
25
|
+
if (name === "localhost" || name.endsWith(".localhost")) return true;
|
|
26
|
+
return allowedHosts.some((allowed) => allowed === name || allowed.startsWith(".") && (allowed.slice(1) === name || name.endsWith(allowed)));
|
|
27
|
+
};
|
|
28
|
+
//#endregion
|
|
29
|
+
export { isAllowedHost };
|
|
@@ -1,9 +1,19 @@
|
|
|
1
|
+
import { isAllowedHost } from "./allowed-host.js";
|
|
1
2
|
import { isProjectFile } from "./project-files.js";
|
|
2
3
|
import { createAdaptorServer } from "@hono/node-server";
|
|
3
4
|
import { WebSocketServer } from "ws";
|
|
4
5
|
//#region src/dev/api-websockets.ts
|
|
5
|
-
const isApiWebSocket = (url) => /^\/api\/sb\/realtime\/v1\/websocket(\?|$)/.test(url);
|
|
6
|
+
const isApiWebSocket = (url) => /^\/api\/sb\/realtime\/v1\/websocket(\?|$)/.test(url) || /^\/api\/functions\/[^/?#]+(\/|\?|$)/.test(url);
|
|
6
7
|
const restartCode = 1012;
|
|
8
|
+
/**
|
|
9
|
+
* The listener for Vite's `upgrade` event: an API socket goes to `forward` once its Host passes Vite's host check, as
|
|
10
|
+
* every other dev request does, and is refused with 403 otherwise; any other upgrade is left to Vite.
|
|
11
|
+
*/
|
|
12
|
+
const apiUpgrades = (allowedHosts, forward) => (request, socket, head) => {
|
|
13
|
+
if (!isApiWebSocket(request.url ?? "")) return;
|
|
14
|
+
if (isAllowedHost(request.headers.host, allowedHosts())) return forward(request, socket, head);
|
|
15
|
+
socket.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
|
|
16
|
+
};
|
|
7
17
|
const apiWebSockets = (entry, dirs) => {
|
|
8
18
|
const wss = new WebSocketServer({ noServer: true });
|
|
9
19
|
return {
|
|
@@ -14,9 +24,7 @@ const apiWebSockets = (entry, dirs) => {
|
|
|
14
24
|
overrideGlobalObjects: false,
|
|
15
25
|
websocket: { server: wss }
|
|
16
26
|
});
|
|
17
|
-
server.httpServer?.on("upgrade", (request, socket, head) =>
|
|
18
|
-
if (isApiWebSocket(request.url ?? "")) upgrades.emit("upgrade", request, socket, head);
|
|
19
|
-
});
|
|
27
|
+
server.httpServer?.on("upgrade", apiUpgrades(() => server.config.server.allowedHosts, (request, socket, head) => upgrades.emit("upgrade", request, socket, head)));
|
|
20
28
|
server.httpServer?.on("close", () => upgrades.emit("close"));
|
|
21
29
|
},
|
|
22
30
|
handleHotUpdate: ({ file }) => {
|
|
@@ -25,4 +33,4 @@ const apiWebSockets = (entry, dirs) => {
|
|
|
25
33
|
};
|
|
26
34
|
};
|
|
27
35
|
//#endregion
|
|
28
|
-
export { apiWebSockets, isApiWebSocket };
|
|
36
|
+
export { apiUpgrades, apiWebSockets, isApiWebSocket };
|
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);
|
|
@@ -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,15 @@
|
|
|
1
|
+
//#region src/serve/close-sockets.ts
|
|
2
|
+
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
3
|
+
/**
|
|
4
|
+
* Closes every open socket with 1001 (Going Away) and waits until they are gone, at most `graceMs`; whatever is still
|
|
5
|
+
* open then, a socket opened meanwhile included, is dropped. A server's `close` waits for its sockets, which a
|
|
6
|
+
* connected client never closes by itself.
|
|
7
|
+
*/
|
|
8
|
+
const closeSockets = async (clients, { graceMs = 5e3, pollMs = 50 } = {}) => {
|
|
9
|
+
for (const client of clients) client.close(1001, "Server shutting down");
|
|
10
|
+
const deadline = Date.now() + graceMs;
|
|
11
|
+
while (clients.size > 0 && Date.now() < deadline) await wait(pollMs);
|
|
12
|
+
for (const client of clients) client.terminate();
|
|
13
|
+
};
|
|
14
|
+
//#endregion
|
|
15
|
+
export { closeSockets };
|
package/dist/serve/lifecycle.js
CHANGED
|
@@ -3,6 +3,7 @@ import { projectAdmin } from "../project/project-admin.js";
|
|
|
3
3
|
import { createPgDb } from "../project/pg-db.js";
|
|
4
4
|
import { createServeApp } from "./app.js";
|
|
5
5
|
import { startCleanupTimer } from "./cleanup-timer.js";
|
|
6
|
+
import { closeSockets } from "./close-sockets.js";
|
|
6
7
|
import { backgroundSettled, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkWebhooksSchema, configExports, createFileCleanup, startJobs } from "@protobase/server";
|
|
7
8
|
import { createAdaptorServer, upgradeWebSocket } from "@hono/node-server";
|
|
8
9
|
import { WebSocketServer } from "ws";
|
|
@@ -48,10 +49,11 @@ const startServe = async ({ project, env, createDb = (url) => createPgDb(pg, url
|
|
|
48
49
|
...jobs && { jobs },
|
|
49
50
|
...env.drainToken && { drainToken: env.drainToken }
|
|
50
51
|
});
|
|
52
|
+
const sockets = new WebSocketServer({ noServer: true });
|
|
51
53
|
const server = createAdaptorServer({
|
|
52
54
|
fetch: withClientAddress(app.fetch, env.trustedProxies),
|
|
53
55
|
overrideGlobalObjects: false,
|
|
54
|
-
websocket: { server:
|
|
56
|
+
websocket: { server: sockets }
|
|
55
57
|
});
|
|
56
58
|
await listen(server, env.port).catch(async (error) => {
|
|
57
59
|
await jobs?.stop();
|
|
@@ -59,10 +61,11 @@ const startServe = async ({ project, env, createDb = (url) => createPgDb(pg, url
|
|
|
59
61
|
});
|
|
60
62
|
return {
|
|
61
63
|
server,
|
|
64
|
+
sockets,
|
|
62
65
|
jobs
|
|
63
66
|
};
|
|
64
67
|
};
|
|
65
|
-
const { server, jobs } = await startJobsAndListen().catch(async (error) => {
|
|
68
|
+
const { server, sockets, jobs } = await startJobsAndListen().catch(async (error) => {
|
|
66
69
|
await ownDb?.destroy();
|
|
67
70
|
throw error;
|
|
68
71
|
});
|
|
@@ -73,7 +76,9 @@ const startServe = async ({ project, env, createDb = (url) => createPgDb(pg, url
|
|
|
73
76
|
});
|
|
74
77
|
const timer = cleanup && env.filesCleanupMinutes > 0 ? startCleanupTimer(cleanup.run, env.filesCleanupMinutes, (error) => console.error(error)) : void 0;
|
|
75
78
|
const close = async () => {
|
|
76
|
-
|
|
79
|
+
const closed = closeServer(server);
|
|
80
|
+
await closeSockets(sockets.clients);
|
|
81
|
+
await closed;
|
|
77
82
|
await backgroundSettled();
|
|
78
83
|
await timer?.stop();
|
|
79
84
|
await jobs?.stop();
|
|
@@ -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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@protobase/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.34.0",
|
|
4
4
|
"description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -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.0",
|
|
40
|
+
"@protobase/query": "0.34.0",
|
|
41
|
+
"@protobase/schema": "0.34.0",
|
|
42
|
+
"@protobase/server": "0.34.0",
|
|
43
|
+
"@protobase/ui": "0.34.0",
|
|
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",
|
|
@@ -50,9 +50,10 @@ The second argument of a handler (`c.env` in a [Hono app](#hono-apps)):
|
|
|
50
50
|
| `records` | The app's resources, acting as the caller: `list`, `get`, `create`, `update`, `delete`. |
|
|
51
51
|
| `db` | The Kysely instance itself. It skips every access rule, row filter and tenant scope. |
|
|
52
52
|
| `caller()` | Resolves to `{ session, records }`. Public functions use it to ask for a caller when they need one. |
|
|
53
|
+
| `acceptWebSocket(events)` | Answers a WebSocket upgrade with a socket; return its response. See [WebSockets](#websockets). |
|
|
53
54
|
| `name` | The function's name. |
|
|
54
55
|
|
|
55
|
-
A [public function](#public-functions-and-webhooks) has only `db`, `caller()` and `name`.
|
|
56
|
+
A [public function](#public-functions-and-webhooks) has only `db`, `caller()`, `acceptWebSocket` and `name`.
|
|
56
57
|
|
|
57
58
|
## Reading and writing records as the caller
|
|
58
59
|
|
|
@@ -128,6 +129,136 @@ export default defineFunction({ public: true }, async (request, { db }) => {
|
|
|
128
129
|
|
|
129
130
|
A public function has no caller, so it has no `records`. Its `db` skips the tenant scope too, so filter by tenant yourself where it matters. When a function should serve anyone but treat a signed-in caller differently, `await context.caller()` resolves the caller from the request, or rejects with the `401` problem.
|
|
130
131
|
|
|
132
|
+
## WebSockets
|
|
133
|
+
|
|
134
|
+
A function can answer a WebSocket instead of a request, for a live console, a chat or an agent that keeps one connection open. It returns `acceptWebSocket(events)`:
|
|
135
|
+
|
|
136
|
+
```ts title="functions/workshop-chat.ts"
|
|
137
|
+
import { defineFunction, type FunctionSocket } from '@protobase/server'
|
|
138
|
+
|
|
139
|
+
// Everyone in the workshop chat, in this process.
|
|
140
|
+
const everyone = new Set<FunctionSocket>()
|
|
141
|
+
|
|
142
|
+
// /api/functions/workshop-chat, opened as a WebSocket by a signed-in page: each text message goes to everyone in the
|
|
143
|
+
// chat, with who sent it. Awaiting the sends holds the sender's next message back until everyone has this one.
|
|
144
|
+
export default defineFunction((_request, { session, acceptWebSocket }) => {
|
|
145
|
+
let own: FunctionSocket | undefined
|
|
146
|
+
return acceptWebSocket({
|
|
147
|
+
onOpen: (socket) => {
|
|
148
|
+
own = socket
|
|
149
|
+
everyone.add(socket)
|
|
150
|
+
},
|
|
151
|
+
onMessage: async (data) => {
|
|
152
|
+
if (typeof data !== 'string') return
|
|
153
|
+
await Promise.all([...everyone].map((socket) => socket.send(`${session.user.id}: ${data}`)))
|
|
154
|
+
},
|
|
155
|
+
onClose: () => {
|
|
156
|
+
if (own) everyone.delete(own)
|
|
157
|
+
},
|
|
158
|
+
})
|
|
159
|
+
})
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
A page of the app opens it with the browser's own `WebSocket`. The session cookie signs it in, so the function sees the signed-in user and their roles, as for a plain call:
|
|
163
|
+
|
|
164
|
+
```ts
|
|
165
|
+
const chat = new WebSocket(`${location.origin.replace(/^http/, 'ws')}/api/functions/workshop-chat`)
|
|
166
|
+
chat.onmessage = (event) => console.log(event.data)
|
|
167
|
+
chat.onopen = () => chat.send('Truing stand is free')
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
A client that is no browser sends `Authorization: Bearer <token>` with its upgrade instead. The events:
|
|
171
|
+
|
|
172
|
+
| | |
|
|
173
|
+
| --- | --- |
|
|
174
|
+
| `onOpen(socket)` | The socket is open. |
|
|
175
|
+
| `onMessage(data, socket)` | Text arrives as a string, binary as an `ArrayBuffer`, byte for byte. Messages come one at a time and in order. |
|
|
176
|
+
| `onClose(code, reason)` | Either side closed it, after the last message. |
|
|
177
|
+
|
|
178
|
+
`socket.send(data)` takes a string, an `ArrayBuffer` or a `Uint8Array`, and `socket.close(code?, reason?)` closes it. A handler that throws closes the socket with `1011`, and the error is reported like any other.
|
|
179
|
+
|
|
180
|
+
### Who may open one
|
|
181
|
+
|
|
182
|
+
- **Refusals come before the socket.** A caller without a valid session or token gets the usual `401`, and one without the function's roles a `403`; the handler never runs. The browser only sees a socket that failed to open, since an upgrade's refusal has a status but no body.
|
|
183
|
+
- **Only the app's own pages** may open a socket with the cookie. An upgrade from a page on any other origin is a `403`, so another site cannot borrow a visitor's session.
|
|
184
|
+
- **While it is open,** a protected function's caller is checked again every minute, as a plain call would be. Signing out, a ban, a role taken away, or another active role or organization closes the socket with `1008`, and a socket opened with a bearer token closes once the token expires. The client opens it again, as who they are now.
|
|
185
|
+
- **A plain request** to a function that accepts a socket is a `426` problem.
|
|
186
|
+
|
|
187
|
+
### Agents and other clients without a cookie
|
|
188
|
+
|
|
189
|
+
A [public function](#public-functions-and-webhooks) can accept a socket too, and checks its caller itself, for example a host agent's key in a header. The framework does not check it again while the socket is open, so a function whose access can be revoked keeps checking, and calls `socket.close()` when it is.
|
|
190
|
+
|
|
191
|
+
A page with no session cookie of the app, such as the workshop's display board on its own origin, gets a short-lived ticket from a plain call with its token and puts it in the socket's address:
|
|
192
|
+
|
|
193
|
+
```ts title="functions/_shared/tickets.ts"
|
|
194
|
+
import { createHmac, timingSafeEqual } from 'node:crypto'
|
|
195
|
+
import { requireEnv } from '@protobase/server'
|
|
196
|
+
|
|
197
|
+
const lifetimeSeconds = 30
|
|
198
|
+
|
|
199
|
+
const signature = (payload: string) => createHmac('sha256', requireEnv('TICKET_SECRET')).update(payload).digest('base64url')
|
|
200
|
+
|
|
201
|
+
// A ticket names a user and when it expires, signed with the app's own secret.
|
|
202
|
+
export const mintTicket = (userId: string | number) => {
|
|
203
|
+
const payload = `${userId}.${Math.floor(Date.now() / 1000) + lifetimeSeconds}`
|
|
204
|
+
return `${payload}.${signature(payload)}`
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// The user a ticket names, or undefined when it is forged or expired.
|
|
208
|
+
export const ticketUser = (ticket: string) => {
|
|
209
|
+
const payload = ticket.slice(0, ticket.lastIndexOf('.'))
|
|
210
|
+
const given = Buffer.from(ticket.slice(payload.length + 1))
|
|
211
|
+
const expected = Buffer.from(signature(payload))
|
|
212
|
+
if (given.length !== expected.length || !timingSafeEqual(given, expected)) return undefined
|
|
213
|
+
const userId = payload.slice(0, payload.lastIndexOf('.'))
|
|
214
|
+
const expires = Number(payload.slice(userId.length + 1))
|
|
215
|
+
return expires * 1000 > Date.now() ? userId : undefined
|
|
216
|
+
}
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
```ts title="functions/display-ticket.ts"
|
|
220
|
+
import { defineFunction } from '@protobase/server'
|
|
221
|
+
import { mintTicket } from './_shared/tickets'
|
|
222
|
+
|
|
223
|
+
// POST /api/functions/display-ticket, from the display board's page: a ticket that opens its socket for 30 seconds.
|
|
224
|
+
export default defineFunction({ roles: ['mechanic'], cors: { origin: 'https://workshop.pips-bikes.example' } }, (_request, { session }) =>
|
|
225
|
+
Response.json({ ticket: mintTicket(session.user.id) }),
|
|
226
|
+
)
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
```ts title="functions/display.ts"
|
|
230
|
+
import { defineFunction, unauthorized } from '@protobase/server'
|
|
231
|
+
import { ticketUser } from './_shared/tickets'
|
|
232
|
+
|
|
233
|
+
// /api/functions/display?ticket=…, the workshop's display board, opened as a WebSocket from a page with no session
|
|
234
|
+
// cookie of this app. Public, so it checks the ticket itself: a missing, forged or expired one gets a 401 and no socket.
|
|
235
|
+
export default defineFunction({ public: true }, (request, { acceptWebSocket }) => {
|
|
236
|
+
const user = ticketUser(new URL(request.url).searchParams.get('ticket') ?? '')
|
|
237
|
+
if (!user) throw unauthorized('Get a ticket from /api/functions/display-ticket first')
|
|
238
|
+
return acceptWebSocket({
|
|
239
|
+
onOpen: (socket) => socket.send(JSON.stringify({ shownFor: user })),
|
|
240
|
+
})
|
|
241
|
+
})
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
```ts
|
|
245
|
+
// On https://workshop.pips-bikes.example, with a client made by createClient
|
|
246
|
+
const { ticket } = await client.invoke('display-ticket', { method: 'POST' })
|
|
247
|
+
const board = new WebSocket(`wss://pips-bikes.example/api/functions/display?ticket=${encodeURIComponent(ticket)}`)
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
The ticket only lets the socket open: anyone who holds it may use it for its 30 seconds, so keep it out of logs. For a socket that stays open long, check the user again from the function, as a protected function's socket is.
|
|
251
|
+
|
|
252
|
+
### Slow readers and large messages
|
|
253
|
+
|
|
254
|
+
- **Await `send`** when the other side may read slowly: it resolves once the data is written, so a relay that awaits each send never piles up data in the server. It never rejects; after a close it resolves at once.
|
|
255
|
+
- **Return a promise from `onMessage`** to hold the next message back until it settles. Above 1 MiB of waiting messages the server stops reading from the client, which slows it down, and reads again once they are handled. Bun's built-in `ws`, which `protobase dev` uses on Bun, cannot stop reading: there the socket closes with `1013` once 16 MiB are waiting.
|
|
256
|
+
- **A message** may be up to 100 MiB.
|
|
257
|
+
|
|
258
|
+
### Restarts
|
|
259
|
+
|
|
260
|
+
`protobase dev` closes every open socket with `1012` when you edit the project, so it reconnects to the rebuilt API. `protobase serve` closes them with `1001` when it stops, and drops any still open after 5 seconds. Clients that reconnect on these codes keep working across both.
|
|
261
|
+
|
|
131
262
|
## Secrets and other APIs
|
|
132
263
|
|
|
133
264
|
```ts title="functions/notify-customer.ts"
|
|
@@ -27,7 +27,7 @@ dist/
|
|
|
27
27
|
plugins and the app's version
|
|
28
28
|
```
|
|
29
29
|
|
|
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. Nothing in the bundle or the runtime changes the database: run the project's `db:migrate`, which applies its migrations and those of the auth schema, before a new version serves it, with no other writes while it runs. 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)).
|
|
30
|
+
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. Nothing in the bundle or the runtime changes the database: run the project's `db:migrate`, which applies its migrations and those of the auth schema, before a new version serves it, with no other writes while it runs. 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
31
|
|
|
32
32
|
## Images
|
|
33
33
|
|
|
@@ -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
|
|
|
@@ -214,7 +214,7 @@ By default the bundle runs on Node and on Bun. `--bun` makes it a bundle for Bun
|
|
|
214
214
|
"server": "protobase.config.js",
|
|
215
215
|
"public": "public",
|
|
216
216
|
"spa": "index.html",
|
|
217
|
-
"api": ["/api"],
|
|
217
|
+
"api": ["/api", "/.well-known/oauth-authorization-server", "/.well-known/oauth-protected-resource"],
|
|
218
218
|
"theme": "protobase.theme.css",
|
|
219
219
|
"plugins": [
|
|
220
220
|
{ "name": "app", "path": "plugins/app/plugin.json", "api": 1, "protobase": ">=0.12.0", "fields": { "steps": ["enum"] } }
|
|
@@ -230,7 +230,7 @@ By default the bundle runs on Node and on Bun. `--bun` makes it a bundle for Bun
|
|
|
230
230
|
- `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
231
|
- `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
232
|
- `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
|
-
- `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 `[
|
|
233
|
+
- `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
234
|
- 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
235
|
- 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
236
|
- `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`.
|
|
@@ -377,6 +377,7 @@ Serves the API of a bundle from `protobase build` and owns the process around it
|
|
|
377
377
|
| `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
378
|
| `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
379
|
| `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 |
|
|
380
|
+
| `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
381
|
| `PROTOBASE_JOBS` | `false` runs none of the app's [jobs](jobs.md)) in this process, which still enqueues them; default `true` |
|
|
381
382
|
| `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
383
|
| `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,12 +386,12 @@ Serves the API of a bundle from `protobase build` and owns the process around it
|
|
|
385
386
|
|
|
386
387
|
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
388
|
|
|
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
|
|
389
|
+
- **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
390
|
- **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
391
|
- **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.
|
|
392
|
+
- **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
393
|
- **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
|
-
- **Shutdown:** the first SIGTERM or SIGINT stops accepting connections, 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
|
+
- **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
395
|
- **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.
|
|
395
396
|
- **Read-only hosts:** nothing is written: no install (`--no-install`), and for a bundle built with `--bun` no transpiling and so no transpiler cache. A bundle with `node_modules/` needs its folder mounted without `noexec`, since its add-ons are mapped as executable code.
|
|
396
397
|
|
|
@@ -411,6 +412,29 @@ protobase files cleanup <bundle> # a bundle from `protobase build`: its folder
|
|
|
411
412
|
|
|
412
413
|
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
414
|
|
|
415
|
+
## `encryption status`
|
|
416
|
+
|
|
417
|
+
```sh
|
|
418
|
+
protobase encryption status # the project in the current directory
|
|
419
|
+
protobase encryption status <bundle> # a bundle from `protobase build`: its folder or its protobase.config.js
|
|
420
|
+
```
|
|
421
|
+
|
|
422
|
+
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`.
|
|
423
|
+
|
|
424
|
+
## `encryption apply`
|
|
425
|
+
|
|
426
|
+
```sh
|
|
427
|
+
protobase encryption apply [bundle]
|
|
428
|
+
protobase encryption apply --rebind people --from-table persons # after a table rename
|
|
429
|
+
protobase encryption apply --rebind people.iban --from-column bank_iban # after a column rename
|
|
430
|
+
```
|
|
431
|
+
|
|
432
|
+
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.
|
|
433
|
+
|
|
434
|
+
`--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.
|
|
435
|
+
|
|
436
|
+
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.
|
|
437
|
+
|
|
414
438
|
## `users`
|
|
415
439
|
|
|
416
440
|
```sh
|
|
@@ -427,7 +451,7 @@ Run inside a project whose `protobase.config.ts` exports `auth` (Better Auth). T
|
|
|
427
451
|
|
|
428
452
|
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.
|
|
429
453
|
|
|
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.
|
|
454
|
+
`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
455
|
|
|
432
456
|
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
457
|
|
|
@@ -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`.
|