@quickback-dev/cli 0.67.1 → 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.
Files changed (54) hide show
  1. package/dist/index.js +1 -1
  2. package/dist/skill/docs/api/batch-operations.md +5 -0
  3. package/dist/skill/docs/api/errors.md +7 -4
  4. package/dist/skill/docs/configure/auth.md +26 -0
  5. package/dist/skill/docs/configure/index.md +28 -9
  6. package/dist/skill/docs/define/access.md +15 -2
  7. package/dist/skill/docs/define/authz-roles.md +1 -1
  8. package/dist/skill/docs/define/encryption.md +39 -7
  9. package/dist/skill/docs/define/firewall.md +6 -0
  10. package/dist/skill/docs/define/schema.md +31 -2
  11. package/dist/skill/docs/platform/auth/api-keys.md +77 -1
  12. package/dist/skill/docs/platform/auth/plugins/agent-auth.md +1 -1
  13. package/dist/skill/docs/platform/auth/plugins/index.md +33 -34
  14. package/dist/skill/docs/platform/auth/security.md +53 -6
  15. package/dist/skill/docs/platform/auth/using-auth.md +1 -1
  16. package/dist/skill/docs/platform/realtime/partyserver-rooms.md +2 -0
  17. package/dist/skill/docs/platform/storage/r2.md +2 -0
  18. package/dist/skill/docs/platform/storage/using-kv.md +6 -36
  19. package/dist/skill/docs/platform/webhooks/inbound.md +2 -1
  20. package/dist/skill/docs/tooling/cloud-compiler/endpoints.md +4 -0
  21. package/dist/skill/docs/tooling/cloud-compiler/troubleshooting.md +12 -8
  22. package/dist/skill/docs/ui/account/features/api-keys.md +2 -1
  23. package/dist/skill/docs/ui/account/features/index.md +7 -6
  24. package/dist/skill/docs/ui/account/features/passwordless.md +1 -1
  25. package/dist/skill/docs/ui/account/hooks.md +1 -1
  26. package/dist/skill/docs/ui/account/index.md +2 -2
  27. package/dist/skill/docs/ui/admin/actions.md +2 -1
  28. package/package.json +1 -1
  29. package/src/skill/docs/api/batch-operations.md +5 -0
  30. package/src/skill/docs/api/errors.md +7 -4
  31. package/src/skill/docs/configure/auth.md +26 -0
  32. package/src/skill/docs/configure/index.md +28 -9
  33. package/src/skill/docs/define/access.md +15 -2
  34. package/src/skill/docs/define/authz-roles.md +1 -1
  35. package/src/skill/docs/define/encryption.md +39 -7
  36. package/src/skill/docs/define/firewall.md +6 -0
  37. package/src/skill/docs/define/schema.md +31 -2
  38. package/src/skill/docs/platform/auth/api-keys.md +77 -1
  39. package/src/skill/docs/platform/auth/plugins/agent-auth.md +1 -1
  40. package/src/skill/docs/platform/auth/plugins/index.md +33 -34
  41. package/src/skill/docs/platform/auth/security.md +53 -6
  42. package/src/skill/docs/platform/auth/using-auth.md +1 -1
  43. package/src/skill/docs/platform/realtime/partyserver-rooms.md +2 -0
  44. package/src/skill/docs/platform/storage/r2.md +2 -0
  45. package/src/skill/docs/platform/storage/using-kv.md +6 -36
  46. package/src/skill/docs/platform/webhooks/inbound.md +2 -1
  47. package/src/skill/docs/tooling/cloud-compiler/endpoints.md +4 -0
  48. package/src/skill/docs/tooling/cloud-compiler/troubleshooting.md +12 -8
  49. package/src/skill/docs/ui/account/features/api-keys.md +2 -1
  50. package/src/skill/docs/ui/account/features/index.md +7 -6
  51. package/src/skill/docs/ui/account/features/passwordless.md +1 -1
  52. package/src/skill/docs/ui/account/hooks.md +1 -1
  53. package/src/skill/docs/ui/account/index.md +2 -2
  54. package/src/skill/docs/ui/admin/actions.md +2 -1
