@protobase/cli 0.37.1 → 0.38.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/cli/package.js +1 -1
- package/dist/dev/entry.js +2 -1
- package/dist/migration/load-project.js +3 -1
- package/dist/migration/parts.js +6 -1
- package/dist/serve/lifecycle.js +2 -1
- package/package.json +6 -6
- package/skills/protobase/references/guides/api-functions.md +30 -3
- package/skills/protobase/references/reference/assistant.md +4 -2
- package/skills/protobase/references/reference/cli.md +1 -1
package/dist/cli/package.js
CHANGED
package/dist/dev/entry.js
CHANGED
|
@@ -4,7 +4,7 @@ import { projectErrorReporter } from "../project/error-reporter.js";
|
|
|
4
4
|
import { projectAdmin } from "../project/project-admin.js";
|
|
5
5
|
import { loadProject, projectDb } from "./project.js";
|
|
6
6
|
import { setMissing, supabaseEnv } from "./supabase-env.js";
|
|
7
|
-
import { apiKeySettings, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkWebhooksSchema, configExports, hasUsers } from "@protobase/server";
|
|
7
|
+
import { apiKeySettings, assistantSettings, authStoreTables, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkQueryRunner, checkWebhooksSchema, configExports, hasUsers } from "@protobase/server";
|
|
8
8
|
import { upgradeWebSocket } from "@hono/node-server";
|
|
9
9
|
import { Hono } from "hono";
|
|
10
10
|
//#region src/dev/entry.ts
|
|
@@ -21,6 +21,7 @@ if (project.auth && !store.__protobaseAuthSchemaChecked) {
|
|
|
21
21
|
await checkChanges(db, resources.map((resource) => resource.toModel()), project.events);
|
|
22
22
|
await checkComments(db, resources.map((resource) => resource.toModel()));
|
|
23
23
|
await checkComputed(db, resources.map((resource) => resource.toModel()));
|
|
24
|
+
if (assistantSettings(project.options?.assistant, process.env)?.kind === "built-in") await checkQueryRunner(db, project.auth ? authStoreTables(project.auth) : []);
|
|
24
25
|
checkAi({
|
|
25
26
|
models: resources.map((resource) => resource.toModel()),
|
|
26
27
|
views: views.map((source) => source.toModel()),
|
|
@@ -3,7 +3,7 @@ import { importProjectFile } from "../project/import-project-file.js";
|
|
|
3
3
|
import { createPgDb } from "../project/pg-db.js";
|
|
4
4
|
import { existsSync } from "node:fs";
|
|
5
5
|
import path from "node:path";
|
|
6
|
-
import { configExports, jobDefinitions, mergeConfig } from "@protobase/server";
|
|
6
|
+
import { assistantSettings, authStoreTables, configExports, jobDefinitions, mergeConfig } from "@protobase/server";
|
|
7
7
|
import pg from "pg";
|
|
8
8
|
//#region src/migration/load-project.ts
|
|
9
9
|
const configOf = async (file) => (await importProjectFile(file)).default ?? {};
|
|
@@ -39,6 +39,8 @@ const migrationProject = (project, url) => {
|
|
|
39
39
|
...project.events && { events: project.events },
|
|
40
40
|
...project.webhooks && { webhooks: project.webhooks },
|
|
41
41
|
jobs: jobDefinitions(project.jobs ?? {}),
|
|
42
|
+
readOnlyQueries: assistantSettings(project.options?.assistant, process.env)?.kind === "built-in",
|
|
43
|
+
authTables: project.auth ? authStoreTables(project.auth) : [],
|
|
42
44
|
close: async () => {
|
|
43
45
|
await ownDb?.destroy();
|
|
44
46
|
}
|
package/dist/migration/parts.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { authSchemaMigration, changesMigration, commentsMigration, computedMigration, isCaptured, jobsSchemaMigration, webhooksMigration } from "@protobase/server";
|
|
1
|
+
import { authSchemaMigration, changesMigration, commentsMigration, computedMigration, isCaptured, jobsSchemaMigration, queryRunnerMigration, webhooksMigration } from "@protobase/server";
|
|
2
2
|
//#region src/migration/parts.ts
|
|
3
3
|
/** Every feature the project's config enables, in the order their files are written. */
|
|
4
4
|
const migrationParts = (project) => {
|
|
@@ -25,6 +25,11 @@ const migrationParts = (project) => {
|
|
|
25
25
|
title: "The columns of the resources' rollup and formula fields, and the triggers that keep the rollups",
|
|
26
26
|
sql: () => computedMigration(project.db, project.models)
|
|
27
27
|
},
|
|
28
|
+
...project.readOnlyQueries ? [{
|
|
29
|
+
name: "query",
|
|
30
|
+
title: "The role the assistant's read-only queries run as, which reads only the resources' tables",
|
|
31
|
+
sql: () => queryRunnerMigration(project.db, project.models, project.authTables)
|
|
32
|
+
}] : [],
|
|
28
33
|
...comments ? [{
|
|
29
34
|
name: "comments",
|
|
30
35
|
title: "The comments table of the resources with comments",
|
package/dist/serve/lifecycle.js
CHANGED
|
@@ -5,7 +5,7 @@ import { createPgDb } from "../project/pg-db.js";
|
|
|
5
5
|
import { createServeApp } from "./app.js";
|
|
6
6
|
import { startCleanupTimer } from "./cleanup-timer.js";
|
|
7
7
|
import { closeSockets } from "./close-sockets.js";
|
|
8
|
-
import { backgroundSettled, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkWebhooksSchema, configExports, createFileCleanup, startJobs } from "@protobase/server";
|
|
8
|
+
import { assistantSettings, authStoreTables, backgroundSettled, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkQueryRunner, checkWebhooksSchema, configExports, createFileCleanup, startJobs } from "@protobase/server";
|
|
9
9
|
import { createAdaptorServer, upgradeWebSocket } from "@hono/node-server";
|
|
10
10
|
import pg from "pg";
|
|
11
11
|
//#region src/serve/lifecycle.ts
|
|
@@ -27,6 +27,7 @@ const startServe = async ({ project, env, createDb = (url) => createPgDb(pg, url
|
|
|
27
27
|
if (env.startupChecks) await checkChanges(db, resources.map((resource) => resource.toModel()), project.events);
|
|
28
28
|
if (env.startupChecks) await checkComments(db, resources.map((resource) => resource.toModel()));
|
|
29
29
|
if (env.startupChecks) await checkComputed(db, resources.map((resource) => resource.toModel()));
|
|
30
|
+
if (env.startupChecks && assistantSettings(project.options?.assistant, process.env)?.kind === "built-in") await checkQueryRunner(db, project.auth ? authStoreTables(project.auth) : []);
|
|
30
31
|
if (env.startupChecks) checkAi({
|
|
31
32
|
models: resources.map((resource) => resource.toModel()),
|
|
32
33
|
views: views.map((source) => source.toModel()),
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@protobase/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.38.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": {
|
|
@@ -36,11 +36,11 @@
|
|
|
36
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.38.0",
|
|
40
|
+
"@protobase/query": "0.38.0",
|
|
41
|
+
"@protobase/schema": "0.38.0",
|
|
42
|
+
"@protobase/server": "0.38.0",
|
|
43
|
+
"@protobase/ui": "0.38.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",
|
|
@@ -174,19 +174,40 @@ A client that is no browser sends `Authorization: Bearer <token>` with its upgra
|
|
|
174
174
|
| `onOpen(socket)` | The socket is open. |
|
|
175
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
176
|
| `onClose(code, reason)` | Either side closed it, after the last message. |
|
|
177
|
+
| `recheck()` | Runs every minute while the socket is open, after the framework's own check. A `401`, `403` or `404` problem it throws closes the socket with `1008`; any other error is reported and closes it with `1011`, as does a check that has not finished a minute later. What it returns is ignored, so refuse by throwing. |
|
|
177
178
|
|
|
178
179
|
`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
|
|
|
181
|
+
Sockets need `@hono/node-server`'s `upgradeWebSocket`, the only upgrade supported, which `protobase dev` and `protobase serve` use. A server of your own that passes another host's upgrade to `createAdmin` gets sockets that misbehave, since they rely on its send callback and `bufferedAmount`.
|
|
182
|
+
|
|
180
183
|
### Who may open one
|
|
181
184
|
|
|
182
185
|
- **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
186
|
- **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,**
|
|
187
|
+
- **While it is open,** the framework checks the caller again every minute: their session or token, the function's roles, and that the user, tenant, organization and roles are unchanged. It does so for a protected function, and for a public one once `caller()` resolved. 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.
|
|
188
|
+
- **The function's own checks are not repeated,** such as whether the caller may still see one record. Pass them as `recheck`, which runs right after the framework's check:
|
|
189
|
+
|
|
190
|
+
```ts title="functions/repair-watch.ts"
|
|
191
|
+
import { defineFunction, notFound } from '@protobase/server'
|
|
192
|
+
|
|
193
|
+
// /api/functions/repair-watch/7, opened as a WebSocket by a signed-in page: repair 7's status, for as long as the caller
|
|
194
|
+
// may see the repair. A repair their access rules hide is a 404 and no socket; once it moves out of their sight, such
|
|
195
|
+
// as to another mechanic, `recheck` rejects with that 404 and the socket closes with 1008 within a minute.
|
|
196
|
+
export default defineFunction({ roles: ['mechanic', 'desk'] }, async (request, { records, acceptWebSocket }) => {
|
|
197
|
+
const id = Number(new URL(request.url).pathname.slice(1))
|
|
198
|
+
if (!Number.isInteger(id) || id <= 0) throw notFound('Watch a repair at /api/functions/repair-watch/<id>')
|
|
199
|
+
const { record: repair } = await records.get('repairs', id)
|
|
200
|
+
return acceptWebSocket({
|
|
201
|
+
onOpen: (socket) => socket.send(JSON.stringify({ status: repair.status })),
|
|
202
|
+
recheck: () => records.get('repairs', id),
|
|
203
|
+
})
|
|
204
|
+
})
|
|
205
|
+
```
|
|
185
206
|
- **A plain request** to a function that accepts a socket is a `426` problem.
|
|
186
207
|
|
|
187
208
|
### Agents and other clients without a cookie
|
|
188
209
|
|
|
189
|
-
A [public function](#public-functions-and-webhooks) can accept a socket too
|
|
210
|
+
A [public function](#public-functions-and-webhooks) can accept a socket too. One that admits its caller with `await caller()` is checked again like a protected one. One that checks a credential of its own, for example a host agent's key in a header, passes `recheck` to check it again, since the framework cannot.
|
|
190
211
|
|
|
191
212
|
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
213
|
|
|
@@ -232,11 +253,17 @@ import { ticketUser } from './_shared/tickets'
|
|
|
232
253
|
|
|
233
254
|
// /api/functions/display?ticket=…, the workshop's display board, opened as a WebSocket from a page with no session
|
|
234
255
|
// cookie of this app. Public, so it checks the ticket itself: a missing, forged or expired one gets a 401 and no socket.
|
|
256
|
+
// Nothing checks the ticket's user again while the socket is open, so `recheck` ends it after 15 minutes, as a signed-in
|
|
257
|
+
// token would end, and the board opens it again with a new ticket.
|
|
235
258
|
export default defineFunction({ public: true }, (request, { acceptWebSocket }) => {
|
|
236
259
|
const user = ticketUser(new URL(request.url).searchParams.get('ticket') ?? '')
|
|
237
260
|
if (!user) throw unauthorized('Get a ticket from /api/functions/display-ticket first')
|
|
261
|
+
const until = Date.now() + 15 * 60_000
|
|
238
262
|
return acceptWebSocket({
|
|
239
263
|
onOpen: (socket) => socket.send(JSON.stringify({ shownFor: user })),
|
|
264
|
+
recheck: () => {
|
|
265
|
+
if (Date.now() >= until) throw unauthorized('Get a new ticket')
|
|
266
|
+
},
|
|
240
267
|
})
|
|
241
268
|
})
|
|
242
269
|
```
|
|
@@ -247,7 +274,7 @@ const { ticket } = await client.invoke('display-ticket', { method: 'POST' })
|
|
|
247
274
|
const board = new WebSocket(`wss://pips-bikes.example/api/functions/display?ticket=${encodeURIComponent(ticket)}`)
|
|
248
275
|
```
|
|
249
276
|
|
|
250
|
-
The ticket only lets the socket open
|
|
277
|
+
The ticket only lets the socket open, and anyone who holds it may open one with it during its 30 seconds. It is in the address, so it appears in the request log when `REQUEST_LOG` is `true`. Nothing checks the ticket's user again, so `display.ts`'s `recheck` ends the socket after 15 minutes, and the board opens it again with a new ticket, which `display-ticket` mints only after checking the role again.
|
|
251
278
|
|
|
252
279
|
### Slow readers and large messages
|
|
253
280
|
|
|
@@ -57,10 +57,12 @@ The model needs tool calling for the queries. A refused key, an exhausted accoun
|
|
|
57
57
|
|
|
58
58
|
It lives at `/api/assistant` on the app's own origin and answers with the user's token like the rest of the API. Its system prompt describes the resources, tables and fields the user can see in `/meta`. It has two tools of its own, and [the app's](#the-apps-own-tools):
|
|
59
59
|
|
|
60
|
-
- **`run_read_only_query`** runs one `SELECT` (or `VALUES`, or a `WITH` query) and shows its rows as a table in the chat. It runs in a `READ ONLY` transaction that is always rolled back, with a statement timeout of 5 seconds and at most 200 rows. The statement
|
|
60
|
+
- **`run_read_only_query`** runs one `SELECT` (or `VALUES`, or a `WITH` query) and shows its rows as a table in the chat. It runs in a `READ ONLY` transaction that is always rolled back, with a statement timeout of 5 seconds and at most 200 rows. Postgres refuses every write inside (`SET TRANSACTION READ WRITE`, writable CTEs, `nextval`, `DO` blocks, functions that write), and settings it changes go with the rollback. The statement runs through the function `query.run_read_only` as the role `<database>_query`, which [`protobase migration`](cli.md#migration)) makes: that role may read every column of the resources' tables, `.sensitive()` fields and the [webhook subscriptions'](webhooks.md)) signing secrets included, and nothing else: not the auth store, nor a table without a resource. The function opens the statement as a cursor, so only one statement runs, and Postgres refuses a change of role inside it. Numbers other than integers of up to 15 digits come back as their exact text, such as `"12.50"`.
|
|
61
61
|
- **`propose_write_query`** never runs on its own. It shows the statement and a summary on a card with **Approve** and **Reject**. Only Approve runs it, as one statement in a read-write transaction; Reject, or no answer within 10 minutes, runs nothing. The model gets the returned rows, or that nothing ran. Statements are `INSERT`, `UPDATE` or `DELETE` with a `RETURNING` clause.
|
|
62
62
|
|
|
63
|
-
Both run
|
|
63
|
+
Both run **outside Protobase's access rules and tenant scoping**: whoever has the `admin` or `ai` role can read every resource's table, and with approval change everything the app's database role can, since `propose_write_query` still runs as that role. Give the app a database role without superuser rights, and those roles only to people who may see all of the data.
|
|
64
|
+
|
|
65
|
+
Making the query role needs `CREATEROLE` once, for the role that applies the migrations; that role becomes a member of it and may run the function. The query role bypasses row-level security only when the migrating role may grant that, a superuser or, on Postgres 16 and later, a role with `BYPASSRLS`; otherwise it reads what the tables' policies give it. When the app serves as another database role than the one that migrates, grant that role `usage on schema query` and `execute on function query.run_read_only(text, integer)`. `protobase migration` writes the role only when it finds the built-in assistant's key, `PROTOBASE_ASSISTANT_API_KEY` in the `.env` it reads or `options.assistant.apiKey`, so run it with the key set even when only production has the real one. The server does not start while the role or its function is missing, while the role can read an auth table, or while it may call a `SECURITY DEFINER` function, other than a trigger function, whose owner can read one: the statement would read the auth store through it, so revoke `execute` on such a function from `PUBLIC`, or keep it in a schema without a resource. A resource added since the last migration is refused by Postgres until the next one grants its table.
|
|
64
66
|
|
|
65
67
|
### The app's own tools
|
|
66
68
|
|
|
@@ -485,7 +485,7 @@ For a project with [organizations](auth.md#organizations)); `<organization>` is
|
|
|
485
485
|
protobase migration [--dir db/migrations] [--extend <dir>]
|
|
486
486
|
```
|
|
487
487
|
|
|
488
|
-
Writes what the database still needs for every feature the config enables, as the project's next migrations in `--dir`, one file per feature: the auth schema when `protobase.config.ts` exports `auth` (`NNN_auth.sql`, as [`auth migration`](#auth-migration) writes it), the [jobs schema](jobs.md#the-jobs-schema)) when the config has jobs or a resource has events, history, comments or an [AI field](ai.md)) (`NNN_jobs.sql`), the [capture of events](events.md#migrations-and-startup)) and the [history table](history.md#the-table)) (`NNN_changes.sql`), the columns of [rollup and formula fields](data-config.md#rollups-and-formulas)) and the triggers that keep the rollups (`NNN_computed.sql`), the [comments table](comments.md#the-table)) (`NNN_comments.sql`), and the [webhook subscriptions](webhooks.md#subscriptions-in-the-admin-app)) of `webhooks()` (`NNN_webhooks.sql`). It compares the database, with the project's migrations applied, with the config, merged with the configs it extends and those of `--extend` as `dev` merges them, and writes nothing when the database is current. Apply the files with the project's other migrations. It reads the `.env` nearest the current directory and needs `DATABASE_URL` unless the config exports `db`.
|
|
488
|
+
Writes what the database still needs for every feature the config enables, as the project's next migrations in `--dir`, one file per feature: the auth schema when `protobase.config.ts` exports `auth` (`NNN_auth.sql`, as [`auth migration`](#auth-migration) writes it), the [jobs schema](jobs.md#the-jobs-schema)) when the config has jobs or a resource has events, history, comments or an [AI field](ai.md)) (`NNN_jobs.sql`), the [capture of events](events.md#migrations-and-startup)) and the [history table](history.md#the-table)) (`NNN_changes.sql`), the columns of [rollup and formula fields](data-config.md#rollups-and-formulas)) and the triggers that keep the rollups (`NNN_computed.sql`), the role the [assistant's read-only queries](assistant.md#the-built-in-backend)) run as, when it finds the built-in assistant's key (`NNN_query.sql`), the [comments table](comments.md#the-table)) (`NNN_comments.sql`), and the [webhook subscriptions](webhooks.md#subscriptions-in-the-admin-app)) of `webhooks()` (`NNN_webhooks.sql`). It compares the database, with the project's migrations applied, with the config, merged with the configs it extends and those of `--extend` as `dev` merges them, and writes nothing when the database is current. Apply the files with the project's other migrations. It reads the `.env` nearest the current directory and needs `DATABASE_URL` unless the config exports `db`.
|
|
489
489
|
|
|
490
490
|
```sh
|
|
491
491
|
bun run db:migrate # the database at the project's current schema
|