@quickback-dev/cli 0.59.0 → 0.59.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/dist/commands/compile.d.ts.map +1 -1
  2. package/dist/commands/compile.js +14 -1
  3. package/dist/commands/compile.js.map +1 -1
  4. package/dist/commands/schema.d.ts +10 -0
  5. package/dist/commands/schema.d.ts.map +1 -1
  6. package/dist/commands/schema.js +48 -16
  7. package/dist/commands/schema.js.map +1 -1
  8. package/dist/commands/schema.test.js +81 -1
  9. package/dist/commands/schema.test.js.map +1 -1
  10. package/dist/docs/content.d.ts.map +1 -1
  11. package/dist/docs/content.js +48 -28
  12. package/dist/docs/content.js.map +1 -1
  13. package/dist/index.js +1 -1
  14. package/dist/lib/file-loader.d.ts +10 -0
  15. package/dist/lib/file-loader.d.ts.map +1 -1
  16. package/dist/lib/file-loader.js +41 -22
  17. package/dist/lib/file-loader.js.map +1 -1
  18. package/dist/lib/file-loader.test.js +20 -1
  19. package/dist/lib/file-loader.test.js.map +1 -1
  20. package/dist/lib/prepare-output.d.ts +2 -0
  21. package/dist/lib/prepare-output.d.ts.map +1 -1
  22. package/dist/lib/prepare-output.js +2 -2
  23. package/dist/lib/prepare-output.js.map +1 -1
  24. package/dist/lib/prepare-state-output.d.ts +33 -4
  25. package/dist/lib/prepare-state-output.d.ts.map +1 -1
  26. package/dist/lib/prepare-state-output.js +71 -12
  27. package/dist/lib/prepare-state-output.js.map +1 -1
  28. package/dist/lib/prepare-state-output.test.js +91 -11
  29. package/dist/lib/prepare-state-output.test.js.map +1 -1
  30. package/dist/lib/schema-sync/index.d.ts.map +1 -1
  31. package/dist/lib/schema-sync/index.js +39 -4
  32. package/dist/lib/schema-sync/index.js.map +1 -1
  33. package/dist/lib/schema-sync/index.test.js +89 -1
  34. package/dist/lib/schema-sync/index.test.js.map +1 -1
  35. package/dist/schema-engine/index.d.ts +1 -0
  36. package/dist/schema-engine/index.d.ts.map +1 -1
  37. package/dist/schema-engine/index.js +50 -0
  38. package/dist/schema-engine/index.js.map +3 -3
  39. package/dist/schema-engine/provider-dialects.d.ts +22 -0
  40. package/dist/schema-engine/provider-dialects.d.ts.map +1 -0
  41. package/dist/schema-engine/source-sync.d.ts +8 -0
  42. package/dist/schema-engine/source-sync.d.ts.map +1 -1
  43. package/dist/skill/SKILL.md +45 -0
  44. package/dist/skill/agents/quickback-specialist/AGENT.md +18 -1
  45. package/dist/skill/docs/changelog/index.md +28 -2
  46. package/dist/skill/docs/changelog/v0.1x.md +2 -2
  47. package/dist/skill/docs/configure/agents.md +19 -0
  48. package/dist/skill/docs/configure/index.md +1 -1
  49. package/dist/skill/docs/define/access.md +23 -820
  50. package/dist/skill/docs/define/actions/access.md +4 -4
  51. package/dist/skill/docs/define/areas.md +307 -4
  52. package/dist/skill/docs/define/authz-roles.md +164 -0
  53. package/dist/skill/docs/define/changesets.md +1 -1
  54. package/dist/skill/docs/define/fga.md +1 -1
  55. package/dist/skill/docs/define/firewall.md +3 -3
  56. package/dist/skill/docs/define/index.md +32 -3
  57. package/dist/skill/docs/define/masking.md +1 -1
  58. package/dist/skill/docs/define/permissions.md +1 -1
  59. package/dist/skill/docs/define/read.md +103 -1
  60. package/dist/skill/docs/define/relationships.md +313 -0
  61. package/dist/skill/docs/define/scopes.md +1 -1
  62. package/dist/skill/docs/platform/realtime/using-realtime.md +1 -1
  63. package/dist/skill/docs/platform/storage/r2.md +39 -0
  64. package/dist/skill/docs/platform/webhooks/inbound.md +17 -6
  65. package/dist/skill/docs/start/deploy-browser.md +118 -0
  66. package/dist/skill/docs/start/deploy-owner-access.md +62 -0
  67. package/dist/skill/docs/start/deploy.md +2 -0
  68. package/dist/skill/docs/tooling/cli.md +22 -0
  69. package/dist/skill/docs/tooling/cloud-compiler/endpoints.md +1 -1
  70. package/dist/skill/docs/tooling/cloud-compiler/local-compiler.md +3 -5
  71. package/dist/skill/docs/tooling/output.md +72 -1
  72. package/dist/skill/docs/ui/account/environment-variables.md +3 -3
  73. package/dist/skill/docs/ui/account/features/admin.md +2 -2
  74. package/dist/skill/docs/ui/account/features/passkeys.md +1 -1
  75. package/dist/skill/docs/ui/account/index.md +1 -1
  76. package/dist/skill/docs/ui/account/with-quickback.md +5 -9
  77. package/package.json +1 -1
  78. package/src/skill/SKILL.md +45 -0
  79. package/src/skill/agents/quickback-specialist/AGENT.md +18 -1
  80. package/src/skill/docs/changelog/index.md +28 -2
  81. package/src/skill/docs/changelog/v0.1x.md +2 -2
  82. package/src/skill/docs/configure/agents.md +19 -0
  83. package/src/skill/docs/configure/index.md +1 -1
  84. package/src/skill/docs/define/access.md +23 -820
  85. package/src/skill/docs/define/actions/access.md +4 -4
  86. package/src/skill/docs/define/areas.md +307 -4
  87. package/src/skill/docs/define/authz-roles.md +164 -0
  88. package/src/skill/docs/define/changesets.md +1 -1
  89. package/src/skill/docs/define/fga.md +1 -1
  90. package/src/skill/docs/define/firewall.md +3 -3
  91. package/src/skill/docs/define/index.md +32 -3
  92. package/src/skill/docs/define/masking.md +1 -1
  93. package/src/skill/docs/define/permissions.md +1 -1
  94. package/src/skill/docs/define/read.md +103 -1
  95. package/src/skill/docs/define/relationships.md +313 -0
  96. package/src/skill/docs/define/scopes.md +1 -1
  97. package/src/skill/docs/platform/realtime/using-realtime.md +1 -1
  98. package/src/skill/docs/platform/storage/r2.md +39 -0
  99. package/src/skill/docs/platform/webhooks/inbound.md +17 -6
  100. package/src/skill/docs/start/deploy-browser.md +118 -0
  101. package/src/skill/docs/start/deploy-owner-access.md +62 -0
  102. package/src/skill/docs/start/deploy.md +2 -0
  103. package/src/skill/docs/tooling/cli.md +22 -0
  104. package/src/skill/docs/tooling/cloud-compiler/endpoints.md +1 -1
  105. package/src/skill/docs/tooling/cloud-compiler/local-compiler.md +3 -5
  106. package/src/skill/docs/tooling/output.md +72 -1
  107. package/src/skill/docs/ui/account/environment-variables.md +3 -3
  108. package/src/skill/docs/ui/account/features/admin.md +2 -2
  109. package/src/skill/docs/ui/account/features/passkeys.md +1 -1
  110. package/src/skill/docs/ui/account/index.md +1 -1
  111. package/src/skill/docs/ui/account/with-quickback.md +5 -9