@@ -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 never installs them — it has no network. A project that
315
- declares `build.dependencies` therefore skips the [Worker bundle
316
- check](/tooling/cloud-compiler/troubleshooting#complete-compile-wrangler-bundle-failed)
317
- and reports that as a compile warning.
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 — all built from your config at compile time.
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 excluded from the Account UI bundle at compile time (routes removed before the Vite build, keeping bundle sizes minimal) **and** enforced on the server side via the Better Auth config — so "signup off" actually closes `POST /auth/v1/sign-up/email`, not just the SPA's signup screen.
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 `emailAndPassword.disableSignUp: false`) fails the compile with a precise error rather than picking a silent winner.
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` | `emailAndPassword.disableSignUp` (inverted) | Self-service account registration — false hides the UI **and** rejects the server endpoint with 403 |
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 |
@@ -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. `{ null: true }` treats an absent value as
423
- null, and on collection reads it becomes `IS NULL` in the `WHERE` clause:
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 } } } },
@@ -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 a random 256-bit data key (DEK), stored **wrapped** under the `ENCRYPTION_KEK` worker secret. Created lazily on the org's first encrypted write.
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 without `ENCRYPTION_KEK` (503 `MISSING_ENV`), instead of silently storing plaintext.
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:1:<keyVersion>:<iv>:<ciphertext>` — the prefix makes accidental plaintext detectable, and the embedded key version is recorded for future key rotation. Rotation is not built yet: every value is written and read under the org's single current DEK.
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
- Each wrapped DEK is bound to its organization (AES-GCM additional data), so a wrapped key copied into another org's `org_data_keys` row fails to unwrap. Rows written before this binding are still read and are rewrapped the first time they load (on D1; on Neon the request connection has no `UPDATE` on `org_data_keys`, so legacy rows stay in the older format until a service-role pass).
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 or rotation 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`.
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. The CMS has no editor for `.array()` columns yet. `inputHints` overrides the inference:
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` | Multi-value 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 |
@@ -16,9 +16,85 @@ The compiler validates the key by calling the Quickback API's Better Auth `GET /
16
16
 
17
17
  ## What a key can reach
18
18
 
19
- In a generated project an `x-api-key` authenticates two things:
19
+ Send a key as `x-api-key: <key>`, or — for keys that carry the project prefix (every key created since prefixes were added) — as `Authorization: Bearer <key>`. Older unprefixed keys work only through `x-api-key`. Either way a key authenticates two things:
20
20
 
21
21
  - **Your API** (`/api/*`) — the auth middleware verifies the key and resolves its owner's role in the organization named by the key's `metadata.organizationId`.
22
22
  - **`GET /auth/v1/get-session`** — the one Better Auth endpoint where a key stands in for its owner's session (the key-validation "whoami").
23
23
 
24
24
  Every other Better Auth endpoint ignores the header and answers as for an unauthenticated caller: a key cannot mint an identity JWT (`GET /auth/v1/token`), list sessions, create or manage keys, change the user, register a passkey, or act on organizations. Those need a real session.
