@quickback-dev/cli 0.13.0 → 0.14.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 (26) hide show
  1. package/dist/docs/content.js +11 -11
  2. package/dist/docs/content.js.map +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/skill/docs/changelog.md +192 -1
  5. package/dist/skill/docs/compiler/definitions/access.md +164 -2
  6. package/dist/skill/docs/compiler/definitions/actions.md +145 -0
  7. package/dist/skill/docs/compiler/definitions/firewall.md +46 -0
  8. package/dist/skill/docs/compiler/definitions/index.md +2 -0
  9. package/dist/skill/docs/compiler/definitions/masking.md +11 -0
  10. package/dist/skill/docs/compiler/definitions/read.md +8 -7
  11. package/dist/skill/docs/compiler/definitions/views.md +100 -12
  12. package/dist/skill/docs/compiler/getting-started/full-example.md +12 -11
  13. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/crud.md +1 -2
  14. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/views-api.md +8 -13
  15. package/package.json +1 -1
  16. package/src/skill/docs/changelog.md +192 -1
  17. package/src/skill/docs/compiler/definitions/access.md +164 -2
  18. package/src/skill/docs/compiler/definitions/actions.md +145 -0
  19. package/src/skill/docs/compiler/definitions/firewall.md +46 -0
  20. package/src/skill/docs/compiler/definitions/index.md +2 -0
  21. package/src/skill/docs/compiler/definitions/masking.md +11 -0
  22. package/src/skill/docs/compiler/definitions/read.md +8 -7
  23. package/src/skill/docs/compiler/definitions/views.md +100 -12
  24. package/src/skill/docs/compiler/getting-started/full-example.md +12 -11
  25. package/src/skill/docs/compiler/targets/hono-api/using-the-api/crud.md +1 -2
  26. package/src/skill/docs/compiler/targets/hono-api/using-the-api/views-api.md +8 -13
@@ -135,7 +135,7 @@ Quickback ships four UPPERCASE role markers that are **not backed by a Better Au
135
135
 
136
136
  | Role | Auth gate | Compile-time requirement | Runtime check |
137
137
  |------|-----------|-------------------------|---------------|
138
- | `PUBLIC` | bypassed | **read-only** — rejected on `crud.create`/`update`/`delete` and on actions | always passes (auth skipped) |
138
+ | `PUBLIC` | bypassed | none — explicit opt-in for unauthenticated access | always passes (auth skipped) |
139
139
  | `AUTHENTICATED` | required | none | `ctx.authenticated === true` |
140
140
  | `USER` | required | resource firewall **must** scope by `userId` | `ctx.authenticated` AND (`ctx.userRole` is unset OR `ctx.userRole === "user"`) |
141
141
  | `ADMIN` | required | Better Auth admin plugin **must** be enabled | `ctx.authenticated && ctx.userRole === "admin"` |
@@ -152,7 +152,7 @@ access: { roles: ["PUBLIC"] }
152
152
 
153
153
  **Important:**
154
154
  - `PUBLIC` skips authentication and role checks — anyone can call the endpoint
155
- - **`PUBLIC` is read-only.** It's allowed on `read.access`, `crud.list`, `crud.get`, and `read.views.*`, but **rejected at compile time** on `crud.create`, `crud.update`, `crud.delete`, and on actions. Anonymous writes are almost always a misconfiguration (vibe-coded `/comments` POST endpoints, runaway forms). If you genuinely need an anonymous write surface — public form submission, webhook ingest — declare a custom action that does its own auth (signed payload, captcha, HMAC) and use `firewall: { exception: true }` on the resource.
155
+ - **`PUBLIC` is the explicit, uppercase opt-in for unauthenticated access.** It works on every access node — reads, CRUD writes (`crud.create`/`update`/`delete`), views, and actions. The compiler trusts the marker; row-level safety comes from the firewall, masking, and (for token-gated endpoints like RSVP confirm, magic-link redemption, List-Unsubscribe-Post, webhook ingest) your handler's own validation. Anonymous CRUD endpoints typically pair `roles: ["PUBLIC"]` with `firewall: { exception: true }` on the resource so the row predicate doesn't reject every unauthenticated caller.
156
156
  - **Firewall still applies** — data is scoped by the firewall (organization, owner, team)
157
157
  - Every `PUBLIC` action invocation is **mandatory audit logged** to the security audit table (IP address, input, result, timing)
158
158
  - The wildcard `"*"` is **not supported** — using it throws a compile-time error
@@ -268,6 +268,168 @@ type FieldCondition =
268
268
  | { greaterThanOrEqual: number };
