@protobase/cli 0.33.2 → 0.33.4

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.
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.33.2";
2
+ var version = "0.33.4";
3
3
  //#endregion
4
4
  export { version };
@@ -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 };
@@ -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 };
@@ -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: new WebSocketServer({ noServer: true }) }
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
- await closeServer(server);
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();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.33.2",
3
+ "version": "0.33.4",
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.7",
37
37
  "@hono/node-server": "^2.1.3",
38
38
  "@hono/vite-dev-server": "^0.26.1",
39
- "@protobase/layout": "0.33.2",
40
- "@protobase/query": "0.33.2",
41
- "@protobase/schema": "0.33.2",
42
- "@protobase/server": "0.33.2",
43
- "@protobase/ui": "0.33.2",
39
+ "@protobase/layout": "0.33.4",
40
+ "@protobase/query": "0.33.4",
41
+ "@protobase/schema": "0.33.4",
42
+ "@protobase/server": "0.33.4",
43
+ "@protobase/ui": "0.33.4",
44
44
  "@react-email/render": "^2.1.0",
45
45
  "@scalar/hono-api-reference": "^0.12.10",
46
46
  "@tailwindcss/vite": "^4.3.3",
@@ -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"
@@ -530,4 +530,4 @@ Only the Better Auth routes under `/api/auth/*` (sign-in, password reset, [open
530
530
 
531
531
  Roles are bundles of capabilities (`defineRoles` in `@protobase/schema`: `orders.read.own`, `costs.read`, `*.read`, ...). Pass the result as `options.roles` to `createAdmin`, and every operation without an explicit rule needs the matching capability; a capability may be limited to [fields and rows](access.md#capabilities)). The token's `roles` become `ctx.user.roles` in rules; the user id (`sub`) is what `.own` compares with the resource's `.owner(...)` field, so it must be the id that field stores. How the API enforces them (hidden fields, row filters, record permissions) is in [the REST API reference](api.md#access)).
532
532
 
533
- **User ids.** Better Auth gives a new user a random 32-character text id, so an `.owner(...)` field holds `text`: the server refuses to start (`protobase dev`, `serve`) when one holds integers or UUIDs, naming the field. An app whose owner columns are integers, such as a relation to its own users table, gives `createAuth` a `generateUserId` that takes the next value of that table's sequence, and adds the user's row there, as the ERP example does (`examples/erp/auth/auth.ts`, with the row added by `db/migrations/019_auth_users.sql` when someone joins an organization). One whose owner columns are UUIDs gives it `generateUserId: 'uuid'` (see [An existing users table](#an-existing-users-table)). A request by a user whose id the owner field cannot hold, such as one made before `generateUserId`, fails with an `owner-id-mismatch` problem that names the field.
533
+ **User ids.** Better Auth gives a new user a random 32-character text id, so an `.owner(...)` field holds `text`: the server refuses to start (`protobase dev`, `serve`) when one holds integers or UUIDs, naming the field. An app whose owner columns are integers, such as a relation to its own users table, gives `createAuth` a `generateUserId` that takes the next value of that table's sequence, and adds the user's row there, as the ERP example does (`examples/erp/auth/auth.ts`, with the row added by `db/migrations/019_auth_users.sql` when someone joins an organization). One whose owner columns are UUIDs gives it `generateUserId: 'uuid'` (see [An existing users table](#an-existing-users-table)). An authenticator that maps the signed-in account to a user of the app's own, such as a wrapper around `betterAuthAuthenticator` that returns the id of a row in its users table, declares the type of those ids instead, `Object.assign(authenticate, { userIdType: 'uuid' })` (or `'integer'`, `'bigint'`, `'text'`), and the owner fields are checked against that. A request by a user whose id the owner field cannot hold, such as one made before `generateUserId`, fails with an `owner-id-mismatch` problem that names the field.
@@ -390,7 +390,7 @@ Better Auth and other settings are the project's own variables (`BETTER_AUTH_SEC
390
390
  - **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
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
392
  - **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.
393
+ - **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
394
  - **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
395
  - **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
396