@@ -12,9 +12,9 @@ access: {
12
12
  }
13
13
  ```
14
14
 
15
- If the same role expression shows up on more than one action or resource, define it once in `authz.roles` and reference it by name — see [Centrally defined access rules](/define/access#centrally-defined-access-rules).
15
+ If the same role expression shows up on more than one action or resource, define it once in `authz.roles` and reference it by name — see [Centrally defined access rules](/define/authz-roles#centrally-defined-access-rules).
16
16
 
17
- [Named gates](/define/access#named-gates-authzrules) (`authz.rules`) also work in an action's `roles: [...]` array — a who-only gate expands as its `who`, a who+`record` gate as `{ and: [who, { record }] }` (the record predicate is evaluated against the bound record, exactly like an inline `access.record`). Function-form `access` is opaque to the rewrite and is left untouched.
17
+ [Named gates](/define/authz-roles#named-gates-authzrules) (`authz.rules`) also work in an action's `roles: [...]` array — a who-only gate expands as its `who`, a who+`record` gate as `{ and: [who, { record }] }` (the record predicate is evaluated against the bound record, exactly like an inline `access.record`). Function-form `access` is opaque to the rewrite and is left untouched.
18
18
 
19
19
  **A firewall-bearing gate on an action is a compile error.** An action has no firewall array — there is no row query for the gate's lanes to constrain before execution — so the compiler refuses rather than letting the row lanes silently not apply. The escape hatch: split the gate into a who-rule referenced from the action plus a firewall-only gate stamped on the owning resource's `firewall:`.
20
20
 
@@ -148,7 +148,7 @@ export default defineAction({
148
148
  The standalone action's surface (path params + input fields) must expose the
149
149
  relationship's `resource.column`. A missing key is a compile error, so the
150
150
  resolver can never be skipped silently. See [Access — standalone
151
- actions](/define/access#standalone-actions-surface-keys-and-loads--exposeas-v019)
151
+ actions](/define/relationships#standalone-actions-surface-keys-and-loads--exposeas-v019)
152
152
  for the full mechanism.
153
153
 
154
154
  For a record-based action, Quickback already has the firewalled record in
@@ -182,6 +182,6 @@ the firewall, because the record supplies the relationship key. No manual
182
182
  lookup or firewall exception is required.
183
183
 
184
184
  See [Access — relationship
185
- authorization](/define/access#relationship-based-authorization)
185
+ authorization](/define/relationships)
186
186
  for the full surface matrix, namespace hoisting, and tenant-context stamping.
187
187
 
@@ -8,6 +8,26 @@ outside the folder cannot reference any of it: the compiler fails the build.
8
8
  > Naming note: this concept is an **area**. `domain` in Quickback always means a DNS custom
9
9
  > domain (see [custom domains](/configure/domains)).
10
10
 
11
+ ## Do you need one?
12
+
13
+ An area is [rung 3](/define#the-authorization-ladder) — reach for it only when a subtree shares
14
+ a URL prefix **and** a per-row admission gate. Most apps never need one.
15
+
16
+ | You want | Use |
17
+ |---|---|
18
+ | Every row scoped to the caller's tenant | Nothing — `organizationId: q.scope('organization')` already does it. **Not an area.** |
19
+ | Routes grouped under a shared path, no per-row gate | A `path` on each feature |
20
+ | A shared role/rule vocabulary, no route prefix | Root [`authz.roles`](/define/authz-roles#centrally-defined-access-rules) — or an area with no `prefix` |
21
+ | Everything under `/project/:projectId` gated by "is the caller on this project?", with the project row hydrated onto `ctx` | **An area** |
22
+
23
+ > **An area is not multi-tenancy**
24
+ >
25
+ > The gated thing is a **row inside a tenant** — this project, this event, this location. Your
26
+ > tenant boundary is the Better Auth organization and the firewall, and it is already in place
27
+ > before any area runs. An area named after your tenant (`workspace/`, `team/`, `tenant/`) is a
28
+ > sign that tenancy is being modeled twice — see [Tenancy is not yours to model](/define#tenancy-is-not-yours-to-model).
29
+
30
+
11
31
  ## Why
12
32
 
13
33
  Cross-cutting authz for a concept like a project, an event, or a location used to live in the
@@ -20,7 +40,7 @@ never leaks outside the subtree.
20
40
 
21
41
  ```