269
269
  ```
270
270
 
271
+ ## Relationship-based authorization
272
+
273
+ Beyond Better Auth roles (org membership, user-table role) and pseudo-roles, Quickback supports **relationship-based authorization roles** — names that bind to a declared relationship between the caller and a resource. Use these when access should follow a domain-table membership ("user is a confirmed guest of this event") rather than an org/admin gate.
274
+
275
+ ### `authz.relationships` { #authz-relationships }
276
+
277
+ Declare relationships once in `quickback.config.ts`:
278
+
279
+ ```typescript
280
+ // quickback.config.ts
281
+ import { defineConfig } from '@quickback/compiler';
282
+
283
+ export default defineConfig({
284
+ // ...providers...
285
+ authz: {
286
+ relationships: {
287
+ guestOf: {
288
+ from: 'event_guests', // table name string
289
+ subject: { column: 'userId', equals: 'ctx.userId' }, // caller side
290
+ resource: { column: 'eventId' }, // resource side
291
+ where: { status: 'confirmed' }, // optional filter
292
+ },
293
+ },
294
+ roles: {
295
+ guest: { via: 'guestOf' },
296
+ // Composite: any guest OR an org owner/admin
297
+ eventStaff: {
298
+ or: [
299
+ { via: 'guestOf' },
300
+ { roles: ['admin', 'owner'] },
301
+ ],
302
+ },
303
+ },
304
+ },
305
+ });
306
+ ```
307
+
308
+ ### Using relationship-roles in resources
309
+
310
+ Resource definitions reference declared roles by name in `roles: [...]` arrays exactly like BA roles or pseudo-roles. The compiler rewrites the access tree at build time so the runtime route does an inline relationship lookup against the declared table.
311
+
312
+ **Today (v1) this works on:**
313
+
314
+ | Surface | Status | Notes |
315
+ |---|---|---|
316
+ | `firewall:` `via:` predicate | ✓ Supported | Subquery composes as outermost AND |
317
+ | `crud.*.access` `roles: ['guest']` | ✓ Supported | Inline async lookup per request |
318
+ | `read.access` / `read.views.*.access` `roles: ['guest']` | ✓ Supported | Same inline path |
319
+ | `masking.<field>.show` `roles: ['guest']` | ⚠ Refused at compile | v1 limitation — async/batched mask functions deferred |
320
+ | `actions.<name>.access` `roles: ['guest']` | ⚠ Refused at compile | v1 limitation — explicit `relationshipBindings` deferred |
321
+
322
+ For the surfaces that are not yet supported, the compiler refuses at build time with a clear error pointing to a workaround. The runtime evaluator fails closed on relationship arms regardless, so silent grants are impossible.
323
+
324
+ ### Recommended pattern: gate at the firewall layer
325
+
326
+ Most of the time, relationship-based row visibility is what you want, and putting it at the **firewall** layer is the cleanest expression. The firewall is row-filter; the access layer is route/role-filter; let each do its job:
327
+
328
+ ```typescript
329
+ // features/sessions/sessions.ts
330
+ firewall: [
331
+ { field: 'organizationId', equals: 'ctx.activeOrgId' },
332
+ { field: 'eventId', via: 'guestOf' }, // ← row visibility
333
+ ],
334
+ read: {
335
+ access: { roles: ['admin', 'member'] }, // ← who can hit the route
336
+ views: {
337
+ cms: { access: { roles: ['admin', 'member'] }, fields: [...] },
338
+ guest: { access: { roles: ['member', 'admin'] }, fields: [...] },
339
+ },
340
+ },
341
+ ```
342
+
343
+ A guest who's in your org as `member` can hit the endpoint and the firewall filters them down to events they're guests of. Cross-tenant access is impossible because the org filter is the outermost AND.
344
+
345
+ ### Cross-tenant "my events" dashboards are NOT this
346
+
347
+ A common adjacent pattern — "logged-in user wants `GET /my-events` returning events they're a guest of *across all tenants*" — is **not** solved by relationship-roles. The tenant firewall is enforced at the outermost AND, so a guest of an event in another tenant remains correctly blocked.
348
+
349
+ For cross-tenant aggregation, use one of:
350
+
351
+ - **User-scoped firewall**: `firewall: { owner: { column: 'userId' } }` — a flat per-user table.
352
+ - **A standalone action that walks the relationship table itself** — see worked example below.
353
+
354
+ Don't reach for relationship-roles first and then get confused when the tenant firewall blocks. The two patterns serve different problems.
355
+
356
+ #### Worked example: `GET /my-events` standalone action
357
+
358
+ The cleanest expression of the cross-tenant attendee dashboard is a standalone action with a custom path that does its own join against the relationship table. The action is gated by `roles: ['AUTHENTICATED']` (any signed-in user can hit it; per-row scoping is the query itself), and the SQL filters by `ctx.userId` so each caller sees exactly the events they're a guest of:
359
+
360
+ ```ts
361
+ // features/dashboard/actions/myEvents.ts
362
+ import { z } from 'zod';
363
+ import { eq, and, inArray } from 'drizzle-orm';
364
+ import { defineAction } from '../.quickback/define-action';
365
+ import { events } from '../../events/events';
366
+ import { guests } from '../../guests/guests';
367
+
368
+ export default defineAction({
369
+ description: "List events the caller is a confirmed guest of, across all tenants.",
370
+ path: '/my-events',
371
+ method: 'GET',
372
+ input: z.object({}),
373
+ // Any signed-in user. Row visibility comes from the query, not the role.
374
+ access: { roles: ['AUTHENTICATED'] },
375
+ async execute({ db, ctx }) {
376
+ // 1. Find every event the caller has a confirmed guest row for.
377
+ const guestRows = await db
378
+ .select({ eventId: guests.eventId })
379
+ .from(guests)
380
+ .where(
381
+ and(
382
+ eq(guests.userId, ctx.userId!),
383
+ eq(guests.status, 'confirmed'),
384
+ // guests.organizationId is NOT filtered here — that's the whole
385
+ // point of the cross-tenant lane. The relationship row's org is
386
+ // ambient information that this action explicitly traverses.
387
+ )
388
+ );
389
+
390
+ if (guestRows.length === 0) return { events: [] };
391
+
392
+ // 2. Pull the matching events. NOTE: this query also bypasses
393
+ // `events.organizationId` scope — by design — so explicitly filter
394
+ // out soft-deleted rows yourself if your `events` table uses them.
395
+ const eventIds = guestRows.map((r) => r.eventId);
396
+ const rows = await db
397
+ .select()
398
+ .from(events)
399
+ .where(inArray(events.id, eventIds));
400
+
401
+ return { events: rows };
402
+ },
403
+ });
404
+ ```
405
+
406
+ Why this is a standalone action and not a CRUD route:
407
+
408
+ - **Tenant firewall would block it.** The default `firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }]` on `events` is correct for every other read — only the cross-tenant dashboard wants to step outside it, and that's a deliberate, explicit step taken in handler code.
409
+ - **The join is the access control.** A relationship-role at the firewall layer can't express "filter by this user's relationships, ignoring the org context." The handler does that join directly.
410
+ - **Audit-logged automatically.** Standalone actions are mandatorily audit-logged in the runtime — the cross-tenant traversal is recorded with `ctx.userId`, IP, and timing.
411
+
412
+ Two important guardrails when you write one of these:
413
+
414
+ 1. **Always filter by `ctx.userId` in the relationship lookup.** If you accept a `userId` from the request body and trust it, you've built an IDOR. The example above uses `ctx.userId!` directly so the only events returned are the caller's.
415
+ 2. **You take responsibility for soft-delete and other invariants the firewall would otherwise apply.** Add the `deletedAt` filter, status checks, and any other row-level predicates by hand. The action is OUTSIDE the firewall pipeline by design — the cost is that you can't lean on the auto-applied predicates.
416
+
417
+ If you find yourself writing more than one of these per project, that's usually a signal to revisit the schema (could a user-owned `userEvents` materialized view replace the join?) rather than a sign Quickback should ship a higher-level abstraction. Cross-tenant lanes are intentionally explicit.
418
+
419
+ ### Compile-time refusals (consolidated)
420
+
421
+ The validator and resolver reject:
422
+
423
+ - Unknown key in `authz` block (typo guard — `realtionships` would otherwise silently produce a permanently-denied role).
424
+ - Reserved role-name (auth-provider-derived). Names like `guest`, `speaker`, `attendee` are free; `admin`/`owner`/`member` are reserved when the BA org plugin is on.
425
+ - Cycle in role composition (`a → b → a`).
426
+ - Relationship `from` references unknown table.
427
+ - Relationship-role used on a resource missing the `resource.column`.
428
+ - Relationship table with `firewall: { exception: true }` (would let cross-tenant grants slip through).
429
+ - `lowering: 'session'` (reserved for v2 — staleness/invalidation ergonomics not yet shipped).
430
+ - `+` hierarchy suffix on a relationship-role name (terminal, like pseudo-roles).
431
+ - Relationship-roles in `masking.show` / `actions.access` (deferred surfaces — see the table above).
432
+
271
433
  ## Read & CRUD Configuration
272
434
 
273
435
  Reads (`GET /` and `GET /:id`) live under `read:`; mutations live under `crud:`. See [Read](/compiler/definitions/read) for the full read pipeline reference.
@@ -133,6 +133,7 @@ export default defineAction({
133
133
  | `allowRawSql` | No | Explicit compile-time opt-in for raw SQL in execute code |
134
134
  | `unsafe` | No | Unsafe raw DB mode. Object config (`reason`, `adminOnly`, `crossTenant`, `targetScope`). |
135
135
  | `transition` | No | State-machine policy enforcing the from/to pair (record-based actions). See [Transitions](#transition-state-machine-policy) |
136
+ | `bulkVariant` | No | Auto-generate a `POST /:resource/batch/{action}` route alongside the per-record route (record-based actions). See [Bulk Variant](#bulk-variant) |
136
137
  | `cms` | No | Pass-through metadata blob for CMS surfaces |
137
138
 
138
139
  `execute` must be an `async (ctx) => { … }` arrow function. `async function`
@@ -217,6 +218,107 @@ Content-Type: application/json
217
218
  }
218
219
  ```
