@protobase/cli 0.29.1 → 0.30.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.29.1";
2
+ var version = "0.30.1";
3
3
  //#endregion
4
4
  export { version };
@@ -0,0 +1,34 @@
1
+ import { findInvalidTrustedProxies, getIPFromHeader } from "@better-auth/core/utils/ip";
2
+ //#region src/serve/client-address.ts
3
+ /** The proxies whose `X-Forwarded-For` is believed: addresses or CIDR ranges, comma separated (PROTOBASE_TRUSTED_PROXIES). */
4
+ const readTrustedProxies = (value) => {
5
+ const proxies = (value ?? "").split(",").map((entry) => entry.trim()).filter(Boolean);
6
+ const invalid = findInvalidTrustedProxies(proxies);
7
+ if (invalid.length > 0) throw new Error(`PROTOBASE_TRUSTED_PROXIES must be addresses or CIDR ranges, comma separated, not "${invalid.join(", ")}"`);
8
+ return proxies;
9
+ };
10
+ /**
11
+ * The client a request comes from: the socket's peer, or, when that is one of `trustedProxies`, the rightmost address
12
+ * of its `X-Forwarded-For` that is not one, as each proxy appends the address it took the request from. A chain of
13
+ * trusted proxies only, or one with an entry that is no address, leaves the peer.
14
+ */
15
+ const clientAddress = (peer, forwardedFor, trustedProxies) => {
16
+ const chain = trustedProxies.length > 0 && forwardedFor ? `${forwardedFor}, ${peer}` : peer;
17
+ return getIPFromHeader(chain, {
18
+ trustedProxies,
19
+ ipv6Subnet: 128
20
+ }) ?? peer;
21
+ };
22
+ /**
23
+ * `fetch` with each request's `X-Forwarded-For` replaced by its client's one address, which the sign-in and form rate
24
+ * limits key on and audit events record, so a client never picks its own bucket. Without a peer, a closed socket, the
25
+ * header is dropped.
26
+ */
27
+ const withClientAddress = (fetch, trustedProxies) => (request, env) => {
28
+ const peer = env.incoming.socket.remoteAddress;
29
+ if (peer) request.headers.set("x-forwarded-for", clientAddress(peer, request.headers.get("x-forwarded-for"), trustedProxies));
30
+ else request.headers.delete("x-forwarded-for");
31
+ return fetch(request, env);
32
+ };
33
+ //#endregion
34
+ export { clientAddress, readTrustedProxies, withClientAddress };
package/dist/serve/env.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { readTrustedProxies } from "./client-address.js";
1
2
  //#region src/serve/env.ts
2
3
  const defaultPort = 8787;
3
4
  const readBoolean = (env, name, fallback) => {
@@ -21,7 +22,8 @@ const readServeEnv = (env) => {
21
22
  filesCleanupMinutes: minutes,
22
23
  runJobs: readBoolean(env, "PROTOBASE_JOBS", true),
23
24
  startupChecks: readBoolean(env, "PROTOBASE_STARTUP_CHECKS", true),
24
- ...env.PROTOBASE_JOBS_DRAIN_TOKEN && { drainToken: env.PROTOBASE_JOBS_DRAIN_TOKEN }
25
+ ...env.PROTOBASE_JOBS_DRAIN_TOKEN && { drainToken: env.PROTOBASE_JOBS_DRAIN_TOKEN },
26
+ trustedProxies: readTrustedProxies(env.PROTOBASE_TRUSTED_PROXIES)
25
27
  };
26
28
  };
27
29
  //#endregion
@@ -1,3 +1,4 @@
1
+ import { withClientAddress } from "./client-address.js";
1
2
  import { projectAdmin } from "../project/project-admin.js";
2
3
  import { createPgDb } from "../project/pg-db.js";
3
4
  import { createServeApp } from "./app.js";