25
+
26
+ The generated MCP endpoint (`POST /mcp`) is bearer-only: it forwards `Authorization`, not `x-api-key`, to the routes its tools call. So an MCP client uses a prefixed key as `Authorization: Bearer <key>`. A scoped key may open `/mcp` (and list tools); each tool call re-enters the REST route it wraps, where the key's scopes are checked — a `tasks:read` key can call the list-tasks tool but gets `403 ACCESS_KEY_SCOPE_REQUIRED` from the create-task tool.
27
+
28
+ The prefix is what makes the Bearer form unambiguous: `plugins.apiKey.prefix` must end in `_` or `-` (Better Auth session tokens are alphanumeric, so they can never start with one) and must not start with `eyJ` (a JWT).
29
+
30
+ ## Scopes
31
+
32
+ By default a key carries its owner's **full** role in the organization it names. Give it `metadata.scopes` to narrow that — for an agent, a CI job, or an integration that only needs part of the API:
33
+
34
+ ```bash
35
+ curl -X POST https://api.example.com/auth/v1/api-key/create \
36
+ -H "Cookie: ${SESSION_COOKIE}" -H "Content-Type: application/json" \
37
+ -d '{"name":"reporting agent","metadata":{"organizationId":"org_123","scopes":["customers:read","deals:read"]}}'
38
+ ```
39
+
40
+ The [Account UI](/ui/account/features/api-keys) has a Scopes field for the same thing. The vocabulary is closed:
41
+
42
+ | Scope | Admits |
43
+ |-------|--------|
44
+ | `read` | `GET` / `HEAD` / `OPTIONS` on every route under `/api/v1` |
45
+ | `write` | Every other method under `/api/v1` — create, update, delete, batch, and non-`GET` actions |
46
+ | `<resource>:read` | Reads under `/api/v1/<resource>/` — list, get, views, `GET` actions |
47
+ | `<resource>:write` | Writes under `/api/v1/<resource>/` — including actions mounted there |
48
+
49
+ `<resource>` is the first path segment of a generated resource route (`customers` for `/api/v1/customers`). The method decides read vs write, so a `GET` action is a read. `write` does not imply `read`; list both if the key needs both. Routes outside a resource mount — area/namespace routes (`/api/v1/<scope>/:id/…`), root-mounted standalone actions, `/api/v1/schema` — are reachable only through the global `read` / `write`.
50
+
51
+ **Scopes narrow, they never widen.** The auth middleware checks the scope first; the route's own [Access](/define/access) and [Firewall](/define/firewall) then run with the owner's org role exactly as before. A `customers:write` key held by a `member` still cannot delete what `crud.delete.access` reserves for `admin`.
52
+
53
+ **Outside `/api/v1`, a scoped key is refused.** Storage, realtime tickets, webhooks, FGA, and public discovery routes answer a scoped key with `403`. `/auth/v1/*` is allowed — there the key is only the `get-session` whoami. Use an unscoped key or a session for those surfaces.
54
+
55
+ A denied request is a standard [Problem Details](/api/errors) `403`:
56
+
57
+ ```json
58
+ {
59
+ "type": "https://quickback.dev/problems/access-key-scope-required",
60
+ "title": "Access key scope required",
61
+ "status": 403,
62
+ "code": "ACCESS_KEY_SCOPE_REQUIRED",
63
+ "detail": "API key scope does not allow this request",
64
+ "layer": "access",
65
+ "details": { "required": ["customers:write"], "current": ["customers:read"] },
66
+ "hint": "Create a key with the \"customers:write\" scope (or omit scopes for a full-access key)"
67
+ }
68
+ ```
69
+
70
+ ### Validation
71
+
72
+ Scopes are checked when a key is created or updated (`POST /auth/v1/api-key/create`, `/api-key/update`). An unknown resource, an unknown verb, an empty list, or a non-array value fails with `400` and `code: "INVALID_API_KEY_SCOPES"`; nothing is normalized. A scope naming a resource that was later removed simply matches nothing. Stored scopes that are not an array of strings fail the key closed (`401 AUTH_INVALID_TOKEN`, `details.reason: "malformed_scopes"`).
73
+
74
+ ### Existing keys
75
+
76
+ A key with no `scopes` in its metadata is a full-role key, so every key created before scopes existed keeps working unchanged. Scopes live in `metadata`, which the owner can change through `/api-key/update`; replacing the metadata without `scopes` turns the key back into a full-role key. That is the owner's call — they can always create a full-role key anyway. Scopes protect against a leaked key, not against its owner.
77
+
78
+ Scopes are stored in metadata rather than Better Auth's `permissions` field because `permissions` is server-only: the Account UI and other session clients could not set it.
79
+
80
+ ## Key prefix
81
+
82
+ New keys start with a display prefix so they are recognisable in logs and secret scanners. It defaults to the project name, slugged (`my-app` → `my_app_…`). Override it with the object form of the plugin:
83
+
84
+ ```ts
85
+ auth: defineAuth("better-auth", {
86
+ plugins: {
87
+ apiKey: { prefix: "acme_live_" },
88
+ },
89
+ }),
90
+ ```
91
+
92
+ The prefix must be 1–32 characters of `A-Z a-z 0-9 _ -`; anything else fails the compile. It is display-only — Better Auth hashes the whole key — so keys created before the prefix existed keep verifying.
93
+
94
+ ## Banned owners
95
+
96
+ When the admin plugin bans a user, every API key they own stops working: the API answers `401 AUTH_INVALID_TOKEN` with `details.reason: "owner_banned"`, and `GET /auth/v1/get-session` refuses the key. A ban whose `banExpires` has passed no longer counts, matching the admin plugin. A deleted owner's keys stop working too.
97
+
98
+ ## Rate limit
99
+
100
+ Better Auth rate limits each key using the auth config's `rateLimit.window` (seconds) and `rateLimit.max` — 100 requests per 60 seconds by default. The limit is on unless that block sets `enabled: false`. Over the limit the API answers `429 AUTH_RATE_LIMITED`. The values are stamped on each key when it is created, so a change applies to new keys only.
@@ -128,4 +128,4 @@ When `fromOpenAPI: false`, the emitted call has `capabilities: []` and no proxy
128
128
 