219
220
 
221
+ ### Bulk variant
222
+
223
+ Set `bulkVariant: true` to auto-generate a bulk version of the action at
224
+ `POST /:resource/batch/{action}`. The compiler emits a second route alongside
225
+ the per-record one, looping the same access + transition + execute pipeline
226
+ over an array of ids. This is the answer to "I need to advance 50
227
+ applications at once" — you don't have to hand-roll a parallel standalone
228
+ action that duplicates the per-record logic.
229
+
230
+ ```typescript
231
+ // features/applications/actions/advance.ts
232
+ export default defineAction({
233
+ description: "Move an application forward in the pipeline.",
234
+ input: z.object({ nextStatus: z.enum(["screening", "interview", "offer"]) }),
235
+ access: { roles: ["owner", "admin"] },
236
+ bulkVariant: true,
237
+ transition: {
238
+ field: "status",
239
+ via: "nextStatus",
240
+ fromTo: { applied: ["screening"], screening: ["interview"], interview: ["offer"] },
241
+ },
242
+ async execute({ db, record, input, whereTransition }) {
243
+ const [updated] = await db
244
+ .update(applications)
245
+ .set({ status: input.nextStatus })
246
+ .where(whereTransition!(applications))
247
+ .returning();
248
+ if (!updated) throw new TransitionLostError("status", record.status, input.nextStatus);
249
+ return updated;
250
+ },
251
+ });
252
+ ```
253
+
254
+ **Request shape:**
255
+
256
+ ```http
257
+ POST /applications/batch/advance
258
+ Content-Type: application/json
259
+
260
+ {
261
+ "ids": ["app_001", "app_002", "app_003"],
262
+ "input": { "nextStatus": "interview" },
263
+ "failFast": false
264
+ }
265
+ ```
266
+
267
+ The `input` is shared across the batch — the action's Zod schema is
268
+ validated once, not per id. For per-record input variation, use the
269
+ single-record endpoint (`POST /:id/{action}`) or write a standalone action.
270
+
271
+ **Response (207 Multi-Status when any record fails, 200 when clean):**
272
+
273
+ ```json
274
+ {
275
+ "success": [{ "id": "app_001", "status": "interview" }],
276
+ "errors": [
277
+ {
278
+ "index": 1,
279
+ "id": "app_002",
280
+ "error": {
281
+ "error": "Action not allowed for current state",
282
+ "code": "ACCESS_ACTION_NOT_ALLOWED_FOR_STATE",
283
+ "details": { "field": "status", "currentValue": "rejected" }
284
+ }
285
+ }
286
+ ],
287
+ "meta": {
288
+ "total": 3,
289
+ "succeeded": 2,
290
+ "failed": 1,
291
+ "failFast": false,
292
+ "transactional": false
293
+ }
294
+ }
295
+ ```
296
+
297
+ **Per-record pipeline** mirrors the single-record route exactly — the same
298
+ firewall fetch, access reason split (403 vs 409), transition pre-check,
299
+ `whereTransition` factory, and `TransitionLostError` handling. Per-record
300
+ failures land in `errors[]` with their original index; successful records
301
+ land in `success[]` masked the same way the single-record response is.
302
+
303
+ **Transactional matrix** (same as `PATCH /batch`):
304
+
305
+ | Provider | failFast | transactional | Behavior |
306
+ |---|---|---|---|
307
+ | postgres / supabase / neon / libsql / sqlite drivers | `true` | `true` | `db.transaction()` wraps the loop; any throw rolls back all writes |
308
+ | (any) | `false` | `false` | Independent per-record outcomes, partial success |
309
+ | cloudflare-d1 | `true` | `false` | Fail-fast loop without rollback — earlier records stay committed |
310
+
311
+ **Constraints:**
312
+
313
+ - Record-based actions only. Standalone actions reject `bulkVariant: true`
314
+ at compile time (no record context to loop over).
315
+ - `unsafe` actions reject `bulkVariant: true` in v1 — the cross-tenant
316
+ per-record audit story is not yet wired through.
317
+ - Method is forced to POST regardless of the action's `method` setting. The
318
+ semantic asymmetry (one row → many rows) makes inheriting GET/DELETE
319
+ confusing.
320
+ - Max batch size is 100 ids per request.
321
+
220
322
  ## Standalone Actions