@@ -48,7 +49,7 @@ const startServe = async ({ project, env, createDb = (url) => createPgDb(pg, url
48
49
  ...env.drainToken && { drainToken: env.drainToken }
49
50
  });
50
51
  const server = createAdaptorServer({
51
- fetch: app.fetch,
52
+ fetch: withClientAddress(app.fetch, env.trustedProxies),
52
53
  overrideGlobalObjects: false,
53
54
  websocket: { server: new WebSocketServer({ noServer: true }) }
54
55
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.29.1",
3
+ "version": "0.30.1",
4
4
  "description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -33,13 +33,14 @@
33
33
  "access": "public"
34
34
  },
35
35
  "dependencies": {
36
+ "@better-auth/core": "^1.7.7",
36
37
  "@hono/node-server": "^2.1.3",
37
38
  "@hono/vite-dev-server": "^0.26.1",
38
- "@protobase/layout": "0.29.1",
39
- "@protobase/query": "0.29.1",
40
- "@protobase/schema": "0.29.1",
41
- "@protobase/server": "0.29.1",
42
- "@protobase/ui": "0.29.1",
39
+ "@protobase/layout": "0.30.1",
40
+ "@protobase/query": "0.30.1",
41
+ "@protobase/schema": "0.30.1",
42
+ "@protobase/server": "0.30.1",
43
+ "@protobase/ui": "0.30.1",
43
44
  "@react-email/render": "^2.1.0",
44
45
  "@scalar/hono-api-reference": "^0.12.10",
45
46
  "@tailwindcss/vite": "^4.3.3",
@@ -62,6 +62,7 @@ Reference:
62
62
  - When asking how the packages fit together → read [Architecture](references/reference/architecture.md)
63
63
  - When calling or changing the REST API, its filters, writes and errors → read [REST API](references/reference/api.md)
64
64
  - When an app calls it with supabase-js, `from()` and `rpc()` under RLS → read [Supabase client API](references/reference/supabase-rest.md)
65
+ - When an app calls `storage` with supabase-js, under the storage policies → read [Supabase Storage API](references/reference/supabase-storage.md)
65
66
  - When working with file fields and uploads → read [Files](references/reference/files.md)
66
67
  - When reacting to changes of records → read [Events](references/reference/events.md)
67
68
  - When delivering events to URLs → read [Webhooks](references/reference/webhooks.md)
@@ -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))) 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 (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)).
31
31
 
32
32
  ## Images
33
33
 
@@ -80,12 +80,22 @@ The columns Better Auth needs that the table lacks, filled from what the other s
80
80
  | `PROTOBASE_APP_NAME` | the app's name, passed by the platform: it overrides `appName` |
