@quickback-dev/cli 0.70.23 → 0.70.24

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/index.js CHANGED
@@ -10,7 +10,7 @@
10
10
  */
11
11
  import pc from "picocolors";
12
12
  // Version injected at build time by scripts/inject-version.ts
13
- const CLI_VERSION = "0.70.23";
13
+ const CLI_VERSION = "0.70.24";
14
14
  function getPackageVersion() {
15
15
  return CLI_VERSION;
16
16
  }
@@ -199,6 +199,10 @@ missing field falls back to its hardcoded value:
199
199
  - **CLI-heavy / long-running CI tokens:** `expiresIn: 3600` for one-hour bearer tokens. Pair with `issuer` / `audience` if multiple services consume the same JWT.
200
200
  - **Need immediate revocation:** set `revocationCheck: 'kv'` (Cloudflare runtime) — revoked tokens are rejected within seconds, and stamps are written automatically on user ban, member removal, role change, and scope-conferring row changes (see the [scope revocation notes](/define/scopes#revocation--ttl)). It fails closed, so bearer auth then depends on KV being readable — declare `bindings.kv` on every environment and alert on `AUTH_REVOCATION_UNAVAILABLE`. Or drop TTL to ~30s — similar effect with bounded delay, zero KV reads, and no availability coupling.
201
201
 
202
+ ## `auth.organizationRoster` — members read on the JWT
203
+
204
+ `auth: { organizationRoster: { access: { roles: ['member'] } } }` emits `GET /auth/v1/organization/roster`, the active organization's members (`id`, `name`, `email`, `image`, `role`). Better Auth's `list-members` needs a session; this works on the JWT bearer. See [Listing organization members](/platform/auth/using-auth#listing-organization-members).
205
+
202
206
  ## `auth.loginUrl` — external sign-in for consumer Workers
203
207
 
204
208
  When a Quickback Worker doesn't host its own Account SPA — e.g. an internal-app mesh where one Worker on the parent domain owns identity (`auth.example.com`) and other Workers share cookies — the compiler-emitted CMS access gate needs to redirect unauthenticated visitors to the central sign-in surface, not the local `/account/login` (which doesn't exist there).
@@ -97,7 +97,8 @@ Every optional top-level key the config accepts is listed below. You never have
97
97
  | `domain` | `string` | Primary custom domain serving every surface. Required when only cms/api/auth hostnames are declared and the CMS or Account SPA is enabled; never inferred — see [Domains](/configure/domains) |
98
98
  | `contract` | `{ routes?: "v1" \| "v2" }` | `routes` selects the URL prefix and nothing else (default `"v1"`). See [API Contract](/platform/api-contract#one-axis-routes). |
99
99
  | `api` | `object` | Dedicated hostname for the selected feature API contract (`/api/v1/*` or `/api/v2/*`); additive alias — see [Domains](/configure/domains) |
100
- | `auth` | `object` | App-level auth settings (`roles`, `roleHierarchy`, `jwt`, delegated `principals`, `loginUrl`, `domain`) — see [Auth](/configure/auth), [Access](/define/access#role-hierarchy), and [Delegated principals](#delegated-principals) |
100
+ | `auth` | `object` | App-level auth settings (`roles`, `roleHierarchy`, `jwt`, delegated `principals`, `loginUrl`, `domain`, `organizationRoster`) — see [Auth](/configure/auth), [Access](/define/access#role-hierarchy), and [Delegated principals](#delegated-principals) |
101
+ | `changes` | `object` | Table change signals for organization-scoped tables: `broadcast` (`data.changed` realtime frame per table per request) and `counter` (per-organization change version) — see [Table change signals](/platform/realtime/table-changes) |
101
102
  | `authz` | `object` | Relationship-based authorization (`relationships`, `roles`, `rules`, `tenants`, `permissions`, `arrows`) — see [Access](/define/authz-roles#centrally-defined-access-rules) and [Permissions](/define/permissions). `rules` = named gates (who + `record:` + firewall lanes under one name); `tenants` = named tenant anchors (`{ column, equals }`, referenced as `{ tenant: '<name>' }` in firewalls and `tenant: '<name>'` in auth-view includes). Root `authz` is the GLOBAL vocabulary level — names scoped to one concept belong in that concept's [feature area](/define/areas) (`_area.ts`), and root bodies may reference root-declared names only |
102
103
  | `requires` | `string[]` | Capability floor (fail-closed guard). Declare `['feature-areas']` when the project uses `features/**/_area.ts` — an area-unaware CLI/compiler then refuses the compile instead of silently dropping nested features. See [Feature areas](/define/areas#the-capability-floor-requires-feature-areas) |
103
104
  | `trustedOrigins` | `string[]` | CORS trusted origins for cross-domain auth |
@@ -731,6 +731,13 @@ export default defineAction({
731
731
  mode it's a separate D1 from your features). That is the native membership
732
732
  check.
733
733
 
734
+ On a single-database project — Postgres, or D1 without split databases — it is
735
+ the same database as your features. On Postgres it runs under the caller's
736
+ claims, so Better Auth's own RLS applies: `members` rows of the active
737
+ organization are readable, `users` only the caller's own row. To list the
738
+ active organization's members with names and emails, use the generated
739
+ [roster read](/platform/auth/using-auth#listing-organization-members).
740
+
734
741
  For a richer query, use the same `authDb` and import tables from
735
742
  `../../../auth/schema` — from an **`actions/` file**. On D1 the tables are
736
743
  `user`, `organization`, and `member` — not `organization_membership`. (Neon
@@ -121,6 +121,11 @@ export default defineBundle({
121
121
  ),
122
122
  ```
123
123
 
124
+ With `changes: { counter: true }`, `changeCounter(db, ctx.activeOrgId)`
125
+ is a probe that every write in the organization moves — including hard
126
+ deletes, queue, cron and raw SQL. See
127
+ [Table change signals](/platform/realtime/table-changes#counter--a-safe-bundle-version-probe).
128
+
124
129
  The contract you accept: **the ETag changes only when the version
125
130
  changes**. A probe that misses a mutation (a hard delete does not move
126
131
  `max(modifiedAt)`) keeps clients on `notModified`. A probe that throws
@@ -413,6 +413,7 @@ When the `firewall:` block is omitted, the compiler scans the schema for known s
413
413
 
414
414
  - **Audit columns.** `createdAt`, `modifiedAt`, `createdBy`, `modifiedBy` are on every table (declared with `...q.audit()`), and `deletedAt` / `deletedBy` are on every table whose resource soft-deletes (declared with `...q.softDelete()`). Disable the whole mechanism globally with `compiler.features.auditFields: false`.
415
415
  - **Soft-delete filtering.** If the table has a `deletedAt` column — which it does unless both `crud.delete.mode` and `crud.batchDelete.mode` are `'hard'` — the firewall still emits `isNull(<table>.deletedAt)` so soft-deleted records stay hidden. To opt out on an exception resource, switch the resource to hard deletes or set `compiler.features.auditFields: false` globally.
416
+ - **A hard-delete table has no soft-delete arm.** Declaring one anyway — `softDelete: {}` in the named form, or `{ field: 'deletedAt', isNull: true }` — on a table without the column is a compile error on Postgres, rather than an RLS policy over a column that does not exist. Drop the arm, or add `...q.softDelete()` and use `delete: { mode: 'soft' }`.
416
417
 
417
418
  So `firewall: [{ exception: true }]` on the default configuration returns `isNull(<table>.deletedAt)` from `buildFirewallConditions()` — no tenant filter, soft-delete filter still applied.
418
419
 
@@ -13,7 +13,17 @@ Better Auth supports multiple sign-in methods:
13
13
 
14
14
  ## Session Handling
15
15
 
16
- Sessions live in the **auth database**, and every session lookup reads it — the compiler does not configure Better Auth `secondaryStorage`, so a KV namespace does not cache sessions. To take session reads off the database hot path, enable the signed cookie cache (`session.cookieCache`), which trades revocation latency (capped by its `maxAge`) for fewer reads.
16
+ Sessions live in the **auth database**. The signed cookie cache (`session.cookieCache`) is **on by default** with a 300 s `maxAge`: the auth middleware serves most requests from the cookie instead of the session + user lookups, which are otherwise two statements on every authenticated request (on Postgres over Hyperdrive, most of the fixed per-request cost). The trade is revocation latency: a ban, sign-out-everywhere or role change can take up to `maxAge` to reach a cached session. Bump `cookieCache.version` to invalidate every cached session at once, lower `maxAgeSeconds`, or set `session: { cookieCache: { enabled: false } }` when every request must see the row. The compiler does not configure Better Auth `secondaryStorage`, so a KV namespace does not cache sessions.
17
+
18
+ ```typescript
19
+ providers: {
20
+ auth: defineAuth("better-auth", {
21
+ session: {
22
+ cookieCache: { enabled: true, maxAgeSeconds: 60 }, // or { enabled: false }
23
+ },
24
+ }),
25
+ }
26
+ ```
17
27
 
18
28
  The generated auth middleware resolves the session once per request and hydrates a single Hono context variable, `ctx` — it does **not** set `session` or `user` variables:
19
29
 
@@ -84,6 +94,26 @@ const orgId = c.get('ctx').activeOrgId;
84
94
  > `activeOrganizationId` is Better Auth's *session* field name (`session.session.activeOrganizationId`). Quickback canonicalises it to `ctx.activeOrgId`; firewall rules written against `ctx.activeOrganizationId` are rewritten to `ctx.activeOrgId` at compile time.
85
95
 
86
96
 
97
+ ## Listing organization members
98
+
99
+ Better Auth's `GET /auth/v1/organization/list-members` needs a session — a JWT bearer gets 401. To list the active organization's members on the JWT, opt into the roster read:
100
+
101
+ ```ts title="quickback.config.ts"
102
+ export default defineConfig({
103
+ // ...
104
+ auth: {
105
+ organizationRoster: { access: { roles: ['member', 'admin'] } },
106
+ },
107
+ });
108
+ ```
109
+
110
+ `GET /auth/v1/organization/roster` then returns `{ data: [{ id, name, email, image, role }] }` for `ctx.activeOrgId`:
111
+
112
+ - **401** with no credentials, **403** `ACCESS_NO_ORG` with no active organization, **403** when the caller holds none of `access.roles`.
113
+ - It reads on the service lane and filters to the active organization in the query, because Postgres RLS lets a caller-scoped handle read only their own `users` row.
114
+ - The column set is fixed. Sessions, accounts and credentials are never returned.
115
+ - `roles` is required, and the organization plugin must be enabled — otherwise the compile fails.
116
+
87
117
  ## Related
88
118
 
89
119
  - [Auth Overview](/platform/auth) — Setup and configuration
@@ -310,6 +310,44 @@ environment for Drizzle schema generation and migrations. Better Auth and
310
310
  feature queries both use Hyperdrive at runtime, eliminating a second direct
311
311
  Neon connection lane.
312
312
 
313
+ Create the config against the **direct** Neon host (uncheck "Connection
314
+ pooling" in the Neon dashboard — Hyperdrive is the pool):
315
+
316
+ ```bash
317
+ npx wrangler hyperdrive create my-app-db \
318
+ --caching-disabled \
319
+ --origin-connection-limit 60 \
320
+ --connection-string="postgresql://quickback:<password>@<endpoint>.<region>.aws.neon.tech/neondb?sslmode=require"
321
+ ```
322
+
323
+ `--caching-disabled` is mandatory: Hyperdrive keys its cache on query text
324
+ alone and never invalidates on write, so a cached `SELECT` would be replayed
325
+ to another tenant. `--origin-connection-limit` is the soft cap on connections
326
+ Hyperdrive opens to Neon (minimum 5; about 100 on a paid Workers plan). Each
327
+ in-flight request holds one origin connection per leased client, so size it
328
+ to your concurrency, not your statement count. Raise it later with
329
+ `npx wrangler hyperdrive update <id> --origin-connection-limit <n>`.
330
+
331
+ ### Tuning the Worker for Hyperdrive
332
+
333
+ - **Set placement.** Every authenticated request makes several sequential
334
+ round trips (session, membership, the query), so Worker-to-database
335
+ distance dominates latency: a single `SELECT` measured ~180 ms from the
336
+ caller's colo and ~90 ms with `placement.region` set to the database
337
+ region. Set `providers.runtime.config.placement: { region: "aws:us-east-2" }`
338
+ (your Neon region; see [runtime options](/configure/providers#runtime-options)),
339
+ or per target with `environments.<name>.worker.placement`. The compiler
340
+ warns when a Hyperdrive project has neither.
341
+ - **Keep the session cookie cache on.** It is on by default
342
+ (`session.cookieCache`, 300 s) and removes the session + user lookups —
343
+ two of the three fixed statements on every authenticated request. See
344
+ [Session handling](/platform/auth/using-auth#session-handling) before
345
+ turning it off.
346
+ - **Check Neon autosuspend.** Hyperdrive keeps origin connections warm, but it
347
+ does not keep an idle Neon compute awake: the first request after a
348
+ suspend pays the compute start. Lengthen or disable autosuspend on the
349
+ production branch.
350
+
313
351
  For local `wrangler dev` without named environments, set
314
352
  `providers.database.config.hyperdrive.localConnectionString` to a local or
315
353
  development-only Postgres URL. With named environments, put it on the target
@@ -1274,8 +1312,9 @@ read under different claims (a service-lane lookup between caller reads, a
1274
1312
  scope minted mid-request) re-stamps the preamble inside the open transaction —
1275
1313
  `set_config(…, true)` is transaction-local, so the previous claims are gone the
1276
1314
  moment the new ones land. The read lane is rolled back before a write or a
1277
- `db.transaction()` takes the connection, after any read error, and when the
1278
- invocation scope closes the pool. That `ROLLBACK` is its own round trip, never
1315
+ `db.transaction()` takes the connection, after any read error, as soon as the
1316
+ handler returns (before deferred `waitUntil` work runs — a deferred read opens
1317
+ a fresh lane), and when the invocation scope closes the pool. That `ROLLBACK` is its own round trip, never
1279
1318
  pipelined with the write's `BEGIN`: Hyperdrive's transaction pooler releases
1280
1319
  the origin connection at the transaction end and loses anything pipelined past
1281
1320
  it, which hung every write that followed a read in 0.70.10–0.70.12. A
@@ -1286,8 +1325,9 @@ else is a write.
1286
1325
 
1287
1326
  Each read sees everything committed before it, including the request's own
1288
1327
  writes — Postgres runs `READ COMMITTED` by default, and a read-only transaction
1289
- changes nothing about that. The open lane pins its Hyperdrive origin connection
1290
- for the invocation; `idle_in_transaction_session_timeout` (15 s on the deployed
1328
+ changes nothing about that. Hyperdrive pools in transaction mode, so an open
1329
+ lane pins one origin connection until the handler returns (up to five under
1330
+ `Promise.all`); `idle_in_transaction_session_timeout` (15 s on the deployed
1291
1331
  role) and the scope close bound the worst case. A ten-statement read path costs
1292
1332
  about eleven round trips instead of thirteen to thirty-four, which is where the
1293
1333
  `tx` versus `stmts` ratio in [`Server-Timing`](#measuring-database-cost-server-timing)
@@ -136,9 +136,16 @@ another place for session state to be reused.
136
136
  ```bash
137
137
  npx wrangler hyperdrive create my-app-db \
138
138
  --caching-disabled \
139
+ --origin-connection-limit 60 \
139
140
  --connection-string="postgres://quickback.<branch_id>:<password>@<host>:5432/<database>?sslmode=verify-full"
140
141
  ```
141
142
 
143
+ `--origin-connection-limit` is the soft cap on connections Hyperdrive opens to
144
+ the branch (minimum 5; about 100 on a paid Workers plan). Each in-flight
145
+ request holds one origin connection per leased client until its handler
146
+ returns, so size it to your concurrency and raise it later with
147
+ `npx wrangler hyperdrive update <id> --origin-connection-limit <n>`.
148
+
142
149
  > `--caching-disabled` is mandatory. Quickback scopes RLS per request by writing
143
150
  > the caller's claims into transaction-local settings; a cached result set would
144
151
  > be replayed to a different caller, across tenants. Caching happens at the app
@@ -194,7 +201,10 @@ Set `providers.runtime.config.placement: { region: "aws:us-east-2" }` (your
194
201
  branch's region) so the Worker runs next to the database — every statement is
195
202
  several round-trips, so Worker-to-database distance dominates latency. A target
196
203
  whose branch lives elsewhere overrides it with
197
- `environments.<name>.worker.placement`.
204
+ `environments.<name>.worker.placement`. The compiler warns when a Hyperdrive
205
+ project sets neither. The rest of the tuning notes — the session cookie cache
206
+ and connection limits — are on
207
+ [Neon → Tuning the Worker for Hyperdrive](/platform/database/neon#tuning-the-worker-for-hyperdrive).
198
208
 
199
209
  ## What is shared with Neon, and what is not
200
210
 
@@ -0,0 +1,62 @@
1
+ # Table Change Signals
2
+
3
+ `changes` gives every organization-scoped table two signals without per-table hooks:
4
+
5
+ - **`broadcast`** — a realtime `data.changed` frame, payload `{ table }`, sent to the organization's members after a write commits.
6
+ - **`counter`** — a per-organization version in `qb_change_counter`, bumped by database triggers on every write. Read it with `changeCounter()`.
7
+
8
+ ```ts title="quickback.config.ts"
9
+ export default defineConfig({
10
+ // ...
11
+ changes: {
12
+ broadcast: { access: { roles: ['member+'] } },
13
+ counter: true,
14
+ },
15
+ });
16
+ ```
17
+
18
+ Both cover tables with an `organizationId` column. Tables without one get neither.
19
+
20
+ ## `broadcast` — refetch by table
21
+
22
+ The write chokepoint (the audit-wrapped `db`) sends one frame per (organization, table) per request:
23
+
24
+ ```json
25
+ { "type": "broadcast", "event": "data.changed", "payload": { "table": "invoices" } }
26
+ ```
27
+
28
+ - **Once per table per request.** Ten writes to `invoices` in one request send one frame.
29
+ - **After commit.** Inside `db.transaction()` the frames wait for the commit and are dropped on rollback. Outside a transaction each statement has already committed when its frame is sent.
30
+ - **Audience.** `access.roles` (expanded through `auth.roleHierarchy`) becomes the frame's `targetRoles`, in the caller's active organization. A cron or queue write has no active organization, so the frame goes to the `organizationId` of the written rows — which requires `.returning()`; without it there are no rows to read and no frame.
31
+ - **Coverage.** Every write through the wrapped `db`: CRUD routes, actions, cron, queue, and email handlers. Raw SQL and writes through an unwrapped handle send nothing — use the counter to catch those.
32
+ - **Best-effort.** A failed send never fails the write.
33
+
34
+ `table` is the SQL table name — the same name trigger handlers receive.
35
+
36
+ Requires realtime (`realtime: true` on the database provider) and audit fields (on by default). Otherwise the compile fails.
37
+
38
+ ## `counter` — a safe bundle version probe
39
+
40
+ Compiler-owned `AFTER INSERT / UPDATE / DELETE` triggers on each organization-scoped table bump that organization's row in `qb_change_counter`. Because they are database triggers, queue, cron and raw-SQL writes count too. A soft delete counts once.
41
+
42
+ Use it as a bundle's [`version` probe](/define/bundles). A probe built on `max(modifiedAt)` misses hard deletes and every table the bundle reads indirectly. The counter misses neither:
43
+
44
+ {/* doc-compile: skip — fragment of a defineBundle call */}
45
+ ```typescript
46
+ import { changeCounter } from "../../../lib/change-counter";
47
+
48
+ version: custom(({ db, ctx }) => changeCounter(db, ctx.activeOrgId)),
49
+ ```
50
+
51
+ The trade-off: any write in the organization changes the version, so unrelated writes cost a full read. That is never a stale `notModified`. Clients can also compare the counter after a reconnect to decide whether to refetch.
52
+
53
+ - **Postgres:** the trigger functions are `SECURITY DEFINER`, owned by `quickback_owner`. The Worker role reads only its active organization's row, or any row on the service lane, and cannot write the table.
54
+ - **D1:** plain SQLite triggers in the features database.
55
+ - **Contention:** one row per organization serializes concurrent writes within that organization until each commits.
56
+ - **Providers:** `cloudflare-d1` and the Postgres providers. Elsewhere the compile fails.
57
+
58
+ ## Related
59
+
60
+ - [Named invalidations](/platform/realtime/named-invalidations) — typed, action-fired signals
61
+ - [Bundles](/define/bundles) — `version` probes and ETags
62
+ - [Triggers](/define/triggers) — the same journaled SQL-trigger lane
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quickback-dev/cli",
3
- "version": "0.70.23",
3
+ "version": "0.70.24",
4
4
  "description": "CLI for Quickback — define your backend in TypeScript, compile to a fully wired Cloudflare Worker (or Bun / Node) with auth, database, migrations, security, CMS, and Account UI.",
5
5
  "author": "Kardoe Incorporated <paul@kardoe.com>",
6
6
  "license": "MIT",
@@ -199,6 +199,10 @@ missing field falls back to its hardcoded value:
199
199
  - **CLI-heavy / long-running CI tokens:** `expiresIn: 3600` for one-hour bearer tokens. Pair with `issuer` / `audience` if multiple services consume the same JWT.
200
200
  - **Need immediate revocation:** set `revocationCheck: 'kv'` (Cloudflare runtime) — revoked tokens are rejected within seconds, and stamps are written automatically on user ban, member removal, role change, and scope-conferring row changes (see the [scope revocation notes](/define/scopes#revocation--ttl)). It fails closed, so bearer auth then depends on KV being readable — declare `bindings.kv` on every environment and alert on `AUTH_REVOCATION_UNAVAILABLE`. Or drop TTL to ~30s — similar effect with bounded delay, zero KV reads, and no availability coupling.
201
201
 
202
+ ## `auth.organizationRoster` — members read on the JWT
203
+
204
+ `auth: { organizationRoster: { access: { roles: ['member'] } } }` emits `GET /auth/v1/organization/roster`, the active organization's members (`id`, `name`, `email`, `image`, `role`). Better Auth's `list-members` needs a session; this works on the JWT bearer. See [Listing organization members](/platform/auth/using-auth#listing-organization-members).
205
+
202
206
  ## `auth.loginUrl` — external sign-in for consumer Workers
203
207
 
204
208
  When a Quickback Worker doesn't host its own Account SPA — e.g. an internal-app mesh where one Worker on the parent domain owns identity (`auth.example.com`) and other Workers share cookies — the compiler-emitted CMS access gate needs to redirect unauthenticated visitors to the central sign-in surface, not the local `/account/login` (which doesn't exist there).
@@ -97,7 +97,8 @@ Every optional top-level key the config accepts is listed below. You never have
97
97
  | `domain` | `string` | Primary custom domain serving every surface. Required when only cms/api/auth hostnames are declared and the CMS or Account SPA is enabled; never inferred — see [Domains](/configure/domains) |
98
98
  | `contract` | `{ routes?: "v1" \| "v2" }` | `routes` selects the URL prefix and nothing else (default `"v1"`). See [API Contract](/platform/api-contract#one-axis-routes). |
99
99
  | `api` | `object` | Dedicated hostname for the selected feature API contract (`/api/v1/*` or `/api/v2/*`); additive alias — see [Domains](/configure/domains) |
100
- | `auth` | `object` | App-level auth settings (`roles`, `roleHierarchy`, `jwt`, delegated `principals`, `loginUrl`, `domain`) — see [Auth](/configure/auth), [Access](/define/access#role-hierarchy), and [Delegated principals](#delegated-principals) |
100
+ | `auth` | `object` | App-level auth settings (`roles`, `roleHierarchy`, `jwt`, delegated `principals`, `loginUrl`, `domain`, `organizationRoster`) — see [Auth](/configure/auth), [Access](/define/access#role-hierarchy), and [Delegated principals](#delegated-principals) |
101
+ | `changes` | `object` | Table change signals for organization-scoped tables: `broadcast` (`data.changed` realtime frame per table per request) and `counter` (per-organization change version) — see [Table change signals](/platform/realtime/table-changes) |
101
102
  | `authz` | `object` | Relationship-based authorization (`relationships`, `roles`, `rules`, `tenants`, `permissions`, `arrows`) — see [Access](/define/authz-roles#centrally-defined-access-rules) and [Permissions](/define/permissions). `rules` = named gates (who + `record:` + firewall lanes under one name); `tenants` = named tenant anchors (`{ column, equals }`, referenced as `{ tenant: '<name>' }` in firewalls and `tenant: '<name>'` in auth-view includes). Root `authz` is the GLOBAL vocabulary level — names scoped to one concept belong in that concept's [feature area](/define/areas) (`_area.ts`), and root bodies may reference root-declared names only |
102
103
  | `requires` | `string[]` | Capability floor (fail-closed guard). Declare `['feature-areas']` when the project uses `features/**/_area.ts` — an area-unaware CLI/compiler then refuses the compile instead of silently dropping nested features. See [Feature areas](/define/areas#the-capability-floor-requires-feature-areas) |
103
104
  | `trustedOrigins` | `string[]` | CORS trusted origins for cross-domain auth |
@@ -731,6 +731,13 @@ export default defineAction({
731
731
  mode it's a separate D1 from your features). That is the native membership
732
732
  check.
733
733
 
734
+ On a single-database project — Postgres, or D1 without split databases — it is
735
+ the same database as your features. On Postgres it runs under the caller's
736
+ claims, so Better Auth's own RLS applies: `members` rows of the active
737
+ organization are readable, `users` only the caller's own row. To list the
738
+ active organization's members with names and emails, use the generated
739
+ [roster read](/platform/auth/using-auth#listing-organization-members).
740
+
734
741
  For a richer query, use the same `authDb` and import tables from
735
742
  `../../../auth/schema` — from an **`actions/` file**. On D1 the tables are
736
743
  `user`, `organization`, and `member` — not `organization_membership`. (Neon
@@ -121,6 +121,11 @@ export default defineBundle({
121
121
  ),
122
122
  ```
123
123
 
124
+ With `changes: { counter: true }`, `changeCounter(db, ctx.activeOrgId)`
125
+ is a probe that every write in the organization moves — including hard
126
+ deletes, queue, cron and raw SQL. See
127
+ [Table change signals](/platform/realtime/table-changes#counter--a-safe-bundle-version-probe).
128
+
124
129
  The contract you accept: **the ETag changes only when the version
125
130
  changes**. A probe that misses a mutation (a hard delete does not move
126
131
  `max(modifiedAt)`) keeps clients on `notModified`. A probe that throws
@@ -413,6 +413,7 @@ When the `firewall:` block is omitted, the compiler scans the schema for known s
413
413
 
414
414
  - **Audit columns.** `createdAt`, `modifiedAt`, `createdBy`, `modifiedBy` are on every table (declared with `...q.audit()`), and `deletedAt` / `deletedBy` are on every table whose resource soft-deletes (declared with `...q.softDelete()`). Disable the whole mechanism globally with `compiler.features.auditFields: false`.
415
415
  - **Soft-delete filtering.** If the table has a `deletedAt` column — which it does unless both `crud.delete.mode` and `crud.batchDelete.mode` are `'hard'` — the firewall still emits `isNull(<table>.deletedAt)` so soft-deleted records stay hidden. To opt out on an exception resource, switch the resource to hard deletes or set `compiler.features.auditFields: false` globally.
416
+ - **A hard-delete table has no soft-delete arm.** Declaring one anyway — `softDelete: {}` in the named form, or `{ field: 'deletedAt', isNull: true }` — on a table without the column is a compile error on Postgres, rather than an RLS policy over a column that does not exist. Drop the arm, or add `...q.softDelete()` and use `delete: { mode: 'soft' }`.
416
417
 
417
418
  So `firewall: [{ exception: true }]` on the default configuration returns `isNull(<table>.deletedAt)` from `buildFirewallConditions()` — no tenant filter, soft-delete filter still applied.
418
419
 
@@ -13,7 +13,17 @@ Better Auth supports multiple sign-in methods:
13
13
 
14
14
  ## Session Handling
15
15
 
16
- Sessions live in the **auth database**, and every session lookup reads it — the compiler does not configure Better Auth `secondaryStorage`, so a KV namespace does not cache sessions. To take session reads off the database hot path, enable the signed cookie cache (`session.cookieCache`), which trades revocation latency (capped by its `maxAge`) for fewer reads.
16
+ Sessions live in the **auth database**. The signed cookie cache (`session.cookieCache`) is **on by default** with a 300 s `maxAge`: the auth middleware serves most requests from the cookie instead of the session + user lookups, which are otherwise two statements on every authenticated request (on Postgres over Hyperdrive, most of the fixed per-request cost). The trade is revocation latency: a ban, sign-out-everywhere or role change can take up to `maxAge` to reach a cached session. Bump `cookieCache.version` to invalidate every cached session at once, lower `maxAgeSeconds`, or set `session: { cookieCache: { enabled: false } }` when every request must see the row. The compiler does not configure Better Auth `secondaryStorage`, so a KV namespace does not cache sessions.
17
+
18
+ ```typescript
19
+ providers: {
20
+ auth: defineAuth("better-auth", {
21
+ session: {
22
+ cookieCache: { enabled: true, maxAgeSeconds: 60 }, // or { enabled: false }
23
+ },
24
+ }),
25
+ }
26
+ ```
17
27
 
18
28
  The generated auth middleware resolves the session once per request and hydrates a single Hono context variable, `ctx` — it does **not** set `session` or `user` variables:
19
29
 
@@ -84,6 +94,26 @@ const orgId = c.get('ctx').activeOrgId;
84
94
  > `activeOrganizationId` is Better Auth's *session* field name (`session.session.activeOrganizationId`). Quickback canonicalises it to `ctx.activeOrgId`; firewall rules written against `ctx.activeOrganizationId` are rewritten to `ctx.activeOrgId` at compile time.
85
95
 
86
96
 
97
+ ## Listing organization members
98
+
99
+ Better Auth's `GET /auth/v1/organization/list-members` needs a session — a JWT bearer gets 401. To list the active organization's members on the JWT, opt into the roster read:
100
+
101
+ ```ts title="quickback.config.ts"
102
+ export default defineConfig({
103
+ // ...
104
+ auth: {
105
+ organizationRoster: { access: { roles: ['member', 'admin'] } },
106
+ },
107
+ });
108
+ ```
109
+
110
+ `GET /auth/v1/organization/roster` then returns `{ data: [{ id, name, email, image, role }] }` for `ctx.activeOrgId`:
111
+
112
+ - **401** with no credentials, **403** `ACCESS_NO_ORG` with no active organization, **403** when the caller holds none of `access.roles`.
113
+ - It reads on the service lane and filters to the active organization in the query, because Postgres RLS lets a caller-scoped handle read only their own `users` row.
114
+ - The column set is fixed. Sessions, accounts and credentials are never returned.
115
+ - `roles` is required, and the organization plugin must be enabled — otherwise the compile fails.
116
+
87
117
  ## Related
88
118
 
89
119
  - [Auth Overview](/platform/auth) — Setup and configuration
@@ -310,6 +310,44 @@ environment for Drizzle schema generation and migrations. Better Auth and
310
310
  feature queries both use Hyperdrive at runtime, eliminating a second direct
311
311
  Neon connection lane.
312
312
 
313
+ Create the config against the **direct** Neon host (uncheck "Connection
314
+ pooling" in the Neon dashboard — Hyperdrive is the pool):
315
+
316
+ ```bash
317
+ npx wrangler hyperdrive create my-app-db \
318
+ --caching-disabled \
319
+ --origin-connection-limit 60 \
320
+ --connection-string="postgresql://quickback:<password>@<endpoint>.<region>.aws.neon.tech/neondb?sslmode=require"
321
+ ```
322
+
323
+ `--caching-disabled` is mandatory: Hyperdrive keys its cache on query text
324
+ alone and never invalidates on write, so a cached `SELECT` would be replayed
325
+ to another tenant. `--origin-connection-limit` is the soft cap on connections
326
+ Hyperdrive opens to Neon (minimum 5; about 100 on a paid Workers plan). Each
327
+ in-flight request holds one origin connection per leased client, so size it
328
+ to your concurrency, not your statement count. Raise it later with
329
+ `npx wrangler hyperdrive update <id> --origin-connection-limit <n>`.
330
+
331
+ ### Tuning the Worker for Hyperdrive
332
+
333
+ - **Set placement.** Every authenticated request makes several sequential
334
+ round trips (session, membership, the query), so Worker-to-database
335
+ distance dominates latency: a single `SELECT` measured ~180 ms from the
336
+ caller's colo and ~90 ms with `placement.region` set to the database
337
+ region. Set `providers.runtime.config.placement: { region: "aws:us-east-2" }`
338
+ (your Neon region; see [runtime options](/configure/providers#runtime-options)),
339
+ or per target with `environments.<name>.worker.placement`. The compiler
340
+ warns when a Hyperdrive project has neither.
341
+ - **Keep the session cookie cache on.** It is on by default
342
+ (`session.cookieCache`, 300 s) and removes the session + user lookups —
343
+ two of the three fixed statements on every authenticated request. See
344
+ [Session handling](/platform/auth/using-auth#session-handling) before
345
+ turning it off.
346
+ - **Check Neon autosuspend.** Hyperdrive keeps origin connections warm, but it
347
+ does not keep an idle Neon compute awake: the first request after a
348
+ suspend pays the compute start. Lengthen or disable autosuspend on the
349
+ production branch.
350
+
313
351
  For local `wrangler dev` without named environments, set
314
352
  `providers.database.config.hyperdrive.localConnectionString` to a local or
315
353
  development-only Postgres URL. With named environments, put it on the target
@@ -1274,8 +1312,9 @@ read under different claims (a service-lane lookup between caller reads, a
1274
1312
  scope minted mid-request) re-stamps the preamble inside the open transaction —
1275
1313
  `set_config(…, true)` is transaction-local, so the previous claims are gone the
1276
1314
  moment the new ones land. The read lane is rolled back before a write or a
1277
- `db.transaction()` takes the connection, after any read error, and when the
1278
- invocation scope closes the pool. That `ROLLBACK` is its own round trip, never
1315
+ `db.transaction()` takes the connection, after any read error, as soon as the
1316
+ handler returns (before deferred `waitUntil` work runs — a deferred read opens
1317
+ a fresh lane), and when the invocation scope closes the pool. That `ROLLBACK` is its own round trip, never
1279
1318
  pipelined with the write's `BEGIN`: Hyperdrive's transaction pooler releases
1280
1319
  the origin connection at the transaction end and loses anything pipelined past
1281
1320
  it, which hung every write that followed a read in 0.70.10–0.70.12. A
@@ -1286,8 +1325,9 @@ else is a write.
1286
1325
 
1287
1326
  Each read sees everything committed before it, including the request's own
1288
1327
  writes — Postgres runs `READ COMMITTED` by default, and a read-only transaction
1289
- changes nothing about that. The open lane pins its Hyperdrive origin connection
1290
- for the invocation; `idle_in_transaction_session_timeout` (15 s on the deployed
1328
+ changes nothing about that. Hyperdrive pools in transaction mode, so an open
1329
+ lane pins one origin connection until the handler returns (up to five under
1330
+ `Promise.all`); `idle_in_transaction_session_timeout` (15 s on the deployed
1291
1331
  role) and the scope close bound the worst case. A ten-statement read path costs
1292
1332
  about eleven round trips instead of thirteen to thirty-four, which is where the
1293
1333
  `tx` versus `stmts` ratio in [`Server-Timing`](#measuring-database-cost-server-timing)
@@ -136,9 +136,16 @@ another place for session state to be reused.
136
136
  ```bash
137
137
  npx wrangler hyperdrive create my-app-db \
138
138
  --caching-disabled \
139
+ --origin-connection-limit 60 \
139
140
  --connection-string="postgres://quickback.<branch_id>:<password>@<host>:5432/<database>?sslmode=verify-full"
140
141
  ```
141
142
 
143
+ `--origin-connection-limit` is the soft cap on connections Hyperdrive opens to
144
+ the branch (minimum 5; about 100 on a paid Workers plan). Each in-flight
145
+ request holds one origin connection per leased client until its handler
146
+ returns, so size it to your concurrency and raise it later with
147
+ `npx wrangler hyperdrive update <id> --origin-connection-limit <n>`.
148
+
142
149
  > `--caching-disabled` is mandatory. Quickback scopes RLS per request by writing
143
150
  > the caller's claims into transaction-local settings; a cached result set would
144
151
  > be replayed to a different caller, across tenants. Caching happens at the app
@@ -194,7 +201,10 @@ Set `providers.runtime.config.placement: { region: "aws:us-east-2" }` (your
194
201
  branch's region) so the Worker runs next to the database — every statement is
195
202
  several round-trips, so Worker-to-database distance dominates latency. A target
196
203
  whose branch lives elsewhere overrides it with
197
- `environments.<name>.worker.placement`.
204
+ `environments.<name>.worker.placement`. The compiler warns when a Hyperdrive
205
+ project sets neither. The rest of the tuning notes — the session cookie cache
206
+ and connection limits — are on
207
+ [Neon → Tuning the Worker for Hyperdrive](/platform/database/neon#tuning-the-worker-for-hyperdrive).
198
208
 
199
209
  ## What is shared with Neon, and what is not
200
210
 
@@ -0,0 +1,62 @@
1
+ # Table Change Signals
2
+
3
+ `changes` gives every organization-scoped table two signals without per-table hooks:
4
+
5
+ - **`broadcast`** — a realtime `data.changed` frame, payload `{ table }`, sent to the organization's members after a write commits.
6
+ - **`counter`** — a per-organization version in `qb_change_counter`, bumped by database triggers on every write. Read it with `changeCounter()`.
7
+
8
+ ```ts title="quickback.config.ts"
9
+ export default defineConfig({
10
+ // ...
11
+ changes: {
12
+ broadcast: { access: { roles: ['member+'] } },
13
+ counter: true,
14
+ },
15
+ });
16
+ ```
17
+
18
+ Both cover tables with an `organizationId` column. Tables without one get neither.
19
+
20
+ ## `broadcast` — refetch by table
21
+
22
+ The write chokepoint (the audit-wrapped `db`) sends one frame per (organization, table) per request:
23
+
24
+ ```json
25
+ { "type": "broadcast", "event": "data.changed", "payload": { "table": "invoices" } }
26
+ ```
27
+
28
+ - **Once per table per request.** Ten writes to `invoices` in one request send one frame.
29
+ - **After commit.** Inside `db.transaction()` the frames wait for the commit and are dropped on rollback. Outside a transaction each statement has already committed when its frame is sent.
30
+ - **Audience.** `access.roles` (expanded through `auth.roleHierarchy`) becomes the frame's `targetRoles`, in the caller's active organization. A cron or queue write has no active organization, so the frame goes to the `organizationId` of the written rows — which requires `.returning()`; without it there are no rows to read and no frame.
31
+ - **Coverage.** Every write through the wrapped `db`: CRUD routes, actions, cron, queue, and email handlers. Raw SQL and writes through an unwrapped handle send nothing — use the counter to catch those.
32
+ - **Best-effort.** A failed send never fails the write.
33
+
34
+ `table` is the SQL table name — the same name trigger handlers receive.
35
+
36
+ Requires realtime (`realtime: true` on the database provider) and audit fields (on by default). Otherwise the compile fails.
37
+
38
+ ## `counter` — a safe bundle version probe
39
+
40
+ Compiler-owned `AFTER INSERT / UPDATE / DELETE` triggers on each organization-scoped table bump that organization's row in `qb_change_counter`. Because they are database triggers, queue, cron and raw-SQL writes count too. A soft delete counts once.
41
+
42
+ Use it as a bundle's [`version` probe](/define/bundles). A probe built on `max(modifiedAt)` misses hard deletes and every table the bundle reads indirectly. The counter misses neither:
43
+
44
+ {/* doc-compile: skip — fragment of a defineBundle call */}
45
+ ```typescript
46
+ import { changeCounter } from "../../../lib/change-counter";
47
+
48
+ version: custom(({ db, ctx }) => changeCounter(db, ctx.activeOrgId)),
49
+ ```
50
+
51
+ The trade-off: any write in the organization changes the version, so unrelated writes cost a full read. That is never a stale `notModified`. Clients can also compare the counter after a reconnect to decide whether to refetch.
52
+
53
+ - **Postgres:** the trigger functions are `SECURITY DEFINER`, owned by `quickback_owner`. The Worker role reads only its active organization's row, or any row on the service lane, and cannot write the table.
54
+ - **D1:** plain SQLite triggers in the features database.
55
+ - **Contention:** one row per organization serializes concurrent writes within that organization until each commits.
56
+ - **Providers:** `cloudflare-d1` and the Postgres providers. Elsewhere the compile fails.
57
+
58
+ ## Related
59
+
60
+ - [Named invalidations](/platform/realtime/named-invalidations) — typed, action-fired signals
61
+ - [Bundles](/define/bundles) — `version` probes and ETags
62
+ - [Triggers](/define/triggers) — the same journaled SQL-trigger lane