221
323
 
222
324
  Standalone actions are independent endpoints that don't require a record context. Set a `path:` to declare the action standalone.
@@ -400,6 +502,49 @@ access: async (ctx, record) => {
400
502
  }
401
503
  ```
402
504
 
505
+ ### Relationship-roles in actions (v1 limitation)
506
+
507
+ Relationship-roles declared under `authz.roles` (e.g. `guest: { via: 'guestOf' }`) are **not yet supported in action access blocks**. The compiler refuses to build with a clear error message because the binding semantics — which input field or which loaded record's column to check the relationship against — differ between record-actions and standalone-actions and require explicit declaration not yet wired in v1.
508
+
509
+ The runtime evaluator fails closed on unrecognized relationship arms, so silent grants are impossible.
510
+
511
+ **Workaround**: gate the action on BA roles only and apply the relationship at the resource layer via a firewall `via:` predicate:
512
+
513
+ ```typescript
514
+ // quickback.config.ts
515
+ authz: {
516
+ relationships: {
517
+ guestOf: {
518
+ from: 'event_guests',
519
+ subject: { column: 'userId', equals: 'ctx.userId' },
520
+ resource: { column: 'eventId' },
521
+ where: { status: 'confirmed' },
522
+ },
523
+ },
524
+ }
525
+
526
+ // features/sessions/sessions.ts — firewall scopes rows; action gates on BA role
527
+ firewall: [
528
+ { field: 'organizationId', equals: 'ctx.activeOrgId' },
529
+ { field: 'eventId', via: 'guestOf' }, // ← row-level relationship check
530
+ ],
531
+ actions: {
532
+ comment: defineAction({
533
+ access: { roles: ['member', 'admin'] }, // ← BA role only on the action
534
+ input: z.object({ text: z.string() }),
535
+ execute: async (input, ctx, db, record) => {
536
+ // record is already filtered by the firewall — guest membership
537
+ // is enforced before this handler runs.
538
+ return db.insert(comments).values({ ... });
539
+ },
540
+ }),
541
+ }
542
+ ```
543
+
544
+ This pattern composes cleanly: the firewall guarantees the caller has the relationship to the record being acted on; the action's access list keeps the role surface obvious.
545
+
546
+ A future `actions.<name>.relationshipBindings` declaration is on the roadmap to remove this limitation. See [Access — relationship authorization](/compiler/definitions/access#relationship-based-authorization) for the full picture.
547
+
403
548
  ## Scoped Database
404
549
 
405
550
  All actions receive a **scoped `db`** instance that automatically enforces security:
@@ -64,6 +64,7 @@ type FirewallPredicate =
64
64
  | { field: string; equals: string } // column = ctx.* (or literal)
65
65
  | { field: string; isNull: true } // column IS NULL
66
66
  | { field: string; in: string[] | string }// column IN (...)
67
+ | { field: string; via: string } // column IN (relationship subquery)
67
68
  | { exception: true }; // opt out of tenant scoping
68
69
 
69
70
  type FirewallConfig = ReadonlyArray<FirewallPredicate>;
@@ -74,6 +75,51 @@ firewallErrorMode?: 'reveal' | 'hide';
74
75
 
75
76
  Predicates are AND'd together. `firewallErrorMode` lives at the resource top level — it's a presentation-layer choice (403 vs 404), not a query-shape one.
76
77
 
78
+ ## Relationship-based scoping (`via:`)
79
+
80
+ 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:
81
+
82
+ ```typescript
83
+ // quickback.config.ts
84
+ authz: {
85
+ relationships: {
86
+ guestOf: {
87
+ from: 'event_guests', // table name
88
+ subject: { column: 'userId', equals: 'ctx.userId' }, // caller side
89
+ resource: { column: 'eventId' }, // resource side
90
+ where: { status: 'confirmed' }, // optional row filter
91
+ },
92
+ },
93
+ }
94
+
95
+ // features/sessions/sessions.ts
96
+ firewall: [
97
+ { field: 'organizationId', equals: 'ctx.activeOrgId' },
98
+ { field: 'eventId', via: 'guestOf' },
99
+ ]
100
+ ```
101
+
102
+ Compiles to:
103
+
104
+ ```sql
105
+ WHERE sessions.organizationId = ?
106
+ AND sessions.eventId IN (
107
+ SELECT eventId FROM event_guests
108
+ WHERE userId = ?
109
+ AND status = 'confirmed'
110
+ AND <event_guests' own firewall — tenant scope + soft-delete>
111
+ )
112
+ ```
113
+
114
+ Key properties:
115
+
116
+ - **Firewall stays the outermost AND.** A guest of an event in another tenant is still blocked by your tenant predicate. Relationship-based scoping never bypasses tenant isolation.
117
+ - **The relationship table's own firewall is AND'd into the subquery.** Soft-deleting a `event_guests` row revokes access immediately; cross-tenant relationship rows can't grant access.
118
+ - **Anonymous callers fail closed.** `ctx.userId` is null-guarded; the subquery short-circuits to `WHERE 1 = 0` for unauthenticated requests.
119
+ - **The relationship table must be tenant-scoped** (`firewall: { exception: true }` is rejected at compile time on relationship tables).
120
+
121
+ See [Access — relationships](/compiler/definitions/access#authz-relationships) for the full `authz.relationships` shape and role-binding patterns.
122
+
77
123
  ## Context Sources
78
124
 
79
125
  When `equals` references the request context, use these standard sources:
@@ -110,6 +110,8 @@ The firewall controls **which records** a user can see. It automatically adds WH
110
110
 
111
111
  No manual configuration needed - Quickback applies smart rules based on your schema.
112
112
 
113
+ For relationship-based row visibility (e.g. "user can see this event because they have a confirmed `event_guests` row pointing at it"), declare the relationship under `authz.relationships` and reference it from the firewall with a `via:` predicate. See [Firewall → Relationship-based scoping](/compiler/definitions/firewall#relationship-based-scoping-via).
114
+
113
115
  [Learn more about Firewall →](/compiler/definitions/firewall)
114
116
 
115
117
  ### 2. Access (CRUD Permissions)
@@ -139,6 +139,17 @@ show: {
139
139
 
140
140
  The `'owner'` condition compares against the owner column declared via `q.scope('owner')` (or auto-detected from a `userId` / `ownerId` column). If no owner scope is present, it falls back to `createdBy`.
141
141
 
142
+ ### Relationship-roles in masking (v1 limitation)
143
+
144
+ Relationship-roles declared under `authz.roles` (e.g. `guest: { via: 'guestOf' }`) are **not yet supported in `show:` clauses**. The compiler refuses to build with a clear error message because async, db-aware mask functions plus a batched relationship matcher (to avoid N+1 on list responses) are required to ship safely — that pipeline has not yet landed. The runtime evaluator fails closed on unrecognized arms, so silent grants are impossible.
145
+
146
+ **Workarounds**, depending on intent:
147
+
148
+ - **Gate on BA roles only**: keep masking simple and put the relationship check at the access layer instead — `read.views.<v>.access: { roles: ['guest'] }` returns a curated field projection that excludes the sensitive column entirely for non-staff callers, without involving masking.
149
+ - **Move the field into a view that's gated by the relationship-role at access**: same pattern — column-level security via field projection rather than per-row masking.
150
+
151
+ A future async-mask pipeline with batched lookups will lift this limitation; the schema slot is reserved so the v2 add will be non-breaking.
152
+
142
153
  ## Query Gate (filter / sort / search)
143
154
 
144
155
  Masking has a second concern beyond hiding values in the response: a non-admin caller could enumerate masked PII via the query string — e.g. `?filter=email:like:%@target.com` — and infer presence even when the response payload is redacted. The `query` allowlist closes this:
@@ -53,8 +53,7 @@ export default defineTable(customers, {
53
53
  |----------|------|
54
54
  | `GET /api/v1/{resource}` | `read.access` |
55
55
  | `GET /api/v1/{resource}/:id` | `read.access` |
56
- | `GET /api/v1/{resource}?view={name}` | `read.views[name].access` (falls back to `read.access`) |
57
- | `GET /api/v1/{resource}/views/{name}` | Same — explicit path form of the `?view=` dispatch |
56
+ | `GET /api/v1/{resource}/views/{name}` | `read.views[name].access` (falls back to `read.access`) |
58
57
 
59
58
  Single-record `GET /:id` inherits `read.access` automatically — there's no
60
59
  separate `read.get` block. If you need different access for single records,
@@ -145,10 +144,10 @@ read: {
145
144
  }
146
145
  ```
