@quickback-dev/cli 0.72.8 → 0.72.10

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 (240) hide show
  1. package/dist/commands/build.d.ts.map +1 -1
  2. package/dist/commands/build.js +8 -1
  3. package/dist/commands/build.js.map +1 -1
  4. package/dist/commands/db-explain.d.ts +67 -0
  5. package/dist/commands/db-explain.d.ts.map +1 -0
  6. package/dist/commands/db-explain.js +141 -0
  7. package/dist/commands/db-explain.js.map +1 -0
  8. package/dist/commands/db-export.d.ts +34 -0
  9. package/dist/commands/db-export.d.ts.map +1 -0
  10. package/dist/commands/db-export.js +250 -0
  11. package/dist/commands/db-export.js.map +1 -0
  12. package/dist/commands/db-insights.d.ts +60 -0
  13. package/dist/commands/db-insights.d.ts.map +1 -0
  14. package/dist/commands/db-insights.js +106 -0
  15. package/dist/commands/db-insights.js.map +1 -0
  16. package/dist/commands/db-recovery.d.ts +98 -0
  17. package/dist/commands/db-recovery.d.ts.map +1 -0
  18. package/dist/commands/db-recovery.js +558 -0
  19. package/dist/commands/db-recovery.js.map +1 -0
  20. package/dist/commands/db-target.d.ts +27 -0
  21. package/dist/commands/db-target.d.ts.map +1 -0
  22. package/dist/commands/db-target.js +83 -0
  23. package/dist/commands/db-target.js.map +1 -0
  24. package/dist/commands/db.d.ts +3 -0
  25. package/dist/commands/db.d.ts.map +1 -0
  26. package/dist/commands/db.js +43 -0
  27. package/dist/commands/db.js.map +1 -0
  28. package/dist/commands/effects.d.ts +8 -0
  29. package/dist/commands/effects.d.ts.map +1 -0
  30. package/dist/commands/effects.js +48 -0
  31. package/dist/commands/effects.js.map +1 -0
  32. package/dist/commands/platform-budget.d.ts +143 -0
  33. package/dist/commands/platform-budget.d.ts.map +1 -0
  34. package/dist/commands/platform-budget.js +619 -0
  35. package/dist/commands/platform-budget.js.map +1 -0
  36. package/dist/commands/preview.d.ts +57 -0
  37. package/dist/commands/preview.d.ts.map +1 -0
  38. package/dist/commands/preview.js +268 -0
  39. package/dist/commands/preview.js.map +1 -0
  40. package/dist/commands/search.d.ts +20 -0
  41. package/dist/commands/search.d.ts.map +1 -0
  42. package/dist/commands/search.js +133 -0
  43. package/dist/commands/search.js.map +1 -0
  44. package/dist/index.js +35 -1
  45. package/dist/index.js.map +1 -1
  46. package/dist/lib/api-client.d.ts +4 -0
  47. package/dist/lib/api-client.d.ts.map +1 -1
  48. package/dist/lib/api-client.js.map +1 -1
  49. package/dist/lib/cloudflare-spend-policies.d.ts +92 -0
  50. package/dist/lib/cloudflare-spend-policies.d.ts.map +1 -0
  51. package/dist/lib/cloudflare-spend-policies.js +289 -0
  52. package/dist/lib/cloudflare-spend-policies.js.map +1 -0
  53. package/dist/lib/compiler-stubs.d.ts +2 -0
  54. package/dist/lib/compiler-stubs.d.ts.map +1 -1
  55. package/dist/lib/compiler-stubs.js +2 -0
  56. package/dist/lib/compiler-stubs.js.map +1 -1
  57. package/dist/lib/d1-fingerprint.d.ts +8 -0
  58. package/dist/lib/d1-fingerprint.d.ts.map +1 -0
  59. package/dist/lib/d1-fingerprint.js +113 -0
  60. package/dist/lib/d1-fingerprint.js.map +1 -0
  61. package/dist/lib/file-loader.d.ts +12 -0
  62. package/dist/lib/file-loader.d.ts.map +1 -1
  63. package/dist/lib/file-loader.js +27 -1
  64. package/dist/lib/file-loader.js.map +1 -1
  65. package/dist/lib/migrations/plan.js +3 -0
  66. package/dist/lib/migrations/plan.js.map +1 -1
  67. package/dist/lib/migrations/postprocessors/index.d.ts +6 -5
  68. package/dist/lib/migrations/postprocessors/index.d.ts.map +1 -1
  69. package/dist/lib/migrations/postprocessors/index.js +24 -12
  70. package/dist/lib/migrations/postprocessors/index.js.map +1 -1
  71. package/dist/lib/migrations/postprocessors/search.d.ts +49 -0
  72. package/dist/lib/migrations/postprocessors/search.d.ts.map +1 -0
  73. package/dist/lib/migrations/postprocessors/search.js +160 -0
  74. package/dist/lib/migrations/postprocessors/search.js.map +1 -0
  75. package/dist/lib/migrations/prior-state.d.ts +7 -0
  76. package/dist/lib/migrations/prior-state.d.ts.map +1 -1
  77. package/dist/lib/migrations/prior-state.js +3 -0
  78. package/dist/lib/migrations/prior-state.js.map +1 -1
  79. package/dist/lib/migrations/types.d.ts +1 -1
  80. package/dist/lib/migrations/types.d.ts.map +1 -1
  81. package/dist/lib/migrations/types.js +1 -0
  82. package/dist/lib/migrations/types.js.map +1 -1
  83. package/dist/lib/preview-lifecycle.d.ts +139 -0
  84. package/dist/lib/preview-lifecycle.d.ts.map +1 -0
  85. package/dist/lib/preview-lifecycle.js +429 -0
  86. package/dist/lib/preview-lifecycle.js.map +1 -0
  87. package/dist/lib/preview.d.ts +146 -0
  88. package/dist/lib/preview.d.ts.map +1 -0
  89. package/dist/lib/preview.js +417 -0
  90. package/dist/lib/preview.js.map +1 -0
  91. package/dist/lib/wrangler-resources.d.ts.map +1 -1
  92. package/dist/lib/wrangler-resources.js +4 -2
  93. package/dist/lib/wrangler-resources.js.map +1 -1
  94. package/dist/skill/SKILL.md +9 -3
  95. package/dist/skill/agents/quickback-specialist/AGENT.md +9 -11
  96. package/dist/skill/docs/api/batch-operations.md +19 -0
  97. package/dist/skill/docs/api/caching.md +17 -0
  98. package/dist/skill/docs/api/crud.md +9 -0
  99. package/dist/skill/docs/api/errors.md +31 -2
  100. package/dist/skill/docs/api/query-params.md +6 -0
  101. package/dist/skill/docs/changelog/index.md +1 -0
  102. package/dist/skill/docs/configure/agents.md +1 -1
  103. package/dist/skill/docs/configure/bindings.md +177 -1
  104. package/dist/skill/docs/configure/cloudflare-access.md +43 -0
  105. package/dist/skill/docs/configure/domains.md +2 -2
  106. package/dist/skill/docs/configure/index.md +2 -2
  107. package/dist/skill/docs/configure/providers.md +5 -0
  108. package/dist/skill/docs/configure/single-tenant.md +1 -0
  109. package/dist/skill/docs/configure/tenant-databases.md +627 -14
  110. package/dist/skill/docs/define/access.md +26 -0
  111. package/dist/skill/docs/define/actions/defining.md +7 -1
  112. package/dist/skill/docs/define/actions/index.md +5 -0
  113. package/dist/skill/docs/define/actions/scoped-db.md +127 -1
  114. package/dist/skill/docs/define/authoring-basics.md +92 -0
  115. package/dist/skill/docs/define/changesets.md +8 -0
  116. package/dist/skill/docs/define/encryption.md +48 -2
  117. package/dist/skill/docs/define/feature.md +17 -2
  118. package/dist/skill/docs/define/guards.md +11 -3
  119. package/dist/skill/docs/define/index.md +1 -1
  120. package/dist/skill/docs/define/invariants.md +321 -0
  121. package/dist/skill/docs/define/issue-tracker-example.md +225 -0
  122. package/dist/skill/docs/define/masking.md +3 -3
  123. package/dist/skill/docs/define/rate-limit.md +63 -22
  124. package/dist/skill/docs/define/read.md +332 -5
  125. package/dist/skill/docs/define/relationships.md +10 -0
  126. package/dist/skill/docs/define/schema.md +137 -10
  127. package/dist/skill/docs/define/scopes.md +1 -0
  128. package/dist/skill/docs/define/transitions.md +9 -0
  129. package/dist/skill/docs/define/triggers.md +127 -1
  130. package/dist/skill/docs/platform/api-contract/index.md +35 -4
  131. package/dist/skill/docs/platform/auth/api-keys.md +26 -3
  132. package/dist/skill/docs/platform/auth/index.md +5 -2
  133. package/dist/skill/docs/platform/auth/plugins/index.md +1 -1
  134. package/dist/skill/docs/platform/auth/plugins/organization-defaults.md +37 -0
  135. package/dist/skill/docs/platform/auth/using-auth.md +2 -0
  136. package/dist/skill/docs/platform/database/d1.md +73 -1
  137. package/dist/skill/docs/platform/database/durable-effects.md +224 -0
  138. package/dist/skill/docs/platform/database/read-replication.md +9 -0
  139. package/dist/skill/docs/platform/database/recovery.md +292 -0
  140. package/dist/skill/docs/platform/database/using-d1.md +152 -2
  141. package/dist/skill/docs/platform/index.md +1 -0
  142. package/dist/skill/docs/platform/operations/budgets.md +224 -0
  143. package/dist/skill/docs/platform/queues/handlers.md +1 -0
  144. package/dist/skill/docs/platform/queues/index.md +18 -0
  145. package/dist/skill/docs/platform/realtime/table-changes.md +1 -0
  146. package/dist/skill/docs/platform/storage/using-r2.md +13 -0
  147. package/dist/skill/docs/platform/vector/embeddings.md +28 -4
  148. package/dist/skill/docs/platform/vector/using-embeddings.md +17 -0
  149. package/dist/skill/docs/platform/workflows/index.md +385 -0
  150. package/dist/skill/docs/start/deploy-browser.md +51 -0
  151. package/dist/skill/docs/start/deploy.md +97 -1
  152. package/dist/skill/docs/tooling/cli.md +117 -0
  153. package/dist/skill/docs/tooling/cloud-compiler/index.md +15 -0
  154. package/dist/skill/docs/ui/account/customization.md +6 -2
  155. package/dist/skill/docs/ui/account/environment-variables.md +7 -1
  156. package/dist/skill/docs/ui/account/features/admin.md +2 -2
  157. package/dist/skill/docs/ui/account/features/api-keys.md +1 -1
  158. package/dist/skill/docs/ui/account/features/index.md +10 -8
  159. package/dist/skill/docs/ui/account/features/organizations.md +19 -9
  160. package/dist/skill/docs/ui/account/features/passkeys.md +6 -2
  161. package/dist/skill/docs/ui/account/features/sessions.md +2 -2
  162. package/dist/skill/docs/ui/account/index.md +61 -30
  163. package/dist/skill/docs/ui/account/with-quickback.md +1 -1
  164. package/dist/skill/docs/ui/admin/connecting.md +1 -1
  165. package/dist/skill/docs/ui/admin/index.md +1 -1
  166. package/dist/skill/docs/ui/admin/record-layouts.md +3 -3
  167. package/package.json +1 -1
  168. package/src/skill/SKILL.md +9 -3
  169. package/src/skill/agents/quickback-specialist/AGENT.md +9 -11
  170. package/src/skill/docs/api/batch-operations.md +19 -0
  171. package/src/skill/docs/api/caching.md +17 -0
  172. package/src/skill/docs/api/crud.md +9 -0
  173. package/src/skill/docs/api/errors.md +31 -2
  174. package/src/skill/docs/api/query-params.md +6 -0
  175. package/src/skill/docs/changelog/index.md +1 -0
  176. package/src/skill/docs/configure/agents.md +1 -1
  177. package/src/skill/docs/configure/bindings.md +177 -1
  178. package/src/skill/docs/configure/cloudflare-access.md +43 -0
  179. package/src/skill/docs/configure/domains.md +2 -2
  180. package/src/skill/docs/configure/index.md +2 -2
  181. package/src/skill/docs/configure/providers.md +5 -0
  182. package/src/skill/docs/configure/single-tenant.md +1 -0
  183. package/src/skill/docs/configure/tenant-databases.md +627 -14
  184. package/src/skill/docs/define/access.md +26 -0
  185. package/src/skill/docs/define/actions/defining.md +7 -1
  186. package/src/skill/docs/define/actions/index.md +5 -0
  187. package/src/skill/docs/define/actions/scoped-db.md +127 -1
  188. package/src/skill/docs/define/authoring-basics.md +92 -0
  189. package/src/skill/docs/define/changesets.md +8 -0
  190. package/src/skill/docs/define/encryption.md +48 -2
  191. package/src/skill/docs/define/feature.md +17 -2
  192. package/src/skill/docs/define/guards.md +11 -3
  193. package/src/skill/docs/define/index.md +1 -1
  194. package/src/skill/docs/define/invariants.md +321 -0
  195. package/src/skill/docs/define/issue-tracker-example.md +225 -0
  196. package/src/skill/docs/define/masking.md +3 -3
  197. package/src/skill/docs/define/rate-limit.md +63 -22
  198. package/src/skill/docs/define/read.md +332 -5
  199. package/src/skill/docs/define/relationships.md +10 -0
  200. package/src/skill/docs/define/schema.md +137 -10
  201. package/src/skill/docs/define/scopes.md +1 -0
  202. package/src/skill/docs/define/transitions.md +9 -0
  203. package/src/skill/docs/define/triggers.md +127 -1
  204. package/src/skill/docs/platform/api-contract/index.md +35 -4
  205. package/src/skill/docs/platform/auth/api-keys.md +26 -3
  206. package/src/skill/docs/platform/auth/index.md +5 -2
  207. package/src/skill/docs/platform/auth/plugins/index.md +1 -1
  208. package/src/skill/docs/platform/auth/plugins/organization-defaults.md +37 -0
  209. package/src/skill/docs/platform/auth/using-auth.md +2 -0
  210. package/src/skill/docs/platform/database/d1.md +73 -1
  211. package/src/skill/docs/platform/database/durable-effects.md +224 -0
  212. package/src/skill/docs/platform/database/read-replication.md +9 -0
  213. package/src/skill/docs/platform/database/recovery.md +292 -0
  214. package/src/skill/docs/platform/database/using-d1.md +152 -2
  215. package/src/skill/docs/platform/index.md +1 -0
  216. package/src/skill/docs/platform/operations/budgets.md +224 -0
  217. package/src/skill/docs/platform/queues/handlers.md +1 -0
  218. package/src/skill/docs/platform/queues/index.md +18 -0
  219. package/src/skill/docs/platform/realtime/table-changes.md +1 -0
  220. package/src/skill/docs/platform/storage/using-r2.md +13 -0
  221. package/src/skill/docs/platform/vector/embeddings.md +28 -4
  222. package/src/skill/docs/platform/vector/using-embeddings.md +17 -0
  223. package/src/skill/docs/platform/workflows/index.md +385 -0
  224. package/src/skill/docs/start/deploy-browser.md +51 -0
  225. package/src/skill/docs/start/deploy.md +97 -1
  226. package/src/skill/docs/tooling/cli.md +117 -0
  227. package/src/skill/docs/tooling/cloud-compiler/index.md +15 -0
  228. package/src/skill/docs/ui/account/customization.md +6 -2
  229. package/src/skill/docs/ui/account/environment-variables.md +7 -1
  230. package/src/skill/docs/ui/account/features/admin.md +2 -2
  231. package/src/skill/docs/ui/account/features/api-keys.md +1 -1
  232. package/src/skill/docs/ui/account/features/index.md +10 -8
  233. package/src/skill/docs/ui/account/features/organizations.md +19 -9
  234. package/src/skill/docs/ui/account/features/passkeys.md +6 -2
  235. package/src/skill/docs/ui/account/features/sessions.md +2 -2
  236. package/src/skill/docs/ui/account/index.md +61 -30
  237. package/src/skill/docs/ui/account/with-quickback.md +1 -1
  238. package/src/skill/docs/ui/admin/connecting.md +1 -1
  239. package/src/skill/docs/ui/admin/index.md +1 -1
  240. package/src/skill/docs/ui/admin/record-layouts.md +3 -3