22
42
  quickback/features/
23
- ├── workspace/ ← AREA (has _area.ts)
43
+ ├── project/ ← AREA (has _area.ts)
24
44
  │ ├── _area.ts ← defineArea({...})
25
45
  │ ├── projects.ts ← the area folder may itself be a feature
26
46
  │ ├── project_collaborators.ts
@@ -32,6 +52,9 @@ quickback/features/
32
52
  └── billing/ ← flat feature (unchanged)
33
53
  ```
34
54
 
55
+ The gate here is `collaboratorOf` — a row in *your* `project_collaborators` table. That's what
56
+ makes it an area: the answer isn't in `ctx.roles` already.
57
+
35
58
  Reserved sub-directories (`actions/`, `lib/`, `pages/`) are never child features. A directory
36
59
  **without** `_area.ts` is a leaf feature — its unreserved subdirectories are not loaded, and a
37
60
  subdirectory containing `defineTable(...)` / `defineAction(...)` **fails the compile** (silent
@@ -42,7 +65,7 @@ moving a feature into an area changes nothing about its generated identity.
42
65
  ## `_area.ts`
43
66
 
44
67
  ```typescript
45
- // features/workspace/_area.ts
68
+ // features/project/_area.ts
46
69
  import { defineArea } from '@quickback/compiler';
47
70
 