147
146
 
148
- Both endpoint shapes are emitted automatically:
147
+ Named views are emitted at dedicated path routes:
149
148
 
150
- - Query-string dispatch: `GET /api/v1/jobs?view=internal`
151
- - Explicit path: `GET /api/v1/jobs/views/internal`
149
+ - `GET /api/v1/jobs/views/internal`
150
+ - If `read.defaultView` is set, bare `GET /api/v1/jobs` resolves to that view.
152
151
 
153
152
  ## Migrating from `crud.list` / `crud.get`
154
153
 
@@ -161,7 +160,7 @@ DSL v2 rejects both at compile time. The migration is mechanical:
161
160
  | `crud.list.maxPageSize` | `read.maxPageSize` |
162
161
  | `crud.list.fields: [...]` | Move to a named view under `read.views` |
163
162
  | `crud.get.access` | `read.access` (or record-level conditions) |
164
- | `crud.get.fields: [...]` | Move to a named view; clients call `?view=...` |
163
+ | `crud.get.fields: [...]` | Move to a named view; clients call `/views/{name}` |
165
164
  | Top-level `views: {...}` | `read.views: {...}` |
166
165
 
167
166
  Example before/after:
@@ -197,7 +196,9 @@ crud: {
197
196
  ```
198
197
 
199
198
  Clients that previously hit `GET /:id` to retrieve only summary fields now
200
- call `GET /:id?view=summary`.
199
+ move that projection to a named collection view such as
200
+ `GET /api/v1/jobs/views/summary`. Single-record `GET /:id` always returns the
201
+ full masked record.
201
202
 
202
203
  ## Read-Only Resources
203
204
 
@@ -75,20 +75,18 @@ export default defineTable(candidates, {
75
75
 
76
76
  ## Generated Endpoints
77
77
 
78
- Each view generates **two** equivalent GET endpoints — pick whichever is more ergonomic for your client:
78
+ Each named view generates a dedicated GET endpoint:
79
79
 
80
80
  ```
81
81
  GET /api/v1/candidates # Full read - read.access fields
82
- GET /api/v1/candidates?view=pipeline # Query-string dispatch
83
- GET /api/v1/candidates/views/pipeline # Explicit path form
84
- GET /api/v1/candidates?view=full # hiring-manager/recruiter only
82
+ GET /api/v1/candidates/views/pipeline # interviewer/recruiter/etc.
83
+ GET /api/v1/candidates/views/full # hiring-manager/recruiter only
85
84
  GET /api/v1/candidates/views/report # report fields
86
85
  ```
87
86
 
88
- The `?view=` query-string form is convenient when the rest of your client
89
- already builds collection URLs and you only need to swap the projection.
90
- The `/views/{name}` path form is better when you want a stable URL per
91
- projection.
87
+ If `read.defaultView` is set, bare `GET /api/v1/candidates` can also resolve
88
+ to that named view. Without `defaultView`, bare `GET /api/v1/candidates`
89
+ returns `VIEW_REQUIRED` once views are declared.
92
90
 
93
91
  ## Query Parameters
94
92
 
@@ -227,6 +225,93 @@ read: {
227
225
  | `/views/full` | interviewer | Yes | `j***@c******.com` |
228
226
  | `/views/full` | recruiter | Yes | `jane@company.com` |
229
227
 
228
+ ## Aggregations
229
+
230
+ Views can declare pre-computed aggregations that run alongside the row
231
+ query and surface as `aggregations: { ... }` on the response. This avoids a
232
+ custom standalone action for every "count of X grouped by Y" dashboard
233
+ tile — the firewall and view filters already in place drive the metric.
234
+
235
+ ```typescript
236
+ read: {
237
+ access: { roles: ['owner', 'admin', 'member'] },
238
+ views: {
239
+ pipeline: {
240
+ fields: ['id', 'jobId', 'candidateId', 'status', 'appliedAt'],
241
+ aggregations: {
242
+ totalApplications: { fn: 'count' },
243
+ byStatus: { fn: 'groupBy', field: 'status' },
244
+ },
245
+ },
246
+ },
247
+ }
248
+ ```
249
+
250
+ Response now carries the aggregations alongside `data`:
251
+
252
+ ```json
253
+ {
254
+ "data": [/* paginated rows */],
255
+ "view": "pipeline",
256
+ "pagination": { "count": 50, "page": 1, "pageSize": 50, "hasMore": true },
257
+ "aggregations": {
258
+ "totalApplications": 173,
259
+ "byStatus": {
260
+ "applied": 102,
261
+ "screening": 41,
262
+ "interview": 18,
263
+ "offer": 7,
264
+ "rejected": 5
265
+ }
266
+ }
267
+ }
268
+ ```
269
+
270
+ ### Supported aggregation functions
271
+
272
+ | `fn` | `field` | Returns | Example |
273
+ |---|---|---|---|
274
+ | `sum` | required, numeric | scalar number | `{ fn: 'sum', field: 'guestCount' }` |
275
+ | `avg` | required, numeric | scalar number | `{ fn: 'avg', field: 'salary' }` |
276
+ | `min` | required | scalar number | `{ fn: 'min', field: 'price' }` |
277
+ | `max` | required | scalar number | `{ fn: 'max', field: 'price' }` |
278
+ | `count` | optional | `COUNT(*)` if omitted, `COUNT(field)` (non-null) if given | `{ fn: 'count' }` |
279
+ | `count_distinct` | required | scalar number | `{ fn: 'count_distinct', field: 'sourceId' }` |
280
+ | `groupBy` | required | `{ value: count }` map | `{ fn: 'groupBy', field: 'status' }` |
281
+
282
+ `groupBy` always returns a count map keyed by the distinct values of `field`.
283
+ `NULL` values bucket under the literal string `"(none)"`. Other rollup
284
+ functions (`groupBy` + `sum` of another column) are deferred to a future
285
+ release.
286
+
287
+ ### Filter and firewall inheritance
288
+
289
+ Aggregations always run over the **same** filtered, firewalled set as the
290
+ row query. Pagination is intentionally ignored — you get the value over
291
+ every matching record, not just the current page.
292
+
293
+ In practice: a request like
294
+ `GET /applications/views/pipeline?status=applied&jobId=job_123&limit=10`
295
+ returns the first 10 applied rows for that job, AND `byStatus` reflects
296
+ only that filtered set (which will be `{ applied: <total> }` since the
297
+ filter pinned the status). This is the only consistent default — divorcing
298
+ the metric from the user's filters would surprise.
299
+
300
+ ### Constraints (compile-time)
301
+
302
+ - `field` must reference a real column on the table.
303
+ - `sum`/`avg` require numeric column types (`int`, `real`, `decimal`,
304
+ `numeric`, `bigint`). Non-numeric columns are rejected at compile time.
305
+ - The same masking opt-out gate that governs `query.{filterable, sortable,
306
+ searchable}` applies to aggregations: the view's roles must satisfy the
307
+ masking rule, otherwise the aggregation is rejected. (A `sum(salary)`
308
+ leaks structure across the masked set even when the row payload is
309
+ redacted.)
310
+ - Aggregation names cannot collide with the reserved response fields
311
+ `data`, `pagination`, `view`.
312
+ - No raw SQL `expr:` form. Column references only — declare a generated
313
+ column or write a custom action if you need arithmetic.
314
+
230
315
  ## Response Format
231
316
 
232
317
  View responses include metadata about the view:
@@ -238,15 +323,18 @@ View responses include metadata about the view:
238
323
  { "id": "cnd_456", "name": "John Smith", "source": "referral" }
239
324
  ],
240
325
  "view": "pipeline",
241
- "fields": ["id", "name", "source"],
242
326
  "pagination": {
243
- "limit": 50,
244
- "offset": 0,
245
- "count": 2
327
+ "count": 2,
328
+ "page": 1,
329
+ "pageSize": 50,
330
+ "hasMore": false
246
331
  }
247
332
  }
248
333
  ```
249
334
 
335
+ When the view declares `aggregations`, the response also includes an
336
+ `aggregations: { ... }` field. See [Aggregations](#aggregations).
337
+
250
338
  ## Complete Example
251
339
 
252
340
  ```typescript