@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.
- package/dist/commands/build.d.ts.map +1 -1
- package/dist/commands/build.js +4 -1
- package/dist/commands/build.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/lib/api-client.d.ts +2 -0
- package/dist/lib/api-client.d.ts.map +1 -1
- package/dist/lib/api-client.js.map +1 -1
- package/dist/lib/file-loader.d.ts.map +1 -1
- package/dist/lib/file-loader.js +1 -0
- package/dist/lib/file-loader.js.map +1 -1
- package/dist/skill/docs/api/actions.md +1 -1
- package/dist/skill/docs/api/crud.md +8 -0
- package/dist/skill/docs/api/errors.md +9 -6
- package/dist/skill/docs/api/openapi.md +1 -0
- package/dist/skill/docs/api/typescript.md +3 -1
- package/dist/skill/docs/configure/providers.md +15 -0
- package/dist/skill/docs/define/access.md +12 -1
- package/dist/skill/docs/define/actions/scoped-db.md +80 -4
- package/dist/skill/docs/define/areas.md +3 -1
- package/dist/skill/docs/define/arrows.md +70 -9
- package/dist/skill/docs/define/fga.md +4 -2
- package/dist/skill/docs/define/firewall.md +6 -3
- package/dist/skill/docs/define/permissions.md +1 -1
- package/dist/skill/docs/define/schema.md +1 -1
- package/dist/skill/docs/define/scopes.md +1 -1
- package/dist/skill/docs/define/triggers.md +13 -1
- package/dist/skill/docs/platform/auth/plugins/subscriptions.md +23 -1
- package/dist/skill/docs/platform/auth/security.md +23 -1
- package/dist/skill/docs/platform/database/neon.md +3 -1
- package/dist/skill/docs/platform/push/index.md +1 -1
- package/dist/skill/docs/ui/account/features/admin.md +29 -0
- package/dist/skill/docs/ui/account/features/sessions.md +2 -0
- package/dist/skill/docs/ui/account/hooks.md +49 -1
- package/package.json +1 -1
- package/src/skill/docs/api/actions.md +1 -1
- package/src/skill/docs/api/crud.md +8 -0
- package/src/skill/docs/api/errors.md +9 -6
- package/src/skill/docs/api/openapi.md +1 -0
- package/src/skill/docs/api/typescript.md +3 -1
- package/src/skill/docs/configure/providers.md +15 -0
- package/src/skill/docs/define/access.md +12 -1
- package/src/skill/docs/define/actions/scoped-db.md +80 -4
- package/src/skill/docs/define/areas.md +3 -1
- package/src/skill/docs/define/arrows.md +70 -9
- package/src/skill/docs/define/fga.md +4 -2
- package/src/skill/docs/define/firewall.md +6 -3
- package/src/skill/docs/define/permissions.md +1 -1
- package/src/skill/docs/define/schema.md +1 -1
- package/src/skill/docs/define/scopes.md +1 -1
- package/src/skill/docs/define/triggers.md +13 -1
- package/src/skill/docs/platform/auth/plugins/subscriptions.md +23 -1
- package/src/skill/docs/platform/auth/security.md +23 -1
- package/src/skill/docs/platform/database/neon.md +3 -1
- package/src/skill/docs/platform/push/index.md +1 -1
- package/src/skill/docs/ui/account/features/admin.md +29 -0
- package/src/skill/docs/ui/account/features/sessions.md +2 -0
- package/src/skill/docs/ui/account/hooks.md +49 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Auth Hooks
|
|
2
2
|
|
|
3
|
-
Quickback discovers project-level auth hooks at `quickback/hooks/`. Most `before-`/`after-` lifecycle hooks wire directly into [Better Auth's `databaseHooks`](https://www.better-auth.com/docs/concepts/database#database-hooks); `before-email-otp-activate.ts` is a narrower compiler-owned atomic ceremony, and the `resolve-*` hooks are trusted server resolvers called from generated middleware (OAuth) or the email send. Use them for post-signup bootstrap, signup gating, tenant resolution, and per-recipient email context.
|
|
3
|
+
Quickback discovers project-level auth hooks at `quickback/hooks/`. Most `before-`/`after-` lifecycle hooks wire directly into [Better Auth's `databaseHooks`](https://www.better-auth.com/docs/concepts/database#database-hooks); `before-email-otp-activate.ts` is a narrower compiler-owned atomic ceremony, and the `resolve-*` hooks are trusted server resolvers called from generated middleware (OAuth) or the email send. `before-invitation-create.ts` is the organization plugin's own `beforeCreateInvitation` hook. Use them for post-signup bootstrap, signup gating, tenant resolution, and per-recipient email context.
|
|
4
4
|
|
|
5
5
|
The classic case is multi-tenant: when `account.auth.organizations: true` is set, a freshly signed-up user has no `activeOrganizationId`, so every authenticated `/api/v1/*` returns `403 ORG_REQUIRED`. An `after-user-create` hook can auto-provision a personal workspace + member row so the next request just works.
|
|
6
6
|
|
|
@@ -14,6 +14,7 @@ quickback/
|
|
|
14
14
|
before-email-otp-activate.ts
|
|
15
15
|
after-session-create.ts
|
|
16
16
|
after-admin-user-create.ts
|
|
17
|
+
before-invitation-create.ts
|
|
17
18
|
resolve-oauth-context.ts
|
|
18
19
|
resolve-email-context.ts
|
|
19
20
|
```
|
|
@@ -29,6 +30,7 @@ Each file has a single default export — an `async (entity, ctx) => ...` functi
|
|
|
29
30
|
| `before-email-otp-activate.ts` | Atomic email-OTP activation before `user.update` | `{ userId, email, user }` | `void \| false` |
|
|
30
31
|
| `after-session-create.ts` | `databaseHooks.session.create.after` | `Session` | `void` |
|
|
31
32
|
| `after-admin-user-create.ts` | `databaseHooks.user.create.after` (filtered) | `User` | `void` |
|
|
33
|
+
| `before-invitation-create.ts` | `organizationHooks.beforeCreateInvitation` | `{ invitation, inviter, organization }` | `void \| { data?: Partial<Invitation> }` |
|
|
32
34
|
| `resolve-oauth-context.ts` | OAuth bearer middleware | OAuth identity + session | Partial `AppContext` tenant fields |
|
|
33
35
|
| `resolve-email-context.ts` | emailOTP `sendVerificationOTP` | `{ email, type, name }` | Extra fields merged into the email template context |
|
|
34
36
|
|
|
@@ -201,6 +203,51 @@ Notes:
|
|
|
201
203
|
- This is **not** a Better Auth `databaseHook` — it's consumed only by the
|
|
202
204
|
emailOTP send, so it adds no signup/session latency.
|
|
203
205
|
|
|
206
|
+
## Gate or reroute an organization invitation
|
|
207
|
+
|
|
208
|
+
`POST /auth/v1/organization/invite-member` sends mail to whatever address the
|
|
209
|
+
caller types, from generated code — a sandbox or demo plan that contains every
|
|
210
|
+
other send through a policy cannot reach it. Add
|
|
211
|
+
`quickback/hooks/before-invitation-create.ts` and the compiler wires it as the
|
|
212
|
+
organization plugin's `organizationHooks.beforeCreateInvitation`. Throw to
|
|
213
|
+
abort; return `{ data: { email } }` to redirect the recipient. Better Auth
|
|
214
|
+
merges `data` onto the invitation row, so any invitation field (`role`,
|
|
215
|
+
`expiresAt`, …) can be overridden the same way.
|
|
216
|
+
|
|
217
|
+
```ts title="quickback/hooks/before-invitation-create.ts"
|
|
218
|
+
import { APIError } from "better-auth/api";
|
|
219
|
+
import { eq } from "drizzle-orm";
|
|
220
|
+
|
|
221
|
+
export default async ({ invitation, inviter, organization }, { authDb, authSchema }) => {
|
|
222
|
+
const [plan] = await authDb
|
|
223
|
+
.select({ policy: authSchema.organization.metadata })
|
|
224
|
+
.from(authSchema.organization)
|
|
225
|
+
.where(eq(authSchema.organization.id, organization.id))
|
|
226
|
+
.limit(1);
|
|
227
|
+
|
|
228
|
+
if (plan?.policy === "sandbox") {
|
|
229
|
+
throw new APIError("FORBIDDEN", { message: "Sandbox organizations cannot invite members." });
|
|
230
|
+
}
|
|
231
|
+
if (plan?.policy === "redirect") {
|
|
232
|
+
// Deliver every invite to the org owner instead of the typed address.
|
|
233
|
+
return { data: { email: inviter.email } };
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
Notes:
|
|
239
|
+
|
|
240
|
+
- **Not a `databaseHook`.** It runs inside the organization plugin, before the
|
|
241
|
+
invitation row is written and before `sendInvitationEmail`. `ctx` is the
|
|
242
|
+
standard [hook ctx](#ctx-shape) minus `baContext`.
|
|
243
|
+
- **The seat cap runs first.** With the
|
|
244
|
+
[subscriptions plugin](/platform/auth/plugins/subscriptions), a full plan
|
|
245
|
+
refuses the invite before your hook is called.
|
|
246
|
+
- **`invitationLimit` is a config option, not a hook.** Better Auth's cap on
|
|
247
|
+
pending invitations per organization passes straight through
|
|
248
|
+
`plugins.organization` — see [Better Auth plugins](/configure/providers#better-auth-plugins).
|
|
249
|
+
- Requires the organization plugin; the file is a compile error without it.
|
|
250
|
+
|
|
204
251
|
## ctx shape
|
|
205
252
|
|
|
206
253
|
Every hook receives `(entity, ctx)`:
|
|
@@ -259,6 +306,7 @@ What happens when a hook throws is the #1 thing that bites people:
|
|
|
259
306
|
| `before-email-otp-activate` | The entire atomic ceremony rolls back: OTP consumption, hook writes, verification update, and session insert. |
|
|
260
307
|
| `after-user-create` | The user **is** created (the BA insert already committed). Any derived rows your hook started writing become orphans. |
|
|
261
308
|
| `after-session-create`| Same as above — the session row exists; partial writes leak. |
|
|
309
|
+
| `before-invitation-create` | The invitation is **not** created and no email is sent. Throw Better Auth's `APIError` for a clean 4xx. |
|
|
262
310
|
|
|
263
311
|
For `after-*` hooks, design for **idempotency**: use the entity's `id` as a stable seed for any derived rows so re-running the hook (manually or via a background reconciler) is safe. Don't generate fresh `cuid()`s for derived rows you'd want to recover.
|
|
264
312
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@quickback-dev/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.67.1",
|
|
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",
|
|
@@ -132,7 +132,7 @@ All actions (both standalone and record-based) receive a **scoped `db`** that ap
|
|
|
132
132
|
|
|
133
133
|
- `SELECT` / `UPDATE` / `DELETE` get the table's firewall `WHERE`, AND-merged with yours.
|
|
134
134
|
- `INSERT` stamps every claim column the firewall binds (`organizationId`, `ownerId`, …) from context.
|
|
135
|
-
- A caller
|
|
135
|
+
- A caller who carries none of the claims a table's firewall can bind cannot query it: every statement on that table fails with 403 `FIREWALL_CLAIM_MISSING` instead of silently matching nothing. The action's `db` type rejects such tables at compile time when its `access` can't guarantee the claim.
|
|
136
136
|
|
|
137
137
|
Full semantics: [Scoped Database](/define/actions/scoped-db).
|
|
138
138
|
|
|
@@ -169,6 +169,14 @@ not just what it mints today:
|
|
|
169
169
|
| other integer column | integer |
|
|
170
170
|
| Postgres `uuid` column | UUID, whatever the strategy |
|
|
171
171
|
|
|
172
|
+
Every **text** id column also accepts a hand-written id — a letter or digit
|
|
173
|
+
followed by up to 63 letters, digits, `_` or `-` (`plan_sandbox`, `demo-event`,
|
|
174
|
+
a hex id that starts with a digit). Seeds, migrations and fixtures write ids the
|
|
175
|
+
compiler never minted, and a real row must stay addressable; what the check
|
|
176
|
+
still rejects is garbage — spaces, slashes, dots, quotes, a leading `_`/`-`,
|
|
177
|
+
anything longer than 64 characters. Postgres `uuid` columns and integer columns
|
|
178
|
+
take only their own type.
|
|
179
|
+
|
|
172
180
|
Every id a client may supply on create (`allowClientIds`, below) passes this
|
|
173
181
|
check, so a created id is always addressable.
|
|
174
182
|
|
|
@@ -125,12 +125,15 @@ Firewall filtering is transparent — the query is scoped by `WHERE organization
|
|
|
125
125
|
| `FIREWALL_SOFT_DELETED` | Record has been soft deleted |
|
|
126
126
|
| `FIREWALL_WRITE_DENIED` | A create would land a row outside the caller's firewall (see [Firewall on write](/define/firewall#firewall-on-write)); also a Postgres RLS refusal (`42501`) |
|
|
127
127
|
|
|
128
|
-
Inside an action,
|
|
129
|
-
|
|
130
|
-
`activeOrgId` for an org-scoped table, say
|
|
131
|
-
|
|
132
|
-
`
|
|
133
|
-
|
|
128
|
+
Inside an action, any statement through the [scoped `db`](/define/actions/scoped-db)
|
|
129
|
+
on a table whose firewall needs a claim the caller does not carry (no
|
|
130
|
+
`activeOrgId` for an org-scoped table, say — a `PUBLIC` or `AUTHENTICATED`
|
|
131
|
+
action, or a scope principal on a table with no arm for its kind) fails with
|
|
132
|
+
**403** `FIREWALL_CLAIM_MISSING`, `layer: "action"`, and
|
|
133
|
+
`details: { table, claims }` (the claim sets the firewall accepts) — the
|
|
134
|
+
statement never runs, so a read cannot silently return `[]` and a row is never
|
|
135
|
+
written into whatever tenant the body named. An `INSERT` whose conjunctive
|
|
136
|
+
claim is missing reports `details: { table, column, claim }`.
|
|
134
137
|
|
|
135
138
|
An `INSERT` through the scoped `db` whose row would land outside the table's
|
|
136
139
|
firewall (a project the caller has no relationship to) fails with **403**
|
|
@@ -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')
|
|
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
|
|
39
|
-
|
|
40
|
-
`
|
|
41
|
-
|
|
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.
|
|
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
|
-
**
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
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
|
|
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`
|
|
339
|
-
|
|
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,
|
|
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
|
|
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`
|
|
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
|
|