@quickback-dev/cli 0.66.25 → 0.67.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.
Files changed (58) hide show
  1. package/dist/commands/build.d.ts.map +1 -1
  2. package/dist/commands/build.js +4 -1
  3. package/dist/commands/build.js.map +1 -1
  4. package/dist/index.js +1 -1
  5. package/dist/index.js.map +1 -1
  6. package/dist/lib/api-client.d.ts +2 -0
  7. package/dist/lib/api-client.d.ts.map +1 -1
  8. package/dist/lib/api-client.js.map +1 -1
  9. package/dist/lib/file-loader.d.ts.map +1 -1
  10. package/dist/lib/file-loader.js +1 -0
  11. package/dist/lib/file-loader.js.map +1 -1
  12. package/dist/skill/docs/api/actions.md +1 -1
  13. package/dist/skill/docs/api/crud.md +8 -0
  14. package/dist/skill/docs/api/errors.md +9 -6
  15. package/dist/skill/docs/api/openapi.md +1 -0
  16. package/dist/skill/docs/api/typescript.md +3 -1
  17. package/dist/skill/docs/configure/providers.md +15 -0
  18. package/dist/skill/docs/define/access.md +12 -1
  19. package/dist/skill/docs/define/actions/scoped-db.md +80 -4
  20. package/dist/skill/docs/define/areas.md +3 -1
  21. package/dist/skill/docs/define/arrows.md +70 -9
  22. package/dist/skill/docs/define/fga.md +4 -2
  23. package/dist/skill/docs/define/firewall.md +6 -3
  24. package/dist/skill/docs/define/permissions.md +1 -1
  25. package/dist/skill/docs/define/schema.md +1 -1
  26. package/dist/skill/docs/define/scopes.md +1 -1
  27. package/dist/skill/docs/define/triggers.md +13 -1
  28. package/dist/skill/docs/platform/auth/plugins/subscriptions.md +23 -1
  29. package/dist/skill/docs/platform/auth/security.md +23 -1
  30. package/dist/skill/docs/platform/database/neon.md +3 -1
  31. package/dist/skill/docs/platform/push/index.md +1 -1
  32. package/dist/skill/docs/ui/account/features/admin.md +29 -0
  33. package/dist/skill/docs/ui/account/features/sessions.md +2 -0
  34. package/dist/skill/docs/ui/account/hooks.md +49 -1
  35. package/package.json +1 -1
  36. package/src/skill/docs/api/actions.md +1 -1
  37. package/src/skill/docs/api/crud.md +8 -0
  38. package/src/skill/docs/api/errors.md +9 -6
  39. package/src/skill/docs/api/openapi.md +1 -0
  40. package/src/skill/docs/api/typescript.md +3 -1
  41. package/src/skill/docs/configure/providers.md +15 -0
  42. package/src/skill/docs/define/access.md +12 -1
  43. package/src/skill/docs/define/actions/scoped-db.md +80 -4
  44. package/src/skill/docs/define/areas.md +3 -1
  45. package/src/skill/docs/define/arrows.md +70 -9
  46. package/src/skill/docs/define/fga.md +4 -2
  47. package/src/skill/docs/define/firewall.md +6 -3
  48. package/src/skill/docs/define/permissions.md +1 -1
  49. package/src/skill/docs/define/schema.md +1 -1
  50. package/src/skill/docs/define/scopes.md +1 -1
  51. package/src/skill/docs/define/triggers.md +13 -1
  52. package/src/skill/docs/platform/auth/plugins/subscriptions.md +23 -1
  53. package/src/skill/docs/platform/auth/security.md +23 -1
  54. package/src/skill/docs/platform/database/neon.md +3 -1
  55. package/src/skill/docs/platform/push/index.md +1 -1
  56. package/src/skill/docs/ui/account/features/admin.md +29 -0
  57. package/src/skill/docs/ui/account/features/sessions.md +2 -0
  58. package/src/skill/docs/ui/account/hooks.md +49 -1
@@ -32,6 +32,7 @@ Each endpoint includes request/response schemas derived from your Drizzle column
32
32
  The generated component schemas carry enough type information that strict validators (zod, openapi-typescript, openapi-fetch) produce non-optional, narrowed types out of the box:
33
33
 
34
34
  - **`required[]` on response components** — every selected column is listed; nullable columns are present as `T | null`, not optional.
35
+ - **Nullable columns are `type: [T, "null"]`** — the OpenAPI 3.1 form, never the 3.0 `nullable: true` keyword (which 3.1 generators drop, leaving a client with no way to send the explicit `null` that PATCH accepts to clear a column). Enum columns add `null` to their `enum`. Action inputs follow the same rule: `.nullable()` widens the type; `.optional()` only makes the key omittable.
35
36
  - **Logical q types survive database lowering** — `q.bool()` remains `boolean`, `q.timestamp()` remains an ISO date-time string, and `q.url()` retains its URI format even when D1 stores the value as text or integer.
36
37
  - **Closed enums on `text(_, { enum: [...] })` columns** — emitted as `{ type: "string", enum: [...] }`, narrowing to a literal union in TS.
37
38
  - **`Error.code` is a closed enum** — every `code` value the API can emit (`AUTH_MISSING`, `DB_UNIQUE_VIOLATION`, `BATCH_SIZE_EXCEEDED`, …) is enumerated so consumers can `switch` exhaustively.
@@ -72,7 +72,9 @@ const jobId = routeParams.id as Api.jobs.Id;
72
72
 
73
73
  Columns that point at a Better Auth principal are branded too, even though
74
74
  those tables are not part of your project: tenant scopes (`q.scope('organization')`,
75
- `q.scope('owner')`, `q.scope('team')`), the audit stamps (`createdBy`,
75
+ `q.scope('owner')`, `q.scope('team')`, or a raw Drizzle column bound by the
76
+ firewall — branded by the arm it binds, so an owner firewall on `userId` makes
77
+ it a `Qb.UserId` whatever the column is called), the audit stamps (`createdBy`,
76
78
  `modifiedBy`, `deletedBy`), and any `.references('user' | 'organization' | 'team')`
77
79
  column.