48
71
  export default defineArea({
@@ -86,7 +109,7 @@ A descendant feature references everything by bare name — no imports, no root
86
109
 
87
110
  {/* 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. */}
88
111
  ```typescript
89
- // features/workspace/tasks/actions/addTask.ts
112
+ // features/project/tasks/actions/addTask.ts
90
113
  import { z } from "zod";
91
114
  import { defineAction } from "../.quickback/define-action";
92
115
 
@@ -111,7 +134,7 @@ nested areas). The compiler checks **every** reference channel — access `roles
111
134
 
112
135
  ```
113
136
  Feature "billing" ... references role "projectStaff" declared by area "projectScope"
114
- (features/workspace/_area.ts), but this site is not inside that area. ... move the
137
+ (features/project/_area.ts), but this site is not inside that area. ... move the
115
138
  referencing code under the declaring area, or lift the declaration to root authz if it
116
139
  is genuinely global.
117
140
  ```
@@ -193,3 +216,283 @@ features correctly.
193
216
  Root `authz` remains the home for genuinely global vocabulary — names used across areas or by
194
217
  flat features. Everything scoped to one concept belongs in that concept's `_area.ts`. When in
195
218
  doubt: if only one folder's features reference it, it belongs in that folder's area.
219
+
220
+ ## Namespace mounts (hoisted relationship middleware)
221
+
222
+ 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).
223
+
224
+ Namespace mounts hoist the resolver into one Hono middleware that runs once per request. Every action under the prefix skips the inline gate; `ctx.<exposeAs>` is hydrated by the middleware before the action's `execute()` runs. With the per-namespace helper (v0.27+, [below](#narrow-ctxexposeas-typing-v027)), that field is also statically typed as the loaded row.
225
+
226
+ ### When to use roles vs. relationships
227
+
228
+ A user is authorized for a row when **any** of the following is true:
229
+
230
+ - they have a **per-row relationship** to it (e.g. an attendee row, a named organizer row), or
231
+ - they have a **role on the row's tenant** (org admin/owner of the row's `organizationId`), or
232
+ - they have **team membership** matching the row's `teamId`.
233
+
234
+ Use **relationships** when membership is specific to *this row* — external collaborators who aren't in your org, attendees, anyone connected to the resource by virtue of data rather than payroll. Use **roles / team** when staff at your org/team should see everything in their scope by default.
235
+
236
+ The two compose at the action level (`access.or` accepts both relationship-roles and tenant roles) and — as of v0.25 — at the namespace level too: `namespace.via` accepts an array of lanes, first match wins.
237
+
238
+ > **Rule of thumb.** If the answer is *"yes if you work here,"* reach for org/team roles. If the answer is *"yes if you have something to do with **this** row,"* reach for a per-row relationship. Reach for both together — at the namespace or via `access.or` — when an action should let either side in.
239
+
240
+ Two declaration sites depending on whether the participating actions live in one feature or many:
241
+
242
+ ### Single feature: `defineTable({ namespace })` (v0.23+)
243
+
244
+ Use when every action under the prefix lives in the same feature directory. The namespace travels with the table that owns it — no addition to `quickback.config.ts` needed.
245
+
246
+ {/* doc-compile: skip — cross-fence dependency: `namespace.via: 'attendeeOf'` must resolve against `authz.relationships`, which is declared in the `quickback.config.ts` fence in the next section. The gate compiles each fence as an isolated project against a fixed harness config, so the lane can never be declared here. */}
247
+ ```typescript
248
+ // features/events/events.ts
249
+ import { q, defineTable } from '@quickback/compiler';
250
+
251
+ export const events = q.table('events', {
252
+ id: q.id(),
253
+ name: q.text().required(),
254
+ organizationId: q.scope('organization'),
255
+ ...q.audit(),
256
+ ...q.softDelete(),
257
+ });
258
+
259
+ export default defineTable(events, {
260
+ firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],
261
+ namespace: {
262
+ prefix: '/event/:eventId', // absolute URL path
263
+ via: 'attendeeOf', // relationship gate (must exist in authz.relationships)
264
+ },
265
+ });
266
+
267
+ // features/events/actions/postAnnouncement.ts
268
+ import { z } from "zod";
269
+ import { defineAction } from "../.quickback/define-action";
270
+
271
+ export default defineAction({
272
+ description: "Post an announcement to everyone attending the event.",
273
+ path: '/event/:eventId/announcements',
274
+ method: 'POST',
275
+ input: z.object({ body: z.string().max(2000) }),
276
+ // No `via:` gate boilerplate — the namespace already ran the resolver, so
277
+ // `access` only names roles and ctx.event is typed inside execute().
278
+ access: { roles: ['admin', 'member'] },
279
+ async execute({ db, input, ctx }) { /* … */ },
280
+ });
281
+ ```
282
+
283
+ The compiler emits one `app.use(...)` on the events feature's Hono app. Every standalone action in `features/events/actions/` whose path starts with `/event/:eventId/` joins the namespace automatically.
284
+
285
+ Multi-lane via (v0.25+) and bulk-grant lanes (v0.26+) work identically on the table-level declaration — `via:` accepts the same shapes documented below for the project-level form.
286
+
287
+ ### Cross-feature: `authz.namespaces` (v0.24+)
288
+
289
+ Use when the namespace spans multiple features. The declaration sits next to your other authz config in `quickback.config.ts`.
290
+
291
+ ```typescript
292
+ // quickback.config.ts
293
+ authz: {
294
+ relationships: {
295
+ attendeeOf: {
296
+ from: 'guests',
297
+ subject: { column: 'userId', equals: 'ctx.userId' },
298
+ resource: { column: 'eventId' },
299
+ loads: 'events',
300
+ exposeAs: 'event',
301
+ },
302
+ },
303
+ namespaces: {
304
+ eventScope: { prefix: '/event/:eventId', via: 'attendeeOf' },
305
+ },
306
+ }
307
+ ```
308
+
309
+ With the namespace declared, any standalone action whose `path:` matches the prefix joins the gate — regardless of which feature owns it:
310
+
311
+ ```typescript
312
+ // features/feeds/actions/feedMoments.ts (in one feature)
313
+ import { z } from "zod";
314
+ import { defineAction } from "../.quickback/define-action";
315
+
316
+ export default defineAction({
317
+ description: "Publish a moment to the event's live feed.",
318
+ path: '/event/:eventId/feed-moments',
319
+ method: 'POST',
320
+ input: z.object({ caption: z.string().max(280), photoId: z.string().optional() }),
321
+ access: { roles: ['admin', 'member'] },
322
+ async execute({ db, input, ctx }) { /* … */ },
323
+ });
324
+
325
+ // features/rsvp/actions/respond.ts (in a different feature)
326
+ import { z } from "zod";
327
+ import { defineAction } from "../.quickback/define-action";
328
+
329
+ export default defineAction({
330
+ description: "Record the caller's RSVP for the event.",
331
+ path: '/event/:eventId/respond',
332
+ method: 'POST',
333
+ input: z.object({ response: z.enum(['yes', 'no', 'maybe']) }),
334
+ access: { roles: ['admin', 'member'] },
335
+ async execute({ db, input, ctx }) { /* … */ },
336
+ });
337
+ ```
338
+
339
+ The compiler emits one synthetic `src/routes/__namespace-event-scope.routes.ts` that imports each contributing feature's `actions` map under a distinct alias, mounts the resolver middleware once, and dispatches to the matching action. Worker-root mount order ensures the middleware fires before any per-feature route handler under the prefix.
340
+
341
+ ### Multi-lane via (v0.25+) — first match wins
342
+
343
+ When more than one relationship can authorize a caller for the namespaced resource, pass `via:` as an array. The middleware tries each lane in declaration order and stops at the first match — `ctx.<exposeAs>` is hydrated from whichever lane fired.
344
+
345
+ ```typescript
346
+ authz: {
347
+ relationships: {
348
+ attendeeOf: {
349
+ from: 'guests',
350
+ subject: { column: 'linkedUserId', equals: 'ctx.userId' },
351
+ resource: { column: 'eventId' },
352
+ where: { status: 'confirmed' },
353
+ loads: 'events',
354
+ exposeAs: 'event',
355
+ },
356
+ // Named per-event organizers (potentially EXTERNAL — these users may
357
+ // not be a member of the event's org. That's the point: lets you grant
358
+ // event-level access to freelancers / partner staff without adding
359
+ // them to the org's member list.)
360
+ organizerOf: {
361
+ from: 'eventOrganizers',
362
+ subject: { column: 'linkedUserId', equals: 'ctx.userId' },
363
+ resource: { column: 'eventId' },
364
+ loads: 'events',
365
+ exposeAs: 'event',
366
+ },
367
+ },
368
+ namespaces: {
369
+ eventScope: {
370
+ prefix: '/event/:eventId',
371
+ via: ['attendeeOf', 'organizerOf'],
372
+ },
373
+ },
374
+ }
375
+ ```
376
+
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.
378
+
379
+ ### Bulk-grant lanes (v0.26+)
380
+
381
+ Relationship lanes cover "specifically connected to this row." Bulk-grant lanes cover "anyone with this role / team membership in the row's tenant" — the case where an org admin or a team member should see every event in their scope without writing per-event relationship rows.
382
+
383
+ ```typescript
384
+ namespaces: {
385
+ eventScope: {
386
+ prefix: '/event/:eventId',
387
+ via: [
388
+ 'attendeeOf',
389
+ 'organizerOf',
390
+ { roles: ['admin', 'owner'] }, // org-role bulk grant
391
+ { team: true }, // active-team-membership bulk grant
392
+ ],
393
+ },
394
+ }
395
+ ```
396
+
397
+ Each bulk-grant lane:
398
+
399
+ - **`{ roles: [...] }`** — passes when the caller's BA org-role for the loaded resource's tenant includes any listed role. Short-circuits the relationship loop entirely; the role check is in-memory and cheap. Use for the "company admin sees everything" case.
400
+ - **`{ team: true }`** — passes when `ctx.activeTeamId` is set. The loads-table firewall does the actual `events.teamId === ctx.activeTeamId` check during hydration. Use when the resource is team-scoped and you want active-team membership to grant access.
401
+
402
+ Both bulk-grant lanes piggyback on the namespace's relationship lane(s) for hydration — they don't fetch a separate per-row subject; they just gate access and let the loads-table firewall handle the tenant scoping. **At least one relationship lane is required** alongside bulk-grant lanes in v0.26 (to anchor `loads:` + `exposeAs:`).
403
+
404
+ When a request misses every lane, the 403 deny payload lists every authorization path the caller could have taken — relationship names, role names, and `"team-membership"` for `{ team: true }` lanes — so a developer debugging an unexpected 403 sees the full surface they need to satisfy.
405
+
406
+ A namespace can also fold the scope machinery into this same gate: `mintScope: true` **mints** a scope token on a matched userId lane, and `acceptScope: '<kind>'` **accepts** an already-minted scope claim as proof of entry — one handler under the prefix serves both a Better-Auth user and a sessionless scope principal. See [Scopes → `acceptScope`](/define/scopes#acceptscope--accept-an-incoming-scope-claim-as-proof-of-entry).
407
+
408
+ ### Discovery is path-prefix-only
409
+
410
+ Actions opt in by matching `path:` against a declared namespace prefix. There's no `namespace: 'foo'` field on `defineAction` — the path string is the discoverable surface, consistent with how `path:` already determines an action's URL.
411
+
412
+ ### Requirements (enforced at compile time)
413
+
414
+ Both forms share the same shape checks:
415
+
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.
419
+ - **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
+ - **`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
+ - **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.
422
+
423
+ Project-level only:
424
+
425
+ - **Ambiguous prefixes** like `/a/:x` and `/a/:y` (same shape, different `:param` names) are rejected. Strict super/sub-set relationships (`/event/:e` vs `/event/:e/admin`) are fine — the harvester routes each action to the longest matching prefix.
426
+ - **Unused namespace** emits a `[quickback:authz]` warning when no action's path matches the declared prefix. Not a hard error — the namespace may be staged ahead of the actions.
427
+
428
+ ### What namespace actions get for free
429
+
430
+ Inside a namespace action's `execute()`:
431
+
432
+ - `ctx.<exposeAs>` is populated by the middleware with the loaded resource row. Statically `any` by default — narrowed to `typeof <loadsTable>.$inferSelect` when the action's import points at the per-namespace helper (see [below](#narrow-ctxexposeas-typing-v027)).
433
+ - Tenant context (`ctx.activeOrgId` / `ctx.activeTeamId`) is stamped from the matched relationship row when its `from` table carries those columns. Downstream scoped queries work without further setup.
434
+ - The action's own `access:` block (additional roles, userRole, record predicates, OTHER relationship arms) still runs after the namespace gate — namespace handles entry, per-action gates further.
435
+
436
+ ### Narrow `ctx.<exposeAs>` typing (v0.27+)
437
+
438
+ The namespace middleware hydrates `ctx.<exposeAs>` at runtime — that's been true since v0.23. The static type of that field, though, is `any` via the `AppContext` index signature: useful for not blocking access, but a missed opportunity for autocomplete and typo-catching.
439
+
440
+ v0.27 emits one **per-namespace `defineAction` helper** alongside the standard `<feature>/.quickback/define-action.ts`. Importing from the narrowed helper retypes `ctx.<exposeAs>` inside `execute({ ctx })` to the loaded row's `$inferSelect` shape. Nothing else changes — runtime behavior, action discovery, and the `path:` namespace match are identical.
441
+
442
+ ```ts title="features/feeds/actions/feedMoments.ts"
443
+ // One-line flip per namespace-scoped action:
444
+ import { z } from 'zod';
445
+ import { defineAction } from '../.quickback/define-action.event-scope';
446
+ // └──────┬──────┘
447
+ // kebab(namespaceName)
448
+
449
+ export default defineAction({
450
+ description: "Publish a moment to the event's live feed.",
451
+ path: '/event/:eventId/feed-moments',
452
+ method: 'POST',
453
+ input: z.object({ body: z.string() }),
454
+ access: { roles: ['attendee'] },
455
+ async execute({ ctx, input }) {
456
+ ctx.event.id // ✓ string
457
+ ctx.event.startsAt // ✓ Date — autocomplete works
458
+ ctx.event.organizerId // ✓ narrows on the field's declared type
459
+
460
+ ctx.event.idd // ✗ TS2339 — typo caught at compile time
461
+ },
462
+ });
463
+ ```
464
+
465
+ The compiler emits one helper per `(feature, namespace)` pair where the feature owns at least one action whose `path:` falls under the namespace prefix. Filename is `define-action.<kebab(namespaceName)>.ts` — `eventScope` becomes `define-action.event-scope.ts`. Helpers live next to the standard `define-action.ts` in `<feature>/.quickback/`, so the relative import is the same shape as every other action file in your project.
466
+
467
+ #### Opt-in, not breaking
468
+
469
+ Actions that keep their existing `import { defineAction } from '../.quickback/define-action'` continue to compile unchanged — `ctx.<exposeAs>` is `any` via the `AppContext` index signature, which is exactly the v0.23–v0.26 behavior. You flip imports per action at your own pace.
470
+
471
+ #### Compile-time advisory
472
+
473
+ When `quickback compile` sees a namespace-scoped action still importing the generic helper, it emits a one-line advisory pointing at the narrowed path:
474
+
475
+ ```text
476
+ [quickback:typing] action "feedMoments" in feature "feeds" lives under
477
+ namespace "eventScope" — switch its import to
478
+ `../.quickback/define-action.event-scope` for narrow ctx.<exposeAs> typing.
479
+ (Runtime behavior is unchanged; the narrowed helper only refines TS types.)
480
+ ```
481
+
482
+ Non-blocking — same `[quickback:typing]` family as `[quickback:authz]`. The advisory only mentions actions the compiler can be confident about (namespace-claimed actions whose source still imports the generic helper).
483
+
484
+ #### Multi-namespace features
485
+
486
+ A single feature can contribute actions to several namespaces — say, an `interviews` feature with actions under both `interviewScope` and `eventScope`. The compiler emits one narrowed helper per namespace the feature participates in, and each action picks the import that matches its path.
487
+
488
+ ```text
489
+ src/features/interviews/.quickback/
490
+ ├── define-action.ts # generic — standard fallback
491
+ ├── define-action.interview-scope.ts # ctx.interview typed
492
+ └── define-action.event-scope.ts # ctx.event typed
493
+ ```
494
+
495
+ #### Why per-namespace and not per-action
496
+
497
+ A `defineAction` helper that's narrow to *one* exposed key (the namespace's `exposeAs`) is enough — every action under a namespace sees the same hydrated key. The alternative (per-action emit) duplicates the same prelude N times for the same shape; per-namespace keeps emission proportional to the number of distinct hydration shapes in the project.
498
+
@@ -0,0 +1,164 @@
1
+ # Named Access Rules - authz.roles & authz.rules
2
+
3
+ **[Rung 2](/define#the-authorization-ladder).** Once the same role expression appears
4
+ across many features, give it a name and declare it once. If you only have a couple of
5
+ repeats, inline them — stay on [rung 1](/define/access).
6
+
7
+ ## Centrally defined access rules
8
+
9
+ Instead of repeating the same `roles: [...]` expression across every feature, define it **once** in `authz.roles` and reference it by name everywhere. This is the recommended way to manage access as your app grows: one source of truth per rule, changed in one place.
10
+
11
+ Named roles (and named gates, tenant anchors, scope kinds) can be declared at **two levels**:
12
+ at root `authz` in `quickback.config.ts` (visible everywhere), or inside a
13
+ [feature area](/define/areas)'s `_area.ts` (visible to that area's
14
+ subtree only — a feature outside the area referencing the name is a compile error, and root
15
+ `authz` bodies may reference root-declared names only). Declare each name in exactly one
16
+ place: re-declaring an inherited name is a compile error.
17
+
18
+ ```typescript
19
+ // quickback.config.ts — define ONCE
20
+ export default defineConfig({
21
+ // ...providers...
22
+ authz: {
23
+ roles: {
24
+ // Compose from BA roles, pseudo-roles, and other named rules:
25
+ staff: { roles: ['admin', 'member'] },
26
+ // Boolean combinators:
27
+ eventStaff: { or: [{ roles: ['staff'] }, { via: 'organizerOf' }] },
28
+ // Relationship-backed (see below):
29
+ attendee: { via: 'attendeeOf' },
30
+ },
31
+ },
32
+ });
33
+ ```
34
+
35
+ ```typescript
36
+ // any feature — REFERENCE by bare name
37
+ import { q, defineTable } from '@quickback/compiler';
38
+
39
+ export const agendaItems = q.table('agendaItems', {
40
+ id: q.id(),
41
+ title: q.text().required(),
42
+ startsAt: q.text().required(),
43
+ organizationId: q.scope('organization'),
44
+ ...q.audit(),
45
+ ...q.softDelete(),
46
+ });
47
+
48
+ export default defineTable(agendaItems, {
49
+ read: { access: { roles: ['eventStaff'] } },
50
+ update: { access: { roles: ['eventStaff'] } },
51
+ });
52
+
53
+ // features/events/actions/checkIn.ts
54
+ import { z } from "zod";
55
+ import { defineAction } from "../.quickback/define-action";
56
+
57
+ export default defineAction({
58
+ description: "Check a guest in to the event and record the arrival time.",
59
+ input: z.object({ guestId: z.string() }),
60
+ access: { roles: ['eventStaff', 'attendee'] },
61
+ async execute({ db, input, ctx }) { /* ... */ },
62
+ });
63
+ ```
64
+
65
+ ### Rule shapes
66
+
67
+ Each entry in `authz.roles` is one of four shapes:
68
+
69
+ | Shape | Meaning |
70
+ |---|---|
71
+ | `{ roles: ['admin', 'member'] }` | Composition — matches any of the listed roles (BA, pseudo, or other named rules) |
72
+ | `{ or: [ruleA, ruleB] }` | Matches if **any** sub-rule matches |
73
+ | `{ and: [ruleA, ruleB] }` | Matches only if **all** sub-rules match |
74
+ | `{ via: 'relationshipName' }` | Caller proves a declared relationship — see [Relationship-based authorization](#relationship-based-authorization) below |
75
+
76
+ Rules compose freely — a rule may reference another rule by name (cycles are a compile error).
77
+
78
+ ### Where references resolve
79
+
80
+ A named rule works in the `roles: [...]` array of every access surface. The compiler expands it at build time:
81
+
82
+ | Surface | |
83
+ |---|---|
84
+ | `crud.*.access` | ✓ |
85
+ | `read.access` / `read.views.*.access` | ✓ |
86
+ | `masking.<field>.show` | ✓ for role/composite rules; relationship (`via`) rules refused at compile (v1) |
87
+ | `actions.<name>.access` | ✓ |
88
+ | `realtime.requiredRoles` | ✓ — relationship arms fail closed at the WS handshake and are enforced by the row-stream firewall |
89
+
90
+ Names that **aren't** declared in `authz.roles` — Better Auth roles, pseudo-roles like `AUTHENTICATED` — pass through untouched, so you can mix named rules and raw roles in the same array.
91
+
92
+ ### Beyond roles: named permissions
93
+
94
+ For access that traverses the data graph (FK hops, SpiceDB-style permission composition), see [`authz.permissions` + `authz.arrows`](/define/permissions) — the same define-once-reference-by-name model, one level richer than `authz.roles`.
95
+
96
+ ## Named gates (`authz.rules`)
97
+
98
+ `authz.roles` centralizes the *who*. A **gate** (`authz.rules.<name>`) bundles a full access rule — *who* + an optional row predicate (`record:`) + optional [firewall lanes](/define/firewall#named-gate-references-rule) — under ONE name, declared once:
99
+
100
+ ```typescript
101
+ // quickback.config.ts
102
+ authz: {
103
+ tenants: { org: { column: 'organizationId', equals: 'ctx.activeOrgId' } },
104
+ rules: {
105
+ // who + record: "org staff, but only rows still active"
106
+ activeStaff: {
107
+ who: { roles: ['member', 'admin', 'owner'] },
108
+ record: { status: { equals: 'active' } },
109
+ },
110
+ // who + firewall: an org-OR-event-scope row gate, declared ONCE
111
+ eventRow: {
112
+ who: { roles: ['owner', 'admin', 'member'] },
113
+ firewall: [{ any: [
114
+ { tenant: 'org' },
115
+ { field: 'eventId', equals: 'ctx.scope.event' },
116
+ ] }],
117
+ },
118
+ },
119
+ }
120
+ ```
121
+
122
+ {/* doc-compile: skip — cross-fence dependency: the `eventRow` gate is declared in the `quickback.config.ts` fence directly above. Named refs are expanded once at the compiler's normalization seam with the project's authz config in hand, and the gate compiles each fence as an isolated project against a fixed harness config, so `{ rule: 'eventRow' }` can never resolve here. */}
123
+ ```typescript
124
+ // any feature — the gate name works like a role name
125
+ export default defineTable(eventLinks, {
126
+ firewall: [{ rule: 'eventRow' }], // firewall stamp
127
+ read: { access: { roles: ['eventRow'] } }, // access stamp
128
+ });
129
+ ```
130
+
131
+ ### The two-stamp contract
132
+
133
+ One shared name, two independent stamps — **a single reference never applies both**:
134
+
135
+ - An **access-position reference** (the bare name in any `roles: [...]` array) applies the gate's `who` + `record` arms **only**. It expands exactly like an inline rule: a who-only gate splices as the flat role list; a who+record gate as `{ and: [who, { record }] }`.
136
+ - A **firewall reference** (`firewall: [{ rule: '<name>' }]`) applies the gate's `firewall` lanes **only**, spliced into the resource's top-level AND array. The `who` of a gate referenced only from `firewall:` is **not consulted** — that is the documented contract, not a silent drop. Firewall-who is legitimately *wider* than access-who (e.g. the firewall admits scope-token holders to rows while read access stays staff-only).
137
+
138
+ Both directions are enforced fail-closed at compile time:
139
+
140
+ | You wrote | Compiler says |
141
+ |---|---|
142
+ | Access reference to a firewall-bearing gate, but the resource's `firewall:` doesn't reference it | **Error** — the row lanes would silently not apply |
143
+ | `firewall: [{ rule }]` naming a gate with no `firewall` arm | **Error** — a who/record-only gate would splice zero lanes |
144
+ | A firewall-bearing gate referenced from an **action's** access or from `masking.show` | **Error, unconditional** — no firewall array exists at those sites (nested `show.or` / `show.and` arms included) |
145
+ | A who-less (firewall-only) gate referenced from an access position | **Error** — row lanes can't masquerade as a who-grant |
146
+ | A gate's `record:` field is not a column of the referencing table | **Error, per reference** — a missing field evaluates against `undefined` at runtime (`notEquals`/`notIn` would silently *grant*) |
147
+ | A spliced gate's firewall lane filters on a column the stamped table doesn't have | **Error, per reference** — the lane could never scope rows there |
148
+
149
+ ### Naming rules
150
+
151
+ Rule names share the reference namespace with roles, so the compiler rejects (at declaration time) a rule name that collides with an `authz.roles` entry, a reserved/provider role, **any scoped-role name** (bare sugar like `attendee` or the canonical `scope:<kind>:<role>` spelling), or a name containing `+` or `:` (the `scope:` prefix always means a token-verified scope principal — a colon-named rule could capture references meant for one).
152
+
153
+ Inside `authz.roles` / gate `who` bodies, `+` hierarchy sugar is banned — write the expanded list (`['member', 'admin', 'owner']`), because `+` expansion runs at resource sites only and a `member+` inside a body would silently never match. Roles may not reference rules (the dependency arrow is one-way), and gates never nest.
154
+
155
+ ### Typo safety
156
+
157
+ A `roles: [...]` name that matches nothing declared is fail-closed at runtime (it never grants) but historically silent. The compiler now emits a warning-level `AUTHZ_UNKNOWN_ROLE_NAME` diagnostic for any name that is not a provider/hierarchy role, pseudo-role, scoped role, or declared role/rule — a typo'd gate name is visible at compile time without breaking projects that use dynamic auth-provider role names. The heuristic runs only for projects that use the authz naming system (any of `authz.roles`, `authz.rules`, or `authz.scopes` declared); projects outside it keep the pre-existing silent-passthrough behavior for dynamic role names.
158
+
159
+
160
+ ## Outgrown this?
161
+
162
+ If the answer depends on a row in one of *your* domain tables ("is this caller a
163
+ collaborator on this project?") rather than on org membership, that's
164
+ [rung 3 → Relationships](/define/relationships).
@@ -216,7 +216,7 @@ Compile-time, fail-closed (everything throws, nothing normalizes silently):
216
216
  firewall — including **every branch of an `any:` OR** — must be satisfiable
217
217
  by `fk`/`inherit`. Covering one arm of an OR is not coverage. This runs over
218
218
  the post-expansion firewall, so lanes spliced from
219
- [`authz.rules`](/define/access#centrally-defined-access-rules)
219
+ [`authz.rules`](/define/authz-roles#centrally-defined-access-rules)
220
220
  gates and `{ tenant }` anchors are checked too.
221
221
  - Children firewalled through a **subquery arm** (`via:`, `{ permission }`,
222
222
  arrows) cannot be owned in v1 — even when the arm arrives through a gate
@@ -7,7 +7,7 @@ compiler-owned table, and resolve graph-shaped permission checks at request
7
7
  time — no external authorization service, all inside your Worker.
8
8
 
9
9
  It is **opt-in** and sits alongside the role-based [Access](/define/access)
10
- pillar and the lightweight [`authz.relationships`](/define/access#relationship-roles)
10
+ pillar and the lightweight [`authz.relationships`](/define/relationships)
11
11
  join-roles. Use whichever fits:
12
12
 
13
13
  | Need | Use |
@@ -183,7 +183,7 @@ The `ctx.scope.*` arms are how **relationship-derived scopes** (attendees, shutt
183
183
 
184
184
  ## Relationship-based scoping (`via:`)
185
185
 
186
- For relationship authorization — "this user can see rows X if they have a confirmed `event_guests` row pointing at X" — declare the relationship under `authz.relationships` in `quickback.config.ts`, then reference it from `firewall:` with a `via:` predicate. These relationships (and the named roles/permissions built on them) are defined once, centrally — see [Centrally defined access rules](/define/access#centrally-defined-access-rules).
186
+ For relationship authorization — "this user can see rows X if they have a confirmed `event_guests` row pointing at X" — declare the relationship under `authz.relationships` in `quickback.config.ts`, then reference it from `firewall:` with a `via:` predicate. These relationships (and the named roles/permissions built on them) are defined once, centrally — see [Centrally defined access rules](/define/authz-roles#centrally-defined-access-rules).
187
187
 
188
188
  ```typescript
189
189
  // quickback.config.ts
@@ -224,7 +224,7 @@ Key properties:
224
224
  - **Anonymous callers fail closed.** `ctx.userId` is null-guarded; the subquery short-circuits to `WHERE 1 = 0` for unauthenticated requests.
225
225
  - **The relationship table must be tenant-scoped** (`firewall: { exception: true }` is rejected at compile time on relationship tables).
226
226
 
227
- See [Access — relationships](/define/access#authz-relationships) for the full `authz.relationships` shape and role-binding patterns.
227
+ See [Access — relationships](/define/relationships#authzrelationships) for the full `authz.relationships` shape and role-binding patterns.
228
228
 
229
229
  ## Named permissions (`{ permission }`)
230
230
 
@@ -304,7 +304,7 @@ Expansion happens at compile time, before rendering — the emitted SQL is byte-
304
304
 
305
305
  ## Named gate references (`{ rule }`)
306
306
 
307
- A [gate](/define/access#named-gates-authzrules) that declares `firewall` lanes can be stamped onto a resource by name:
307
+ A [gate](/define/authz-roles#named-gates-authzrules) that declares `firewall` lanes can be stamped onto a resource by name:
308
308
 
309
309
  ```typescript
310
310
  // quickback.config.ts