@quickback-dev/cli 0.13.0 → 0.16.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 (43) hide show
  1. package/dist/commands/compile.d.ts.map +1 -1
  2. package/dist/commands/compile.js +40 -2
  3. package/dist/commands/compile.js.map +1 -1
  4. package/dist/docs/content.js +13 -13
  5. package/dist/docs/content.js.map +1 -1
  6. package/dist/index.js +1 -1
  7. package/dist/lib/copy-public-assets.d.ts +34 -0
  8. package/dist/lib/copy-public-assets.d.ts.map +1 -0
  9. package/dist/lib/copy-public-assets.js +118 -0
  10. package/dist/lib/copy-public-assets.js.map +1 -0
  11. package/dist/lib/copy-public-assets.test.d.ts +2 -0
  12. package/dist/lib/copy-public-assets.test.d.ts.map +1 -0
  13. package/dist/lib/copy-public-assets.test.js +151 -0
  14. package/dist/lib/copy-public-assets.test.js.map +1 -0
  15. package/dist/skill/docs/changelog.md +350 -1
  16. package/dist/skill/docs/compiler/config/index.md +18 -0
  17. package/dist/skill/docs/compiler/config/output.md +34 -0
  18. package/dist/skill/docs/compiler/definitions/access.md +180 -4
  19. package/dist/skill/docs/compiler/definitions/actions.md +145 -0
  20. package/dist/skill/docs/compiler/definitions/firewall.md +73 -0
  21. package/dist/skill/docs/compiler/definitions/index.md +2 -0
  22. package/dist/skill/docs/compiler/definitions/masking.md +11 -0
  23. package/dist/skill/docs/compiler/definitions/read.md +8 -7
  24. package/dist/skill/docs/compiler/definitions/schema.md +9 -0
  25. package/dist/skill/docs/compiler/definitions/views.md +100 -12
  26. package/dist/skill/docs/compiler/getting-started/full-example.md +12 -11
  27. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/crud.md +1 -2
  28. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/views-api.md +8 -13
  29. package/package.json +1 -1
  30. package/src/skill/docs/changelog.md +350 -1
  31. package/src/skill/docs/compiler/config/index.md +18 -0
  32. package/src/skill/docs/compiler/config/output.md +34 -0
  33. package/src/skill/docs/compiler/definitions/access.md +180 -4
  34. package/src/skill/docs/compiler/definitions/actions.md +145 -0
  35. package/src/skill/docs/compiler/definitions/firewall.md +73 -0
  36. package/src/skill/docs/compiler/definitions/index.md +2 -0
  37. package/src/skill/docs/compiler/definitions/masking.md +11 -0
  38. package/src/skill/docs/compiler/definitions/read.md +8 -7
  39. package/src/skill/docs/compiler/definitions/schema.md +9 -0
  40. package/src/skill/docs/compiler/definitions/views.md +100 -12
  41. package/src/skill/docs/compiler/getting-started/full-example.md +12 -11
  42. package/src/skill/docs/compiler/targets/hono-api/using-the-api/crud.md +1 -2
  43. package/src/skill/docs/compiler/targets/hono-api/using-the-api/views-api.md +8 -13