@@ -42,11 +42,28 @@ export default feature('jobs', {
42
42
  });
43
43
  ```
44
44
 
45
- Type inference still works — `typeof import('./jobs').default.$infer` gives you the row type. Action files don't import the table file directly: they import both `defineAction` and the table from the generated per-feature helper (`../.quickback/define-action`), which re-exports the table typed with the generated schema. See [Actions](/define/actions).
45
+ Type inference still works — `typeof import('./jobs').default.$infer` gives you the row type. Action files should normally import both `defineAction` and the table from the generated per-feature helper (`../.quickback/define-action`), which re-exports the table typed with the generated schema. See [Actions](/define/actions).
46
+
47
+ ### Import paths by authoring context
48
+
49
+ | File doing the import | Preferred import |
50
+ | --- | --- |
51
+ | `features/projects/issues.ts`, FK to its sibling | `import projects from "./projects"` |
52
+ | `features/projects/actions/assign.ts`, primary-table action | `import { defineAction, projects, issues } from "../.quickback/define-action"` |
53
+ | `features/projects/actions/issues/assign.ts`, sibling-table action | `import { defineAction } from "../../.quickback/define-action.issues"`; import tables from `../../.quickback/define-action` |
54
+ | Table FK to another feature | `import people from "../people/people"` |
55
+ | Action using another feature's table | Import the named table from that feature's generated helper, e.g. `import { people } from "../../people/.quickback/define-action"` from a flat `projects/actions/` file |
56
+
57
+ The primary helper re-exports **all tables in its feature**. A sibling-bound
58
+ helper `define-action.<table>` binds `record` and `whereRecord` to that sibling
59
+ for correctly typed mutations. Use it for `defineAction` in sibling actions;
60
+ import all table values from the primary helper. Direct named table imports from `feature()` files remain supported in
61
+ actions; prefer the helper for generated managed-column types. Relative paths
62
+ are measured from the importing file, not from the feature root.
46
63
 
47
64
  ## q.table() + defineTable() — the expanded form
48
65
 
49
- This is what `feature()` compiles into. Write it by hand only when another file needs the table identifier as a named export.
66
+ This is what `feature()` compiles into. Use this when you need direct control of the table declaration. A named import from a `feature()` file is also supported by `quickback check` and the build; a named import alone does not require switching to this form.
50
67
 
51
68
  ```typescript
52
69
  // quickback/features/jobs/jobs.ts
@@ -66,10 +83,10 @@ export const jobs = q.table('jobs', {
66
83
 
67
84
  export default defineTable(jobs, {
68
85
  guards: { /* ... */ },
69
- read: { /* ... */ },
70
- create: { /* ... */ },
71
- update: { /* ... */ },
72
- delete: { /* ... */ },
86
+ read: { access: { roles: ["owner", "hiring-manager", "recruiter", "interviewer"] } },
87
+ create: { access: { roles: ["owner", "hiring-manager"] } },
88
+ update: { access: { roles: ["owner", "hiring-manager"] } },
89
+ delete: { access: { roles: ["owner", "hiring-manager"] } },
73
90
  });
74
91
 
75
92
  export type Job = typeof jobs.$infer;
@@ -104,8 +121,41 @@ If `stageId` is null, the match is not required. The compiler rejects unknown
104
121
  columns or an unresolved target table. This is opt-in: some visible records
105
122
  may legitimately link across projects.
106
123
 
124
+ **Null-safe matches.** When "no project" is a value both rows can share, add
125
+ `nulls: 'equal'`. The comparison becomes null-safe (SQLite `IS`, Postgres
126
+ `IS NOT DISTINCT FROM`): a line with no project may point at a receipt with no
127
+ project, and a line with a project may not point at one without (or the other
128
+ way round).
129
+
130
+ ```ts
131
+ receiptId: q.text().required().references(() => receipts.id, {
132
+ match: { source: 'projectId', target: 'projectId', nulls: 'equal' },
133
+ }),
134
+ ```
135
+
136
+ The default, `nulls: 'distinct'`, is the strict rule above.
137
+
138
+ **Several rules on one FK.** `match` also takes a list, and every rule must
139
+ hold. A payment allocation that must carry its bill allocation's bill **and**
140
+ its project (or no project):
141
+
142
+ ```ts
143
+ billAllocationId: q.text().optional().references(() => billAllocations.id, {
144
+ match: [
145
+ { source: 'billId', target: 'billId' },
146
+ { source: 'projectId', target: 'projectId', nulls: 'equal' },
147
+ ],
148
+ }),
149
+ ```
150
+
151
+ A row with two optional FKs that must each agree with it, such as a credit
152
+ application tied to either a bill or a vendor credit, declares one `match` on
153
+ each FK. Whichever FK is set is checked.
154
+
107
155
  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
156
+ row, and for changes to the target's parent column (one pair per rule). They
157
+ are emitted the same way on a shared database and inside each
158
+ [tenant database](/configure/tenant-databases). Use the Quickback API for
109
159
  client writes; the triggers backstop generated CRUD, batch writes, changesets,
110
160
  and actions at the database boundary. Updating `projectId` while
111
161
  leaving `stageId` unchanged still checks the resulting pair. A mismatch returns
@@ -115,6 +165,23 @@ check existing rows for mismatches before rollout. The ordinary target
115
165
  [firewall check](/define/firewall#foreign-key-referential-checks) remains in
116
166
  place for generated CRUD writes.
117
167
 
168
+ ### Require the referenced row's state
169
+
170
+ `match` compares a column on both rows. To require something of the
171
+ referenced row itself (its kind, or that it isn't archived), add `requires`.
172
+ The database checks it from both sides: a source write that points at a
173
+ failing row is refused, and so is a target update that would break a live
174
+ reference.
175
+
176
+ ```ts
177
+ itemLineId: q.text().required().references(() => itemLines.id, {
178
+ requires: { kind: 'reimbursable' },
179
+ }),
180
+ ```
181
+
182
+ See [Invariants → requires](/define/invariants#requires-on-references) for the
183
+ condition syntax and the per-rule `when` form.
184
+
118
185
  > **Never FK Better Auth tables**
119
186
  >
120
187
  > `.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:
@@ -213,6 +280,52 @@ The schema must be written inline from `z` and literals, because the compiler co
213
280
  - using `z` anywhere else in the table file
214
281
  - importing anything from `zod` other than `{ z }`
215
282
 
283
+ #### Indexed JSON projections (SQLite)
284
+
285
+ Use `projections` in the second argument of `q.json(schema, options)` to index a stored scalar inside a typed JSON value. It is supported on `cloudflare-d1`, including organization databases in SQLite Durable Objects. The alias is a query name: it does not add a physical column, a response property, or a field clients can write.
286
+
287
+ ```typescript title="quickback/features/companies/companies.ts"
288
+ import { feature, q } from "@quickback/compiler";
289
+ import { z } from "zod";
290
+
291
+ export default feature("companies", {
292
+ columns: {
293
+ id: q.id(),
294
+ organizationId: q.scope("organization"),
295
+ metadata: q.json(z.object({
296
+ company: z.object({ industry: z.string().nullable() }).optional(),
297
+ score: z.number().optional(),
298
+ }), {
299
+ projections: {
300
+ industry: {
301
+ path: ["company", "industry"],
302
+ filterable: "in",
303
+ sortable: true,
304
+ index: { prefix: ["organizationId"] },
305
+ },
306
+ score: { path: ["score"], filterable: "range", sortable: true },
307
+ },
308
+ }).optional(),
309
+ ...q.audit(),
310
+ ...q.softDelete(),
311
+ },
312
+ guards: { createable: ["metadata"], updatable: ["metadata"] },
313
+ read: { access: { roles: ["member"] } },
314
+ create: { access: { roles: ["member"] } },
315
+ update: { access: { roles: ["member"] } },
316
+ });
317
+ ```
318
+
319
+ The same column options work in `q.table()` with `defineTable()`. The compiler infers `string`, `number` or `boolean` from the inline Zod schema. Optional and nullable properties are supported. `filterable: "eq"` enables equality and `.ne`; `"in"` adds `.in`; numeric `"range"` adds `.gt`, `.gte`, `.lt` and `.lte`. Declare at least one of `filterable` or `sortable: true`. A view can narrow these capabilities with `query.filterable` and `query.sortable`.
320
+
321
+ Paths must be nonempty literal arrays of property names made of ASCII letters, digits and underscores, beginning with a letter or underscore. Arrays, wildcards, objects, arbitrary SQL/JSONPath, dynamic options and ambiguous unions are rejected. Aliases begin with a letter, use the same alphabet, and must be unique across the table's JSON columns; physical column names, SQL column names, pagination controls and JavaScript prototype names are reserved. Table, source and prefix SQL identifiers use that safe property-name alphabet too. `sqlName` is supported within that restriction.
322
+
323
+ A projection cannot read an effectively masked, encrypted, sealed or write-only column, even if some roles can reveal that column. A `keys` entry with `derivedFrom` is also unavailable: it is computed after the SQL read. Stored organizer and platform keys can be indexed; their write authority is unchanged.
324
+
325
+ `index.prefix` names distinct physical scalar columns, in index order. It cannot name another projection or a JSON, array, encrypted or secret column. Each alias owns one non-unique expression index; no `id` suffix is added automatically. Sorting requires a non-null unique physical `id` column and uses the existing `id` tie-breaker in the query. Index names are bounded and derived from the SQL table, SQL source column and alias. Path/type/prefix edits replace that index; alias edits drop the old identity and create the new one. Existing rows need no application backfill, but building an index scans the table and consumes storage. Validate large tenant upgrades against your runtime budget before release.
326
+
327
+ Missing paths, JSON null, malformed legacy JSON, wrong scalar types, arrays/objects and non-finite numbers index as SQL NULL. No scalar coercion occurs. In particular a string `"2"` does not match a numeric projection. SQL comparison semantics apply: `.ne` does not select NULLs. See [JSON projection queries](/define/read#json-projection-queries) for pagination and API restrictions.
328
+
216
329
  #### Per-key write authority (`keys`)
217
330
 
218
331
  `createable` and `updatable` decide whether a client may write a column. One JSON column can mix keys a project member may change with keys only a platform operator may change (entitlements, plan features, feature flags). The second argument of `q.json(schema, opts)` can declare a tier for each key:
@@ -251,6 +364,7 @@ export default feature("projects", {
251
364
  | Option | Meaning |
252
365
  |--------|---------|
253
366
  | `sqlName` | SQL column name. The legacy positional form `q.json(schema, "col")` still works. |
367
+ | `projections.<alias>` | Indexed scalar query alias; see [Indexed JSON projections](#indexed-json-projections-sqlite). |
254
368
  | `keys.<key>.tier` | `"organizer"` (the default): an ordinary key. `"platform"`: see below. |
255
369
  | `keys.<key>.derivedFrom` | The key is computed from another table and never stored. Requires `tier: "platform"` and a `z.boolean()` property. |
256
370
 
@@ -437,6 +551,11 @@ r2Key: q.storageKey({
437
551
  placeholder before `{uuid}`. Each placeholder fills a whole path segment.
438
552
  - **Deleted with the row.** A hard delete through the generated routes or the
439
553
  action `db` deletes the object too.
554
+ - **Tenant tables** (`tenancy.isolation: 'durable-object'`) need
555
+ `tenancy.bridges.files`. The object reserves keys and records deletes. The
556
+ edge signs, verifies and deletes. A tenant upload stays `pending` until
557
+ `db.finalizeUpload` (or its grant's expiry) verifies it. See
558
+ [Tenant databases → Managed files](/configure/tenant-databases#managed-files).
440
559
 
441
560
  The column takes `.required()`, `.optional()`, `.unique()` and `.index()`.
442
561
  Other modifiers fail the compile. The template rules, the error codes, and the
@@ -641,9 +760,9 @@ export default defineTable(jobs, {
641
760
  createable: ["title", "department", "status", "salaryMin", "salaryMax"],
642
761
  updatable: ["title", "department", "status"],
643
762
  },
644
- create: { /* ... */ },
645
- update: { /* ... */ },
646
- delete: { /* ... */ },
763
+ create: { access: { roles: ["owner", "hiring-manager"] } },
764
+ update: { access: { roles: ["owner", "hiring-manager"] } },
765
+ delete: { access: { roles: ["owner", "hiring-manager"] } },
647
766
  });
648
767
 
649
768
  export type Job = typeof jobs.$inferSelect;
@@ -1320,6 +1439,14 @@ A self-reference is a normal FK everywhere else:
1320
1439
  - A batch create checks parents that exist **before** the batch. A record
1321
1440
  can't name a sibling from the same batch as its parent; create the parent
1322
1441
  first.
1442
+ - **No generated soft-delete cascade.** The generated DELETE route's
1443
+ soft-delete cascade reaches child rows in *other* tables only; it never
1444
+ follows a self-reference, so children stay live when their parent is
1445
+ soft-deleted. To take subtasks
1446
+ with their parent, declare an `afterUpdate` trigger on the soft-delete
1447
+ transition (it runs on every write path, not only the generated DELETE
1448
+ route); [Triggers → Soft-delete mapping](/define/triggers#soft-delete-mapping)
1449
+ has one that reaches every descendant.
1323
1450
 
1324
1451
  The legacy resource-level `references: { vendorId: "contact" }` map can override
1325
1452
  schema-registry target metadata for an alias, but it does not create a database
@@ -108,6 +108,7 @@ export default feature('guests', {
108
108
  email: { type: 'email', show: { roles: ['admin', 'scope:event:organizer'] } }, // hidden from the driver
109
109
  },
110
110
  read: {
111
+ access: { roles: ['admin', 'scope:event:organizer'] }, // full rows: staff only
111
112
  views: {
112
113
  manifest: {
113
114
  fields: ['id', 'nameAtInvite', 'shuttleId', 'pickupLocation'],
@@ -26,6 +26,15 @@ declared transitions with hand-written per-verb actions: you lose the
26
26
  generated routes, the `guards.protected` integration, and the CMS
27
27
  affordances.
28
28
 
29
+ A transition's `from` and `guard` are checked by the generated action. To
30
+ hold a state at the **database**, so that no action, batch or raw write can
31
+ undo it, pair transitions with [invariants](/define/invariants):
32
+ `frozen: { when: { status: 'posted' } }` stops a posted row changing,
33
+ `lockedBy` locks its child rows, and `restrict` with
34
+ `blocks: { enter: { status: 'withdrawn' } }` refuses entering a state while
35
+ other rows still point at the row (an existence check on the transition,
36
+ enforced by the database).
37
+
29
38
  ## Two lines per state change
30
39
 
31
40
  ```typescript
@@ -74,6 +74,89 @@ export default feature('invoices', {
74
74
 
75
75
  Events: `beforeInsert`, `afterInsert`, `beforeUpdate`, `afterUpdate`, `beforeDelete`, `afterDelete`. Each event takes an array of named triggers; names must be unique per event.
76
76
 
77
+ ## Awaited preparation (`prepare: true`)
78
+
79
+ On D1 with `changes.counter: true`, a before-handler can prepare a write using
80
+ scoped database reads and the stored row. Declare `prepare: true`; ordinary
81
+ before-handlers keep their synchronous, pending-values contract.
82
+
83
+ ```typescript
84
+ triggers: {
85
+ beforeUpdate: [{
86
+ name: 'calculateTotal',
87
+ prepare: true,
88
+ handler: async ({ row, old, values, db, ctx }) => {
89
+ // row is the stored row merged with the pending values.
90
+ // old is the stored row; values contains only the pending patch.
91
+ if (row.quantity < 1) throw new Error('quantity must be positive');
92
+ return { total: row.unitPrice * row.quantity };
93
+ },
94
+ }],
95
+ }
96
+ ```
97
+
98
+ Preparation runs once when the builder is awaited or passed to `db.batch`.
99
+ The runtime captures the organization's revision **before** loading the stored
100
+ row or running the handler. It executes the resulting mutation and revision
101
+ assertion in one native D1 batch. A concurrent change rejects the whole write
102
+ with `STALE_REVISION` (409), including ordinary CRUD writes. Retry by building a
103
+ new operation and reading fresh state. Awaiting the same prepared builder again
104
+ reuses its result.
105
+
106
+ The handler receives the authenticated `ctx`, the pending `values`, and merged
107
+ `row`. Update and delete handlers also receive `old`. Its `db` allows scoped
108
+ SELECT queries; writes, raw SQL execution, transactions, and batches are refused.
109
+ Return a partial object to derive fields or throw to reject. Scope and audit
110
+ fields are stamped by the write wrappers after preparation. Keep preparation
111
+ free of external side effects: a revision conflict can reject the eventual write.
112
+
113
+ This first version supports one inserted row or exactly one visible row for an
114
+ update/delete, with `values`/`set`, `where`, and optional `returning`. Bulk writes,
115
+ upserts, SQL-expression patches, direct executor methods, and precompiled
116
+ statements fail explicitly. Use individual builders inside `db.batch` for several
117
+ inserts. Lookups see committed data, so a child whose parent is created in that
118
+ same batch needs its derived values supplied by the action and checked by a SQL
119
+ invariant trigger at commit.
120
+
121
+ Prepared handlers run through the generated database wrappers; raw SQL still
122
+ bypasses JavaScript handlers. Use SQL triggers for invariants that must cover raw
123
+ imports. `prepare` cannot be combined with `async` or `withOld`; `async` remains
124
+ reserved for queued after-handlers.
125
+
126
+ ## Scoped integer sequences
127
+
128
+ D1 tables can declare a persistent sequence for invoice numbers, journal
129
+ references, or other integers allocated within an organization:
130
+
131
+ ```typescript
132
+ sequence: { field: 'number', scope: ['organizationId'], start: 1 },
133
+ unique: [{ columns: ['organizationId', 'number'] }],
134
+ ```
135
+
136
+ Declare `number` as `q.int().required()`. Every scope field must be required,
137
+ and the scope must include a `q.scope('organization')` column. The compiler
138
+ requires a non-partial unique constraint on the scope fields plus the number.
139
+ The field is server-managed: callers omit it, and explicit values are refused.
140
+
141
+ The generated insert computes the next number inside its SQL statement. A
142
+ database trigger validates and advances the compiler-owned
143
+ `_quickback_sequences` record atomically. `returning()` includes the assigned
144
+ number. Several individual inserts in a native `db.batch` receive consecutive
145
+ numbers; a failed batch rolls back both rows and sequence advancement. Deleting
146
+ a row does not make its number available again. When enabling a sequence on an
147
+ existing table, allocation starts above its current maximum.
148
+
149
+ Numbers and scope fields cannot change after insertion, including through raw
150
+ SQL. Integer overflow beyond JavaScript's safe range is rejected. Use one row
151
+ per INSERT statement; multi-row VALUES and upserts are explicitly unsupported.
152
+ This version supports D1 only. Raw SQL inserts must supply the exact next number
153
+ and are checked by the same database trigger.
154
+
155
+ With [`tenancy.isolation: 'durable-object'`](/configure/tenant-databases#change-signals-sequences-and-changesets),
156
+ a sequenced tenant table keeps `_quickback_sequences` in each organization's
157
+ Durable Object, with the same rules: each organization counts from its own
158
+ `start`, and a tenant `db.batch` is one object transaction.
159
+
77
160
  ## SQL triggers (`sql:`)
78
161
 
79
162
  The compiler owns the object names and ships the DDL in a journaled
@@ -234,6 +317,31 @@ raw-SQL hard deletes are still covered. `*Update` events get the inverse
234
317
  guard, so a soft delete fires delete triggers exactly once and never
235
318
  double-fires as an update.
236
319
 
320
+ One exception: an `*Update` trigger whose own `when:` requires the transition
321
+ (both `NEW."deleted_at" IS NOT NULL` and `OLD."deleted_at" IS NULL` as top-level
322
+ `AND` terms) is meant to run on it, and keeps its `when:` unchanged. Use this
323
+ when a soft-delete trigger needs `NEW` — an `afterDelete` body cannot use it,
324
+ because its hard-delete variant has only `OLD`:
325
+
326
+ ```ts
327
+ afterUpdate: [
328
+ {
329
+ name: "cascadeSoftDeleteToSubtasks",
330
+ when: `NEW."deleted_at" IS NOT NULL AND OLD."deleted_at" IS NULL`,
331
+ sql: `UPDATE "tasks" SET "deleted_at" = NEW."deleted_at", "deleted_by" = NEW."deleted_by"
332
+ WHERE "deleted_at" IS NULL AND "id" IN (SELECT "id" FROM (
333
+ WITH RECURSIVE "sub"("id") AS (
334
+ SELECT "id" FROM "tasks" WHERE "parent_id" = NEW."id"
335
+ UNION SELECT "t"."id" FROM "tasks" "t" JOIN "sub" ON "t"."parent_id" = "sub"."id"
336
+ ) SELECT "id" FROM "sub"));`,
337
+ },
338
+ ],
339
+ ```
340
+
341
+ This trigger cannot re-fire for the rows it updates (see [Recursion](#recursion)),
342
+ so it would reach only direct children. The recursive CTE soft-deletes
343
+ every descendant in one statement.
344
+
237
345
  Identical on both dialects. On Postgres the two delete variants are two
238
346
  functions, not one, because the transition trigger fires on `UPDATE` and
239
347
  returns `NEW` while the hard-delete one returns `OLD`.
@@ -396,9 +504,22 @@ insert type when a `sql:` body assigns it (`NEW."project_id" := …`) or a
396
504
 
397
505
  ## Choosing a lane
398
506
 
507
+ Most rejection triggers are one of a handful of shapes. Declare those as
508
+ [invariants](/define/invariants) rather than hand-writing the SQL: the
509
+ compiler emits the triggers, keeps them in step with the columns, and returns
510
+ a stable code.
511
+
399
512
  | Need | Use |
400
513
  |---|---|
401
- | Invariant that must hold universally (raw SQL included) | `sql:` with `RAISE(ABORT)` (D1) / `RAISE EXCEPTION` (Postgres) |
514
+ | Rows are never deleted (by anything, cascades included) | [`invariants.permanent`](/define/invariants#permanent) |
515
+ | Rows never change after insert, except a one-time stamp | [`invariants.appendOnly`](/define/invariants#appendonly) |
516
+ | A row (or some columns) can't change once in a state, or ever | [`invariants.frozen`](/define/invariants#frozen) |
517
+ | Child rows are locked while the parent is posted / sent / void | [`invariants.lockedBy`](/define/invariants#lockedby) |
518
+ | A referenced row must have a kind or state | [`.references(…, { requires })`](/define/invariants#requires-on-references) |
519
+ | No delete, change or state entry while referenced | [`invariants.restrict`](/define/invariants#restrict) |
520
+ | A column kept equal to an aggregate of child rows | [`invariants.derived`](/define/invariants#derived) |
521
+ | A parent's lines balance when each write commits | [`invariants.balanced`](/define/invariants#balanced) |
522
+ | Any other invariant that must hold universally (raw SQL included) | `sql:` with `RAISE(ABORT)` (D1) / `RAISE EXCEPTION` (Postgres) |
402
523
  | Denormalized columns, counters, tombstones | `sql:` |
403
524
  | Validation/derivation with application logic | `before*` `handler:` |
404
525
  | Side-effects after a write (notify, write related rows) | `after*` `handler:` |
@@ -473,6 +594,11 @@ feature](/configure/tenant-databases#platform-queues) the message goes through
473
594
  the tenant object's outbox before the response instead, with `tenantId` and
474
595
  `dedupeKey` stamped by the edge.
475
596
 
597
+ `afterCommit` hooks and `effects.enqueue` are best-effort: a Worker that dies
598
+ after the commit loses them. For a queue message that must commit with the
599
+ write, use [durable effects](/platform/database/durable-effects): pass
600
+ `effects` to an atomic `db.batch` on D1.
601
+
476
602
  Effects enqueued by an `execute` that later throws are dropped. The context
477
603
  also carries `now` — one ISO timestamp per invocation; prefer it over
478
604
  `new Date().toISOString()`. See [Column types](/define/schema#decimals-dates-64-bit-integers-and-arrays) for
@@ -72,20 +72,47 @@ column the caller may sort by but not see ([query params](/api/query-params)).
72
72
  ## Idempotency-Key
73
73
 
74
74
  Any `POST`/`PATCH`/`PUT`/`DELETE` may carry an `Idempotency-Key` header (a
75
- caller-generated UUID, ≤ 255 chars) to make the write safe to retry:
75
+ caller-generated UUID, ≤ 255 chars) for response replay and duplicate detection:
76
76
 
77
77
  - First request **claims** the key (the claim is the concurrency lock) and
78
78
  caches the response.
79
79
  - A retry with the same key replays the cached response byte-identically with
80
80
  `Idempotency-Replayed: true`.
81
81
  - A concurrent duplicate gets `409 IDEMPOTENCY_IN_PROGRESS`.
82
- - Reusing a key for a *different* request (method/path) is a
82
+ - Reusing a key for a *different* request (method/path, exact body bytes, query, content type or active organization) is a
83
83
  `422 IDEMPOTENCY_KEY_REUSED`.
84
- - Keys expire after **24 hours** (Stripe semantics); 5xx, `Set-Cookie` and
84
+ - Ordinary replay-cache keys expire after **24 hours**; 5xx, `Set-Cookie` and
85
85
  `Cache-Control: no-store` responses release the lock instead of caching. A
86
86
  `no-store` response (a grant code, a token) is never stored for any caller,
87
87
  so a retry re-runs the handler rather than replaying a secret.
88
88
 
89
+ **D1 atomic batches keep durable operation receipts.** When a request carrying
90
+ an `Idempotency-Key` executes scoped `db.batch`, Quickback persists an attempt
91
+ marker before submission and a commit marker in the same atomic batch as your
92
+ writes. After submission, errors, timeouts, `no-store` and cookie responses
93
+ cannot release the key for re-execution. A completed, replayable response is replayed as
94
+ usual. A caught timeout is not a completed batch: even if the handler returns
95
+ 2xx/4xx, Quickback keeps the unknown receipt pending. If the batch committed but its response was lost (including an after-hook
96
+ failure), retries return `409 IDEMPOTENCY_COMMITTED` with the key as a receipt
97
+ reference. This does not report that failed hooks succeeded and does not expose
98
+ internal result rows. If submission has an unresolved outcome, retries return
99
+ `409 IDEMPOTENCY_OUTCOME_UNKNOWN`; they never execute the operation again.
100
+
101
+ Atomic operation receipts do not expire or participate in stale-claim takeover.
102
+ An unresolved attempt requires operator reconciliation against application data;
103
+ Quickback does not currently provide an automatic reconciliation endpoint. Do
104
+ not submit a new key to work around an unknown outcome. One request claim can
105
+ commit one guarded batch; compose the operation's writes into that batch.
106
+ For financial operations, require callers to persist and reuse the same key.
107
+ Only acknowledged SQL rollback permits clearing an atomic attempt for retry.
108
+ If cleanup fails, the receipt stays fenced. `DB_BATCH_POST_COMMIT_FAILED` is a
109
+ 500 Problem with `details.committed: true`; `DB_BATCH_OUTCOME_UNKNOWN` has
110
+ `details.committed: null`. Neither permits automatic mutation retries. See the
111
+ [five transaction outcomes](/define/actions/scoped-db#transaction-outcomes-and-recovery).
112
+
113
+ Requests without the header retain atomicity but do not receive this replay
114
+ protection. Legacy cache rows without a request fingerprint are refused on reuse.
115
+
89
116
  The key is per **request**. For "this client-side record exists exactly
90
117
  once" across sessions and devices, store a per-**row** token instead — see
91
118
  [Row-token idempotency](/api/crud#row-token-idempotency).
@@ -96,7 +123,11 @@ principal, or a legacy row with no principal — is refused with a `422`
96
123
  Problem: the cached response body is **never served to a foreign
97
124
  principal**, and nothing beyond the `422` itself leaks. The comparison runs
98
125
  before the stale-claim takeover, so a foreign caller can neither read nor
99
- overwrite your claim.
126
+ overwrite your claim. Scope fingerprints encode sorted name/subject tuples, so
127
+ delimiter characters in a subject cannot impersonate another scope set. Existing
128
+ claims using the older delimiter encoding fail closed on collision; no old
129
+ response is reinterpreted under the new encoding. Ordinary unmarked cache rows
130
+ may be reused after their 24-hour expiry, with the old body cleared atomically.
100
131
 
101
132
  **Unauthenticated requests carrying the header are rejected (400)** — an
102
133
  anonymous caller has no principal to bind the claim to. Better Auth's own
@@ -79,17 +79,40 @@ Scopes are stored in metadata rather than Better Auth's `permissions` field beca
79
79
 
80
80
  ## Key prefix
81
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:
82
+ New keys read `<identifier>_<environment>_<random>`, so a key says which project and which environment it belongs to in logs and secret scanners:
83
+
84
+ ```
85
+ my_app_live_0b1fee88…
86
+ my_app_staging_7c2d41aa…
87
+ my_app_dev_3e90b5d1…
88
+ ```
89
+
90
+ The identifier defaults to the project name, slugged (`my-app` → `my_app_`). The environment segment is chosen at runtime:
91
+
92
+ | Worker | Segment |
93
+ |--------|---------|
94
+ | Named environment `production`, `prod`, or `live` | `live_` |
95
+ | Any other named environment | its own name — `staging_`, `dev_`, `pr-12_` |
96
+ | No named environments, `BETTER_AUTH_URL` on `localhost` / `127.0.0.1` / `[::1]` | `dev_` |
97
+ | No named environments, any other `BETTER_AUTH_URL` | `live_` |
98
+
99
+ Every named environment runs the same bundle, so when the `apiKey` plugin is on the compiler stamps `QUICKBACK_ENVIRONMENT = "<name>"` into each target's vars; the Worker reads it to pick the segment.
100
+
101
+ An environment name that can't be a segment fails the compile: other than `production`, `prod` and `live`, each name must be letters, digits and `-` only. `_` is refused because it would blur the `<identifier>_<environment>_` boundaries — rename `qa_east` to `qa-east`.
102
+
103
+ Override the identifier with the object form of the plugin:
83
104
 
84
105
  ```ts
85
106
  auth: defineAuth("better-auth", {
86
107
  plugins: {
87
- apiKey: { prefix: "acme_live_" },
108
+ apiKey: { prefix: "acme_" },
88
109
  },
89
110
  }),
90
111
  ```
91
112
 
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.
113
+ `prefix` is the identifier only — the environment segment is always appended (`acme_live_…`). It must be 1–32 characters of `A-Z a-z 0-9 _ -`, ending in `_` or `-`; anything else fails the compile.
114
+
115
+ The prefix is display-only — Better Auth hashes the whole key — so keys created before it (unprefixed, or `my_app_<random>` without an environment segment) keep verifying. `Authorization: Bearer` recognition matches the identifier, so every environment's keys and older `my_app_` keys are all accepted there.
93
116
 
94
117
  ## Banned owners
95
118
 
@@ -131,5 +131,8 @@ report every table as missing.
131
131
 
132
132
  The bundled Account UI uses `signIn.social` and `linkSocial` for generic OAuth
133
133
  providers, including Cloudflare. Their callback is
134
- `/auth/v1/oauth2/callback/cloudflare`; update the registered redirect URI when
135
- upgrading an existing Cloudflare login integration.
134
+ `/auth/v1/callback/cloudflare` on Better Auth 1.7. Register the full URL on
135
+ your Cloudflare OAuth client (for example,
136
+ `https://api.example.com/auth/v1/callback/cloudflare`). Earlier versions used
137
+ `/auth/v1/oauth2/callback/cloudflare`; add the current callback when upgrading.
138
+ Cloudflare rejects sign-in before consent if the exact redirect URI is absent.
@@ -302,7 +302,7 @@ Sending `x-api-key` together with a session cookie or an `Authorization` header
302
302
 
303
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).
304
304
 
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.
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 and environment prefix (`my_app_live_…` / `my_app_staging_…`; [Key prefix](/platform/auth/api-keys#key-prefix)), a banned owner's keys stop working, and each key is rate limited.
306
306
 
307
307
  ### OAuth Provider (MCP-ready)
308
308
 
@@ -0,0 +1,37 @@
1
+ # Organization Defaults
2
+
3
+ Every Better Auth project ships `organizationDefaults()`, a Better Auth plugin the compiler emits into `src/plugins/organization-defaults/` and adds to `src/lib/auth.ts` alongside `organization()`. It needs no configuration.
4
+
5
+ ## Reserved organization slugs
6
+
7
+ An organization slug becomes a URL segment: `/account/<slug>` in the Account UI, and `<appUrl>/<slug>` in your app with the default `tenantPattern`. A slug that matches a route shadows it. An organization called `security` could never open its own page, and one called `admin` or `support` impersonates something it isn't.
8
+
9
+ The plugin refuses about 150 reserved slugs with `400` and `code: "ORGANIZATION_SLUG_RESERVED"` on:
10
+
11
+ - `POST /auth/v1/organization/create`
12
+ - `POST /auth/v1/organization/update` (renaming the slug)
13
+ - `POST /auth/v1/organization/check-slug`, so the Account UI's "is this URL available" check agrees with the write
14
+ - the operator route `POST /auth/v1/admin/create-organization`, which writes the row directly and applies the same rule
15
+
16
+ Matching is exact and case-insensitive: `home` is reserved, `home-depot` is not. The list covers:
17
+
18
+ - every top-level Account UI route (`home`, `profile`, `security`, `dashboard`, `login`, …)
19
+ - auth and account words (`settings`, `billing`, `members`, `invite`, `oauth`, …)
20
+ - platform paths (`api`, `cms`, `app`, `static`, `webhooks`, `www`, …)
21
+ - roles and system accounts (`admin`, `root`, `sysadmin`, `superuser`, `system`, …)
22
+ - common shell commands (`sudo`, `ls`, `rm`, `cd`, `git`, `curl`, …)
23
+ - values that read as code (`null`, `undefined`, `true`, `localhost`, `env`, …)
24
+
25
+ The full list is `RESERVED_ORGANIZATION_SLUGS` in `src/plugins/organization-defaults/reserved-slugs.ts`. A compiler test fails if a new top-level Account UI route is missing from it.
26
+
27
+ Organizations that already hold a reserved slug keep it. Updates that don't change the slug still work, but the org's Account page is shadowed by the route until it is renamed.
28
+
29
+ ## Default active organization
30
+
31
+ New sessions start with no active organization, so the app, the CMS, and org-scoped API calls have nothing to default to. The plugin fills that gap when the choice is unambiguous:
32
+
33
+ - **Pinned project** (`features.pinnedOrganizationId`): a member of the pinned organization starts every session in it.
34
+ - **One membership**: the session starts in that organization.
35
+ - **Several memberships, or none**: nothing is chosen; the user picks an organization in the app or the Account UI.
36
+
37
+ It never overrides an active organization the session already carries. The Account UI applies the same rule client-side for sessions created before the plugin existed.
@@ -89,6 +89,8 @@ When organizations are enabled, the active organization is on the auth context a
89
89
  const orgId = c.get('ctx').activeOrgId;
90
90
  ```
91
91
 
92
+ A new session starts in the user's organization when the choice is unambiguous (the pinned organization, or their only membership). With several memberships, `activeOrgId` stays unset until the user picks one. See [Organization Defaults](/platform/auth/plugins/organization-defaults).
93
+
92
94
  > **`activeOrgId`, not `activeOrganizationId`**
93
95
  >
94
96
  > `activeOrganizationId` is Better Auth's *session* field name (`session.session.activeOrganizationId`). Quickback canonicalises it to `ctx.activeOrgId`; firewall rules written against `ctx.activeOrganizationId` are rewritten to `ctx.activeOrgId` at compile time.