81
81
  | `PROTOBASE_SIGN_IN_ISSUER`, `PROTOBASE_SIGN_IN_CLIENT_ID`, `PROTOBASE_SIGN_IN_CLIENT_SECRET` | the [platform sign-in provider](#platform-sign-in-provider) for people who have an account, passed by the platform; off without them. `PROTOBASE_SIGN_IN_PROVIDER` and `PROTOBASE_SIGN_IN_NAME` are optional |
82
82
  | `PROTOBASE_OPERATOR_ISSUER`, `PROTOBASE_OPERATOR_CLIENT_ID`, `PROTOBASE_OPERATOR_CLIENT_SECRET` | the [operator provider](#operator-provider) its staff sign in with to sign in as people, passed by the platform; staff sign-in is off without them. `PROTOBASE_OPERATOR_NAME` and `PROTOBASE_OPERATOR_GROUP` are optional |
83
+ | `PROTOBASE_TRUSTED_PROXIES` | the proxies in front of `protobase serve`, addresses or CIDR ranges, comma separated, such as `172.16.0.0/12`; see [Client addresses](#client-addresses) |
83
84
 
84
85
  - Cookies are `SameSite=Lax`, and `Secure` when `BETTER_AUTH_URL` is https.
85
- - Sign-in is rate limited (5 password attempts per minute and client by default, `signInPerMinute`, which also limits [sign-up](#open-sign-up) requests; 3 per minute for emailed codes); the limiter keys on `x-forwarded-for`, so run behind a proxy that sets it.
86
+ - Sign-in is rate limited (5 password attempts per minute and client by default, `signInPerMinute`, which also limits [sign-up](#open-sign-up) requests; 3 per minute for emailed codes); [Client addresses](#client-addresses) says how a client is known.
86
87
  - New passwords need at least 12 characters.
87
88
  - `appName` is the app's name: authenticator apps and passkey prompts show it, the admin app's sidebar shows it at the top beside the app's [icon](app-identity.md#the-icons)), else Protobase's mark (Protobase's wordmark when it is `Protobase`), every browser tab of the admin app ends its title with it, the [installed app](installable-app.md)) is called by it, the [auth emails](email.md#protobases-own-mail)) name the app with it, and the platform's mailer sends them as it (the sender's display name). `PROTOBASE_APP_NAME`, when set, overrides it; without either it is `Protobase`, then without a display name. See [App identity](app-identity.md)).
88
89
 
90
+ ### Client addresses
91
+
92
+ The rate limits count each client address on its own: an IPv4 address, or an IPv6 address by its /64. `protobase serve` and the runtime image find it themselves and pass it on in `X-Forwarded-For`, replacing whatever the client sent:
93
+
94
+ - Without `PROTOBASE_TRUSTED_PROXIES`, the client is the address the connection comes from. That fits a server the clients reach directly, such as `docker run -p 8787:8787`.
95
+ - Behind a reverse proxy (Caddy, nginx, Traefik, a load balancer), every connection comes from the proxy, so every client would share its one limit, and three emailed codes a minute from anyone would stop everyone signing in. Set `PROTOBASE_TRUSTED_PROXIES` to the proxy's address, or the range it connects from, such as `172.16.0.0/12` for a Docker network, and have the proxy append the address it took the request from to `X-Forwarded-For` (Caddy and Traefik do by default, nginx with `proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for`). The client is then the rightmost address in it that is not a trusted proxy, so one the client wrote itself counts for nothing. Behind several proxies, such as a CDN in front of Caddy, trust them all.
96
+
97
+ An app served another way than `protobase serve`, such as its own server around `createAdmin`, gets what its server passes: the limits read `X-Forwarded-For` holding one address, and requests without one share a single limit.
98
+
89
99
  ## First run
90
100
 
91
101
  Accounts are never created over the web while the store is empty: there is no setup route, and [open sign-up](#open-sign-up), when an app turns it on, waits for the first admin, so a freshly deployed URL cannot be claimed by whoever reaches it first. The first admin is created on the host, with the CLI (`protobase users create you@example.com --generate-password`, or `--no-password` for an account that signs in by emailed code, passkey or a sign-in provider only) or from code:
@@ -377,6 +377,7 @@ Serves the API of a bundle from `protobase build` and owns the process around it
377
377
  | `PROTOBASE_JOBS` | `false` runs none of the app's [jobs](jobs.md)) in this process, which still enqueues them; default `true` |
378
378
  | `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 |
379
379
  | `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)) |
380
+ | `PROTOBASE_TRUSTED_PROXIES` | the proxies in front of the server, addresses or CIDR ranges, comma separated: a request from one of them names its client in `X-Forwarded-For`; without it the client is the connection's address ([Client addresses](auth.md#client-addresses))) |
380
381
  | `PROTOBASE_JOBS_DRAIN_TOKEN` | the operator's bearer token for `POST /api/jobs/drain`, which [runs the due jobs](jobs.md#hosts-that-sleep)) of a host that lets the app sleep; without it there is no such endpoint |
381
382
 
382
383
  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.
@@ -112,7 +112,7 @@ export const newContactRequests = subscription('newContactRequests', {
112
112
 
113
113
  ## Rate limit
114
114
 
115
- Each client may send a form `perMinute` times a minute, 5 by default, as many as it may try to sign in. Past that, the form answers `429` with `Retry-After`. A client is known by its address in `X-Forwarded-For`, read as the sign-in limit reads it: a header with one address, an IPv6 address by its /64. Requests without one, or with several addresses, as a proxy makes when it appends to a header the client sent, share a single limit. The count is kept in each server process's memory, so with several instances each counts on its own, and a restart starts over.
115
+ Each client may send a form `perMinute` times a minute, 5 by default, as many as it may try to sign in. Past that, the form answers `429` with `Retry-After`. A client is known by its address, as the sign-in limit knows it: see [Client addresses](auth.md#client-addresses)), and `PROTOBASE_TRUSTED_PROXIES` behind a proxy. The count is kept in each server process's memory, so with several instances each counts on its own, and a restart starts over.
116
116
 
117
117
  ## Bot check
118
118
 
@@ -0,0 +1,54 @@
1
+ <!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/reference/supabase-storage.md: run `bun run docs:skill`, do not edit. -->
2
+
3
+ # Supabase Storage API
4
+
5
+ The Storage-compatible /storage/v1 that supabase-js's storage calls, over the app's file provider, under the restored storage policies.
6
+
7
+ An app with API keys also serves `/storage/v1`, the API that supabase-js's `storage` calls. An app moved from Supabase keeps its uploads, downloads, public URLs and signed URLs: point the client at the app and give it the publishable key.
8
+
9
+ ```ts
10
+ import { createClient } from '@supabase/supabase-js'
11
+
12
+ const supabase = createClient('https://my-app.example.com', 'sb_publishable_...')
13
+ const { data, error } = await supabase.storage.from('avatars').upload(`${userId}/avatar.png`, file)
14
+ ```
15
+
16
+ ## Where things are kept
17
+
18
+ The buckets and objects are the rows of `storage.buckets` and `storage.objects`, the schema that `protobase import supabase` restores with its policies. The bytes go to one of the app's [file providers](files.md)): `files.storage.provider` in `protobase.config.ts`, `private` by default, so a local folder or an S3-compatible bucket, with that provider's `max_bytes` and `max_files` quota. An object's bytes are kept at `storage/<SHA-256 of bucket and name>/<version>` in the provider. `files.storage.maxFileSize` caps every upload, `50 MB` by default, and a bucket's `file_size_limit` can only lower it. `files: { storage: false }` serves no `/storage/v1`.
19
+
20
+ ## Keys and roles
21
+
22
+ The keys are `options.apiKeys` of `createAdmin`, `{ publishable_key, secret_key }`, or else `PROTOBASE_PUBLISHABLE_KEY` and `PROTOBASE_SECRET_KEY`. Without either, or with `apiKeys: false`, the app serves no `/storage/v1`. A request sends a key in the `apikey` header and runs as:
23
+
24
+ | The request sends | It runs as |
25
+ | --- | --- |
26
+ | the publishable key | `anon` |
27
+ | either key and a signed-in user's token | `authenticated` |
28
+ | the secret key | the app's own role, which owns the tables |
29
+
30
+ The role is set with `SET LOCAL ROLE` and the token's claims in `request.jwt.claims` and `request.jwt.claim.sub`, so Supabase's `auth.uid()` works in the policies. The database needs the `anon` and `authenticated` roles, and the app's role must be allowed to `SET ROLE` to them. Every read and write of `storage.objects` and `storage.buckets` runs as that role, with the token's claims set, so the restored policies decide, as on Supabase:
31
+
32
+ - an upload needs an `insert` policy, and one with `upsert` also `select` and `update`;
33
+ - a download, a signed URL, `info`, `list`, `copy`'s source and `move` need `select`, and `move` also `update`;
34
+ - `remove` and `empty` delete only what a `delete` policy allows;
35
+ - the bucket calls need policies on `storage.buckets`, which usually only the secret key gets past.
36
+
37
+ An upload is checked against the policies before its bytes are stored, then its row is written as the caller in one transaction. A refused upload stores nothing, and the bytes of a write that fails are deleted.
38
+
39
+ Public buckets are served at `/storage/v1/object/public/<bucket>/<name>` without a key. A signed URL serves one object to anyone until it expires; a signed upload URL takes one upload for two hours, written for the user who signed it.
40
+
41
+ ## What it serves
42
+
43
+ - `object/<bucket>/<name>`: upload (POST, with `x-upsert`), replace (PUT), download (GET, also `object/authenticated/...`), `exists` (HEAD) and delete.
44
+ - `object/public/...`, `object/sign/...` (one or many) and `object/upload/sign/...`.
45
+ - `object/list/<bucket>`, `object/move`, `object/copy` and `object/info/...`.
46
+ - `bucket`: list, get, create, update, empty and delete.
47
+
48
+ A download is sent with the type it was uploaded with, `nosniff` and a sandboxing Content-Security-Policy, so an uploaded page cannot run on the app's origin, and `?download` makes it an attachment.
49
+
50
+ Not yet: image transforms, resumable (TUS) uploads, the S3 protocol, object versioning and copying the bytes of an existing Supabase project.
51
+
52
+ ## Errors
53
+
54
+ Errors come back as Supabase Storage sends them: status `400` with `{ statusCode, error, message }`, where `statusCode` says what happened: `404` for an object or bucket that is not there or not visible, `403` for a refusal by policy, `409` for an object or bucket that exists, `413` for an object over the size limit, `415` for a type the bucket does not allow. A failure is `500`.