@quickback-dev/cli 0.67.0 → 0.67.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +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/batch-operations.md +5 -0
- package/dist/skill/docs/api/crud.md +8 -0
- package/dist/skill/docs/api/errors.md +7 -4
- package/dist/skill/docs/api/openapi.md +1 -0
- package/dist/skill/docs/configure/auth.md +26 -0
- package/dist/skill/docs/configure/index.md +28 -9
- package/dist/skill/docs/configure/providers.md +12 -0
- package/dist/skill/docs/define/access.md +15 -2
- package/dist/skill/docs/define/actions/scoped-db.md +1 -0
- package/dist/skill/docs/define/authz-roles.md +1 -1
- package/dist/skill/docs/define/encryption.md +39 -7
- package/dist/skill/docs/define/firewall.md +6 -0
- package/dist/skill/docs/define/schema.md +31 -2
- package/dist/skill/docs/platform/auth/api-keys.md +77 -1
- package/dist/skill/docs/platform/auth/plugins/agent-auth.md +1 -1
- package/dist/skill/docs/platform/auth/plugins/index.md +33 -34
- package/dist/skill/docs/platform/auth/security.md +53 -6
- package/dist/skill/docs/platform/auth/using-auth.md +1 -1
- package/dist/skill/docs/platform/realtime/partyserver-rooms.md +2 -0
- package/dist/skill/docs/platform/storage/r2.md +2 -0
- package/dist/skill/docs/platform/storage/using-kv.md +6 -36
- package/dist/skill/docs/platform/webhooks/inbound.md +2 -1
- package/dist/skill/docs/tooling/cloud-compiler/endpoints.md +4 -0
- package/dist/skill/docs/tooling/cloud-compiler/troubleshooting.md +12 -8
- package/dist/skill/docs/ui/account/features/api-keys.md +2 -1
- package/dist/skill/docs/ui/account/features/index.md +7 -6
- package/dist/skill/docs/ui/account/features/passwordless.md +1 -1
- package/dist/skill/docs/ui/account/hooks.md +50 -2
- package/dist/skill/docs/ui/account/index.md +2 -2
- package/dist/skill/docs/ui/admin/actions.md +2 -1
- package/package.json +1 -1
- package/src/skill/docs/api/batch-operations.md +5 -0
- package/src/skill/docs/api/crud.md +8 -0
- package/src/skill/docs/api/errors.md +7 -4
- package/src/skill/docs/api/openapi.md +1 -0
- package/src/skill/docs/configure/auth.md +26 -0
- package/src/skill/docs/configure/index.md +28 -9
- package/src/skill/docs/configure/providers.md +12 -0
- package/src/skill/docs/define/access.md +15 -2
- package/src/skill/docs/define/actions/scoped-db.md +1 -0
- package/src/skill/docs/define/authz-roles.md +1 -1
- package/src/skill/docs/define/encryption.md +39 -7
- package/src/skill/docs/define/firewall.md +6 -0
- package/src/skill/docs/define/schema.md +31 -2
- package/src/skill/docs/platform/auth/api-keys.md +77 -1
- package/src/skill/docs/platform/auth/plugins/agent-auth.md +1 -1
- package/src/skill/docs/platform/auth/plugins/index.md +33 -34
- package/src/skill/docs/platform/auth/security.md +53 -6
- package/src/skill/docs/platform/auth/using-auth.md +1 -1
- package/src/skill/docs/platform/realtime/partyserver-rooms.md +2 -0
- package/src/skill/docs/platform/storage/r2.md +2 -0
- package/src/skill/docs/platform/storage/using-kv.md +6 -36
- package/src/skill/docs/platform/webhooks/inbound.md +2 -1
- package/src/skill/docs/tooling/cloud-compiler/endpoints.md +4 -0
- package/src/skill/docs/tooling/cloud-compiler/troubleshooting.md +12 -8
- package/src/skill/docs/ui/account/features/api-keys.md +2 -1
- package/src/skill/docs/ui/account/features/index.md +7 -6
- package/src/skill/docs/ui/account/features/passwordless.md +1 -1
- package/src/skill/docs/ui/account/hooks.md +50 -2
- package/src/skill/docs/ui/account/index.md +2 -2
- package/src/skill/docs/ui/admin/actions.md +2 -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
|
|
|
@@ -332,7 +380,7 @@ export default async (newSession, { authDb, authSchema }) => {
|
|
|
332
380
|
|
|
333
381
|
### Normalize and gate signup
|
|
334
382
|
|
|
335
|
-
`before-*` hooks can return `{ data: Partial<User> }` to mutate the row before insert. Throw to abort.
|
|
383
|
+
`before-*` hooks can return `{ data: Partial<User> }` to mutate the row before insert. Throw to abort. For invite-only or allowed-domain signup, use the built-in [signup policy](/platform/auth/security#signup-policy) instead — it runs before this hook on every sign-in method.
|
|
336
384
|
|
|
337
385
|
```ts title="quickback/hooks/before-user-create.ts"
|
|
338
386
|
export default async (user: { email: string; name?: string }) => {
|
|
@@ -26,7 +26,7 @@ User management dashboard — view all users, search, create accounts, ban/unban
|
|
|
26
26
|
|
|
27
27
|
## How to Enable
|
|
28
28
|
|
|
29
|
-
Add `account` to your `quickback.config.ts` and compile. The compiler
|
|
29
|
+
Add `account` to your `quickback.config.ts` and compile. The compiler copies the generic prebuilt Account bundle into your Worker; your project's settings reach it at serve time through the worker-injected `window.__QUICKBACK_RUNTIME` config.
|
|
30
30
|
|
|
31
31
|
```typescript title="quickback/quickback.config.ts"
|
|
32
32
|
export default {
|
|
@@ -97,7 +97,7 @@ When a flag is `false`, the corresponding routes **guard themselves at runtime**
|
|
|
97
97
|
|
|
98
98
|
## Features
|
|
99
99
|
|
|
100
|
-
- **Authentication** — Email/password, passkeys (WebAuthn), email OTP,
|
|
100
|
+
- **Authentication** — Email/password, passkeys (WebAuthn), email OTP, email verification, password reset, and the confirm page that magic-link emails open (`/magic-link`)
|
|
101
101
|
- **Account Management** — Profile editing, avatar upload, password changes, device/session management, account deletion
|
|
102
102
|
- **Connected Accounts** — Link Google and Cloudflare logins from `/connected-accounts` (linked from profile)
|
|
103
103
|
- **Organizations** — Multi-tenant org management with owner/admin/member roles, invitations, and org settings
|
|
@@ -65,7 +65,8 @@ The dialog generates the appropriate input control for each field:
|
|
|
65
65
|
| `number` | Number input | Step 0.01, supports decimals |
|
|
66
66
|
| `boolean` | Checkbox | With label text |
|
|
67
67
|
| `enum` | Text input | The allowed values are in `inputFields[].enum` |
|
|
68
|
-
| `array
|
|
68
|
+
| `array<object>` | JSON textarea | Validated as an array of objects before submission |
|
|
69
|
+
| Other `array<…>` | Text input | Comma-separated values, split on save |
|
|
69
70
|
|
|
70
71
|
The types come from the action's input JSON Schema — see
|
|
71
72
|
[ActionInputField](/ui/admin/schema-format#actioninputfield).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@quickback-dev/cli",
|
|
3
|
-
"version": "0.67.
|
|
3
|
+
"version": "0.67.2",
|
|
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",
|
|
@@ -220,6 +220,11 @@ PUT /api/v1/{resource}/batch
|
|
|
220
220
|
|
|
221
221
|
Inserts new records or updates existing ones. Every record must include an `id` field.
|
|
222
222
|
|
|
223
|
+
When create and update access policies are configured, batch upsert requires
|
|
224
|
+
create access for the route. Existing records also receive the update access
|
|
225
|
+
check, including any record-level rule. A caller who can create but cannot
|
|
226
|
+
update may insert new IDs; existing IDs fail their update check.
|
|
227
|
+
|
|
223
228
|
**Note:** Batch upsert requires both `generateId: false` (user-provided IDs) in your database configuration and `guards: false` on the table. Explicitly enabling `crud.batchUpsert` without both settings is a compile error. Use `crud.batchUpdate` for guarded updates.
|
|
224
229
|
|
|
225
230
|
### Request
|
|
@@ -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
|
|
|
@@ -94,9 +94,9 @@ Missing or invalid authentication tokens.
|
|
|
94
94
|
| Code | Description |
|
|
95
95
|
|------|-------------|
|
|
96
96
|
| `AUTH_MISSING` | No Authorization header provided |
|
|
97
|
-
| `AUTH_INVALID_TOKEN` | Token is malformed or invalid — including a Quickback-minted JWT that no longer verifies (rotated key, tampered, revoked). Presented-and-bad is always `401`, never treated as no credential |
|
|
97
|
+
| `AUTH_INVALID_TOKEN` | Token is malformed or invalid — including a Quickback-minted JWT that no longer verifies (rotated key, tampered, revoked). Presented-and-bad is always `401`, never treated as no credential. An API key whose owner is banned answers with `details.reason: "owner_banned"`; one whose stored scopes are malformed, `"malformed_scopes"` |
|
|
98
98
|
| `AUTH_EXPIRED` | Token has expired |
|
|
99
|
-
| `AUTH_RATE_LIMITED` | Too many auth attempts |
|
|
99
|
+
| `AUTH_RATE_LIMITED` | Too many auth attempts, or an API key over its [per-key limit](/platform/auth/api-keys#rate-limit) (`429`) |
|
|
100
100
|
| `AUTH_REVOCATION_UNAVAILABLE` | **503, retryable.** Only with [`revocationCheck: 'kv'`](/configure/auth#revocationcheck-none--kv--token-revocation-strategy): the bearer's signature verified, but its revocation state could not be read (KV binding missing or unreachable), so it was not trusted. Retry, or authenticate with a session cookie |
|
|
101
101
|
|
|
102
102
|
### Firewall (403)
|
|
@@ -189,6 +189,7 @@ Access violations return **403 Forbidden** when the user's role doesn't match th
|
|
|
189
189
|
| `ACCESS_CONDITION_FAILED` | Record-level access condition not met |
|
|
190
190
|
| `ACCESS_OWNERSHIP_REQUIRED` | User must own the record |
|
|
191
191
|
| `ACCESS_NO_ORG` | No active organization set |
|
|
192
|
+
| `ACCESS_KEY_SCOPE_REQUIRED` | A [scoped API key](/platform/auth/api-keys#scopes) does not cover this route and method. `details.required` lists the scope that would admit it (empty outside the API base, which scoped keys never reach); `details.current` is the key's scopes |
|
|
192
193
|
|
|
193
194
|
### Guards (400)
|
|
194
195
|
|
|
@@ -320,6 +321,7 @@ form can show the conflict inline. `details.column` is the first of them.
|
|
|
320
321
|
|------|--------|-------------|
|
|
321
322
|
| `DB_NOT_NULL_VIOLATION` | 400 | Required column was null at write time |
|
|
322
323
|
| `DB_UNIQUE_VIOLATION` | 409 | Unique constraint hit |
|
|
324
|
+
| `DB_RELATIONSHIP_MISMATCH` | 400 | A referenced row does not match the required parent column |
|
|
323
325
|
| `DB_INSERT_FAILED` | 500 | INSERT failed for an unrecognized reason |
|
|
324
326
|
| `DB_UPDATE_FAILED` | 500 | UPDATE failed for an unrecognized reason |
|
|
325
327
|
| `ENCRYPTION_UNREADABLE` | 422 | A stored [`.encrypted()`](/define/encryption) value will not decrypt |
|
|
@@ -327,8 +329,9 @@ form can show the conflict inline. `details.column` is the first of them.
|
|
|
327
329
|
The `details.column` field is only present when the driver's error message identified the offending column (SQLite/D1 do; some PG variants don't).
|
|
328
330
|
|
|
329
331
|
`ENCRYPTION_UNREADABLE` always carries `details: { table, column, id }` — the
|
|
330
|
-
row whose stored ciphertext is malformed
|
|
331
|
-
organization key
|
|
332
|
+
row whose stored ciphertext is malformed, was not written under the caller's
|
|
333
|
+
organization key, was copied from another column or table, or names a key
|
|
334
|
+
version the organization does not have. Rewriting the field repairs the row.
|
|
332
335
|
|
|
333
336
|
## Batch Errors
|
|
334
337
|
|
|
@@ -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.
|
|
@@ -6,6 +6,7 @@ The top-level `auth` config block holds provider-agnostic auth knobs that affect
|
|
|
6
6
|
export default defineConfig({
|
|
7
7
|
// ...
|
|
8
8
|
auth: {
|
|
9
|
+
roles: ['bookkeeper'],
|
|
9
10
|
roleHierarchy: ['member', 'admin', 'owner'],
|
|
10
11
|
jwt: {
|
|
11
12
|
expiresIn: 60,
|
|
@@ -16,6 +17,31 @@ export default defineConfig({
|
|
|
16
17
|
});
|
|
17
18
|
```
|
|
18
19
|
|
|
20
|
+
## `auth.roles`
|
|
21
|
+
|
|
22
|
+
Declares exact role names that your authentication provider supplies and your
|
|
23
|
+
project intentionally uses. This is the acknowledgement mechanism for dynamic
|
|
24
|
+
provider roles: declared names do not produce `AUTHZ_UNKNOWN_ROLE_NAME` typo
|
|
25
|
+
warnings, while nearby misspellings still do.
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
auth: {
|
|
29
|
+
roles: ['bookkeeper'],
|
|
30
|
+
roleHierarchy: ['member', 'admin', 'owner'],
|
|
31
|
+
}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
`auth.roles` does not create privilege inheritance. Put a role in
|
|
35
|
+
`auth.roleHierarchy` only when it belongs in that lowest-to-highest ordering
|
|
36
|
+
and should participate in `role+` expansion.
|
|
37
|
+
|
|
38
|
+
With Quickback's generated Better Auth organization plugin, declared roles are
|
|
39
|
+
also registered as custom organization roles with member-equivalent Better Auth
|
|
40
|
+
permissions, so invitations and member-role updates can assign them. Other auth
|
|
41
|
+
providers must include the declared names in their authenticated role claims.
|
|
42
|
+
If you provide your own Better Auth organization-plugin `roles` or `ac`, that
|
|
43
|
+
explicit provider configuration wins and Quickback skips auto-registration.
|
|
44
|
+
|
|
19
45
|
## `auth.roleHierarchy`
|
|
20
46
|
|
|
21
47
|
Lowest-to-highest privilege list. Lets access rules use `'role+'` shorthand to mean "this role and above". Documented in detail under [Access — Role hierarchy](/define/access#role-hierarchy).
|
|
@@ -96,7 +96,7 @@ Every optional top-level key the config accepts is listed below. You never have
|
|
|
96
96
|
| `domain` | `string` | Primary custom domain (auto-inferred from `cms`/`account`/`api` domains if unset) — see [Domains](/configure/domains) |
|
|
97
97
|
| `contract` | `{ routes?: "v1" \| "v2" }` | `routes` selects the URL prefix and nothing else (default `"v1"`). See [API Contract](/platform/api-contract#one-axis-routes). |
|
|
98
98
|
| `api` | `object` | Dedicated hostname for the selected feature API contract (`/api/v1/*` or `/api/v2/*`); additive alias — see [Domains](/configure/domains) |
|
|
99
|
-
| `auth` | `object` | App-level auth settings (`roleHierarchy`, `jwt`, delegated `principals`, `loginUrl`, `domain`) — see [Access](/define/access#role-hierarchy) and [Delegated principals](#delegated-principals) |
|
|
99
|
+
| `auth` | `object` | App-level auth settings (`roles`, `roleHierarchy`, `jwt`, delegated `principals`, `loginUrl`, `domain`) — see [Auth](/configure/auth), [Access](/define/access#role-hierarchy), and [Delegated principals](#delegated-principals) |
|
|
100
100
|
| `authz` | `object` | Relationship-based authorization (`relationships`, `roles`, `rules`, `tenants`, `permissions`, `arrows`) — see [Access](/define/authz-roles#centrally-defined-access-rules) and [Permissions](/define/permissions). `rules` = named gates (who + `record:` + firewall lanes under one name); `tenants` = named tenant anchors (`{ column, equals }`, referenced as `{ tenant: '<name>' }` in firewalls and `tenant: '<name>'` in auth-view includes). Root `authz` is the GLOBAL vocabulary level — names scoped to one concept belong in that concept's [feature area](/define/areas) (`_area.ts`), and root bodies may reference root-declared names only |
|
|
101
101
|
| `requires` | `string[]` | Capability floor (fail-closed guard). Declare `['feature-areas']` when the project uses `features/**/_area.ts` — an area-unaware CLI/compiler then refuses the compile instead of silently dropping nested features. See [Feature areas](/define/areas#the-capability-floor-requires-feature-areas) |
|
|
102
102
|
| `trustedOrigins` | `string[]` | CORS trusted origins for cross-domain auth |
|
|
@@ -311,10 +311,29 @@ export default defineConfig({
|
|
|
311
311
|
|
|
312
312
|
These are merged into the generated `package.json` alongside Quickback's own dependencies. Run `npm install` after compiling to install them.
|
|
313
313
|
|
|
314
|
-
The cloud compiler
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
314
|
+
The cloud compiler bundles against dependencies baked into its image; it does
|
|
315
|
+
not install project dependencies at compile time. A hosted complete compile
|
|
316
|
+
fails if a declared dependency is missing from that image, because its
|
|
317
|
+
[Worker bundle check](/tooling/cloud-compiler/troubleshooting#complete-compile-wrangler-bundle-failed)
|
|
318
|
+
cannot verify the generated Worker. Type-only `@types/*` packages never block
|
|
319
|
+
it.
|
|
320
|
+
|
|
321
|
+
These packages are preinstalled in the image, so declaring them works with
|
|
322
|
+
hosted complete compiles out of the box:
|
|
323
|
+
|
|
324
|
+
| Use | Packages |
|
|
325
|
+
|-----|----------|
|
|
326
|
+
| [PartyServer rooms](/platform/realtime/partyserver-rooms) | `partyserver`, `partysocket` |
|
|
327
|
+
| Yjs collaboration | `y-partyserver`, `yjs` |
|
|
328
|
+
| Collaborative rich text | `y-prosemirror`, `prosemirror-state`, `prosemirror-model`, `prosemirror-view` |
|
|
329
|
+
| Schema-derived validation | `drizzle-zod` |
|
|
330
|
+
| Email templates | `react`, `react-dom`, `react-email` |
|
|
331
|
+
| Utilities | `@paralleldrive/cuid2`, `nanoid`, `aws4fetch`, `postal-mime`, `qrcode` |
|
|
332
|
+
|
|
333
|
+
The bundle check resolves these at the image's versions — keep your declared
|
|
334
|
+
ranges compatible with them. For anything else, build locally with the
|
|
335
|
+
project's installed dependencies or request that the dependency be added to
|
|
336
|
+
the compiler image.
|
|
318
337
|
|
|
319
338
|
## Headless Migration Rename Hints
|
|
320
339
|
|
|
@@ -631,7 +650,7 @@ Off by default. Projects that don't enable it get zero behavior change; setting
|
|
|
631
650
|
|
|
632
651
|
## Account UI Configuration
|
|
633
652
|
|
|
634
|
-
Embed the [Account UI](/ui/account) in your compiled Worker. Provides login, signup, profile management, organization management, and admin —
|
|
653
|
+
Embed the [Account UI](/ui/account) in your compiled Worker. Provides login, signup, profile management, organization management, and admin — one prebuilt bundle, configured from your config at serve time.
|
|
635
654
|
|
|
636
655
|
For post-signup logic — auto-provisioning a workspace, gating signup, setting an active organization — drop a file in `quickback/hooks/`. See [Auth Hooks](/ui/account/hooks).
|
|
637
656
|
|
|
@@ -668,16 +687,16 @@ account: {
|
|
|
668
687
|
|
|
669
688
|
### Auth Feature Flags
|
|
670
689
|
|
|
671
|
-
Control which authentication features are exposed. Disabled features are
|
|
690
|
+
Control which authentication features are exposed. Disabled features are hidden in the Account UI (each feature route guards itself on its runtime flag) **and** enforced on the server side via the Better Auth config — so "signup off" actually refuses new accounts on the server, not just the SPA's signup screen.
|
|
672
691
|
|
|
673
|
-
`account.auth.*` is a shorthand for `providers.auth.config` — the compiler maps each flag onto the Better Auth server config before any code is generated. You can write either side directly; setting both incompatibly (e.g. `account.auth.signup: false` and `
|
|
692
|
+
`account.auth.*` is a shorthand for `providers.auth.config` — the compiler maps each flag onto the Better Auth server config before any code is generated. You can write either side directly; setting both incompatibly (e.g. `account.auth.signup: false` and `signup.inviteOnly: false`) fails the compile with a precise error rather than picking a silent winner.
|
|
674
693
|
|
|
675
694
|
| Flag | Type | Default | Maps to (server) | Description |
|
|
676
695
|
|------|------|---------|------------------|-------------|
|
|
677
696
|
| `auth.password` | `boolean` | `true` | `emailAndPassword.enabled` | Email/password authentication — both server endpoint and UI |
|
|
678
697
|
| `auth.emailOTP` | `boolean` | `false` | adds `emailOtp` plugin | Email one-time password login — adds plugin server-side, surfaces UI |
|
|
679
698
|
| `auth.passkey` | `boolean` | `false` | adds `passkey` plugin | WebAuthn/FIDO2 passkey authentication — adds plugin server-side, surfaces UI |
|
|
680
|
-
| `auth.signup` | `boolean` | `true` | `
|
|
699
|
+
| `auth.signup` | `boolean` | `true` | `signup.inviteOnly` (inverted) | Self-service account registration — false hides open signup in the UI **and** makes the server [invite-only](/platform/auth/security#signup-policy): every sign-in method refuses new accounts with 403 `SIGNUP_NOT_ALLOWED` unless the email holds a pending invitation |
|
|
681
700
|
| `auth.organizations` | `boolean` | `true` | UI surface only | Organization management UI (`/dashboard` org list, invitations, roles). Sign-in lands on `/profile`. Server-side organization support stays on regardless; set `features.pinnedOrganizationId` when you want one fixed org with no switching UI |
|
|
682
701
|
| `auth.admin` | `boolean` | `false` | UI surface only | Admin panel for user management in the Account SPA. The Better Auth admin plugin is compiler-managed separately from this UI toggle |
|
|
683
702
|
| `auth.emailVerification` | `boolean` | `false` | `emailAndPassword.requireEmailVerification` | Require email verification before sessions are issued. False = sessions usable immediately after signup |
|
|
@@ -379,6 +379,18 @@ transport-neutral and is emitted identically for Cloudflare Email and AWS SES:
|
|
|
379
379
|
plugins: { emailOtp: { expiresIn: 1200 } }
|
|
380
380
|
```
|
|
381
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
|
+
|
|
382
394
|
## Storage Providers
|
|
383
395
|
|
|
384
396
|
```typescript
|
|
@@ -100,6 +100,16 @@ any lowercase role name you reference in an access tree (`"recruiter"`,
|
|
|
100
100
|
`"hiring-manager"`, `"support"`, …) is a custom org-membership role, matched
|
|
101
101
|
against `ctx.roles` like the built-ins.
|
|
102
102
|
|
|
103
|
+
Declare intentional provider roles under `auth.roles` so the compiler can
|
|
104
|
+
distinguish them from misspellings without adding hierarchy semantics:
|
|
105
|
+
|
|
106
|
+
```typescript
|
|
107
|
+
auth: {
|
|
108
|
+
roles: ['bookkeeper'],
|
|
109
|
+
roleHierarchy: ['member', 'admin', 'owner'],
|
|
110
|
+
}
|
|
111
|
+
```
|
|
112
|
+
|
|
103
113
|
Custom roles declared in access trees are **auto-registered
|
|
104
114
|
with the Better Auth organization plugin**, so members can actually be
|
|
105
115
|
provisioned into them: `invite-member` and `update-member-role` accept them
|
|
@@ -419,8 +429,11 @@ type FieldCondition =
|
|
|
419
429
|
|
|
420
430
|
Each field takes exactly one condition. Any other shape — `{ isNull: true }`,
|
|
421
431
|
two operators on one field — is a compile error, because at runtime it would
|
|
422
|
-
match nothing and deny every row. `{
|
|
423
|
-
null
|
|
432
|
+
match nothing and deny every row. So is `{ equals: null }` (and
|
|
433
|
+
`{ notEquals: null }`): a null on either side of `equals` is a deny, so the arm
|
|
434
|
+
could never pass. Write `{ null: true }` / `{ notNull: true }` instead.
|
|
435
|
+
`{ null: true }` treats an absent value as null, and on collection reads it
|
|
436
|
+
becomes `IS NULL` in the `WHERE` clause:
|
|
424
437
|
|
|
425
438
|
```typescript
|
|
426
439
|
update: { access: { roles: ["member"], record: { issuedAt: { null: true } } } },
|
|
@@ -118,6 +118,7 @@ up by secret code and then reads that tenant's rows — declares `unsafe` and us
|
|
|
118
118
|
for that tenant, typed with exactly the claims you passed, so everything after
|
|
119
119
|
the lookup is gated and typed again:
|
|
120
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. */}
|
|
121
122
|
```ts
|
|
122
123
|
export default defineAction({
|
|
123
124
|
path: '/invite/enter-event',
|
|
@@ -155,7 +155,7 @@ Inside `authz.roles` / gate `who` bodies, `+` hierarchy sugar is banned — writ
|
|
|
155
155
|
|
|
156
156
|
### Typo safety
|
|
157
157
|
|
|
158
|
-
A `roles: [...]` name that matches nothing declared is fail-closed at runtime (it never grants) but historically silent. The compiler now emits a warning-level `AUTHZ_UNKNOWN_ROLE_NAME` diagnostic for any name that is not a provider/hierarchy role, pseudo-role, scoped role, or declared role/rule — a typo'd gate name is visible at compile time without breaking projects that use dynamic auth-provider role names. The heuristic runs only for projects that use the authz naming system (any of `authz.roles`, `authz.rules`, or `authz.scopes` declared); projects outside it keep the pre-existing silent-passthrough behavior for dynamic role names.
|
|
158
|
+
A `roles: [...]` name that matches nothing declared is fail-closed at runtime (it never grants) but historically silent. The compiler now emits a warning-level `AUTHZ_UNKNOWN_ROLE_NAME` diagnostic for any name that is not a provider/hierarchy role, pseudo-role, scoped role, or declared role/rule — a typo'd gate name is visible at compile time without breaking projects that use dynamic auth-provider role names. Declare intentional dynamic provider roles in [`auth.roles`](/configure/auth#authroles); this acknowledges the exact name without giving it `role+` hierarchy semantics. The heuristic runs only for projects that use the authz naming system (any of `authz.roles`, `authz.rules`, or `authz.scopes` declared); projects outside it keep the pre-existing silent-passthrough behavior for dynamic role names.
|
|
159
159
|
|
|
160
160
|
|
|
161
161
|
## Subscription tiers
|
|
@@ -23,16 +23,18 @@ That one modifier changes what a database breach means: a leaked D1 backup, expo
|
|
|
23
23
|
|
|
24
24
|
## What the compiler generates
|
|
25
25
|
|
|
26
|
-
- **`org_data_keys`** — one row per organization holding
|
|
26
|
+
- **`org_data_keys`** — one row per organization holding its random 256-bit data keys (DEKs), stored **wrapped** under the `ENCRYPTION_KEK` worker secret: the current version in `wrapped_dek` / `key_version`, and any versions it has rotated away from in `retired_deks`. Created lazily on the org's first encrypted write.
|
|
27
27
|
- **Write path** — every write (CRUD routes, batch routes, and `db.insert`/`db.update` inside your actions) flows through the same chokepoint, which AES-256-GCM-encrypts the column before anything else sees it. Audit snapshots, webhook payloads, and realtime deltas therefore carry ciphertext by construction.
|
|
28
28
|
- **Plaintext in, from clients** — CRUD, batch, and changeset request bodies reject a value that starts with `qbenc:` (400). Clients send plaintext; the `qbenc:` prefix is reserved for stored ciphertext. Action code can still write `ctx.crypto.encrypt()` output directly — the chokepoint passes ciphertext through untouched.
|
|
29
29
|
- **Read path** — generated routes decrypt behind the firewall and then apply masking, so authorized callers see plaintext and everyone else sees the redaction — never ciphertext. A stored value that will not decrypt fails the request with `422` [`ENCRYPTION_UNREADABLE`](/api/errors), naming the table, column, and row id — never a silent `null`.
|
|
30
|
-
- **`ctx.crypto`** — explicit `await ctx.crypto.decrypt(value)` / `ctx.crypto.encrypt(value)` for action code that processes the field server-side (building a manifest, sending an email). Scoped to the caller's active organization. `ctx.crypto` is only hydrated for authenticated requests — inside schedules, queue consumers, email handlers, and `PUBLIC` actions it is undefined. There, import the primitives directly: `import { encryptValue, decryptValue } from '../lib/encryption'` and call `decryptValue(env, db, organizationId, stored)`. Writes through the `withInternalContext` handle still encrypt automatically.
|
|
31
|
-
- **Boot guard** — a project with encrypted columns refuses to serve
|
|
30
|
+
- **`ctx.crypto`** — explicit `await ctx.crypto.decrypt(value, { table: 'guests', column: 'emergencyContact' })` / `ctx.crypto.encrypt(value, { table, column })` for action code that processes the field server-side (building a manifest, sending an email). Every call names the column the value belongs to — the SQL table name and the column's property name — because that location is bound into the ciphertext; the generated `EncryptedColumn` type only admits real `.encrypted()` columns, and the runtime refuses any other. Scoped to the caller's active organization. `ctx.crypto` is only hydrated for authenticated requests — inside schedules, queue consumers, email handlers, and `PUBLIC` actions it is undefined. There, import the primitives directly: `import { encryptValue, decryptValue } from '../lib/encryption'` and call `decryptValue(env, db, organizationId, stored, { table, column })`. Writes through the `withInternalContext` handle still encrypt automatically.
|
|
31
|
+
- **Boot guard** — a project with encrypted columns refuses to serve when `ENCRYPTION_KEK` is missing **or malformed** (503 `MISSING_ENV`; the log says which entry is wrong), instead of silently storing plaintext or failing on the first encrypted write.
|
|
32
32
|
|
|
33
|
-
Values at rest look like `qbenc:
|
|
33
|
+
Values at rest look like `qbenc:2:<keyVersion>:<iv>:<ciphertext>`. The prefix makes accidental plaintext detectable; `keyVersion` selects which of the org's DEKs opens the value, so values written before a [rotation](#key-rotation) stay readable. The ciphertext is sealed with AES-GCM **additional data binding the organization, table, and column** — a stored value copied into another column, table, or org fails to decrypt and surfaces as `ENCRYPTION_UNREADABLE`, instead of reading back as someone else's field. To move a value between columns, decrypt it and write the plaintext. The row id is deliberately **not** bound: an update's `.set()` applies one value to every row its `WHERE` matches, so the id is not known where the chokepoint encrypts — swapping a value between two rows of the same column in the same org is not detected.
|
|
34
34
|
|
|
35
|
-
|
|
35
|
+
Values written as `qbenc:1:…` (before location binding) carry no additional data and keep decrypting in place; they become `qbenc:2` the next time the field is written. Values that do not start with `qbenc:` are pre-encryption plaintext and are returned unchanged.
|
|
36
|
+
|
|
37
|
+
Each wrapped DEK records the **kid** of the key that wrapped it and is bound to its organization and version (AES-GCM additional data), so a wrapped key copied into another org's row, or into another version slot, fails to unwrap. Wraps written before kids existed (`2:<iv>:<ct>` and the older `<iv>:<ct>`) are still read — every configured key is tried, primary first — and are rewrapped to the current format the first time they load (on D1; on Neon the request connection has no `UPDATE` on `org_data_keys`, so they stay in the older format until [`rewrapOrgDataKeys`](#rotating-encryption_kek) runs).
|
|
36
38
|
|
|
37
39
|
## Setup
|
|
38
40
|
|
|
@@ -42,6 +44,36 @@ Scaffolded projects already have a generated `ENCRYPTION_KEK` in `.dev.vars`, so
|
|
|
42
44
|
openssl rand -hex 32 | wrangler secret put ENCRYPTION_KEK
|
|
43
45
|
```
|
|
44
46
|
|
|
47
|
+
`ENCRYPTION_KEK` is a **comma-separated list** of 64-hex-char keys. The **first** key wraps every new DEK; **all** of them can unwrap, each selected by its kid — the first 8 hex chars of the SHA-256 of the key's bytes. Validation is strict: an entry that is not exactly 64 hex characters (including an empty entry from a stray comma) refuses to boot rather than being skipped; whitespace around entries and duplicate keys are ignored.
|
|
48
|
+
|
|
49
|
+
## Key rotation
|
|
50
|
+
|
|
51
|
+
Both levels rotate without downtime and without re-encrypting stored values. The generated `src/lib/encryption.ts` exports the two helpers; call them from code you control (a one-off [schedule](/platform/schedules) or an operator-only action). Each needs a database handle that can `UPDATE org_data_keys`: on D1 any handle works; on Neon pass the service-role handle (`createServiceDb(env)` — schedules already receive one), since the request connection is denied by row-level security and the helpers report that instead of pretending.
|
|
52
|
+
|
|
53
|
+
### Rotating `ENCRYPTION_KEK`
|
|
54
|
+
|
|
55
|
+
1. Generate a new key and **prepend** it: `ENCRYPTION_KEK=<new>,<old>`. Deploy. New DEK wraps use the new key; existing wraps still unwrap under the old one by kid.
|
|
56
|
+
2. Run `rewrapOrgDataKeys(env, db)`. It rewraps every organization's DEKs — current and retired — under the primary key, and returns `{ total, rewrapped, remaining }`. Re-run until `remaining` is `0`; a row that no configured key unwraps stays counted and is logged as `encryption.dek_rewrap_failed`.
|
|
57
|
+
3. Drop the old key: `ENCRYPTION_KEK=<new>`. A wrap whose kid is no longer configured fails with an explicit error naming the missing kid — it never silently reads as empty.
|
|
58
|
+
|
|
59
|
+
{/* doc-compile: skip — excerpt: `rewrapOrgDataKeys` lives in the generated project's src/lib/encryption.ts. */}
|
|
60
|
+
```ts title="quickback/services/schedules/rewrap-keys.ts"
|
|
61
|
+
import { defineSchedule } from "quickback";
|
|
62
|
+
import { rewrapOrgDataKeys } from "../../lib/encryption";
|
|
63
|
+
|
|
64
|
+
export default defineSchedule({
|
|
65
|
+
name: "rewrap-keys",
|
|
66
|
+
cron: "0 3 * * *",
|
|
67
|
+
execute: async ({ db, env }) => {
|
|
68
|
+
console.log(JSON.stringify(await rewrapOrgDataKeys(env, db)));
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### Rotating an organization's DEK
|
|
74
|
+
|
|
75
|
+
`rotateOrgDataKey(env, db, organizationId)` creates a fresh DEK, makes it the current version for new writes, and moves the previous version into `retired_deks`, where it stays readable for every value that records it. It returns `{ keyVersion }`, and throws if the org has no key yet, if a concurrent rotation won, or if `db` cannot update the row. Existing values are not re-encrypted; each converges to the new version the next time its field is written. Warm Worker isolates cache an org's keys for up to five minutes, so they may write under the previous version for that long — reads of a newer version refresh immediately.
|
|
76
|
+
|
|
45
77
|
## Rules the compiler enforces
|
|
46
78
|
|
|
47
79
|
Ciphertext cannot be queried, so encrypted columns are **excluded from every query surface at compile time** — these are errors, not warnings:
|
|
@@ -57,7 +89,7 @@ Encrypted columns **may** appear in view projections and responses — they decr
|
|
|
57
89
|
|
|
58
90
|
## Per-organization keys: blast radius and crypto-shredding
|
|
59
91
|
|
|
60
|
-
Each organization's data is encrypted under its own DEK, so one compromised key never exposes another tenant. Deleting an org's `org_data_keys` row makes every encrypted value it wrote unreadable **with the current `ENCRYPTION_KEK`** — provided no copy of that wrapped key survives elsewhere (database backups, point-in-time restore, exports). Shredding is a manual, service-role delete today; there is no generated shred
|
|
92
|
+
Each organization's data is encrypted under its own DEK, so one compromised key never exposes another tenant. Deleting an org's `org_data_keys` row makes every encrypted value it wrote unreadable **with the current `ENCRYPTION_KEK`** — provided no copy of that wrapped key survives elsewhere (database backups, point-in-time restore, exports). The row holds every version of the org's DEK, so the delete shreds values written before a rotation too. Shredding is a manual, service-role delete today; there is no generated shred endpoint. After a delete, the next encrypted write for that org creates a fresh DEK, and reads of the old values fail with `ENCRYPTION_UNREADABLE`.
|
|
61
93
|
|
|
62
94
|
## What this tier does and doesn't claim
|
|
63
95
|
|
|
@@ -65,7 +97,7 @@ The envelope tier protects against **storage compromise**: backups, exports, das
|
|
|
65
97
|
|
|
66
98
|
Two practical notes:
|
|
67
99
|
|
|
68
|
-
- **Action responses**: rows returned from `db.insert(...).returning()` inside your own actions contain ciphertext — decrypt explicitly with `ctx.crypto.decrypt()` if your action returns the field. Generated CRUD routes handle this automatically.
|
|
100
|
+
- **Action responses**: rows returned from `db.insert(...).returning()` inside your own actions contain ciphertext — decrypt explicitly with `ctx.crypto.decrypt(value, { table, column })` if your action returns the field. Generated CRUD routes handle this automatically.
|
|
69
101
|
- **No server-side equality lookups** on encrypted values (blind indexes are a roadmap item). If you need to filter by it, it probably shouldn't be encrypted — or it needs a separate non-sensitive derived column.
|
|
70
102
|
|
|
71
103
|
---
|
|
@@ -573,6 +573,12 @@ Every generated write handler — `POST /`, `POST /batch`, `PATCH /:id`, `PATCH
|
|
|
573
573
|
|
|
574
574
|
This closes a cross-tenant injection vector: even if an attacker knows a foreign tenant's row ID, they cannot attach a child record to it — at creation or by repointing an existing row later — and they cannot trigger a cross-tenant cascade delete. The check uses the target table's `buildXFirewallConditions(ctx)` helper, so it honors whatever firewall predicates the target declared (organization, owner, team, custom). FKs to tables with `{ exception: true }` get a plain existence check (still verifies the row exists, doesn't tenant-scope it). A [self-reference](/define/schema#self-references) (`parentId: q.text().references('self')`) is checked against the table's own firewall the same way.
|
|
575
575
|
|
|
576
|
+
Target visibility alone does not prove that two visible rows share a project or
|
|
577
|
+
other parent. For that invariant, opt into the schema-level
|
|
578
|
+
[`references(..., { match })`](/define/schema#match-a-referenced-rows-parent)
|
|
579
|
+
constraint. Database triggers also backstop action writes; clients should use
|
|
580
|
+
the API rather than writing directly to PostgreSQL.
|
|
581
|
+
|
|
576
582
|
The check runs after guards but before the write, so it appears as `layer: "validation"` in error responses. Status code is `400`, not `404` — returning `404` would leak existence of out-of-scope rows.
|
|
577
583
|
|
|
578
584
|
### Pre-Record ID-Probe Defense
|
|
@@ -86,6 +86,35 @@ A few mechanics to know:
|
|
|
86
86
|
- **`.required()` / `.optional()`** control NOT NULL. Chain before or after `.default(x)`.
|
|
87
87
|
- **References:** `q.text().required().references(() => other.id, { onDelete: 'cascade' })`, or `.references('self')` for a column pointing at another row of the same table (see [Self-references](#self-references)). An FK declares a *pointer*, not ownership — when the child rows are a **composition** of one root (junctions, phones/emails, line items), also declare [`owns`](/define/changesets) on the root to generate the atomic aggregate write path. `other` must be a **feature table in the same database**.
|
|
88
88
|
|
|
89
|
+
### Match a referenced row's parent
|
|
90
|
+
|
|
91
|
+
An ordinary FK checks that its target exists and is visible. It does not infer
|
|
92
|
+
that two rows belong to the same project, event, or other parent. Declare that
|
|
93
|
+
rule on the FK when both rows must share one:
|
|
94
|
+
|
|
95
|
+
```ts
|
|
96
|
+
stageId: q.text().optional().references(() => projectStages.id, {
|
|
97
|
+
match: { source: 'projectId', target: 'projectId' },
|
|
98
|
+
}),
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Here `source` names a column on this table and `target` names one on the
|
|
102
|
+
referenced table. If `stageId` is set, both values must be non-null and equal.
|
|
103
|
+
If `stageId` is null, the match is not required. The compiler rejects unknown
|
|
104
|
+
columns or an unresolved target table. This is opt-in: some visible records
|
|
105
|
+
may legitimately link across projects.
|
|
106
|
+
|
|
107
|
+
The compiler emits database triggers for inserts and updates of the source
|
|
108
|
+
row, and for changes to the target's parent column. Use the Quickback API for
|
|
109
|
+
client writes; the triggers backstop generated CRUD, batch writes, changesets,
|
|
110
|
+
and actions at the database boundary. Updating `projectId` while
|
|
111
|
+
leaving `stageId` unchanged still checks the resulting pair. A mismatch returns
|
|
112
|
+
`400 DB_RELATIONSHIP_MISMATCH` from generated write routes. Apply the generated
|
|
113
|
+
trigger migration before using the new rule; it validates future writes, so
|
|
114
|
+
check existing rows for mismatches before rollout. The ordinary target
|
|
115
|
+
[firewall check](/define/firewall#foreign-key-referential-checks) remains in
|
|
116
|
+
place for generated CRUD writes.
|
|
117
|
+
|
|
89
118
|
> **Never FK Better Auth tables**
|
|
90
119
|
>
|
|
91
120
|
> `.references(() => users.id)` (or `user`, `organization`, `member`, `session`) on a feature column is illegal. Those tables live in `AUTH_DB`; your features live in `DB`. SQLite cannot FK across D1 databases, and drizzle-kit fails generating features migrations:
|
|
@@ -1131,7 +1160,7 @@ rows live in `AUTH_DB`, outside the feature database.
|
|
|
1131
1160
|
|
|
1132
1161
|
## Input Hints
|
|
1133
1162
|
|
|
1134
|
-
Control how the CMS renders form inputs for specific columns. By default the CMS infers the control from the column itself — `q.timestamp()` → date-time picker, `q.date()` → date picker, `q.bool()` → checkbox, `q.int()` / `q.bigint()` / `q.smallint()` → number, `q.decimal()` → text (so the exact string is sent), `q.enum()` → select, `q.url()` → URL input, `q.json()` → textarea, and name patterns for plain text (`*Url`, `*Notes`, `email`). The registry carries the q column `kind`, so this works on SQLite too, where every timestamp is `text` at the SQL layer.
|
|
1163
|
+
Control how the CMS renders form inputs for specific columns. By default the CMS infers the control from the column itself — `q.timestamp()` → date-time picker, `q.date()` → date picker, `q.bool()` → checkbox, `q.int()` / `q.bigint()` / `q.smallint()` → number, `q.decimal()` → text (so the exact string is sent), `q.enum()` → select, `q.enum([...]).array()` → multiple checkboxes that send an array, `q.url()` → URL input, `q.json()` → textarea that validates and sends JSON, and name patterns for plain text (`*Url`, `*Notes`, `email`). The registry carries the q column `kind`, so this works on SQLite too, where every timestamp is `text` at the SQL layer. Other `.array()` columns do not yet have a dedicated CMS editor. `inputHints` overrides the inference except for enum arrays, which must retain an array value:
|
|
1135
1164
|
|
|
1136
1165
|
{/* doc-compile: skip — one-key excerpt: the fence is the `inputHints` map only, with firewall/guards/crud already elided to `// ...`. This page's whole-file examples are the `feature()` and `q.table()`+`defineTable()` forms at the top, which the gate does compile. */}
|
|
1137
1166
|
```typescript
|
|
@@ -1153,7 +1182,7 @@ export default defineTable(jobs, {
|
|
|
1153
1182
|
|------|-----------|
|
|
1154
1183
|
| `richtext` | Rich text editor (tiptap) — bold, italic, headings, lists, links. Stores HTML. Lazy-loaded in edit mode, rendered as formatted HTML in view mode. |
|
|
1155
1184
|
| `select` | Dropdown select (single value) |
|
|
1156
|
-
| `multi-select` |
|
|
1185
|
+
| `multi-select` | Falls back to the inferred control; enum arrays render as multiple checkboxes |
|
|
1157
1186
|
| `radio` | Radio button group |
|
|
1158
1187
|
| `checkbox` | Checkbox toggle |
|
|
1159
1188
|
| `textarea` | Multi-line text input |
|