@@ -60,7 +60,7 @@ crud: {
60
60
  The `+` suffix expands at compile time — `"member+"` becomes `["member", "admin", "owner"]` in the generated code. You can mix hierarchical and exact roles: `roles: ["member+", "finance"]` expands to `["member", "admin", "owner", "finance"]`.
61
61
 
62
62
  - Roles without `+` are exact matches (no expansion)
63
- - Pseudo-roles (`PUBLIC`, `AUTHENTICATED`, `USER`, `ADMIN`) cannot use the `+` suffix — they're terminal markers
63
+ - Pseudo-roles (`PUBLIC`, `AUTHENTICATED`, `USER`, `ADMIN`, `SYSADMIN`) cannot use the `+` suffix — they're terminal markers
64
64
  - Using `+` with a role not in the hierarchy throws a compile error
65
65
  - Using `+` without configuring `auth.roleHierarchy` throws a compile error
66
66
 
@@ -131,14 +131,15 @@ When `roles` and `userRole` both appear in a single `Access` node, they're combi
131
131
 
132
132
  ### Pseudo-roles
133
133
 
134
- Quickback ships four UPPERCASE role markers that are **not backed by a Better Auth role column** — they're system-level shortcuts handled directly by the compiler. The casing carries the boundary: UPPERCASE = pseudo-role (no plugin context required), lowercase = real role from a plugin's table (e.g. `members.role` from the org plugin).
134
+ Quickback ships five UPPERCASE role markers that are **not backed by a Better Auth role column** — they're system-level shortcuts handled directly by the compiler. The casing carries the boundary: UPPERCASE = pseudo-role (no plugin context required), lowercase = real role from a plugin's table (e.g. `members.role` from the org plugin).
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"` |
142
+ | `SYSADMIN` | required | `cms: { sysadmin: true }` **must** be set on the project | `ctx.authenticated && ctx.userRole === "sysadmin"` |
142
143
 
143
144
  You can mix pseudo-roles with real roles in the same list — they're OR'd together.
144
145
 
@@ -152,7 +153,7 @@ access: { roles: ["PUBLIC"] }
152
153
 
153
154
  **Important:**
154
155
  - `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.
156
+ - **`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
157
  - **Firewall still applies** — data is scoped by the firewall (organization, owner, team)
157
158
  - Every `PUBLIC` action invocation is **mandatory audit logged** to the security audit table (IP address, input, result, timing)
158
159
  - The wildcard `"*"` is **not supported** — using it throws a compile-time error
@@ -220,6 +221,19 @@ read: { access: { roles: ["ADMIN"] } }
220
221
 
221
222
  Without the admin plugin you get a compile error pointing you to either enable the plugin or use lowercase `roles: ["admin"]` (the org-membership admin role).
222
223
 
224
+ #### `SYSADMIN` — cross-tenant DB-admin tier
225
+
226
+ Use `roles: ["SYSADMIN"]` for endpoints that should only be reachable by platform sysadmins — the cross-tenant DB-admin tier introduced in v0.15.0. Compiles to `ctx.userRole === "sysadmin"`. **Requires `cms: { sysadmin: true }` on the project config**; without that flag, using `SYSADMIN` fails the compile so the role can't sit as dead code.
227
+
228
+ ```typescript
229
+ // Cross-tenant audit dashboard, sysadmin-only
230
+ read: { access: { roles: ["SYSADMIN"] } }
231
+ ```
232
+
233
+ `SYSADMIN` is a strict superset of `ADMIN` — at runtime, the universal-bypass shortcuts in `evaluateAccess` admit `userRole === 'sysadmin'` anywhere they admit `userRole === 'admin'`. The distinction matters for one thing only: **the firewall escape hatch**. When `cms.sysadmin: true`, 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, not just their own org's. That escape hatch does NOT fire for `userRole === 'admin'`; admins still go through the firewall like everyone else.
234
+
235
+ This separation exists so Better Auth admin-plugin powers (user management, impersonation) and DB-admin powers (cross-tenant data inspection) stay decoupled. A user can have `user.role === 'admin'` without DB-level cross-tenant access; a user can have `user.role === 'sysadmin'` without org-membership context. See [CMS Configuration](/compiler/config#cms-configuration) for the `cms.sysadmin` flag, the cross-tenant `/admin/v1/sysadmin/organizations` endpoint, and the SPA's "All organizations" sentinel.
236
+
223
237
  #### Mixing pseudo-roles with real roles
224
238
 
225
239
  Pseudo-roles and lowercase real roles compose with OR:
@@ -268,6 +282,168 @@ type FieldCondition =
268
282
  | { greaterThanOrEqual: number };
269
283
  ```
270
284
 
285
+ ## Relationship-based authorization
286
+
287
+ 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.
288
+
289
+ ### `authz.relationships` { #authz-relationships }
290
+
291
+ Declare relationships once in `quickback.config.ts`:
292
+
293
+ ```typescript
294
+ // quickback.config.ts
295
+ import { defineConfig } from '@quickback/compiler';
296
+
297
+ export default defineConfig({
298
+ // ...providers...
299
+ authz: {
300
+ relationships: {
301
+ guestOf: {
302
+ from: 'event_guests', // table name string
303
+ subject: { column: 'userId', equals: 'ctx.userId' }, // caller side
304
+ resource: { column: 'eventId' }, // resource side
305
+ where: { status: 'confirmed' }, // optional filter
306
+ },
307
+ },
308
+ roles: {
309
+ guest: { via: 'guestOf' },
310
+ // Composite: any guest OR an org owner/admin
311
+ eventStaff: {
312
+ or: [
313
+ { via: 'guestOf' },
314
+ { roles: ['admin', 'owner'] },
315
+ ],
316
+ },
317
+ },
318
+ },
319
+ });
320
+ ```
321
+
322
+ ### Using relationship-roles in resources
323
+
324
+ 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.
325
+
326
+ **Today (v1) this works on:**
327
+
328
+ | Surface | Status | Notes |
329
+ |---|---|---|
330
+ | `firewall:` `via:` predicate | ✓ Supported | Subquery composes as outermost AND |
331
+ | `crud.*.access` `roles: ['guest']` | ✓ Supported | Inline async lookup per request |
332
+ | `read.access` / `read.views.*.access` `roles: ['guest']` | ✓ Supported | Same inline path |
333
+ | `masking.<field>.show` `roles: ['guest']` | ⚠ Refused at compile | v1 limitation — async/batched mask functions deferred |
334
+ | `actions.<name>.access` `roles: ['guest']` | ⚠ Refused at compile | v1 limitation — explicit `relationshipBindings` deferred |
335
+
336
+ 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.
337
+
338
+ ### Recommended pattern: gate at the firewall layer
339
+
340
+ 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:
341
+
342
+ ```typescript
343
+ // features/sessions/sessions.ts
344
+ firewall: [
345
+ { field: 'organizationId', equals: 'ctx.activeOrgId' },
346
+ { field: 'eventId', via: 'guestOf' }, // ← row visibility
347
+ ],
348
+ read: {
349
+ access: { roles: ['admin', 'member'] }, // ← who can hit the route
350
+ views: {
351
+ cms: { access: { roles: ['admin', 'member'] }, fields: [...] },
352
+ guest: { access: { roles: ['member', 'admin'] }, fields: [...] },
353
+ },
354
+ },
355
+ ```
356
+
357
+ 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.
358
+
359
+ ### Cross-tenant "my events" dashboards are NOT this
360
+
361
+ 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.
362
+
363
+ For cross-tenant aggregation, use one of:
364
+
365
+ - **User-scoped firewall**: `firewall: { owner: { column: 'userId' } }` — a flat per-user table.
366
+ - **A standalone action that walks the relationship table itself** — see worked example below.
367
+
368
+ Don't reach for relationship-roles first and then get confused when the tenant firewall blocks. The two patterns serve different problems.
369
+
370
+ #### Worked example: `GET /my-events` standalone action
371
+
372
+ 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:
373
+
374
+ ```ts
375
+ // features/dashboard/actions/myEvents.ts
376
+ import { z } from 'zod';
377
+ import { eq, and, inArray } from 'drizzle-orm';
378
+ import { defineAction } from '../.quickback/define-action';
379
+ import { events } from '../../events/events';
380
+ import { guests } from '../../guests/guests';
381
+
382
+ export default defineAction({
383
+ description: "List events the caller is a confirmed guest of, across all tenants.",
384
+ path: '/my-events',
385
+ method: 'GET',
386
+ input: z.object({}),
387
+ // Any signed-in user. Row visibility comes from the query, not the role.
388
+ access: { roles: ['AUTHENTICATED'] },
389
+ async execute({ db, ctx }) {
390
+ // 1. Find every event the caller has a confirmed guest row for.
391
+ const guestRows = await db
392
+ .select({ eventId: guests.eventId })
393
+ .from(guests)
394
+ .where(
395
+ and(
396
+ eq(guests.userId, ctx.userId!),
397
+ eq(guests.status, 'confirmed'),
398
+ // guests.organizationId is NOT filtered here — that's the whole
399
+ // point of the cross-tenant lane. The relationship row's org is
400
+ // ambient information that this action explicitly traverses.
401
+ )
402
+ );
403
+
404
+ if (guestRows.length === 0) return { events: [] };
405
+
406
+ // 2. Pull the matching events. NOTE: this query also bypasses
407
+ // `events.organizationId` scope — by design — so explicitly filter
408
+ // out soft-deleted rows yourself if your `events` table uses them.
409
+ const eventIds = guestRows.map((r) => r.eventId);
410
+ const rows = await db
411
+ .select()
412
+ .from(events)
413
+ .where(inArray(events.id, eventIds));
414
+
415
+ return { events: rows };
416
+ },
417
+ });
418
+ ```
419
+
420
+ Why this is a standalone action and not a CRUD route:
421
+
422
+ - **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.
423
+ - **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.
424
+ - **Audit-logged automatically.** Standalone actions are mandatorily audit-logged in the runtime — the cross-tenant traversal is recorded with `ctx.userId`, IP, and timing.
425
+
426
+ Two important guardrails when you write one of these:
427
+
428
+ 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.
429
+ 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.
430
+
431
+ 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.
432
+
433
+ ### Compile-time refusals (consolidated)
434
+
435
+ The validator and resolver reject:
436
+
437
+ - Unknown key in `authz` block (typo guard — `realtionships` would otherwise silently produce a permanently-denied role).
438
+ - 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.
439
+ - Cycle in role composition (`a → b → a`).
440
+ - Relationship `from` references unknown table.
441
+ - Relationship-role used on a resource missing the `resource.column`.
442
+ - Relationship table with `firewall: { exception: true }` (would let cross-tenant grants slip through).
443
+ - `lowering: 'session'` (reserved for v2 — staleness/invalidation ergonomics not yet shipped).
444
+ - `+` hierarchy suffix on a relationship-role name (terminal, like pseudo-roles).
445
+ - Relationship-roles in `masking.show` / `actions.access` (deferred surfaces — see the table above).
446
+
271
447
  ## Read & CRUD Configuration
272
448
 
273
449
  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:
@@ -113,6 +159,33 @@ When the `firewall:` block is omitted, the compiler scans the schema for known s
113
159
 
114
160
  So `firewall: [{ exception: true }]` on the default configuration returns `isNull(<table>.deletedAt)` from `buildFirewallConditions()` — no tenant filter, soft-delete filter still applied.
115
161
 
162
+ ## Sysadmin Escape Hatch
163
+
164
+ When `cms: { sysadmin: true }` is set on the project (introduced in v0.15.0), every `buildFirewallConditions()` emits a runtime branch that drops tenant scopes for `ctx.userRole === 'sysadmin'` callers while keeping the soft-delete predicate:
165
+
166
+ ```typescript
167
+ // Generated for an org-scoped table when cms.sysadmin: true
168
+ export function buildFirewallConditions(ctx: AppContext): SQL | undefined {
169
+ if (ctx.userRole === 'sysadmin') {
170
+ return isNull(invoices.deletedAt); // tenant predicate dropped, soft-delete kept
171
+ }
172
+ return and(
173
+ eq(invoices.organizationId, ctx.activeOrgId!),
174
+ isNull(invoices.deletedAt),
175
+ );
176
+ }
177
+ ```
178
+
179
+ The escape branch is **only** emitted when:
180
+
181
+ - `cms.sysadmin: true` is set on the project config
182
+ - The table has at least one tenant-scope predicate (org / owner / team / `via:` relationship). Tables with no tenant scopes already return what a sysadmin would see, so the runtime check would be dead code.
183
+ - The firewall does not declare `{ exception: true }` (no tenant scopes to drop).
184
+
185
+ **Sysadmin is distinct from admin.** `userRole === 'admin'` callers still go through the firewall normally — only `userRole === 'sysadmin'` triggers the bypass. Admins keep their existing universal-bypass at the *access* layer (cross-org reads on per-record routes via `?organizationId=`), but the firewall's row predicate remains in force. Sysadmin is opt-in, configured per-project, and intended for the cross-tenant CMS DB-admin tier — see [CMS Configuration](/compiler/config#cms-configuration).
186
+
187
+ If your project doesn't set `cms.sysadmin: true`, the escape branch is never emitted and the role value is functionally inert.
188
+
116
189
  ## Common Patterns
117
190
 
118
191
  ```typescript
@@ -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
 
@@ -309,6 +309,15 @@ These internal tables still participate in the database schema and migrations
309
309
 
310
310
  The compiler automatically injects the four **[audit fields](#audit-fields)** (`createdAt`/`createdBy`/`modifiedAt`/`modifiedBy`), the soft-delete pair (`deletedAt`/`deletedBy`, when soft delete is enabled), and **`organizationId`** into child/junction tables when the parent feature is org-scoped. This ensures cascade soft deletes and scoped queries work correctly without manual column definitions.
311
311
 
312
+ > **`id` is currently NOT auto-injected — declare it yourself**
313
+ >
314
+ > Unlike audit fields, the `id` column is your responsibility today. The CRUD/action route generators, FK probing, access checks, and OpenAPI emission all assume every queryable table has a single string-typed `id` column. Tables that omit it — or use a non-`id` single PK (`userId.primaryKey()`) or a compound `primaryKey({ columns: [...] })` constraint — parse fine but produce broken generated code downstream.
315
+ >
316
+ > Use `q.id()` (preferred) or `id: text("id").primaryKey()` / `id: integer("id").primaryKey({ autoIncrement: true })` on every table that participates in routes. For internal tables marked `// @quickback-internal`, the constraint doesn't apply.
317
+ >
318
+ > This asymmetry is being closed in **v0.14.8** — `injectIdField` will run unconditionally alongside audit injection, including on junction tables. See the [v0.14.7 changelog](/docs/changelog#coming-next--id-field-auto-injection-v0148) for the migration plan.
319
+
320
+
312
321
  ## Audit Fields
313
322
 
314
323
  Quickback adds four audit columns to **every table** (including child/junction tables without `defineTable`) — never declare them in your schemas: