@quickback-dev/cli 0.60.9 → 0.61.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/docs/content.d.ts +7 -0
  2. package/dist/docs/content.d.ts.map +1 -0
  3. package/dist/docs/content.js +737 -0
  4. package/dist/docs/content.js.map +1 -0
  5. package/dist/index.js +1 -1
  6. package/dist/lib/helpers.d.ts +39 -0
  7. package/dist/lib/helpers.d.ts.map +1 -0
  8. package/dist/lib/helpers.js +299 -0
  9. package/dist/lib/helpers.js.map +1 -0
  10. package/dist/skill/docs/api/errors.md +1 -0
  11. package/dist/skill/docs/api/query-params.md +26 -0
  12. package/dist/skill/docs/changelog/index.md +79 -0
  13. package/dist/skill/docs/configure/auth.md +17 -12
  14. package/dist/skill/docs/configure/domains.md +1 -1
  15. package/dist/skill/docs/configure/index.md +5 -5
  16. package/dist/skill/docs/define/actions/index.md +18 -0
  17. package/dist/skill/docs/define/areas.md +90 -7
  18. package/dist/skill/docs/define/feature.md +88 -27
  19. package/dist/skill/docs/define/index.md +7 -1
  20. package/dist/skill/docs/define/scopes.md +1 -1
  21. package/dist/skill/docs/define/security.md +10 -0
  22. package/dist/skill/docs/define/transitions.md +11 -35
  23. package/dist/skill/docs/platform/auth/jwt-optimization.md +15 -3
  24. package/dist/skill/docs/platform/database/d1.md +6 -1
  25. package/dist/skill/docs/platform/realtime/index.md +17 -0
  26. package/dist/skill/docs/platform/webhooks/outbound.md +31 -6
  27. package/dist/skill/docs/start/deploy-browser.md +15 -6
  28. package/dist/skill/docs/start/first-api.md +16 -0
  29. package/dist/skill/docs/ui/account/features/admin.md +29 -5
  30. package/dist/skill/docs/ui/account/features/index.md +22 -0
  31. package/dist/skill/docs/ui/admin/connecting.md +6 -4
  32. package/dist/skill/docs/ui/admin/index.md +49 -10
  33. package/dist/skill/docs/ui/admin/security.md +6 -7
  34. package/package.json +1 -1
  35. package/src/skill/docs/api/errors.md +1 -0
  36. package/src/skill/docs/api/query-params.md +26 -0
  37. package/src/skill/docs/changelog/index.md +79 -0
  38. package/src/skill/docs/configure/auth.md +17 -12
  39. package/src/skill/docs/configure/domains.md +1 -1
  40. package/src/skill/docs/configure/index.md +5 -5
  41. package/src/skill/docs/define/actions/index.md +18 -0
  42. package/src/skill/docs/define/areas.md +90 -7
  43. package/src/skill/docs/define/feature.md +88 -27
  44. package/src/skill/docs/define/index.md +7 -1
  45. package/src/skill/docs/define/scopes.md +1 -1
  46. package/src/skill/docs/define/security.md +10 -0
  47. package/src/skill/docs/define/transitions.md +11 -35
  48. package/src/skill/docs/platform/auth/jwt-optimization.md +15 -3
  49. package/src/skill/docs/platform/database/d1.md +6 -1
  50. package/src/skill/docs/platform/realtime/index.md +17 -0
  51. package/src/skill/docs/platform/webhooks/outbound.md +31 -6
  52. package/src/skill/docs/start/deploy-browser.md +15 -6
  53. package/src/skill/docs/start/first-api.md +16 -0
  54. package/src/skill/docs/ui/account/features/admin.md +29 -5
  55. package/src/skill/docs/ui/account/features/index.md +22 -0
  56. package/src/skill/docs/ui/admin/connecting.md +6 -4
  57. package/src/skill/docs/ui/admin/index.md +49 -10
  58. package/src/skill/docs/ui/admin/security.md +6 -7
@@ -88,7 +88,7 @@ The unified domain is useful for development and debugging. You can override it
88
88
  export default {
89
89
  name: "my-app",
90
90
  template: "hono",
91
- cms: { domain: "cms.example.com", access: "admin" },
91
+ cms: { domain: "cms.example.com", access: "sysadmin" },
92
92
  account: {
93
93
  domain: "auth.example.com",
94
94
  adminDomain: "admin.example.com",
@@ -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` | `{ version?: "v1" \| "v2" }` | Public API/auth contract version. Omit for the backward-compatible v1 default; select v2 for `/api/v2/*` and `/auth/v2/*` across generated routes, Better Auth, OpenAPI, MCP, and discovery. |
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`/`profileUrl`, `domain`) — see [Access](/define/access#role-hierarchy) and [Delegated principals](#delegated-principals-contract-v2) |
99
+ | `auth` | `object` | App-level auth settings (`roleHierarchy`, `jwt`, delegated `principals`, `loginUrl`, `domain`) — see [Access](/define/access#role-hierarchy) and [Delegated principals](#delegated-principals-contract-v2) |
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 |
@@ -574,7 +574,7 @@ cms: true,
574
574
  cms: { domain: "cms.example.com" },
575
575
 
576
576
  // With access control (only admins can access CMS)
577
- cms: { domain: "cms.example.com", access: "admin" },
577
+ cms: { domain: "cms.example.com", access: "sysadmin" },
578
578
 
579
579
  // Cross-tenant DB-admin tier — sysadmins see every tenant's data
580
580
  cms: { domain: "cms.example.com", sysadmin: true },
@@ -592,11 +592,11 @@ Quickback's default model assumes every CMS user belongs to at least one organiz
592
592
 
593
593
  `cms: { sysadmin: true }` introduces a separate role tier:
594
594
 
595
- - **Role**: `user.role === "sysadmin"` (set on the Better Auth user table). Distinct from `"appmanager"` — appmanagers keep platform control-plane access (CMS shell, Better Auth admin surfaces, support tooling), while sysadmins get true cross-tenant data access. `ADMIN` is now a rejected legacy pseudo-role; use `userRole: ["appmanager"]` for control-plane gates and `roles: ["SYSADMIN"]` for cross-tenant access.
595
+ - **Role**: `user.role === "sysadmin"` (set on the Better Auth user table). Distinct from `"appmanager"` — appmanagers keep platform control-plane access (Better Auth admin surfaces, organization and user management, support tooling — but NOT the CMS), while sysadmins get true cross-tenant data access. `ADMIN` is now a rejected legacy pseudo-role; use `userRole: ["appmanager"]` for control-plane gates and `roles: ["SYSADMIN"]` for cross-tenant access.
596
596
  - **Firewall**: every `buildFirewallConditions()` emits an `if (ctx.userRole === "sysadmin") return undefined` (or just the soft-delete predicate when present) at the top, so sysadmins see every tenant's rows. See [Firewall escape hatch](/define/firewall#sysadmin-escape-hatch).
597
597
  - **Org listing**: a `GET /auth/v1/admin/list-organizations` endpoint selects directly from the auth-schema `organization` table — every row, every tenant. Sits under Better Auth's admin URL namespace (sibling of `/auth/v1/admin/list-users`) so the URL shape matches BA convention; the handler is Quickback-emitted and gated to `user.role === "sysadmin"` only. For the membership-bound caller's-orgs listing, use BA's own `/auth/v1/organization/list`.
598
598
  - **CMS SPA**: when the user is a sysadmin, the header switcher loads from the cross-tenant endpoint, defaults to "All organizations" (which omits `?organizationId=` and reaches the firewall escape), and pins selected tenants via `?organizationId=` on every API call. Org admins keep the existing membership-based switcher.
599
- - **CMS HTML gate**: admits `userRole === "sysadmin"` alongside `"appmanager"`. Org admins are not locked out when you set `cms.access: "user"`; `cms.access: "admin"` is specifically the platform control-plane gate.
599
+ - **CMS gate**: `cms.access: "sysadmin"` (the default) admits the `sysadmin` tier only; `cms.access: "member"` also admits any caller with an organization membership. `appmanager` opens the CMS in neither mode — see [Access gate](/ui/admin#access-gate).
600
600
 
601
601
  Off by default. Projects that don't enable it get zero behavior change; setting `cms.sysadmin: true` and granting a user `user.role = "sysadmin"` is the only way to unlock the cross-tenant view.
602
602
 
@@ -754,7 +754,7 @@ A complete config with CMS, Account UI, and Admin on separate subdomains:
754
754
  export default {
755
755
  name: "my-app",
756
756
  template: "hono",
757
- cms: { domain: "cms.example.com", access: "admin" },
757
+ cms: { domain: "cms.example.com", access: "sysadmin" },
758
758
  account: {
759
759
  domain: "auth.example.com",
760
760
  adminDomain: "admin.example.com",
@@ -2,6 +2,23 @@
2
2
 
3
3
  Actions are custom API endpoints for business logic beyond CRUD operations. They enable workflows, integrations, and complex operations.
4
4
 
5
+ ## Before you write one — four primitives that may already do it
6
+
7
+ An action is a file you own and maintain. These are declarations the compiler
8
+ owns, and each generates the same real endpoint, OpenAPI operation, and MCP
9
+ tool, on the same firewall/access/guards pipeline. Check all four first — the
10
+ most common needless action is one of these hand-rolled.
11
+
12
+ | If the action would… | Declare instead | Where |
13
+ |---|---|---|
14
+ | check a row's current state, flip a column, stamp who/when | `transitions` on the table — plus `guard`, `stamp`/`clears` (which makes `execute` optional), `idempotent`, `undo`, `onEnter` cascades | [Transitions](/define/transitions) |
15
+ | write a parent row plus its owned children in one call | `changesets` — declare the `owns` boundary; each op still pays the child's own firewall, access, and guards | [Changesets](/define/changesets) |
16
+ | fire a side-effect after a write — denormalize a counter, stamp a column, enqueue a job | `triggers` — SQL triggers cover **every** write path (REST, actions, cron, raw SQL), not just the one route you remembered | [Triggers](/define/triggers) |
17
+ | return the same rows with a different column set per role | `read.views` — its own route, access rule, pagination, and masking | [Views](/define/views) |
18
+
19
+ Write the action for the remainder: third-party calls, multi-step orchestration,
20
+ AI/streaming responses, anything genuinely imperative.
21
+
5
22
  ## Overview
6
23
 
7
24
  Quickback supports two types of actions:
@@ -83,5 +100,6 @@ generated output.
83
100
  - **[Examples](/define/actions/examples)** — end-to-end action files
84
101
 
85
102
  Related: **[Transitions](/define/transitions)** for state-machine policy,
103
+ **[Changesets](/define/changesets)** for aggregate writes,
86
104
  **[Triggers](/define/triggers)** for after-commit hooks, and the
87
105
  **[Actions API](/api/actions)** for calling an action over HTTP.
@@ -55,6 +55,13 @@ quickback/features/
55
55
  The gate here is `collaboratorOf` — a row in *your* `project_collaborators` table. That's what
56
56
  makes it an area: the answer isn't in `ctx.roles` already.
57
57
 
58
+ **Folder membership is the whole opt-in, and it is all-or-nothing.** Every feature in the folder
59
+ inherits the prefix and the gate; there is no per-feature or per-table marker to opt out. To keep
60
+ a feature flat, put it outside the area folder. The one per-*action* escape is
61
+ [`route: 'self'`](#containment-and-the-route-self-marker), and it exists for actions that must
62
+ live in the subtree yet answer off-prefix — a collection route or a `create`, which by definition
63
+ has no row to be related to yet. See [Where `create` goes](#where-create-goes).
64
+
58
65
  Reserved sub-directories (`actions/`, `lib/`, `pages/`) are never child features. A directory
59
66
  **without** `_area.ts` is a leaf feature — its unreserved subdirectories are not loaded, and a
60
67
  subdirectory containing `defineTable(...)` / `defineAction(...)` **fails the compile** (silent
@@ -74,7 +81,10 @@ export default defineArea({
74
81
 
75
82
  // Inherited route mount + admission gate. Optional: an area with no
76
83
  // prefix contributes shared vocabulary only. A prefix REQUIRES at least
77
- // one `via` lane (a mounted prefix with no gate would be ungated).
84
+ // one `via` lane (a mounted prefix with no gate would be ungated), and at
85
+ // least one `:param` segment — the gate runs as middleware, before any
86
+ // request body is parsed, so `c.req.param()` is the only place it can read
87
+ // the resource key from. `prefix: '/project'` is a compile error.
78
88
  prefix: '/project/:projectId',
79
89
  via: ['collaboratorOf', { roles: ['admin', 'owner'] }],
80
90
  mintScope: true,
@@ -105,6 +115,23 @@ export default defineArea({
105
115
  });
106
116
  ```
107
117
 
118
+ > **A bare string in `via:` is a relationship name — never a role name**
119
+ >
120
+ > `via: ['collaboratorOf']` names a **relationship** declared in `relationships:`. Roles go in an
121
+ > object lane: `via: [{ roles: ['admin', 'owner'] }]`, and those are Better Auth **org roles**, not
122
+ > your composed `roles:` entries. A relationship name that isn't declared fails with *"lane
123
+ > &lt;name&gt; is not declared in authz.relationships"*; a role name in the string position fails the
124
+ > same way, because the compiler has no reason to think you meant a role.
125
+ >
126
+ > `via:` accepts exactly three lane shapes:
127
+ >
128
+ > | Lane | Passes when |
129
+ > |---|---|
130
+ > | `'collaboratorOf'` | a row in the named relationship links the caller to the `:param` row |
131
+ > | `{ roles: ['admin'] }` | the caller's Better Auth org role on the row's tenant matches |
132
+ > | `{ team: true }` | `ctx.activeTeamId` is set (the loads-table firewall does the row check) |
133
+
134
+
108
135
  A descendant feature references everything by bare name — no imports, no root declaration:
109
136
 
110
137
  {/* doc-compile: skip — cross-fence dependency: the relative `path: './tasks/add'` and the `projectStaff` role both resolve against the `_area.ts` in the fence directly above, and the area is the whole point of the example. The gate compiles each fence as an isolated project, so this feature has no ancestor area to inherit a prefix from. */}
@@ -142,8 +169,10 @@ is genuinely global.
142
169
  Two structural rules keep the fold sound:
143
170
 
144
171
  - **No overrides (v1).** Re-declaring an inherited name — in any class, including scope kinds,
145
- scoped-role aliases, and namespace names — is a compile error. Declare each name in exactly
146
- one place. (`overrides:` marker syntax is reserved for a future release.)
172
+ scoped-role aliases, and namespace names — is a compile error. Declare each name in exactly one
173
+ place; the fix is always to **delete the duplicate**, keeping the declaration in the deepest
174
+ area that owns it. There is no merge, no shadowing, and no override mechanism. (`overrides:` is
175
+ a reserved key name for a future release — it does nothing today and is not the fix.)
147
176
  - **Declaration-site rule.** Root `authz` bodies (roles, rules, tenants, scopes, namespaces)
148
177
  may reference **root-declared names only** — a root definition is visible everywhere and
149
178
  would launder an area name out of its subtree. An area's bodies may reference root ∪
@@ -156,6 +185,12 @@ manifest under the owning area.
156
185
 
157
186
  ## Containment and the `route: 'self'` marker
158
187
 
188
+ `route: 'self'` marks **one standalone action, inside the area folder, whose `path:` is outside
189
+ the area's prefix**. It is a label on a path you already chose — not a switch that moves a route
190
+ or exempts a feature. Outside those exact conditions the compiler rejects it: on an action whose
191
+ path is *inside* the prefix (the gate applies; the marker is dead), and in a feature with no
192
+ ancestor area that mounts a prefix (there is nothing to opt out of).
193
+
159
194
  The area's prefix is an audited surface:
160
195
 
161
196
  - A feature **outside** the area may not declare an action path (or a table-level
@@ -175,6 +210,44 @@ The area's prefix is an audited surface:
175
210
  Relative paths (`path: './…'`) resolve against the area prefix. Dot segments (`.` / `..`) are
176
211
  rejected outright — the resolved route must stay under the prefix.
177
212
 
213
+ ### Where `create` goes
214
+
215
+ An area gate answers *"is the caller related to **this** row?"* — so it cannot gate the action
216
+ that creates the row. `POST /conversations` has no `:conversationId` to prove anything about.
217
+ Same for the collection list: `GET /conversations` is a query across rows, not a request about one.
218
+
219
+ Split by cardinality, not by feature:
220
+
221
+ ```
222
+ features/conversations/
223
+ ├── _area.ts prefix: '/conversations/:conversationId'
224
+ │ via: ['participant']
225
+ ├── conversations.ts the table — resource path '/conversations'
226
+ │ (collection + create; NOT under the prefix)
227
+ ├── startConversation.ts path: '/conversations', route: 'self'
228
+ └── messages/ everything per-conversation — gated by the area
229
+ └── messages.ts path: './messages' → /conversations/:conversationId/messages
230
+ ```
231
+
232
+ `startConversation` stays in the folder, so it still reads the area's relationships and roles by
233
+ bare name, and `route: 'self'` says out loud that it is gated by its own `access:` only —
234
+ `{ roles: ['member'] }`, or whatever "may open a conversation" means in your app. Its job is to
235
+ insert the row *and* the `conversation_members` row that makes the caller a participant; every
236
+ route under the prefix works from there.
237
+
238
+ Two constraints fall out of the same split:
239
+
240
+ - **The area prefix must carry a `:param`.** `prefix: '/conversations'` is a compile error — the
241
+ gate runs as middleware, before the body is parsed, so `c.req.param()` is the only key it can
242
+ read.
243
+ - **A generated table router under the prefix needs a relationship lane.** The compiler mounts a
244
+ table's CRUD behind an area gate only when the area has one; a bulk-grant-only `via:` can't
245
+ anchor the resolver, and the table is rejected rather than mounted unscoped. A table whose path
246
+ sits outside the prefix (like `conversations` above) is unaffected.
247
+
248
+ Scoping the collection itself — "don't list conversations I'm not in" — is
249
+ [firewall](/define/firewall) work on the table, not area work.
250
+
178
251
  ## Nested areas
179
252
 
180
253
  Areas nest to arbitrary depth. A nested area may declare additional **vocabulary** freely. A
@@ -217,6 +290,17 @@ Root `authz` remains the home for genuinely global vocabulary — names used acr
217
290
  flat features. Everything scoped to one concept belongs in that concept's `_area.ts`. When in
218
291
  doubt: if only one folder's features reference it, it belongs in that folder's area.
219
292
 
293
+ ## Common mistakes
294
+
295
+ | Symptom | Cause | Fix |
296
+ |---|---|---|
297
+ | *"lane &lt;name&gt; is not declared in authz.relationships"* | A role name in the string position of `via:`. | Bare strings name **relationships** only. Roles go in `{ roles: [...] }` — and those are Better Auth org roles, not your composed `roles:`. |
298
+ | *"…has at least one RELATIONSHIP lane… this one does not"* on a table under the prefix | `via:` is bulk-grant-only (`{ roles }` / `{ team }`), which can't anchor the resolver. | Add a relationship lane, or move the table's path outside the prefix. Wrapping a relationship-backed role in `{ roles: [...] }` does **not** make it a relationship lane. |
299
+ | *"prefix … must contain at least one `:param` segment"* | The prefix names a collection (`/conversations`). | The gate is per-row: `/conversations/:conversationId`. Collection and `create` routes belong outside the prefix — see [Where `create` goes](#where-create-goes). |
300
+ | *"already declared at …"* / *"Overrides are not supported in v1"* | The same name declared in two places. | Delete one. Keep it in the deepest area that owns it. `overrides:` is reserved and does nothing. |
301
+ | A feature in the folder should not be area-scoped | Membership is the folder — no per-feature opt-out exists. | Move it out of the folder, or (single action only) give it an off-prefix `path:` and `route: 'self'`. |
302
+ | *"path is OUTSIDE that prefix … mark it explicitly with `route: 'self'`"* | Intentional off-prefix action, or a typo in the path. | If intentional, add `route: 'self'`. If not, fix the path — this error exists so a typo can't silently self-gate. |
303
+
220
304
  ## Namespace mounts (hoisted relationship middleware)
221
305
 
222
306
  When several standalone actions share a path prefix and the same relationship gate — `/event/:eventId/announce`, `/event/:eventId/cancel`, `/event/:eventId/respond` — declaring the gate per-action means writing the same `roles: ['attendee']` over and over AND paying the relationship-resolver cost N times per request (one subquery + one row-load, multiplied by the number of actions).
@@ -374,7 +458,7 @@ authz: {
374
458
  }
375
459
  ```
376
460
 
377
- All relationship lanes in a namespace **must agree on `loads:` + `exposeAs:`** — that's what guarantees `ctx.event` has the same shape regardless of which lane matched. The compiler rejects heterogeneous lanes at parse time.
461
+ Hydration is **per matched lane** (v0.37+): each lane fills `ctx.<its own exposeAs>` from its own `loads:` table, so lanes may load different tables into different keys. Both lanes above name `events` / `event`, so `ctx.event` is populated whichever fires. A lane declaring neither `loads:` nor `exposeAs:` is authorization-only — it opens the gate and hydrates nothing.
378
462
 
379
463
  ### Bulk-grant lanes (v0.26+)
380
464
 
@@ -413,9 +497,8 @@ Actions opt in by matching `path:` against a declared namespace prefix. There's
413
497
 
414
498
  Both forms share the same shape checks:
415
499
 
416
- - **`via:` accepts one of three shapes.** A single relationship name (v0.23+), an array of relationship names (v0.25+, first match wins), or — as of v0.26 — an array mixing relationship names with bulk-grant guards (`{ roles: [...] }`, `{ team: true }`).
417
- - **Every relationship lane must declare `loads + exposeAs`.** Without `loads` there's nothing for the middleware to hydrate; the namespace gate would be indistinguishable from a per-action access rule.
418
- - **All relationship lanes in one namespace must agree on `loads:` + `exposeAs:`.** Otherwise `ctx.<exposeAs>` would change shape depending on which lane matched.
500
+ - **`via:` accepts one of three shapes.** A single relationship name (v0.23+), an array of relationship names (v0.25+, first match wins), or — as of v0.26 — an array mixing relationship names with bulk-grant guards (`{ roles: [...] }`, `{ team: true }`). **A bare string is always a relationship name.** There is no string form for a role: `{ roles: [...] }` is a bulk-grant lane against Better Auth org roles, even when the name you put in it is a composed role defined `via` a relationship.
501
+ - **Each relationship lane declares `loads` + `exposeAs`, or neither.** Both → the lane hydrates `ctx.<exposeAs>` from `loads` when it matches. Neither → an authorization-only lane. Exactly one is a compile error.
419
502
  - **Bulk-grant lanes inherit `loads:` + `exposeAs:` from sibling relationship lanes.** Pure bulk-grant namespaces (no relationship lane at all) are also accepted — set `loads:` + `exposeAs:` directly on the namespace declaration so hydration has somewhere to anchor.
420
503
  - **`prefix:` must contain at least one `:param` segment** (e.g. `/event/:eventId`). The middleware reads the relationship key from `c.req.param()` because no request body has been parsed at middleware time.
421
504
  - **One declaration per namespace name.** The same name in both `defineTable({ namespace })` and `authz.namespaces` is rejected. The project-level form is canonical for cross-feature; the table-level form is the single-feature shorthand.
@@ -1,35 +1,56 @@
1
1
  # feature() — the canonical form
2
2
 
3
- `feature()` is **the** way to write a Quickback feature: one file, one default export, the table and its security contract together. The older `q.table()` + `defineTable()` pair still exists underneath (it's what `feature()` expands into), but it means two exports and two concepts for something a feature file treats as one unit.
3
+ `feature()` is **the** way to write a Quickback feature: one file, one default export, the table and its security contract together. It expands at compile time into `q.table()` + `defineTable()`, which stays available for the cases that need it — see [When to use which](#when-to-use-which).
4
4
 
5
- ## Before
5
+ ## Quick reference
6
6
 
7
- ```ts title="quickback/features/contacts.ts"
8
- import { q, defineTable } from "@quickback/compiler";
9
-
10
- export const contacts = q.table("contacts", {
11
- id: q.id(),
12
- organizationId: q.text().required().index(),
13
- address: q.text().required().index(),
14
- name: q.text().optional(),
15
- ...q.audit(),
16
- ...q.softDelete(),
17
- });
7
+ One object. Everything a table exposes is a key in it, and every key is optional
8
+ except `columns`.
18
9
 
19
- export default defineTable(contacts, {
20
- firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],
21
- // "+" role expansion requires auth.roleHierarchy in quickback.config.ts
22
- read: { access: { roles: ["member+"] } },
23
- create: { access: { roles: ["member+"] } },
24
- update: { access: { roles: ["member+"] } },
25
- delete: { access: { roles: ["admin+"] }, mode: "soft" },
26
- guards: { createable: ["address", "name"] },
10
+ {/* doc-compile: skip — key map, not a config: every value is an empty placeholder. The compiled forms are in the fences below and on each key's own page. */}
11
+ ```ts
12
+ feature("name", {
13
+ columns: {}, // q.* column helpers — the Drizzle schema
14
+
15
+ // Security — the five pillars
16
+ firewall: {}, // which ROWS (auto-derived from organizationId / ownerId / teamId)
17
+ read: {}, // who may read + `views` — named column projections
18
+ create: {}, // who may write
19
+ update: {},
20
+ delete: {}, // + `mode: "soft" | "hard"`
21
+ guards: {}, // which FIELDS a caller may set
22
+ masking: {}, // which VALUES come back redacted
23
+ rateLimit: {}, // per-operation caps
24
+
25
+ // Endpoints beyond CRUD — declared here, not written as action files
26
+ transitions: {}, // guarded state changes → POST /:id/{name}
27
+ triggers: {}, // before/after hooks on every write
28
+ owns: {}, // composition boundary → atomic parent+children writes
29
+ realtime: {}, // broadcast insert/update/delete
30
+ embeddings: {}, // vectors generated on write
31
+
32
+ // Placement + presentation
33
+ path: "", // route base (defaults to the feature name)
34
+ namespace: {}, // hoisted route prefix + admission gate
35
+ displayColumn: "", defaultSort: {}, inputHints: {}, layouts: {}, references: {},
27
36
  });
28
-
29
- export type Contact = typeof contacts.$infer;
30
37
  ```
31
38
 
32
- ## After
39
+ | You want | Key | Page |
40
+ |---|---|---|
41
+ | Tenant isolation, role gates, field and value control | `firewall`, `read`/`create`/`update`/`delete`, `guards`, `masking` | [Security](/define/security) |
42
+ | A narrower shape for a broader audience | `read.views` | [Views](/define/views) |
43
+ | `publish` / `approve` / `checkIn` — a state change | `transitions` | [Transitions](/define/transitions) |
44
+ | A side-effect or data rule on every write | `triggers` | [Triggers](/define/triggers) |
45
+ | Parent plus its children written atomically | `owns` | [Changesets](/define/changesets) |
46
+ | Clients updated live | `realtime` | [Realtime](/platform/realtime/using-realtime) |
47
+ | Semantic search over the table | `embeddings` | [Embeddings](/platform/vector/using-embeddings) |
48
+ | The CMS to render it well | `displayColumn`, `defaultSort`, `inputHints`, `layouts` | [CMS](/ui/admin/table-views) |
49
+
50
+ The rest of this page is the form itself; [One object, not just
51
+ CRUD](#one-object-not-just-crud) shows the non-CRUD keys filled in.
52
+
53
+ ## The form
33
54
 
34
55
  ```ts title="quickback/features/contacts.ts"
35
56
  import { feature, q } from "@quickback/compiler";
@@ -37,13 +58,12 @@ import { feature, q } from "@quickback/compiler";
37
58
  export default feature("contacts", {
38
59
  columns: {
39
60
  id: q.id(),
40
- organizationId: q.text().required().index(),
61
+ organizationId: q.scope("organization"), // firewall auto-derives from this
41
62
  address: q.text().required().index(),
42
63
  name: q.text().optional(),
43
64
  ...q.audit(),
44
65
  ...q.softDelete(),
45
66
  },
46
- firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],
47
67
  // "+" role expansion requires auth.roleHierarchy in quickback.config.ts
48
68
  read: { access: { roles: ["member+"] } },
49
69
  create: { access: { roles: ["member+"] } },
@@ -53,7 +73,48 @@ export default feature("contacts", {
53
73
  });
54
74
  ```
55
75
 
56
- Type inference still works — `typeof import("./contacts").default.$infer` gives you the `Contact` row type.
76
+ Type inference comes with it — `typeof import("./contacts").default.$infer` gives you the `Contact` row type.
77
+
78
+ ## One object, not just CRUD
79
+
80
+ The example above declares security and CRUD because that is the floor. The same
81
+ config object carries every other per-table capability — a live feed, a state
82
+ machine, a narrower projection, a write hook. They are keys next to `read:` and
83
+ `guards:`, not separate files or services, and each generates a real endpoint on
84
+ the same firewall → access → guards → masking pipeline.
85
+
86
+ {/* doc-compile: skip — shape sketch: `columns` is elided so the keys stay readable side by side, and `member+`/`admin+` need `auth.roleHierarchy` in quickback.config.ts. Each key's own page carries the compiled version. */}
87
+ ```ts
88
+ export default feature("episodes", {
89
+ columns: { /* … */ },
90
+ firewall: [{ field: "organizationId", equals: "ctx.activeOrgId" }],
91
+ read: {
92
+ access: { roles: ["member+"] },
93
+ views: { public: { fields: ["id", "title"], access: { roles: ["member+"] } } },
94
+ },
95
+ guards: { updatable: ["title"], protected: { isPublished: ["publish"] } },
96
+ masking: { submitterEmail: { type: "email", show: { roles: ["admin"] } } },
97
+ transitions: { publish: { field: "isPublished", from: false, to: true, access: { roles: ["admin+"] } } },
98
+ realtime: { enabled: true, onInsert: true, onUpdate: true },
99
+ embeddings: { fields: ["title", "summary"] },
100
+ });
101
+ ```
102
+
103
+ | Key | Gives you | Reference |
104
+ |---|---|---|
105
+ | `read.views` | Named column projections, each with its own route and access rule | [Views](/define/views) |
106
+ | `transitions` | Guarded state changes generated as real `POST /:id/{name}` actions — guards, stamps, `undo`, cascades | [Transitions](/define/transitions) |
107
+ | `triggers` | `before`/`after` hooks on write, lowered to a real SQL trigger or an application handler | [Triggers](/define/triggers) |
108
+ | `realtime` | Per-table broadcasts on insert/update/delete, audience-scoped | [Realtime](/platform/realtime/using-realtime) |
109
+ | `owns` | The composition boundary that turns on atomic parent-plus-children writes | [Changesets](/define/changesets) |
110
+ | `embeddings` | Vector embeddings generated on insert/update | [Embeddings](/platform/vector/using-embeddings) |
111
+ | `masking` / `rateLimit` / `namespace` | Field redaction, per-operation caps, a hoisted route prefix + gate | [Masking](/define/masking), [Rate limit](/define/rate-limit), [Areas](/define/areas) |
112
+ | `displayColumn` / `defaultSort` / `inputHints` / `layouts` / `references` | How the CMS renders the table — no runtime effect | [CMS](/ui/admin/table-views) |
113
+
114
+ Reach for these before writing an action file: an action is code you maintain,
115
+ these are declarations the compiler owns. See the full option list in
116
+ [Definitions Overview](/define#other-resource-options) and the "before you write
117
+ one" routing table at the top of [Actions](/define/actions).
57
118
 
58
119
  ## How it works
59
120
 
@@ -273,6 +273,9 @@ Beyond the five security layers, `defineTable` accepts a handful of declarative
273
273
  | Option | What it does | Full reference |
274
274
  |---|---|---|
275
275
  | `views` | Named column projections — `GET /resource/views/{name}` returns a subset of columns under its own access rule. | [Views](/define/views) |
276
+ | `transitions` | Guarded state changes — each entry generates a real `POST /resource/:id/{name}` action file, with guards, stamps, idempotency, `undo` inverses, and `onEnter` cascades. | [Transitions](/define/transitions) |
277
+ | `changesets` | An `owns` boundary — write the parent row and its owned relations in one atomic request, each op paying the child's own firewall, access, and guards. | [Changesets](/define/changesets) |
278
+ | `triggers` | `before`/`after` hooks on `insert`/`update`/`delete`, lowering either to a real SQL trigger in your migrations or to an application handler at the write chokepoint. | [Triggers](/define/triggers) |
276
279
  | `references` | Explicit FK target table for columns that don't follow the "Id"-stripped convention (e.g. `vendorId → contact`). | [CMS Schema Registry](/ui/admin/schema-registry) |
277
280
  | `displayColumn` | Column to use as the human-readable label in FK resolutions and CMS list views (auto-detected as `name`/`title`/`label` if not set). | [CMS Table Views](/ui/admin/table-views) |
278
281
  | `defaultSort` | Default sort order for CMS list rendering (`{ field, order: "asc" \| "desc" }`). | [CMS Table Views](/ui/admin/table-views) |
@@ -294,4 +297,7 @@ All options are optional — omit them and Quickback uses sensible defaults (aut
294
297
  6. [Rate Limit](/define/rate-limit) — Per-operation request caps
295
298
  7. [Views](/define/views) — Column-level security
296
299
  8. [Validation](/define/validation) — Field validation rules
297
- 9. [Actions](/define/actions) — Add custom business logic
300
+ 9. [Transitions](/define/transitions) — Guarded state changes, generated as real endpoints
301
+ 10. [Changesets](/define/changesets) — Atomic parent-plus-owned-relations writes
302
+ 11. [Triggers](/define/triggers) — Data rules and side-effects on write
303
+ 12. [Actions](/define/actions) — Custom business logic, for what the above can't express
@@ -635,7 +635,7 @@ The scope claim is trusted between proofs — it is never re-checked against the
635
635
 
636
636
  So removing a guest/staff row takes effect within **cap + one TTL** for a client that keeps polling, and within one TTL once it goes idle. Two ways to tighten that:
637
637
 
638
- - **`auth.jwt.revocationCheck: 'kv'`** (v0.45+, Cloudflare runtime) — sub-TTL revocation: updating or deleting a conferring relationship row stamps a revocation timestamp in KV, and the bearer fast-path rejects a carried scope claim whose proof (`sct`) predates it. See [auth config](/configure/auth).
638
+ - **`auth.jwt.revocationCheck: 'kv'`** (v0.45+, Cloudflare runtime) — sub-TTL revocation: updating or deleting a conferring relationship row stamps a revocation timestamp in KV, and the bearer fast-path rejects a carried scope claim whose proof (`sct`, with its millisecond companion `sctMs`) is at or before it — no same-second gap. Both halves of the proof time are carried forward verbatim by the rolling refresh; a refresh never substitutes its own mint time for proof time. The check fails closed — a scope claim whose revocation state can't be read is not trusted either. See [auth config](/configure/auth).
639
639
  - **`via` arms** — for tables where any caching is too wide, gate with a `via` arm instead of a bare `ctx.scope.<kind>` arm: `via` emits a live subquery against the relationship table on every request, immune to a stale claim entirely.
640
640
 
641
641
  ## Reference
@@ -94,6 +94,16 @@ omitted from the generated request schemas entirely, so a client cannot even sen
94
94
  caller's role. Use it for data the caller may legitimately address but should not read
95
95
  in full.
96
96
 
97
+ **State changes** — `protected: { status: ["publish", "cancel", "refund"] }` removes the
98
+ column from the PATCH schema and names the only doors to it. Each name is an action:
99
+ either a [transition](/define/transitions) the compiler generates from
100
+ `transitions: { publish: { field: "status", from: "draft", to: "live", access: {...} } }`,
101
+ or an [action file](/define/actions) you write when the change needs real logic — a
102
+ `refund` that calls Stripe, then sets the column. Both carry their own `access` rule and
103
+ appear in OpenAPI; the transition additionally gets row guards, stamps, and an `undo`
104
+ inverse for free. Declare the transition when the change is state plus stamps; write the
105
+ action when it is genuinely imperative. Either beats leaving the column freely writable.
106
+
97
107
  ## Advanced authorization
98
108
 
99
109
  When roles are not enough — when access depends on a *relationship* between the caller
@@ -3,43 +3,19 @@
3
3
  ## Overview
4
4
 
5
5
  Most state changes follow the same shape: check the row is in a legal state,
6
- flip a column, stamp who/when, maybe cascade. Before transitions v2 every one
7
- of those was a hand-written action file — a podcast app had **ten files that
8
- were byte-identical except the table name** (`publish.ts` / `revertToDraft.ts`
9
- across five entities), and an events app had eight near-identical
10
- check-in/check-out files.
6
+ flip a column, stamp who/when, maybe cascade. Declare that shape on the table
7
+ and the compiler generates the action files — including `undo` inverses and
8
+ `onEnter` cascades.
11
9
 
12
- Transitions v2 collapses both patterns:
10
+ Two declaration sites:
13
11
 
14
- - **Action-level extensions** on `defineAction({ transition })` — guards,
15
- stamps, idempotency, compiler-applied writes.
16
- - **Table-level `transitions`** on `defineTable` — the compiler *generates*
17
- the action files, including `undo` inverses and `onEnter` cascades.
12
+ - **Table-level `transitions`** on `defineTable` — the compiler generates the
13
+ actions. Start here.
14
+ - **Action-level `transition`** on `defineAction` — the same guards, stamps,
15
+ idempotency, and compiler-applied writes, for an action you are writing
16
+ anyway.
18
17
 
19
- ## The marquee example: 10 files → 2 lines each
20
-
21
- Before (×10 files across episodes/shows/seasons/collections/profiles):
22
-
23
- ```typescript
24
- // actions/episodes/publish.ts — and nine siblings like it
25
- import { z } from "zod";
26
- import { eq } from "drizzle-orm";
27
- import { defineAction, episodes } from "../../.quickback/define-action.episodes";
28
-
29
- export default defineAction({
30
- description: "Publish an episode",
31
- input: z.object({}),
32
- access: { roles: ["admin+"] },
33
- async execute({ db, record }) {
34
- const [updated] = await db.update(episodes)
35
- .set({ isPublished: true })
36
- .where(eq(episodes.id, record.id)).returning();
37
- return updated;
38
- },
39
- });
40
- ```
41
-
42
- After — on each entity's `defineTable`:
18
+ ## Two lines per state change
43
19
 
44
20
  ```typescript
45
21
  // features/podcast/episodes.ts
@@ -62,7 +38,7 @@ export default defineTable(episodes, {
62
38
  });
63
39
  ```
64
40
 
65
- The generated actions mount exactly where the hand-written files did
41
+ The generated actions mount exactly where an authored file would
66
42
  (`POST /episodes/:id/publish`, operationId `episodesPublish`, same MCP tool
67
43
  name), ride the same OpenAPI/security-contract pipeline, and delete cleanly:
68
44
  **an explicit `actions/<name>.ts` file always wins** (the compiler warns about
@@ -27,9 +27,12 @@ The JWT encodes everything needed for auth middleware:
27
27
  | `userRole` | Global user role (when admin panel is enabled) |
28
28
  | `email` | User email |
29
29
  | `name` | User display name |
30
- | `iat` | Issued-at timestamp |
30
+ | `iat` | Issued-at timestamp (unix **seconds**, the standard claim) |
31
+ | `iatMs` | Issued-at in epoch **milliseconds** — Quickback ordering metadata, not a standard claim. Same clock sample as `iat`, set by the signer only. Lets [revocation](#revocation--revocationcheck-kv) order a token against a marker written in the same second |
31
32
  | `exp` | Expiry — **180 seconds** (3 minutes) after `iat` by default; set via [`auth.jwt.expiresIn`](/configure/auth) |
32
33
 
34
+ Scope-bearing tokens also carry `sct` (proof timestamp, unix seconds) and its millisecond companion `sctMs` — see [Scopes](/define/scopes). Read `iat` / `sct` from external tooling; `iatMs` / `sctMs` exist only so revocation can break ties inside a second.
35
+
33
36
  ### Signing
34
37
 
35
38
  JWTs are signed with HMAC-SHA256 using your `BETTER_AUTH_SECRET` — the same secret you already set for Better Auth, so there is only one secret to manage.
@@ -113,7 +116,9 @@ auth: {
113
116
  },
114
117
  ```
115
118
 
116
- The fast-path then consults per-principal revocation timestamps in your project's existing `KV` binding (keys prefixed `qbrev:`, self-expiring) *before* trusting a token. A token is rejected when its mint timestamp (`iat`, or `sct` for the scope claim) predates the stored timestamp. Cost: 2+ edge-cached KV reads per bearer verify.
119
+ The fast-path then consults per-principal revocation timestamps in your project's existing `KV` binding (keys prefixed `qbrev:`, self-expiring) *before* trusting a token. A token is rejected when its mint timestamp (`iat`/`iatMs`, or `sct`/`sctMs` for the scope claim) is **at or before** the stored timestamp. Cost: 2+ edge-cached KV reads per bearer verify.
120
+
121
+ There is no same-second gap: markers are epoch milliseconds (written `m<ms>`, v0.61.0+), tokens carry millisecond companions, and the comparison denies a tie — so a token minted a few milliseconds *before* the revocation is rejected, while one legitimately re-minted *after* it in that same second is still accepted. Pre-v0.61.0 workers don't understand that marker format and read it as "not revoked" — don't roll back across the upgrade or share one KV namespace between versions; see [`revocationCheck`](/configure/auth#revocationcheck-none--kv--token-revocation-strategy).
117
122
 
118
123
  Revocation stamps are written **automatically** on:
119
124
 
@@ -125,7 +130,14 @@ The generated `src/lib/jwt-revocation.ts` exports `revokeUserTokens`, `revokeMem
125
130
 
126
131
  > **Honest limits**
127
132
  >
128
- > The KV check revokes **per principal**, not per session; it **fails open** if KV is unreachable (degrading to the TTL bound rather than locking bearers out); and stamps propagate cross-PoP in roughly 60 seconds. A rejected token falls through to session auth, which re-checks membership and re-mints — an active legitimate session recovers transparently. For fail-closed semantics, use `expiresIn: 30` instead.
133
+ > The KV check revokes **per principal**, not per session, and stamps propagate cross-PoP in roughly 60 seconds — "immediate" means seconds, not instantaneous.
134
+ >
135
+ > It **fails closed** for bearer auth: if the KV binding is missing or the read fails, the bearer is *not* authenticated — a signature is all that is known about it — and the caller gets a retryable **`503 AUTH_REVOCATION_UNAVAILABLE`**. Recovery is a **separate cookie-only request**, not a fallback inside the same one: a request carrying `Authorization` has its cookie stripped before session auth (bearer is an alternative to the cookie, not a supplement), so during a KV outage every JWT-bearer request gets the 503 until the client retries on its session cookie. A *revoked* token behaves the same way, and a cookie request re-checks membership and re-mints transparently.
136
+
137
+
138
+ > **Operational consequence**
139
+ >
140
+ > Enabling `revocationCheck: 'kv'` ties bearer-token availability to KV. Alert on `AUTH_REVOCATION_UNAVAILABLE` — a sustained rate means the binding is gone (check that every deployment target declares it) or KV itself is degraded. If you want the TTL bound *without* that coupling, leave `revocationCheck` at `'none'` and set `expiresIn: 30`.
129
141
 
130
142
 
131
143
  Full knob-by-knob reference: [Auth & JWT config → `revocationCheck`](/configure/auth#revocationcheck-none--kv--token-revocation-strategy).
@@ -254,10 +254,15 @@ target:
254
254
  npm run deploy:dev # wrangler deploy --env dev
255
255
  npm run deploy:production # wrangler deploy --env production
256
256
 
257
- npm run db:migrate:dev:auth:remote # wrangler d1 migrations apply my-app-auth-dev --remote
257
+ npm run db:migrate:dev:auth:remote # …apply my-app-auth-dev --remote --env dev
258
258
  npm run db:migrate:dev:remote # fan-out over every declared role
259
259
  ```
260
260
 
261
+ Every migration script carries `--env`. With the top-level blocks suppressed,
262
+ a bare database name has no scope to resolve in and wrangler fails with
263
+ `Couldn't find a D1 DB with the name or binding '<name>'` — so a hand-run
264
+ `wrangler d1 migrations apply` needs the flag too.
265
+
261
266
  The contract fails closed:
262
267
 
263
268
  - Better Auth is required, and a logical `dev` target must exist (it is what
@@ -90,6 +90,23 @@ export default feature("applications", {
90
90
  > `access.roles` — it still compiles but should be migrated.)
91
91
 
92
92
 
93
+ Omitting it fails the compile:
94
+
95
+ ```text
96
+ Resource "conversations" enables realtime broadcasts but declares no audience.
97
+ A broadcast fans out to every subscriber in the room, so the audience is not
98
+ optional. Declare realtime.access: { roles: [...] } naming who may receive it
99
+ (use roles: ['PUBLIC'] to broadcast to everyone in the room, deliberately).
100
+ ```
101
+
102
+ **The audience is a second read surface, and it does not inherit `read.access`.**
103
+ Whatever gates the REST read must gate the broadcast too, or the live channel
104
+ publishes rows the REST route would have withheld — private messages being the
105
+ usual casualty. Copy the read rule across, and where the read is gated by a
106
+ relationship (participants of a conversation, accepted followers), use
107
+ `access: { authzRole: "<relationship-role>" }` here rather than falling back to
108
+ `roles: ["AUTHENTICATED"]`, which reaches every signed-in subscriber.
109
+
93
110
  And enable the realtime **transport** in your database config. This is a
94
111
  project-level switch that stands up the Broadcaster Durable Object + the
95
112
  connection route; it does **not** by itself make any resource broadcast