78
80
 
@@ -339,6 +339,9 @@ providers: {
339
339
  |--------|------|-------------|
340
340
  | `session.expiresInDays` | `number` | Session expiration in days |
341
341
  | `session.updateAgeInDays` | `number` | Session refresh interval in days |
342
+ | `session.freshAgeInHours` | `number` | How recent a sign-in must be for change-password / delete-account. Default `0.25` (15 minutes); `0` = always fresh |
343
+ | `emailAndPassword.revokeSessionsOnPasswordReset` | `boolean` | Terminate every other session when a password is reset. Default `true` |
344
+ | `operatorMfa` | `boolean` | Require a passkey or two-factor session for `appmanager` / `sysadmin`. Requires the `passkey` or `twoFactor` plugin. See [Requiring a second factor](/ui/account/features/admin#requiring-a-second-factor) |
342
345
  | `rateLimit.enabled` | `boolean` | Enable rate limiting |
343
346
  | `rateLimit.window` | `number` | Rate limit window in seconds |
344
347
  | `rateLimit.max` | `number` | Max requests per window |
@@ -376,6 +379,18 @@ transport-neutral and is emitted identically for Cloudflare Email and AWS SES:
376
379
  plugins: { emailOtp: { expiresIn: 1200 } }
377
380
  ```
378
381
 
382
+ `organization` accepts Better Auth's own options too. `invitationLimit` caps
383
+ pending invitations per organization (Better Auth defaults to 100):
384
+
385
+ ```typescript
386
+ plugins: { organization: { invitationLimit: 10 } }
387
+ ```
388
+
389
+ `organizationHooks` is compiler-owned and rejected from config; gate or
390
+ reroute invitations with
391
+ [`hooks/before-invitation-create.ts`](/ui/account/hooks#gate-or-reroute-an-organization-invitation)
392
+ instead.
393
+
379
394
  ## Storage Providers
380
395
 
381
396
  ```typescript
@@ -412,7 +412,18 @@ type FieldCondition =
412
412
  | { lessThan: number }
413
413
  | { greaterThan: number }
414
414
  | { lessThanOrEqual: number }
415
- | { greaterThanOrEqual: number };
415
+ | { greaterThanOrEqual: number }
416
+ | { null: true } // the column is unset — e.g. update only while still a draft
417
+ | { notNull: true };
418
+ ```
419
+
420
+ Each field takes exactly one condition. Any other shape — `{ isNull: true }`,
421
+ two operators on one field — is a compile error, because at runtime it would
422
+ match nothing and deny every row. `{ null: true }` treats an absent value as
423
+ null, and on collection reads it becomes `IS NULL` in the `WHERE` clause:
424
+
425
+ ```typescript
426
+ update: { access: { roles: ["member"], record: { issuedAt: { null: true } } } },
416
427
  ```
417
428
 
418
429
  ## Evaluation Order
@@ -35,10 +35,18 @@ as `{ field: 'linkedUserId', equals: 'ctx.userId' }`.
35
35
  **Access decides whether the handler runs; the firewall still decides which
36
36
  rows it touches.** An action admitted by an uppercase marker (`PUBLIC`,
37
37
  `AUTHENTICATED`, `SCOPED`, …) skips the Access layer's active-org
38
- precondition, but not the firewall: a caller without the claim a table's
39
- firewall requires reads and writes **nothing** in that table (`1 = 0`), and an
40
- `INSERT` into it fails with **403 `FIREWALL_CLAIM_MISSING`** rather than
41
- landing in whatever tenant the request body named.
38
+ precondition, but not the firewall. A caller who carries **none** of the
39
+ claims a table's firewall can bind (no `activeOrgId` for an org-scoped table; neither
40
+ org nor `ctx.scope.event` for an `any: [org, scope]` table) cannot query it at
41
+ all: `select`, `update`, `delete`, `$count` and `insert` on that table all fail
42
+ with **403 `FIREWALL_CLAIM_MISSING`** — the statement never runs, so it can never
43
+ silently match nothing, and an `INSERT` never lands in whatever tenant the
44
+ request body named. The Problem's `details.claims` lists the claim sets the
45
+ firewall accepts; the message names the fixes: require a role that carries
46
+ the claim, add a firewall arm for this caller's claim, or declare the action
47
+ `unsafe` and use `unsafeDb` (or `unsafeDb.scopeTo({ organizationId })` with a
48
+ tenant you resolved yourself — the pattern for a `PUBLIC` door that looks a
49
+ row up by secret code first).
42
50
 
43
51
  - **Scope principals** reach rows through the table's `ctx.scope.*` arms, as on CRUD.
44
52
  - **Delegated principals** named in a table's [`databaseAccess`](#delegated-principals-and-databaseaccess) lane keep the soft-delete filter; their row bound is the lane's RLS policy.
@@ -68,6 +76,74 @@ through its firewall. Tables with no `defineTable`, subqueries and raw `sql`
68
76
  sources are not gated. Anchored actions get the same treatment for reads:
69
77
  `select().from(t)` only accepts tables in the anchor's reach.
70
78
 
79
+ What each lane is credited with follows how its callers are proven. An org
80
+ role carries the user, org and team claims. A `scope:<kind>:<role>` lane
81
+ carries `ctx.scope.<kind>` — and also the user claim when the role's
82
+ [`subject`](/define/scopes#sessionless-scope-mint--ctxmintscope) is `'user'` (the
83
+ default): such a role is only ever proven by a signed-in caller, so a `via:`
84
+ or owner arm can serve it. A role with `subject: 'supplied'` or `'both'` can be
85
+ minted sessionless, so its lane is credited the scope claim only; an org-only
86
+ table (no `ctx.scope.<kind>` arm) is then a `tsc` error for that action — and a
87
+ 403 at runtime for the sessionless caller — even though a signed-in attendee
88
+ would have reached it. Give the table a scope arm, branch the action into two
89
+ (`or` lanes are checked separately), or use `unsafeDb` for that read.
90
+
91
+ #### Proving a claim the type cannot see: `db.given`
92
+
93
+ Your code often knows more than the access lane does — a `PUBLIC` or
94
+ `scope:<kind>:<role>` action that branches on `if (ctx.userId)` is, inside that
95
+ branch, a signed-in caller. `db.given({ userId: ctx.userId })` hands back the
96
+ same firewalled handle typed with that claim added to every lane. Its argument
97
+ must be a definite string, so it only compiles where TypeScript has narrowed the
98
+ value; at runtime it checks the value equals the caller's own claim and answers
99
+ 403 `FIREWALL_CLAIM_MISSING` otherwise. It is a proof, never a grant.
100
+
101
+ ```ts
102
+ async execute({ db, ctx }) {
103
+ if (ctx.userId) {
104
+ const mine = db.given({ userId: ctx.userId }); // user claim now credited
105
+ await mine.select().from(chatReads); // chat_reads pins userId = ctx.userId
106
+ }
107
+ }
108
+ ```
109
+
110
+ `given` accepts `organizationId`, `userId` and `teamId` (matched against
111
+ `ctx.activeOrgId`, `ctx.userId`, `ctx.activeTeamId`).
112
+
113
+ #### Re-scoping a raw handle: `unsafeDb.scopeTo`
114
+
115
+ A door that resolves the tenant itself — a `PUBLIC` action that looks an invite
116
+ up by secret code and then reads that tenant's rows — declares `unsafe` and uses
117
+ `unsafeDb.scopeTo({ organizationId })`. The result is a **firewalled** scoped db
118
+ for that tenant, typed with exactly the claims you passed, so everything after
119
+ the lookup is gated and typed again:
120
+
121
+ {/* doc-compile: skip — cross-fence dependency: `inviteTokens` and `guests` live in sibling features (`invitations`, `guests`) the fence does not carry, and the gate compiles each fence as an isolated project; `description` / `input` are elided so the two lines that matter — the raw lookup and `scopeTo` — stay in view. */}
122
+ ```ts
123
+ export default defineAction({
124
+ path: '/invite/enter-event',
125
+ access: { roles: ['PUBLIC'] },
126
+ unsafe: true,
127
+ async execute({ unsafeDb, input }) {
128
+ const [token] = await unsafeDb.select().from(inviteTokens).where(eq(inviteTokens.code, input.code));
129
+ if (!token) throw new ActionError('Invalid invite', 'INVITATION_INVALID_OR_EXPIRED', 404);
130
+ const db = unsafeDb.scopeTo({ organizationId: token.organizationId });
131
+ const [guest] = await db.select().from(guests).where(eq(guests.id, token.guestId)); // org firewall applies
132
+ // …
133
+ },
134
+ });
135
+ ```
136
+
137
+ `scopeTo` takes the same three keys as `given`; every value must be a definite
138
+ string.
139
+
140
+ One more source of claims is the route itself. An action under an
141
+ [`authz.namespaces`](/define/areas#narrow-ctxexposeas-typing) prefix runs after
142
+ the namespace gate has stamped `ctx.activeOrgId` from the proven row or the
143
+ loaded instance, so every lane carries the org claim at runtime. Import that
144
+ namespace's `define-action.<namespace>` helper and the gate credits it; the
145
+ generic `define-action` helper cannot see the namespace and stays strict.
146
+
71
147
  Not gated at the type level: joins (`leftJoin(t)` and friends) and `$count` —
72
148
  both still go through the runtime firewall rules above (`$count` is scoped;
73
149
  a joined table is not re-filtered, so join only through foreign keys you own).
@@ -520,7 +520,9 @@ Inside a namespace action's `execute()`:
520
520
 
521
521
  The namespace middleware hydrates `ctx.<exposeAs>` at runtime. The static type of that field is `any` via the `AppContext` index signature: useful for not blocking access, but a missed opportunity for autocomplete and typo-catching.
522
522
 
523
- The compiler emits one **per-namespace `defineAction` helper** alongside the standard `<feature>/.quickback/define-action.ts`. Importing from the narrowed helper retypes `ctx.<exposeAs>` inside `execute({ ctx })` to the loaded row's `$inferSelect` shape. Nothing else changes — runtime behavior, action discovery, and the `path:` namespace match are identical.
523
+ The compiler emits one **per-namespace `defineAction` helper** alongside the standard `<feature>/.quickback/define-action.ts`. Importing from the narrowed helper retypes `ctx.<exposeAs>` inside `execute({ ctx })` to the loaded row's `$inferSelect` shape. Runtime behavior, action discovery, and the `path:` namespace match are identical.
524
+
525
+ The narrowed helper also knows what the namespace gate did before `execute` ran. When every lane stamps `ctx.activeOrgId` — role lanes carry the caller's own org, each relationship lane's `from` table has an organization column (the proven row's org is stamped), and any `acceptScope` lane hydrates a `loads` table with an organization column (the instance's org is stamped) — the helper credits every access lane the org claim in the [scoped `db` type gate](/define/actions/scoped-db#caught-at-compile-time). A `roles: ['member+', 'scope:event:attendee']` action under `/event/:eventId` can then read an org-scoped table without a `tsc` error, exactly as it does at runtime. The generic helper cannot know the action is namespaced, so it keeps the strict reading: the scope lane carries only `ctx.scope.event`.
524
526
 
525
527
  ```ts title="features/feeds/actions/feedMoments.ts"
526
528
  // One-line flip per namespace-scoped action:
@@ -69,14 +69,26 @@ the permission required **at the target object**, and it participates in the
69
69
  permission composition graph (resolution + cycle detection) exactly like a
70
70
  `{ permissionRef }`.
71
71
 
72
- **M2 target restriction.** The target permission must reduce to
73
- **org-membership roles** (`admin` / `owner` / `member`) — directly or
74
- through a `permissionRef` / `anyOf` / `allOf` of org roles. That's what lets
75
- the hop bind to the caller's verified active-org claim (`ctx.activeOrgId`).
76
- A target permission that references a relation, a scoped role, a pseudo-role,
77
- a `not`, or a nested arrow is a **compile error** in M2 (never a silent
78
- allow) — those richer targets are a documented fast-follow. So
79
- `org:admin = anyOf(role('admin'), role('owner'))` is the canonical target.
72
+ **Target restriction.** An arrow's target permission may reduce to either:
73
+
74
+ - **Org-membership roles** (`admin` / `owner` / `member`) — directly or through
75
+ a `permissionRef` / `anyOf` / `allOf` of org roles. The hop binds to the
76
+ caller's verified active-org claim (`ctx.activeOrgId`). So
77
+ `org:admin = anyOf(role('admin'), role('owner'))` is the canonical org target.
78
+ - **A single relationship** (relation-backed target, non-recursive hops only) —
79
+ the FK hop inherits a relationship the caller holds on the hopped-to parent
80
+ object. "Organizers of the parent event can see its sessions" is a
81
+ `{ arrowRef: 'sessionEvent', permission: 'event:organizer' }` arm where
82
+ `event:organizer` reduces to the `organizerOf` relationship. The arrow's `fk`
83
+ and the relationship's `resource.column` must address the **same parent-id
84
+ space** (the column the FK points at) — for a multi-hop relationship, its
85
+ first hop's `on` column, exactly as a `via:` arm reads it. See
86
+ [Emit shape 3](#emit-shape-3--relation-backed-target) for the composition.
87
+
88
+ A target that references a **scoped role**, a **pseudo-role**, a `not`, or a
89
+ **nested arrow** — or that **mixes** a relation with org roles, or pairs a
90
+ relation-backed target with a **recursive** hop — is a **compile error** (never
91
+ a silent allow). Those remain a documented fast-follow.
80
92
 
81
93
  ## Using the permission in a firewall
82
94
 
@@ -155,6 +167,54 @@ arrow is valid on either provider. Drizzle interpolates the column/table
155
167
  surface (the FK column and tables are compile-time identifiers; the only
156
168
  runtime value is the signed org claim).
157
169
 
170
+ ## Emit shape 3 — relation-backed target
171
+
172
+ When the target permission reduces to a single relationship, the FK hop
173
+ composes with that relationship's subquery on the parent object. For
174
+ `sessionEvent: { from: 'session', fk: 'eventId', to: 'event' }` with target
175
+ `organizerOf` (keyed by `eventId`), an `{ arrowRef: 'sessionEvent' }` arm on a
176
+ resource constrained by `sessionId` lowers to:
177
+
178
+ ```sql
179
+ agenda_item.sessionId IN (
180
+ SELECT session.id FROM session
181
+ WHERE session.eventId IN (
182
+ -- the organizerOf relationship subquery: the events the caller organizes
183
+ SELECT event_staff.eventId FROM event_staff
184
+ WHERE event_staff.userId = ? -- ? = ctx.userId
185
+ AND event_staff.role = 'organizer'
186
+ AND <event_staff's own firewall — soft-delete>
187
+ )
188
+ )
189
+ ```
190
+
191
+ The inner subquery is the **same** [`via:` relationship
192
+ subquery](/compiler/definitions/firewall#relationship-based-scoping-via) — it
193
+ AND's the relationship table's own firewall (soft-delete) and binds `ctx.userId`
194
+ **fail-closed** (a null caller short-circuits to `1 = 0`). So a relation-backed
195
+ arrow inherits every `via:` guarantee; the FK hop just maps the resource's
196
+ column to the parent id space the relationship returns. The outer resource
197
+ firewall stays the outermost AND, so tenant isolation is never bypassed.
198
+
199
+ Relation-backed targets are **non-recursive only** — a recursive self-hop with
200
+ a relation target is a compile error (the bounded closure seed needs the
201
+ org-membership form; relation seeding is a fast-follow).
202
+
203
+ On **Postgres** the RLS policy enforces the same composition. The arrow lowers
204
+ to a `SECURITY DEFINER` helper that returns the `session` rows whose `eventId`
205
+ is in the caller's `public.qb_rel_organizer_of()` set — the same relationship
206
+ helper a `via:` arm calls — and the generated API reads through that same
207
+ helper, so the database and the API run one lookup:
208
+
209
+ ```sql
210
+ agenda_item.session_id IN (SELECT r.id FROM public.qb_arrow_session_event_id_<hash>() r)
211
+ -- qb_arrow_…: SELECT f.* FROM session f
212
+ -- WHERE f.event_id IN (SELECT r.event_id FROM public.qb_rel_organizer_of() r)
213
+ ```
214
+
215
+ A relationship whose `subject` binds a claim the Worker never writes into the
216
+ transaction stays API-enforced there, exactly as its `via:` arm does.
217
+
158
218
  ## Tenant isolation semantics
159
219
 
160
220
  Arrows are tenant-safe by construction. Three guarantees, all enforced at
@@ -260,7 +320,8 @@ authz.permissionMaxDepth?: Record<string, number>
260
320
  - Every `{ arrowRef }` in a permission must name a declared `authz.arrows[*]`
261
321
  entry, and the arrow's `fk` / `to` are checked against the real schema at
262
322
  compile time.
263
- - The target `permission` must reduce to org-membership roles in M2.
323
+ - The target `permission` must reduce to org-membership roles **or** a single
324
+ relationship (relation-backed targets are non-recursive only).
264
325
  - See [Permissions](/define/permissions) for the expression DSL
265
326
  the arrow leaf lives in, and [Firewall — named permissions](/define/firewall#named-permissions-permission)
266
327
  for how the resulting `{ permission }` arm sits inside a firewall. The
@@ -335,5 +335,7 @@ access, even if it was written out-of-band — the model is the ceiling.
335
335
  conditional tuple with a 400, and `POST /fga/v1/read` still returns one, so a
336
336
  row planted out-of-band stays visible to an audit. Nothing Quickback generates
337
337
  writes those columns — only raw SQL, a seed, or an OpenFGA import can.
338
- - `ListObjects` enumerates candidate objects from tuples and Checks each — a
339
- reverse-index optimization is a planned follow-up.
338
+ - `ListObjects` reverse-walks the caller's footprint (their direct, wildcard and
339
+ group grants and the relevant tuplesets) rather than every object of the type,
340
+ then Checks each candidate — so its cost tracks the caller's grants, not the
341
+ tenant's object count.
@@ -118,12 +118,12 @@ type FirewallConfig = ReadonlyArray<FirewallPredicate>;
118
118
  firewallErrorMode?: 'reveal' | 'hide';
119
119
  ```
120
120
 
121
- An `equals` value that doesn't start with `ctx.` is a **literal**: `{ field: 'visibility', equals: 'studio' }` emits `eq(table.visibility, "studio")`. Like any status filter it is enforced by the API only — in Postgres RLS a literal arm lowers to `true`, so `any: [studio, { all: [private, owner] }]` keeps its OR shape instead of hardening into an owner-only policy.
121
+ An `equals` value that doesn't start with `ctx.` is a **literal**: `{ field: 'visibility', equals: 'studio' }` emits `eq(table.visibility, "studio")`. The literal is always written as a string and read as the **column's** type: `{ field: 'includesAllGuests', equals: '1' }` on an `integer` column emits `eq(table.includesAllGuests, 1)`, and `'true'` / `'false'` (or `'1'` / `'0'`) on a boolean column emit a boolean. A literal the column cannot hold — `'yes'` on an integer — is a compile error naming the column. Like any status filter it is enforced by the API only — in Postgres RLS a literal arm lowers to `true`, so `any: [studio, { all: [private, owner] }]` keeps its OR shape instead of hardening into an owner-only policy.
122
122
 
123
123
  On Postgres the RLS scope policy mirrors the firewall's `all`/`any` tree arm for arm, and the **database enforces relationship arms too**:
124
124
 
125
125
  - A `via:` arm lowers to `project_id IN (SELECT r.project_id FROM public.qb_rel_<relationship>() r)` — a `SECURITY DEFINER` helper that runs the same relationship lookup as the API (subject = the caller's claim, the `where:` literals, the related table's soft delete). The generated API calls the same helper for every relationship lookup on Postgres, so a caller with no active org gets the same rows from the API as the policy admits. `[org, { any: [owner, { via }] }]` becomes `org AND (owner OR project_id IN (…))`, never `org AND owner`. See [Relationship arms in SQL](/platform/database/neon#relationship-arms-in-sql).
126
- - A `{ permission }` arm expands exactly as the API expands it: relation leaves become `via:` helpers, arrows become `qb_arrow_…` helpers (a recursive arrow is a `maxDepth`-bounded closure).
126
+ - A `{ permission }` arm expands exactly as the API expands it: relation leaves become `via:` helpers, arrows become `qb_arrow_…` helpers (a recursive arrow is a `maxDepth`-bounded closure; a relation-backed arrow returns the hop's rows whose FK is in the target relationship's `qb_rel_…` set).
127
127
  - Inside an `any` group that also has an org arm, the relationship, scope and principal arms are tenant-bound exactly where the API binds them — `(<arm> AND (organization_id = <active org> OR <no active org>))` — so an org-claiming caller never rides them into another org.
128
128
  - The soft-delete filter the API adds to a table carrying `deletedAt` reaches the policy too, as `deleted_at IS NULL OR public.in_soft_delete()` in `USING` only — see [the soft-delete lane](/platform/database/neon#the-soft-delete-lane).
129
129
  - Literals, literal `in` lists, and claims the Worker never writes into the transaction (`ctx.scope.<kind>.<subKey>`, area anchors like `ctx.event.id`, string `in` sets) stay API-only and lower to `true` — the policy has nothing to compare them against, and a literal conjunct would refuse status-changing updates.
@@ -290,7 +290,10 @@ leaf that traverses a foreign key to inherit authority from a parent object
290
290
  ("org admins of the event's org can see its announcements", "anyone who
291
291
  administers an ancestor folder can read this one"). An arrow leaf lowers to
292
292
  an FK-hop subquery (non-recursive) or a bounded `WITH RECURSIVE` CTE
293
- (self-FK hierarchy), tenant-constrained at every row.
293
+ (self-FK hierarchy), tenant-constrained at every row. An arrow's target
294
+ permission may reduce to org-membership roles **or** a single relationship —
295
+ "organizers of the parent event can see its sessions" composes the FK hop with
296
+ the relationship's subquery (non-recursive hops only).
294
297
 
295
298
  **M1 limit — firewall arms must be SQL-pushable.** A firewall runs as a
296
299
  WHERE clause, so a permission referenced from one may only resolve to
@@ -57,7 +57,7 @@ object forms are the unambiguous escape hatch.
57
57
  | `{ role: 'admin' }` | an org-membership role (`ctx.roles`) |
58
58
  | `{ scopeRole: { kind: 'event', role: 'organizer' } }` | a [scoped role](/define/scopes) |
59
59
  | `{ pseudoRole: 'AUTHENTICATED' }` | `PUBLIC` / `AUTHENTICATED` / `INTERNAL` / … |
60
- | `{ arrowRef: 'eventOrg', permission: 'org:admin' }` | an [FK-traversal arrow](/define/arrows) — resolve the row's FK to its target object and require a permission there |
60
+ | `{ arrowRef: 'eventOrg', permission: 'org:admin' }` | an [FK-traversal arrow](/define/arrows) — resolve the row's FK to its target object and require a permission there. The target `permission` may reduce to org-membership roles **or** a single relationship (e.g. "organizers of the parent event"). |
61
61
 
62
62
  String sugar for the prefixed forms is also accepted inside an expression:
63
63
  `'permission:event:view'`, `'scope:event:organizer'`, `'role:admin'`. A bare
@@ -105,7 +105,7 @@ A few mechanics to know:
105
105
  > `authz.relationships` `subject: { column: 'userId', equals: 'ctx.userId' }` does not need, and must not create, a SQL FK. See [Relationships](/define/relationships). To query Better Auth tables, use `c.get("authDb")` from an action — see [Scoped DB](/define/actions/scoped-db#reaching-better-auth-tables-authdb).
106
106
 
107
107
 
108
- - **Indexes and constraints:** column-level `.index()` / `.unique()` / `.check(expr)`, or table-level `indexes` / `unique` / `check` as a third arg to `q.table(name, cols, { indexes, unique, check })`. With `feature()`, pass `indexes`, `unique` and `check` as top-level keys alongside `columns` — the sugar forwards them into the same `q.table` opts. See [Constraints](#constraints--check-and-unique).
108
+ - **Indexes and constraints:** column-level `.index()` / `.unique()` / `.check(expr)`, or table-level `indexes` / `unique` / `check` as a third arg to `q.table(name, cols, { indexes, unique, check })`. With `feature()`, pass `indexes`, `unique` and `check` as top-level keys alongside `columns` — the sugar forwards them into the same `q.table` opts. In the two-export form they go on `q.table`; on `defineTable(...)` they are a compile error, because they describe the table, not the resource. See [Constraints](#constraints--check-and-unique).
109
109
 
110
110
  ### Column Types
111
111
 
@@ -349,7 +349,7 @@ so it can only ever carry the role the caller actually proved this request.
349
349
  - A **bulk-grant lane** (`{ roles: [...] }` or `{ team: true }`) mints **no** scope role — it opens the gate via the caller's org role without proving a relationship. The gate passes; the caller carries their org role, not a minted scope role.
350
350
  - **The org claim is only ever signed beside a membership role.** Every mint site — `/scope/v1/enter`, the namespace resolver, `/api/v1/token` — writes `orgId` into the token only when a membership `role` accompanies it, and the auth middleware ignores an `orgId` claim that arrives without a `role`. A relationship-promoted tenant (the in-request `ctx.activeOrgId` stamped from the proven row so the firewall resolves) is never persisted as a bare tenant grant.
351
351
  - **`/scope/v1/enter` drops the org claims for a foreign-tenant instance.** When the relationship's `from` table carries an organization column, the enter route reads it off the proven row (the same row the probe already fetched — no extra query) and compares it with `ctx.activeOrgId`. A mismatch — an org-B member entering an org-A event — mints the token **without** `orgId` / `role`: a relationship-only principal, exactly the state the namespace resolver gives the same caller. The caller keeps their org seat for org-B requests by using their session or a plain `/api/v1/token`; the scope token is for the scope. A `from` table with no organization column (a global reference relationship) leaves the claim untouched.
352
- - **Every mint tenant-binds the instance.** A relationship row is matched without tenant scoping (a cross-tenant attendee has no `activeOrgId`), so the row alone can't prove which tenant's instance it names. When the relationship's `from` table carries an organization column, every site that mints from a relationship row — `/scope/v1/enter`, [`ctx.mintScope`](#sessionless-scope-mint--ctxmintscope), and this namespace resolver (the in-memory stamp **and** the `mintScope` token) — also loads the **instance** row, through its own firewall with tenant scopes stripped so soft-delete still applies, and grants the role only when the instance's organization equals the proving row's. A row created in org B naming org A's event proves nothing about org A and grants nothing; a deleted instance grants nothing. (The namespace gate itself still passes on the proven row; the caller just carries no scope for the foreign instance.) The instance table is the target of the relationship's `resource.column` foreign key, or — when that column isn't a declared FK — the one table whose firewall pins its primary key to `ctx.scope.<kind>` (`{ field: 'id', equals: 'ctx.scope.event' }`). If neither resolves, the compiler warns: declare the FK so the instance can be bound. A `from` table with no organization column has no tenant to compare, so it gets no binding.
352
+ - **Every mint tenant-binds the instance.** A relationship row is matched without tenant scoping (a cross-tenant attendee has no `activeOrgId`), so the row alone can't prove which tenant's instance it names. When the relationship's `from` table carries an organization column, every site that mints from a relationship row — `/scope/v1/enter`, [`ctx.mintScope`](#sessionless-scope-mint--ctxmintscope), and this namespace resolver (the in-memory stamp **and** the `mintScope` token) — also loads the **instance** row, through its own firewall with tenant scopes stripped so soft-delete still applies, and grants the role only when the instance's organization equals the proving row's. A row created in org B naming org A's event proves nothing about org A and grants nothing; a deleted instance grants nothing. (The namespace gate itself still passes on the proven row; the caller just carries no scope for the foreign instance.) The instance table is `authz.scopes.<kind>.instance` when declared (`instance: 'events'`), else the target of the relationship's `resource.column` foreign key, else the one table whose firewall pins its primary key to `ctx.scope.<kind>` (`{ field: 'id', equals: 'ctx.scope.event' }`). Several such tables is a compile error naming them — set `instance`. If nothing resolves, the compiler warns: set `instance` (or declare the FK) so the instance can be bound. A `from` table with no organization column has no tenant to compare, so it gets no binding.
353
353
 
354
354
  ### The bulk-grant lane is tenant-bound
355
355
 
@@ -239,7 +239,11 @@ an [action](/define/actions/scoped-db#reaching-better-auth-tables-authdb).
239
239
  into the write payload, or throw to reject — the write never executes and
240
240
  the request gets a structured `TRIGGER_REJECTED` (422) error. Audit
241
241
  fields (`createdBy`, `modifiedAt`, …) are re-stamped after hooks run and
242
- cannot be forged.
242
+ cannot be forged. A `before*` hook gets `values`, the pending write, and
243
+ never the stored row: nothing is read before the write. Destructuring `row`
244
+ or `old` in one is a compile error. To derive a column from the stored row
245
+ on update, use a Postgres `sql:` trigger, where `NEW."col"` is the whole row
246
+ with the update applied.
243
247
  - **`after*` hooks run once per affected row and are awaited** before the
244
248
  write's promise resolves. They may be `async`. A throw surfaces as
245
249
  `TRIGGER_AFTER_FAILED` (500) with `details.committed: true` — the row was
@@ -298,6 +302,14 @@ write path, use the `sql:` lane and reject with `RAISE(ABORT, ...)` (D1) or
298
302
  > `scheduled()` handler + `wrangler.toml` triggers. This note is only about
299
303
  > the table-trigger `handler:` lane not firing inside them.
300
304
 
305
+ ## Columns a `beforeInsert` trigger fills
306
+
307
+ An action's `db.insert(table).values(...)` doesn't have to supply a column a
308
+ `beforeInsert` trigger assigns. The compiler makes that column optional in the
309
+ insert type when a `sql:` body assigns it (`NEW."project_id" := …`) or a
310
+ `handler:` returns it as a key (`{ number: … }`). The column's
311
+ `.required()` stays in the schema, so it is still `NOT NULL` in the table.
312
+
301
313
  ## Choosing a lane
302
314
 
303
315
  | Need | Use |
@@ -306,7 +306,29 @@ export default defineTable(projects, {
306
306
  });
307
307
  ```
308
308
 
309
- To enforce a limit, read `limits` from `GET /subscriptions/me` (or query the subscriptions table directly in an action) and compare it against a count before creating the row. Enforcement is yours to write until tier-aware access rules land; the plugin's job is to make the caller's current tier and its limits available.
309
+ To enforce a limit, read `limits` from `GET /subscriptions/me` (or query the subscriptions table directly in an action) and compare it against a count before creating the row. Enforcement is yours to write; the plugin's job is to make the caller's current tier and its limits available.
310
+
311
+ ### `seats` is the one key the compiler enforces
312
+
313
+ `seats` is reserved: it is memberships per organization, and the compiler enforces it on Better Auth's own seating routes. When the organization plugin is on, the generated auth wires three `organizationHooks` that read the organization's effective subscription and refuse with `403 SEAT_LIMIT_REACHED` when the cap would be exceeded:
314
+
315
+ | Route | Counted against the cap |
316
+ |-------|-------------------------|
317
+ | Create invitation | Current members **plus** pending, unexpired invitations |
318
+ | Accept invitation | Current members |
319
+ | Add member (server-side) | Current members |
320
+
321
+ ```ts
322
+ tiers: {
323
+ solo: { name: 'Solo', limits: { seats: 1 } },
324
+ team: { name: 'Team', priceId: 'price_team', limits: { seats: 10 } },
325
+ enterprise: { name: 'Enterprise', priceId: 'price_ent', limits: { seats: -1 } },
326
+ }
327
+ ```
328
+
329
+ No `seats` key, or a negative value, means unlimited. A subscription that has stopped granting (see [which statuses grant](#which-statuses-grant) and the [expiry bound](#expiry-is-the-second-bound)) counts as the base tier, so a lapsed team plan falls back to the base tier's `seats`. Existing members are never removed by a downgrade; the cap only stops new seating.
330
+
331
+ Two paths are outside Better Auth's routes and therefore outside this check: memberships you insert yourself from `quickback/hooks/after-user-create.ts` (domain auto-join, personal orgs) and direct database writes. The generated `src/plugins/subscriptions/index.ts` exports `seatsAvailable(env, organizationId)` for the first case. The count-then-insert is not transactional, so two acceptances racing for the last seat can both land.
310
332
 
311
333
  ## Local development
312
334
 
@@ -54,6 +54,28 @@ auth: defineAuth("better-auth", {
54
54
 
55
55
  ---
56
56
 
57
+ ## Session Freshness and Password Reset
58
+
59
+ Two Better Auth session controls are emitted with stricter values than the library's own defaults:
60
+
61
+ | Setting | Quickback default | Better Auth default | Override |
62
+ |---------|-------------------|---------------------|----------|
63
+ | `session.freshAge` | 15 minutes | 24 hours | `session.freshAgeInHours` |
64
+ | `emailAndPassword.revokeSessionsOnPasswordReset` | `true` | `false` | `emailAndPassword.revokeSessionsOnPasswordReset: false` |
65
+
66
+ **Freshness** gates the sensitive account operations (`change-password`, `delete-user`, `change-email` confirmation): a session older than `freshAge` has to sign in again first. Better Auth's 24-hour window lets a day-old session on a shared machine delete the account; 15 minutes is the "full, valid login session" an assessor expects.
67
+
68
+ **Reset revocation** terminates every other session the moment a password is reset through the forgot-password flow. That is the point at which someone holding the old password should lose the sessions they opened with it. Password *change* from the Account UI already sends `revokeOtherSessions: true`; direct API callers pass that flag themselves.
69
+
70
+ ```ts
71
+ auth: defineAuth("better-auth", {
72
+ session: { freshAgeInHours: 1 }, // loosen to an hour
73
+ emailAndPassword: { enabled: true, revokeSessionsOnPasswordReset: false }, // keep other sessions
74
+ })
75
+ ```
76
+
77
+ ---
78
+
57
79
  ## Rate Limiting
58
80
 
59
81
  Quickback includes per-IP rate limiting by default to protect against brute-force attacks and abuse.
@@ -172,7 +194,7 @@ Quickback supports three bearer-token flavors alongside the standard browser ses
172
194
  | Session cookie | Browser SPAs (CMS, Account, your app) | Better Auth session lookup |
173
195
  | Session-token bearer | API clients that grabbed `set-auth-token` | Better Auth `bearer` plugin |
174
196
  | JWT bearer | API clients that mint at `GET /auth/v1/token` | In-worker JWT fast-path (no DB hit) |
175
- | API-key bearer | Long-lived programmatic access | `apiKey` plugin / `x-api-key` / `?api_key=` |
197
+ | API-key bearer | Long-lived programmatic access | `apiKey` plugin / `x-api-key` header (never a query parameter) |
176
198
 
177
199
  These match Better Auth's own framing of bearer tokens as **an alternative to cookies, not a supplement** — a request uses one or the other.
178
200
 
@@ -908,7 +908,9 @@ from the relationship table under its own policy.
908
908
  — exactly where the API applies the same binding.
909
909
  - **Permissions.** A `{ permission }` arm expands as the API expands it; arrow
910
910
  hops become `qb_arrow_…` helpers (recursive arrows are a `maxDepth`-bounded
911
- closure that re-checks the tenant on every row), called by the API too.
911
+ closure that re-checks the tenant on every row; a relation-backed arrow keeps
912
+ the hop's rows whose FK is in the relationship's `qb_rel_…` set), called by
913
+ the API too.
912
914
  - **Still API-only.** Literal status filters (a conjunct would refuse
913
915
  status-changing updates, because PostgreSQL checks an UPDATE's new row against
914
916
  the read policy) and claims the Worker never writes into the transaction —
@@ -55,7 +55,7 @@ With `push.defaultSchema: true`, the compiler injects a hardened, owner-scoped `
55
55
 
56
56
  - **INTERNAL-only reads** — the crypto fields (`endpoint`, `p256dh`, `auth`) never leave the worker via any HTTP path. A `views.mine` projection exposes only `id`, `userAgent`, `lastSeenAt`, `createdAt` for "Your devices" UIs.
57
57
  - **Owner firewall** — `owner_id` is auto-stamped on create; user A can never read or delete user B's subscription.
58
- - **Create-time validation** — the endpoint must be `https:` (the worker POSTs VAPID-signed requests at that URL, so an arbitrary endpoint is an SSRF primitive), `p256dh` must decode to a 65-byte uncompressed P-256 point, and `auth` to a 16-byte secret. The `https:` check is not the whole SSRF story: at send time the push sender additionally rejects any endpoint whose host resolves to a private, link-local, loopback, `localhost`, or `.internal` address. Together — **https + a non-public-host block** — this narrows the SSRF surface; treat it as defense-in-depth, not a guarantee that SSRF is impossible.
58
+ - **Create-time validation** — the endpoint must be `https:` (the worker POSTs VAPID-signed requests at that URL, so an arbitrary endpoint is an SSRF primitive), `p256dh` must decode to a 65-byte uncompressed P-256 point, and `auth` to a 16-byte secret. The `https:` check is not the whole SSRF story: at send time the push sender runs the endpoint through the same destination policy as [outbound webhooks](/platform/webhooks/outbound) (`src/lib/webhooks/url-policy.ts`): every IANA special-purpose IPv4/IPv6 range (loopback, link-local and the cloud metadata address, RFC 1918, CGNAT, IPv4-mapped, ULA, NAT64, 6to4, Teredo), plus `localhost`, `.local`, `.internal`, `.home.arpa` and single-label names. Unlike webhooks it does **not** resolve DNS, so a public hostname that resolves to a private address is not caught. Together — **https + the destination policy** — this narrows the SSRF surface; treat it as defense-in-depth, not a guarantee that SSRF is impossible.
59
59
  - **Proven identity tags** — a `tags` column is stamped **server-side** from `ctx`: `user:<id>`, and — only when the request carries a scoped token — `scope:<kind>:<subject>` plus one `scope:<kind>:<instance>#<role>` per scope role the verified claim grants (the same dialect realtime tickets use). Client-supplied tags are ignored: they drive fan-out targeting. **Org roles are never stamped** — a device is user-owned, and org audiences are resolved from live membership at send time; see [Targeting](#targeting).
60
60
  - **Rate limit + cap** — creates are limited to 10/minute per caller, and only the newest 10 live subscriptions per user are kept (older rows are soft-deleted, so a user's new device always works).
61
61
 
@@ -67,6 +67,35 @@ So organization creation asks for an `ownerUserId`, seats that user, and never s
67
67
 
68
68
  An operator who genuinely wants their own organization creates one naming themselves as owner — explicit, and visible in the audit trail rather than implied by whoever happened to make the call.
69
69
 
70
+ ## Requiring a second factor
71
+
72
+ Operator accounts are the highest-value targets in a deployment, and CASA / ASVS require multi-factor authentication on every administrative interface. `operatorMfa` enforces it:
73
+
74
+ ```ts title="quickback.config.ts"
75
+ providers: {
76
+ auth: defineAuth("better-auth", {
77
+ operatorMfa: true,
78
+ plugins: ["passkey", "admin"],
79
+ }),
80
+ },
81
+ ```
82
+
83
+ With it on, an `appmanager` or `sysadmin` whose session was **not** established by a passkey assertion or a two-factor verification is treated as a plain `user` for that request. Every operator surface refuses with `403 MFA_REQUIRED`: the CMS and `/api/v1/schema`, the `/auth/v1/admin/*` operator routes, Better Auth's own admin endpoints (`list-users`, `set-role`, `ban-user`), and the sysadmin cross-tenant bypass. The Account UI keeps working, so the enrolment path is short:
84
+
85
+ 1. Sign in with a password (or magic link / OTP) as usual.
86
+ 2. Register a passkey at `/account/passkeys/setup`.
87
+ 3. Sign out, then sign back in **with the passkey**.
88
+
89
+ How it works: the compiler adds a `session.amr` column (RFC 8176, *Authentication Methods Reference*) and a `session.create.before` hook that stamps `passkey` when the session comes from `/passkey/verify-authentication` and `mfa` when it comes from `/two-factor/verify-*`. Nothing else sets it, and it is not client-settable. The auth middleware reads it on the session lane and copies it into the JWT fast-path claims, so bearer callers are gated identically.
90
+
91
+ Things to know:
92
+
93
+ - **Requires `passkey` or `twoFactor`.** The compile fails otherwise: without a second factor to enrol, every operator would be locked out.
94
+ - **Passkey sign-in only.** A user who has a passkey but signs in with a password is not MFA'd; the session has to be created by the passkey assertion.
95
+ - **Two-factor "trust this device"** skips the verify endpoint, so a trusted-device sign-in does not count. Operators should not use it.
96
+ - **API keys never satisfy it.** An operator's API key is a single factor; operator routes reject it with `MFA_REQUIRED`.
97
+ - **Existing projects** get a new `amr` column on the auth `session` table on the next compile; apply the generated auth migration before deploying.
98
+
70
99
  ## Custom Admin Domain
71
100
 
72
101
  Give the admin panel its own subdomain with `adminDomain`:
@@ -14,6 +14,8 @@ Users can see all devices where they're currently logged in, including:
14
14
 
15
15
  Users can revoke any session except their current one. This immediately invalidates the session token.
16
16
 
17
+ Two events revoke other sessions without a click: changing the password from the profile page (the UI sends `revokeOtherSessions: true`), and resetting it through the forgot-password flow (the server default `revokeSessionsOnPasswordReset: true`, see [Session Freshness and Password Reset](/platform/auth/security#session-freshness-and-password-reset)).
18
+
17
19
  ## Related
18
20
 
19
21
  - [Environment Variables](/ui/account/environment-variables)