129
129
  ## Why bearer-only?
130
130
 
131
- The MCP and agent surfaces are server-to-server by nature. Cookies on those surfaces add CSRF surface for no benefit (no browser callers), and `x-api-key` was the legacy `apiKey`-plugin path that fragments the auth model. Bearer is the one true channel here. If your project still wants API-key auth, configure the `apiKey` plugin to accept its key via `Authorization: Bearer` so everything stays one channel.
131
+ The MCP and agent surfaces are server-to-server by nature. Cookies on those surfaces add CSRF surface for no benefit (no browser callers), and `x-api-key` was the legacy `apiKey`-plugin path that fragments the auth model. Bearer is the one true channel here. API keys ride it too: a prefixed key sent as `Authorization: Bearer <key>` is recognised by the auth middleware, so an MCP client can authenticate with a (scoped) API key. See [API Keys](/platform/auth/api-keys#what-a-key-can-reach).
@@ -40,6 +40,8 @@ export default defineConfig({
40
40
  - `POST /auth/v1/email-otp/send-verification-otp`
41
41
  - `POST /auth/v1/email-otp/verify-otp`
42
42
 
43
+ Codes are stored hashed and expire after 300 seconds by default; set `plugins: { emailOtp: { expiresIn: 600 } }` to change it — the email states the configured lifetime.
44
+
43
45
  **Email readiness check:**
44
46
 
45
47
  Use this to show UI warnings when SES isn't configured.
@@ -67,11 +69,12 @@ auth: defineAuth("better-auth", {
67
69
  }),
68
70
  ```
69
71
 
70
- > `emailOtp.disableSignUp` **inherits the global signup gate**: when
71
- > `account.auth.signup: false` (i.e. `emailAndPassword.disableSignUp: true`) is
72
- > set, the OTP plugin is gated automatically so it can't be used to bypass it. Set
73
- > `emailOtp: { disableSignUp: false }` explicitly to opt the OTP path back open
74
- > while password sign-up stays closed.
72
+ > `emailOtp.disableSignUp` **inherits `emailAndPassword.disableSignUp: true`**, so
73
+ > the OTP path can't bypass a hard password-signup block. Set
74
+ > `emailOtp: { disableSignUp: false }` explicitly to opt the OTP path back open.
75
+ > `account.auth.signup: false` is different: it sets the invite-only
76
+ > [signup policy](/platform/auth/security#signup-policy), which covers every
77
+ > sign-in method and still admits invitees.
75
78
 
76
79
 
77
80
  ### SMS OTP (with AWS SNS)
@@ -125,19 +128,23 @@ Optional vars:
125
128
 
126
129
  ### Magic Links
127
130
 
128
- Magic links provide passwordless authentication by sending a unique login link to the user's email. When clicked, the link authenticates the user without requiring a password.
131
+ Magic links provide passwordless authentication by emailing a single-use sign-in link.
129
132
 
130
133
  **Enable in config:**
131
134
 
132
135
  ```ts
133
136
  auth: defineAuth("better-auth", {
134
- plugins: ["magicLink"],
137
+ plugins: { magicLink: { expiresIn: 900 } }, // seconds; default 300
135
138
  }),
136
139
  ```
137
140
 
138
141
  **Endpoints:**
139
- - `POST /auth/v1/magic-link/send` - Send magic link email
140
- - `GET /auth/v1/magic-link/verify` - Verify magic link token
142
+ - `POST /auth/v1/sign-in/magic-link` - Send the magic link email (`{ email, callbackURL? }`)
143
+ - `GET /auth/v1/magic-link/verify` - Spend the token, set the session, redirect to `callbackURL`
144
+
145
+ **The emailed link opens a confirm page.** Mail scanners fetch every link in a message, which would spend a single-use token before the recipient clicks. So the email links to `<ACCOUNT_URL>/magic-link?token=…` — the [Account UI](/ui/account/features/passwordless) confirm page — and only its **Continue signing in** button navigates to `/magic-link/verify`. If you serve your own frontend at `ACCOUNT_URL`, give it a `/magic-link` page that does the same: forward the query string to `/auth/v1/magic-link/verify` on a user click.
146
+
147
+ Tokens are stored hashed, and the email states the configured `expiresIn`.
141
148
 
142
149
  **Disabling sign-up via magic link:**
143
150
 
@@ -154,31 +161,28 @@ auth: defineAuth("better-auth", {
154
161
  }),
155
162
  ```
156
163
 
157
- It inherits the global signup gate the same way `emailOtp.disableSignUp` does:
158
- `account.auth.signup: false` gates the magic-link path automatically; set
159
- `magicLink: { disableSignUp: false }` to opt it back open.
164
+ It inherits `emailAndPassword.disableSignUp: true` the same way
165
+ `emailOtp.disableSignUp` does; set `magicLink: { disableSignUp: false }` to opt
166
+ it back open. The invite-only [signup policy](/platform/auth/security#signup-policy)
167
+ applies to magic links too.
160
168
 
161
- **Email customization:**
169
+ **Email delivery:**
162
170
 
163
- Magic link emails use the same AWS SES configuration as Email OTP. Customize the email template via environment variables:
164
-
165
- - `APP_NAME` - Application name in email subject
166
- - `APP_URL` - Base URL for magic link redirect
167
- - `EMAIL_FROM` - Sender email address
168
- - `EMAIL_FROM_NAME` - Sender display name
171
+ Magic link emails go through your configured `email.provider` — Cloudflare Email Sending by default, or AWS SES with the same variables as Email OTP (`APP_NAME`, `EMAIL_FROM`, `EMAIL_FROM_NAME`). `ACCOUNT_URL` sets where the confirm page lives.
169
172
 
170
173
  **Frontend integration:**
171
174
 
172
175
  ```ts
173
- // Request magic link
174
- await fetch('/auth/v1/magic-link/send', {
176
+ // Request a magic link
177
+ await fetch('/auth/v1/sign-in/magic-link', {
175
178
  method: 'POST',
176
179
  headers: { 'Content-Type': 'application/json' },
177
- body: JSON.stringify({ email: 'user@yourdomain.com' })
180
+ credentials: 'include',
181
+ body: JSON.stringify({ email: 'user@yourdomain.com', callbackURL: 'https://app.yourdomain.com/' }),
178
182
  });
179
183
 
180
- // User clicks link in email, which redirects to your app
181
- // The token is verified automatically via the callback URL
184
+ // The user opens the link, lands on <ACCOUNT_URL>/magic-link, clicks
185
+ // "Continue signing in", and is redirected to callbackURL signed in.
182
186
  ```
183
187
 
184
188
  ### Passkeys
@@ -283,18 +287,13 @@ Static, long-lived credentials for cron jobs, scripts, and machine-to-machine in
283
287
 
284
288
  **Authenticating requests:**
285
289
 
286
- Pass the key as the `x-api-key` header (preferred) or as an `?api_key=` / `?key=` query parameter:
290
+ Pass the key as the `x-api-key` header, or a prefixed key as `Authorization: Bearer <key>` (query parameters are not accepted, so keys never land in access logs or `Referer`):
287
291
 
288
292
  ```bash
289
- # Header form (preferred — keys don't leak into access logs or Referer)
290
- curl -H "x-api-key: ${KEY}" https://api.example.com/v1/jobs
291
-
292
- # Query-param form (for clients that can't inject custom headers,
293
- # e.g., claude.ai's MCP connector)
294
- curl "https://api.example.com/v1/jobs?api_key=${KEY}"
293
+ curl -H "x-api-key: ${KEY}" https://api.example.com/api/v1/jobs
295
294
  ```
296
295
 
297
- The header takes precedence when both are present. The query-param form lands in nginx / Cloudflare access logs and `Referer` headers when the page navigates away — prefer headers whenever the client supports them.
296
+ Sending `x-api-key` together with a session cookie or an `Authorization` header is a `400 AUTH_METHOD_CONFLICT`.
298
297
 
299
298
  **Endpoints (managed by Better Auth):**
300
299
  - `POST /auth/v1/api-key/create` — issue a new key (returns the secret once; store it)
@@ -303,7 +302,7 @@ The header takes precedence when both are present. The query-param form lands in
303
302
 
304
303
  These need a real session (cookie or session-token bearer). Under `/auth/v1/*` a key authenticates only `GET /auth/v1/get-session`; every other Better Auth endpoint ignores `x-api-key`, so a leaked key cannot mint JWTs, manage keys, or act on organizations. See [API Keys](/platform/auth/api-keys).
305
304
 
306
- Keys can carry organization context via `metadata.organizationId` — when set, the auth middleware looks up the user's role in that org and populates `ctx.roles` accordingly, so a single key inherits the same firewall + access scope as the user who created it.
305
+ Keys can carry organization context via `metadata.organizationId` — when set, the auth middleware looks up the user's role in that org and populates `ctx.roles` accordingly, so a single key inherits the same firewall + access scope as the user who created it. `metadata.scopes` narrows a key to named resources and read/write — see [API Keys → Scopes](/platform/auth/api-keys#scopes). New keys carry a project prefix (`plugins: { apiKey: { prefix } }`), a banned owner's keys stop working, and each key is rate limited.
307
306
 
308
307
  ### OAuth Provider (MCP-ready)
309
308
 
@@ -395,7 +394,7 @@ Consent management:
395
394
 
396
395
  **Account SPA wiring:**
397
396
 
398
- The compiled Account SPA already serves `/consent`. When `oauthProvider` is enabled, Better Auth redirects unauthenticated users to `${ACCOUNT_URL}/login?redirect=...` and authenticated users straight to `${ACCOUNT_URL}/consent?client_id=...&scope=...&oauth_query=...`. The bundled consent screen reads those params, fetches client metadata via `/oauth2/public-client`, and POSTs back to `/oauth2/consent`.
397
+ The compiled Account SPA already serves `/consent`. When `oauthProvider` is enabled, Better Auth sends unauthenticated users to `${ACCOUNT_URL}/login` and authenticated users to `${ACCOUNT_URL}/consent`. Both URLs carry the signed authorize query (`client_id`, `scope`, repeated `ba_param` keys, `sig`, and so on). The bundled consent screen fetches client metadata via `/oauth2/public-client`, then POSTs the page's query back to `/oauth2/consent` as `oauth_query`. The login page does the same on sign-in. The SPA router keeps that query verbatim, because any rewrite fails the signature check with `invalid_signature`.
399
398
 
400
399
  **Token and tenant context:**
401
400
 
@@ -76,6 +76,53 @@ auth: defineAuth("better-auth", {
76
76
 
77
77
  ---
78
78
 
79
+ ## Signup Policy
80
+
81
+ `signup` decides who may create an account. One server-side gate (Better Auth's `user.create.before`) enforces it on **every** creation path — email + password, email OTP, magic link, and social sign-in — so no sign-in method can be used to slip past it.
82
+
83
+ ```ts
84
+ auth: defineAuth("better-auth", {
85
+ signup: { inviteOnly: true }, // invitations + admin-created only
86
+ // or: signup: { allowedEmailDomains: ["example.com"] } // that domain + invitations
87
+ })
88
+ ```
89
+
90
+ | Always admitted | Why |
91
+ |-----------------|-----|
92
+ | Accounts created by an admin (`POST /auth/v1/admin/create-user`) | Operators provision users directly |
93
+ | An email with a **pending, unexpired** organization invitation | Invitees must be able to sign up |
94
+ | The deploy owner's first Cloudflare login | The brokered-deploy owner is promoted to `appmanager` on that login |
95
+
96
+ Everyone else gets `403` with code `SIGNUP_NOT_ALLOWED`. Existing users sign in as before — the gate runs only when an account would be created. `allowedEmailDomains` matches the exact domain (`example.com` admits `me@example.com`, not `me@sub.example.com`).
97
+
98
+ `account.auth.signup: false` is the shorthand for `inviteOnly: true`. The compile fails if you combine `inviteOnly` with `allowedEmailDomains` (allowed domains already admit invitations), or a restricted policy with the `upgradeAnonymous` plugin (it lets an anonymous user claim any email).
99
+
100
+ Invitation acceptance itself still needs the invitation ID from the email, so knowing an invited address isn't enough to join an organization. Pair a restricted policy with `emailVerification` if accounts must prove their email before use.
101
+
102
+ A per-method hard block is separate: `emailAndPassword.disableSignUp` and the `emailOtp` / `magicLink` `disableSignUp` options refuse new accounts on that method even for invitees.
103
+
104
+ ## Account Linking
105
+
106
+ When someone signs in with a social provider and an account with the same email already exists, Better Auth links the two only if the provider verified the email (or is listed as trusted) **and** the existing account's email is verified. The second condition stops a pre-registered, unverified account from absorbing a real owner's Google sign-in. The compiler pins both conditions explicitly, so a future Better Auth default can't loosen them; the local-email condition is not configurable.
107
+
108
+ ```ts
109
+ auth: defineAuth("better-auth", {
110
+ socialProviders: { google: { enabled: true } },
111
+ accountLinking: {
112
+ trustedProviders: ["google"], // trust Google's email even when it says unverified
113
+ // enabled: false, // never link implicitly; users link while signed in
114
+ },
115
+ })
116
+ ```
117
+
118
+ `trustedProviders` entries must be enabled `socialProviders`; anything else fails the compile.
119
+
120
+ ## Sign-In Tokens at Rest
121
+
122
+ Magic-link tokens and email OTP codes are stored **hashed** in the verification table (`storeToken: "hashed"`, `storeOTP: "hashed"`), so a leaked database row can't be replayed. Both lifetimes are emitted explicitly (default 300 seconds, `plugins.<name>.expiresIn` to change), and the emails state the same value.
123
+
124
+ ---
125
+
79
126
  ## Rate Limiting
80
127
 
81
128
  Quickback includes per-IP rate limiting by default to protect against brute-force attacks and abuse.
@@ -194,25 +241,25 @@ Quickback supports three bearer-token flavors alongside the standard browser ses
194
241
  | Session cookie | Browser SPAs (CMS, Account, your app) | Better Auth session lookup |
195
242
  | Session-token bearer | API clients that grabbed `set-auth-token` | Better Auth `bearer` plugin |
196
243
  | JWT bearer | API clients that mint at `GET /auth/v1/token` | In-worker JWT fast-path (no DB hit) |
197
- | API-key bearer | Long-lived programmatic access | `apiKey` plugin / `x-api-key` header (never a query parameter) |
244
+ | API-key bearer | Long-lived programmatic access | `apiKey` plugin / `x-api-key` header, or a prefixed key as `Authorization: Bearer` (never a query parameter) |
198
245
 
199
246
  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.
200
247
 
201
- ### Precedence: bearer always wins
248
+ ### One transport per request
202
249
 
203
- If a request carries both `Authorization` and `Cookie` headers, the bearer wins universally and the cookie is dropped before session resolution:
250
+ A request carries exactly one credential. Two or more of `Cookie`, `Authorization`, and `x-api-key` is a `400 AUTH_METHOD_CONFLICT` — no precedence rules, no silent override:
204
251
 
205
252
  ```
206
253
  Request Resolved as
207
254
  ────────────────────────────────────── ─────────────
208
255
  Cookie only cookie session
209
256
  Authorization: Bearer <jwt> JWT claims
210
- Authorization: Bearer <api-key> API-key owner
211
257
  Authorization: Bearer <session-token> bearer session
212
- Cookie + Authorization: Bearer <token> bearer wins, cookie ignored
258
+ x-api-key: <api-key> API-key owner (narrowed by its scopes)
259
+ Any two of the above 400 AUTH_METHOD_CONFLICT
213
260
  ```
214
261
 
215
- This closes a class of silent-impersonation bugs where an ambient session cookie (multi-account browser tabs, a malicious extension, a misconfigured proxy injecting `Set-Cookie`) would otherwise override an explicit bearer credential. The decision is made before `getSession()` runs, so it applies to every code path in the auth middleware.
262
+ This closes a class of silent-impersonation bugs where an ambient session cookie (multi-account browser tabs, a malicious extension, a misconfigured proxy injecting `Set-Cookie`) would otherwise override an explicit credential. The decision is made before `getSession()` runs, so it applies to every code path in the auth middleware.
216
263
 
217
264
  The api-key and JWT bearers also short-circuit before cookie resolution via dedicated fast-paths — they never touch the database for session lookup. Only session-token bearers reach `getSession()`, where Better Auth's `bearer` plugin resolves the `Authorization` header.
218
265