@quickback-dev/cli 0.59.0 → 0.59.1

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 (97) 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 +41 -21
  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/output.md +64 -0
  70. package/package.json +1 -1
  71. package/src/skill/SKILL.md +45 -0
  72. package/src/skill/agents/quickback-specialist/AGENT.md +18 -1
  73. package/src/skill/docs/changelog/index.md +28 -2
  74. package/src/skill/docs/changelog/v0.1x.md +2 -2
  75. package/src/skill/docs/configure/agents.md +19 -0
  76. package/src/skill/docs/configure/index.md +1 -1
  77. package/src/skill/docs/define/access.md +23 -820
  78. package/src/skill/docs/define/actions/access.md +4 -4
  79. package/src/skill/docs/define/areas.md +307 -4
  80. package/src/skill/docs/define/authz-roles.md +164 -0
  81. package/src/skill/docs/define/changesets.md +1 -1
  82. package/src/skill/docs/define/fga.md +1 -1
  83. package/src/skill/docs/define/firewall.md +3 -3
  84. package/src/skill/docs/define/index.md +32 -3
  85. package/src/skill/docs/define/masking.md +1 -1
  86. package/src/skill/docs/define/permissions.md +1 -1
  87. package/src/skill/docs/define/read.md +103 -1
  88. package/src/skill/docs/define/relationships.md +313 -0
  89. package/src/skill/docs/define/scopes.md +1 -1
  90. package/src/skill/docs/platform/realtime/using-realtime.md +1 -1
  91. package/src/skill/docs/platform/storage/r2.md +39 -0
  92. package/src/skill/docs/platform/webhooks/inbound.md +17 -6
  93. package/src/skill/docs/start/deploy-browser.md +118 -0
  94. package/src/skill/docs/start/deploy-owner-access.md +62 -0
  95. package/src/skill/docs/start/deploy.md +2 -0
  96. package/src/skill/docs/tooling/cli.md +22 -0
  97. package/src/skill/docs/tooling/output.md +64 -0
@@ -2,6 +2,29 @@
2
2
 
3
3
  Define who can perform read and write operations and under what conditions.
4
4
 
5
+ ## Which primitive do I need?
6
+
7
+ Start here. **Most apps need only the first row** — this page, and nothing below it.
8
+
9
+ | The rule you're expressing | Use | Where |
10
+ |---|---|---|
11
+ | "Anyone in the org, with this role" | `roles: ['member+']` / `['admin+']` | this page |
12
+ | "Any signed-in caller" | `roles: ['AUTHENTICATED']` | [below](#authenticated--any-authenticated-caller-the-wrapper) |
13
+ | "Only the caller's own rows" | `roles: ['USER']` + an `ownerId` firewall | [below](#user--per-user-records) |
14
+ | "Anyone at all, signed in or not" | `roles: ['PUBLIC']` | [below](#public--unauthenticated-access) |
15
+ | "Platform operators, regardless of org" | `userRole: ['appmanager']` | [below](#userrole-vs-roles) |
16
+ | The same expression, repeated across many features | `authz.roles` / `authz.rules` | [Named rules](/define/authz-roles) |
17
+ | "The caller has a row in *my* table linking them to this record" | `authz.relationships` | [Relationships](/define/relationships) |
18
+ | A permission *graph* — derived, inherited, share links | FGA | [FGA](/define/fga) |
19
+
20
+ > **If org membership answers it, stop here**
21
+ >
22
+ > Org membership is decided before your handler runs and arrives as `ctx.roles`. Do **not**
23
+ > declare a relationship to ask "is this person in the org?" — a relationship's `from:` must
24
+ > be one of *your* feature tables, and the compiler rejects one pointing at Better Auth's
25
+ > `organization_memberships`. See [the authorization ladder](/define#the-authorization-ladder).
26
+
27
+
5
28
  ## Basic Usage
6
29
 
7
30
  ```typescript
@@ -367,773 +390,6 @@ type FieldCondition =
367
390
  | { greaterThanOrEqual: number };
368
391
  ```
369
392
 
370
- ## Centrally defined access rules
371
-
372
- 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.
373
-
374
- Named roles (and named gates, tenant anchors, scope kinds) can be declared at **two levels**:
375
- at root `authz` in `quickback.config.ts` (visible everywhere), or inside a
376
- [feature area](/define/areas)'s `_area.ts` (visible to that area's
377
- subtree only — a feature outside the area referencing the name is a compile error, and root
378
- `authz` bodies may reference root-declared names only). Declare each name in exactly one
379
- place: re-declaring an inherited name is a compile error.
380
-
381
- ```typescript
382
- // quickback.config.ts — define ONCE
383
- export default defineConfig({
384
- // ...providers...
385
- authz: {
386
- roles: {
387
- // Compose from BA roles, pseudo-roles, and other named rules:
388
- staff: { roles: ['admin', 'member'] },
389
- // Boolean combinators:
390
- eventStaff: { or: [{ roles: ['staff'] }, { via: 'organizerOf' }] },
391
- // Relationship-backed (see below):
392
- attendee: { via: 'attendeeOf' },
393
- },
394
- },
395
- });
396
- ```
397
-
398
- ```typescript
399
- // any feature — REFERENCE by bare name
400
- import { q, defineTable } from '@quickback/compiler';
401
-
402
- export const agendaItems = q.table('agendaItems', {
403
- id: q.id(),
404
- title: q.text().required(),
405
- startsAt: q.text().required(),
406
- organizationId: q.scope('organization'),
407
- ...q.audit(),
408
- ...q.softDelete(),
409
- });
410
-
411
- export default defineTable(agendaItems, {
412
- read: { access: { roles: ['eventStaff'] } },
413
- update: { access: { roles: ['eventStaff'] } },
414
- });
415
-
416
- // features/events/actions/checkIn.ts
417
- import { z } from "zod";
418
- import { defineAction } from "../.quickback/define-action";
419
-
420
- export default defineAction({
421
- description: "Check a guest in to the event and record the arrival time.",
422
- input: z.object({ guestId: z.string() }),
423
- access: { roles: ['eventStaff', 'attendee'] },
424
- async execute({ db, input, ctx }) { /* ... */ },
425
- });
426
- ```
427
-
428
- ### Rule shapes
429
-
430
- Each entry in `authz.roles` is one of four shapes:
431
-
432
- | Shape | Meaning |
433
- |---|---|
434
- | `{ roles: ['admin', 'member'] }` | Composition — matches any of the listed roles (BA, pseudo, or other named rules) |
435
- | `{ or: [ruleA, ruleB] }` | Matches if **any** sub-rule matches |
436
- | `{ and: [ruleA, ruleB] }` | Matches only if **all** sub-rules match |
437
- | `{ via: 'relationshipName' }` | Caller proves a declared relationship — see [Relationship-based authorization](#relationship-based-authorization) below |
438
-
439
- Rules compose freely — a rule may reference another rule by name (cycles are a compile error).
440
-
441
- ### Where references resolve
442
-
443
- A named rule works in the `roles: [...]` array of every access surface. The compiler expands it at build time:
444
-
445
- | Surface | |
446
- |---|---|
447
- | `crud.*.access` | ✓ |
448
- | `read.access` / `read.views.*.access` | ✓ |
449
- | `masking.<field>.show` | ✓ for role/composite rules; relationship (`via`) rules refused at compile (v1) |
450
- | `actions.<name>.access` | ✓ |
451
- | `realtime.requiredRoles` | ✓ — relationship arms fail closed at the WS handshake and are enforced by the row-stream firewall |
452
-
453
- 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.
454
-
455
- ### Beyond roles: named permissions
456
-
457
- 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`.
458
-
459
- ## Named gates (`authz.rules`)
460
-
461
- `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:
462
-
463
- ```typescript
464
- // quickback.config.ts
465
- authz: {
466
- tenants: { org: { column: 'organizationId', equals: 'ctx.activeOrgId' } },
467
- rules: {
468
- // who + record: "org staff, but only rows still active"
469
- activeStaff: {
470
- who: { roles: ['member', 'admin', 'owner'] },
471
- record: { status: { equals: 'active' } },
472
- },
473
- // who + firewall: an org-OR-event-scope row gate, declared ONCE
474
- eventRow: {
475
- who: { roles: ['owner', 'admin', 'member'] },
476
- firewall: [{ any: [
477
- { tenant: 'org' },
478
- { field: 'eventId', equals: 'ctx.scope.event' },
479
- ] }],
480
- },
481
- },
482
- }
483
- ```
484
-
485
- {/* 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. */}
486
- ```typescript
487
- // any feature — the gate name works like a role name
488
- export default defineTable(eventLinks, {
489
- firewall: [{ rule: 'eventRow' }], // firewall stamp
490
- read: { access: { roles: ['eventRow'] } }, // access stamp
491
- });
492
- ```
493
-
494
- ### The two-stamp contract
495
-
496
- One shared name, two independent stamps — **a single reference never applies both**:
497
-
498
- - 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 }] }`.
499
- - 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).
500
-
501
- Both directions are enforced fail-closed at compile time:
502
-
503
- | You wrote | Compiler says |
504
- |---|---|
505
- | Access reference to a firewall-bearing gate, but the resource's `firewall:` doesn't reference it | **Error** — the row lanes would silently not apply |
506
- | `firewall: [{ rule }]` naming a gate with no `firewall` arm | **Error** — a who/record-only gate would splice zero lanes |
507
- | 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) |
508
- | A who-less (firewall-only) gate referenced from an access position | **Error** — row lanes can't masquerade as a who-grant |
509
- | 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*) |
510
- | 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 |
511
-
512
- ### Naming rules
513
-
514
- 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).
515
-
516
- 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.
517
-
518
- ### Typo safety
519
-
520
- 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.
521
-
522
- ## Relationship-based authorization
523
-
524
- 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. These are the `{ via: '...' }` rule shape from [Centrally defined access rules](#centrally-defined-access-rules) above.
525
-
526
- ### `authz.relationships`
527
-
528
- Declare relationships once in `quickback.config.ts`:
529
-
530
- ```typescript
531
- // quickback.config.ts
532
- import { defineConfig } from '@quickback/compiler';
533
-
534
- export default defineConfig({
535
- // ...providers...
536
- authz: {
537
- relationships: {
538
- guestOf: {
539
- from: 'event_guests', // table name string
540
- subject: { column: 'userId', equals: 'ctx.userId' }, // caller side
541
- resource: { column: 'eventId' }, // resource side
542
- where: { status: 'confirmed' }, // optional filter
543
- },
544
- },
545
- roles: {
546
- guest: { via: 'guestOf' },
547
- // Composite: any guest OR an org owner/admin
548
- eventStaff: {
549
- or: [
550
- { via: 'guestOf' },
551
- { roles: ['admin', 'owner'] },
552
- ],
553
- },
554
- },
555
- },
556
- });
557
- ```
558
-
559
- ### Using relationship-roles in resources
560
-
561
- 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.
562
-
563
- #### Supported relationship-role surfaces
564
-
565
- | Surface | Status | Notes |
566
- |---|---|---|
567
- | `firewall:` `via:` predicate | ✓ Supported | Subquery composes as outermost AND |
568
- | `crud.*.access` `roles: ['guest']` | ✓ Supported | Inline async lookup per request |
569
- | `read.access` / `read.views.*.access` `roles: ['guest']` | ✓ Supported | Same inline path |
570
- | **Standalone** `actions.<name>.access` `roles: ['guest']` | ✓ Supported | Inline gate; the surface exposes `resource.column` as a path param or input field |
571
- | **Record-based** `actions.<name>.access` `roles: ['guest']` | ✓ Supported | Inline lookup uses the already-loaded, firewalled record |
572
- | Namespace `via` lanes | ✓ Supported | Hoisted middleware resolves once and can hydrate `ctx.<exposeAs>` |
573
- | `masking.<field>.show` `roles: ['guest']` | Build-time refusal | Use a relationship-gated view for field projection; per-row async masking is not approximated |
574
-
575
- Relationship roles are therefore available across CRUD, reads, standalone
576
- actions, record-based actions, and namespace mounts. Masking is the one
577
- different execution surface: list masking must stay synchronous and batched, so
578
- the compiler rejects a relationship-bearing `masking.show` rule and points to a
579
- relationship-gated view instead. It never drops the relationship arm or turns
580
- it into a broader role grant.
581
-
582
- ### Standalone actions: surface keys and `loads` / `exposeAs` (v0.19+)
583
-
584
- When a standalone action's `access.roles` references a relationship-role, the compiler emits a runtime gate between input validation and `execute()`. The gate reads the relationship's `resource.column` value from the action surface — either a path parameter (`:eventId`) or an input field (`input.eventId`). If neither is present, the current compiler stops with a clear build error; an action can never ship with a relationship rule it has no key to evaluate.
585
-
586
- Pair the relationship with `loads` + `exposeAs` to hydrate the loaded resource onto `ctx`:
587
-
588
- ```typescript
589
- authz: {
590
- relationships: {
591
- attendeeOf: {
592
- from: 'guests',
593
- subject: { column: 'userId', equals: 'ctx.userId' },
594
- resource: { column: 'eventId' },
595
- where: { status: 'confirmed' },
596
- loads: 'events', // ← v0.19+: load matching event row
597
- exposeAs: 'event', // ← onto ctx.event for the action body
598
- },
599
- },
600
- roles: {
601
- attendee: { via: 'attendeeOf' },
602
- },
603
- }
604
- ```
605
-
606
- The resolver (v0.20):
607
-
608
- 1. **Cheap in-memory role check** first — `ctx.roles?.includes('admin')` and friends. If the caller has a qualifying role, this short-circuits and no DB queries fire for the access gate.
609
- 2. **Firewall-gated relationship match** if the role check failed — `SELECT { organizationId, teamId } FROM guests WHERE userId=ctx.userId AND eventId=input.eventId AND status='confirmed'` with the `guests` table's full firewall AND-applied. If neither role nor relationship qualifies → 403.
610
- 3. **Tenant stamping from the matched row** — for any tenant column the `from` table carries (`organizationId`, `teamId`), the resolver stamps `ctx.activeOrgId ??= matchedRow.organizationId` (and similar for team). This is **in-memory mutation of the request-scoped ctx only** — no JWT remint, no session-record write, no persistent grant.
611
- 4. **Firewall-gated load of the loaded resource** — `SELECT * FROM events WHERE id = :eventId AND buildEventsFirewallConditions(ctx, db)`. The events firewall is applied as normal; it succeeds for attendees because tenant was just stamped from the relationship row.
612
- 5. Assigns the loaded row to `ctx.event` for the action body.
613
-
614
- **No firewall bypass anywhere.** Both queries run with their respective tables' full firewalls. The relationship row's existence is the proof that the caller is authorized; its tenant columns are the source of the stamped claim.
615
-
616
- ### Conditional tenant preconditions (v0.20+)
617
-
618
- Standalone actions in features with org/team-scoped tables previously emitted unconditional preconditions:
619
-
620
- ```ts
621
- if (!ctx.activeOrgId) return c.json(AccessErrors.noOrg(), 403);
622
- if (!ctx.activeTeamId) return c.json(AccessErrors.noTeam(), 403);
623
- ```
624
-
625
- These ran **before** the relationship resolver, which 403'd attendees whose sessions don't carry an active tenant claim (the canonical event-attendee shape).
626
-
627
- v0.20 makes these preconditions **conditional on relationship supply**. If the access tree contains a relationship arm whose `from` table carries the matching tenant column, the precondition is skipped — the resolver runs first and stamps the value. Pseudo-role short-circuits (PUBLIC / AUTHENTICATED / USER / SYSADMIN) and `firewall: { exception: true }` still bypass the preconditions as before. `ADMIN` is now rejected at compile time.
628
-
629
- Typical event-attendee setup (`guests` table carries `organizationId`): the org precondition is dropped on every action whose access references `attendee` or `eventStaff`. Org admins still get `ctx.activeOrgId` from their session as today; attendees get it from the relationship row, mid-request. Both paths converge on a valid tenant claim before `execute()` runs.
630
-
631
- ### Requirement on the relationship's `from` table
632
-
633
- For the v0.20 tenant-stamping to work, the relationship's `from` table must carry tenant columns:
634
-
635
- - For org stamping: an `organizationId` column (or whatever spelling the project's auth-provider defaults pick).
636
- - For team stamping: a `teamId` column.
637
-
638
- When the `from` table has **neither**, the compiler emits a `[quickback:authz]` warning at compile time:
639
-
640
- ```
641
- Relationship "X" at authz.relationships.X has no organization or team columns
642
- on its `from` table ("guests"). Action "Y" will compile, but downstream
643
- scoped-db queries inside execute() may 403 because ctx.activeOrgId /
644
- activeTeamId cannot be stamped from the match row. Either add the tenant
645
- column to "guests", or set firewall: { exception: true } on the action.
646
- ```
647
-
648
- The relationship match still works (existence check), but no tenant gets stamped — so the conventional precondition still fires and the action still 403s for callers without a session-resident tenant claim. Add the tenant column (or denormalize it onto the relationship table during writes) to enable the stamping path.
649
-
650
- The body can then trust `ctx.event` and drop the hand-rolled `SELECT … FROM guests WHERE …` boilerplate:
651
-
652
- ```ts
653
- // features/chat/actions/getInbox.ts
654
- import { z } from "zod";
655
- import { defineAction } from "../.quickback/define-action";
656
-
657
- export default defineAction({
658
- description: "List the caller's chat inbox for one event they attend.",
659
- path: '/chat/get-inbox',
660
- input: z.object({ eventId: z.number().int().positive() }),
661
- access: { roles: ['admin', 'member', 'attendee'] }, // attendee is a relationship-role
662
- execute: async ({ db, ctx, input }) => {
663
- // No hand-rolled attendance check needed — the resolver already ran.
664
- // ctx.event is the loaded events row. Typed as `any` here because the
665
- // hand-rolled `roles: ['attendee']` action gates per-action, not per-
666
- // namespace — see "Narrow ctx.<exposeAs> typing" below for the typed
667
- // import flip available when the same hydration runs through a
668
- // namespace mount.
669
- const event = ctx.event as typeof events.$inferSelect;
670
- // … domain logic only.
671
- },
672
- });
673
- ```
674
-
675
- `loads` and `exposeAs` are co-required (set both or neither). `exposeAs` must be a valid JS identifier and must not collide with built-in `ctx` fields (`userId`, `activeOrgId`, `activeTeamId`, `db`, etc.).
676
-
677
- ### Action firewall escape hatch (v0.19+)
678
-
679
- `defineAction({ firewall: { exception: true } })` opts the action out of the inherited session-key preconditions (`ctx.activeOrgId` / `ctx.activeTeamId` requirements) AND the relationship resolver. The handler receives `unsafeDb` for raw Drizzle access. Use for cross-tenant or admin routes whose surface intentionally doesn't name a session/relationship key:
680
-
681
- {/* doc-compile: skip — project-config prerequisite: `roles: ["SYSADMIN"]` requires `cms: { sysadmin: true }` in quickback.config.ts (documented above under SYSADMIN), and the gate compiles every fence against one fixed harness config that does not set it. */}
682
- ```ts
683
- // features/admin/actions/crossTenantReport.ts
684
- import { z } from "zod";
685
- import { defineAction } from "../.quickback/define-action";
686
-
687
- export default defineAction({
688
- description: "Report activity across every tenant for a date range (sysadmin only).",
689
- path: '/admin/cross-tenant-report',
690
- input: z.object({ since: z.string(), until: z.string() }),
691
- firewall: { exception: true },
692
- unsafe: { reason: 'cross-tenant audit', adminOnly: true, targetScope: 'all' },
693
- access: { roles: ['SYSADMIN'] },
694
- execute: async ({ unsafeDb, ctx }) => { /* cross-org query */ },
695
- });
696
- ```
697
-
698
- `firewall: { exception: true }` is the declarative twin of `unsafe: true` — they're conceptually distinct: `firewall.exception` opts out of the gate-emission pillars; `unsafe` signals audit/cross-tenant intent (and still applies for logging). Most cross-tenant actions set both.
699
-
700
- ### Recommended pattern: gate at the firewall layer
701
-
702
- 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:
703
-
704
- ```typescript
705
- // features/sessions/sessions.ts
706
- firewall: [
707
- { field: 'organizationId', equals: 'ctx.activeOrgId' },
708
- { field: 'eventId', via: 'guestOf' }, // ← row visibility
709
- ],
710
- read: {
711
- access: { roles: ['admin', 'member'] }, // ← who can hit the route
712
- views: {
713
- cms: { access: { roles: ['admin', 'member'] }, fields: [...] },
714
- guest: { access: { roles: ['member', 'admin'] }, fields: [...] },
715
- },
716
- },
717
- ```
718
-
719
- 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.
720
-
721
- ### Cross-tenant "my events" dashboards are NOT this
722
-
723
- 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.
724
-
725
- For cross-tenant aggregation, use one of:
726
-
727
- - **User-scoped firewall**: `firewall: { owner: { column: 'userId' } }` — a flat per-user table.
728
- - **A standalone action that walks the relationship table itself** — see worked example below.
729
-
730
- Don't reach for relationship-roles first and then get confused when the tenant firewall blocks. The two patterns serve different problems.
731
-
732
- #### Worked example: `GET /my-events` standalone action
733
-
734
- 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:
735
-
736
- ```ts
737
- // features/dashboard/actions/myEvents.ts
738
- import { z } from 'zod';
739
- import { eq, and, inArray } from 'drizzle-orm';
740
- import { defineAction } from '../.quickback/define-action';
741
- import { events } from '../../events/events';
742
- import { guests } from '../../guests/guests';
743
-
744
- export default defineAction({
745
- description: "List events the caller is a confirmed guest of, across all tenants.",
746
- path: '/my-events',
747
- method: 'GET',
748
- input: z.object({}),
749
- // Any signed-in user. Row visibility comes from the query, not the role.
750
- access: { roles: ['AUTHENTICATED'] },
751
- async execute({ db, ctx }) {
752
- // 1. Find every event the caller has a confirmed guest row for.
753
- const guestRows = await db
754
- .select({ eventId: guests.eventId })
755
- .from(guests)
756
- .where(
757
- and(
758
- eq(guests.userId, ctx.userId!),
759
- eq(guests.status, 'confirmed'),
760
- // guests.organizationId is NOT filtered here — that's the whole
761
- // point of the cross-tenant lane. The relationship row's org is
762
- // ambient information that this action explicitly traverses.
763
- )
764
- );
765
-
766
- if (guestRows.length === 0) return { events: [] };
767
-
768
- // 2. Pull the matching events. NOTE: this query also bypasses
769
- // `events.organizationId` scope — by design — so explicitly filter
770
- // out soft-deleted rows yourself if your `events` table uses them.
771
- const eventIds = guestRows.map((r) => r.eventId);
772
- const rows = await db
773
- .select()
774
- .from(events)
775
- .where(inArray(events.id, eventIds));
776
-
777
- return { events: rows };
778
- },
779
- });
780
- ```
781
-
782
- Why this is a standalone action and not a CRUD route:
783
-
784
- - **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.
785
- - **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.
786
- - **Audit-logged automatically.** Standalone actions are mandatorily audit-logged in the runtime — the cross-tenant traversal is recorded with `ctx.userId`, IP, and timing.
787
-
788
- Two important guardrails when you write one of these:
789
-
790
- 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.
791
- 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.
792
-
793
- 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.
794
-
795
- ### Compile-time refusals (consolidated)
796
-
797
- The validator and resolver reject:
798
-
799
- - Unknown key in `authz` block (typo guard — `realtionships` would otherwise silently produce a permanently-denied role).
800
- - 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.
801
- - Cycle in role composition (`a → b → a`).
802
- - Relationship `from` references unknown table.
803
- - Relationship-role used on a resource missing the `resource.column`.
804
- - Relationship table with `firewall: { exception: true }` (would let cross-tenant grants slip through).
805
- - `lowering: 'session'` (reserved for v2 — staleness/invalidation ergonomics not yet shipped).
806
- - `+` hierarchy suffix on a relationship-role name (terminal, like pseudo-roles).
807
- - Relationship-backed rules in `masking.show` (use a relationship-gated view
808
- for field projection; action access is fully supported).
809
-
810
- ## Namespace mounts (hoisted relationship middleware)
811
-
812
- 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).
813
-
814
- 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.
815
-
816
- ### When to use roles vs. relationships
817
-
818
- A user is authorized for a row when **any** of the following is true:
819
-
820
- - they have a **per-row relationship** to it (e.g. an attendee row, a named organizer row), or
821
- - they have a **role on the row's tenant** (org admin/owner of the row's `organizationId`), or
822
- - they have **team membership** matching the row's `teamId`.
823
-
824
- 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.
825
-
826
- 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.
827
-
828
- > **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.
829
-
830
- Two declaration sites depending on whether the participating actions live in one feature or many:
831
-
832
- ### Single feature: `defineTable({ namespace })` (v0.23+)
833
-
834
- 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.
835
-
836
- {/* 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. */}
837
- ```typescript
838
- // features/events/events.ts
839
- import { q, defineTable } from '@quickback/compiler';
840
-
841
- export const events = q.table('events', {
842
- id: q.id(),
843
- name: q.text().required(),
844
- organizationId: q.scope('organization'),
845
- ...q.audit(),
846
- ...q.softDelete(),
847
- });
848
-
849
- export default defineTable(events, {
850
- firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],
851
- namespace: {
852
- prefix: '/event/:eventId', // absolute URL path
853
- via: 'attendeeOf', // relationship gate (must exist in authz.relationships)
854
- },
855
- });
856
-
857
- // features/events/actions/postAnnouncement.ts
858
- import { z } from "zod";
859
- import { defineAction } from "../.quickback/define-action";
860
-
861
- export default defineAction({
862
- description: "Post an announcement to everyone attending the event.",
863
- path: '/event/:eventId/announcements',
864
- method: 'POST',
865
- input: z.object({ body: z.string().max(2000) }),
866
- // No `via:` gate boilerplate — the namespace already ran the resolver, so
867
- // `access` only names roles and ctx.event is typed inside execute().
868
- access: { roles: ['admin', 'member'] },
869
- async execute({ db, input, ctx }) { /* … */ },
870
- });
871
- ```
872
-
873
- 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.
874
-
875
- 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.
876
-
877
- ### Cross-feature: `authz.namespaces` (v0.24+)
878
-
879
- Use when the namespace spans multiple features. The declaration sits next to your other authz config in `quickback.config.ts`.
880
-
881
- ```typescript
882
- // quickback.config.ts
883
- authz: {
884
- relationships: {
885
- attendeeOf: {
886
- from: 'guests',
887
- subject: { column: 'userId', equals: 'ctx.userId' },
888
- resource: { column: 'eventId' },
889
- loads: 'events',
890
- exposeAs: 'event',
891
- },
892
- },
893
- namespaces: {
894
- eventScope: { prefix: '/event/:eventId', via: 'attendeeOf' },
895
- },
896
- }
897
- ```
898
-
899
- With the namespace declared, any standalone action whose `path:` matches the prefix joins the gate — regardless of which feature owns it:
900
-
901
- ```typescript
902
- // features/feeds/actions/feedMoments.ts (in one feature)
903
- import { z } from "zod";
904
- import { defineAction } from "../.quickback/define-action";
905
-
906
- export default defineAction({
907
- description: "Publish a moment to the event's live feed.",
908
- path: '/event/:eventId/feed-moments',
909
- method: 'POST',
910
- input: z.object({ caption: z.string().max(280), photoId: z.string().optional() }),
911
- access: { roles: ['admin', 'member'] },
912
- async execute({ db, input, ctx }) { /* … */ },
913
- });
914
-
915
- // features/rsvp/actions/respond.ts (in a different feature)
916
- import { z } from "zod";
917
- import { defineAction } from "../.quickback/define-action";
918
-
919
- export default defineAction({
920
- description: "Record the caller's RSVP for the event.",
921
- path: '/event/:eventId/respond',
922
- method: 'POST',
923
- input: z.object({ response: z.enum(['yes', 'no', 'maybe']) }),
924
- access: { roles: ['admin', 'member'] },
925
- async execute({ db, input, ctx }) { /* … */ },
926
- });
927
- ```
928
-
929
- 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.
930
-
931
- ### Multi-lane via (v0.25+) — first match wins
932
-
933
- 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.
934
-
935
- ```typescript
936
- authz: {
937
- relationships: {
938
- attendeeOf: {
939
- from: 'guests',
940
- subject: { column: 'linkedUserId', equals: 'ctx.userId' },
941
- resource: { column: 'eventId' },
942
- where: { status: 'confirmed' },
943
- loads: 'events',
944
- exposeAs: 'event',
945
- },
946
- // Named per-event organizers (potentially EXTERNAL — these users may
947
- // not be a member of the event's org. That's the point: lets you grant
948
- // event-level access to freelancers / partner staff without adding
949
- // them to the org's member list.)
950
- organizerOf: {
951
- from: 'eventOrganizers',
952
- subject: { column: 'linkedUserId', equals: 'ctx.userId' },
953
- resource: { column: 'eventId' },
954
- loads: 'events',
955
- exposeAs: 'event',
956
- },
957
- },
958
- namespaces: {
959
- eventScope: {
960
- prefix: '/event/:eventId',
961
- via: ['attendeeOf', 'organizerOf'],
962
- },
963
- },
964
- }
965
- ```
966
-
967
- 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.
968
-
969
- ### Bulk-grant lanes (v0.26+)
970
-
971
- 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.
972
-
973
- ```typescript
974
- namespaces: {
975
- eventScope: {
976
- prefix: '/event/:eventId',
977
- via: [
978
- 'attendeeOf',
979
- 'organizerOf',
980
- { roles: ['admin', 'owner'] }, // org-role bulk grant
981
- { team: true }, // active-team-membership bulk grant
982
- ],
983
- },
984
- }
985
- ```
986
-
987
- Each bulk-grant lane:
988
-
989
- - **`{ 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.
990
- - **`{ 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.
991
-
992
- 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:`).
993
-
994
- 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.
995
-
996
- 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).
997
-
998
- ### Discovery is path-prefix-only
999
-
1000
- 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.
1001
-
1002
- ### Requirements (enforced at compile time)
1003
-
1004
- Both forms share the same shape checks:
1005
-
1006
- - **`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 }`).
1007
- - **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.
1008
- - **All relationship lanes in one namespace must agree on `loads:` + `exposeAs:`.** Otherwise `ctx.<exposeAs>` would change shape depending on which lane matched.
1009
- - **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.
1010
- - **`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.
1011
- - **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.
1012
-
1013
- Project-level only:
1014
-
1015
- - **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.
1016
- - **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.
1017
-
1018
- ### What namespace actions get for free
1019
-
1020
- Inside a namespace action's `execute()`:
1021
-
1022
- - `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)).
1023
- - 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.
1024
- - 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.
1025
-
1026
- ### Narrow `ctx.<exposeAs>` typing (v0.27+)
1027
-
1028
- 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.
1029
-
1030
- 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.
1031
-
1032
- ```ts title="features/feeds/actions/feedMoments.ts"
1033
- // One-line flip per namespace-scoped action:
1034
- import { z } from 'zod';
1035
- import { defineAction } from '../.quickback/define-action.event-scope';
1036
- // └──────┬──────┘
1037
- // kebab(namespaceName)
1038
-
1039
- export default defineAction({
1040
- description: "Publish a moment to the event's live feed.",
1041
- path: '/event/:eventId/feed-moments',
1042
- method: 'POST',
1043
- input: z.object({ body: z.string() }),
1044
- access: { roles: ['attendee'] },
1045
- async execute({ ctx, input }) {
1046
- ctx.event.id // ✓ string
1047
- ctx.event.startsAt // ✓ Date — autocomplete works
1048
- ctx.event.organizerId // ✓ narrows on the field's declared type
1049
-
1050
- ctx.event.idd // ✗ TS2339 — typo caught at compile time
1051
- },
1052
- });
1053
- ```
1054
-
1055
- 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.
1056
-
1057
- #### Opt-in, not breaking
1058
-
1059
- 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.
1060
-
1061
- #### Compile-time advisory
1062
-
1063
- When `quickback compile` sees a namespace-scoped action still importing the generic helper, it emits a one-line advisory pointing at the narrowed path:
1064
-
1065
- ```text
1066
- [quickback:typing] action "feedMoments" in feature "feeds" lives under
1067
- namespace "eventScope" — switch its import to
1068
- `../.quickback/define-action.event-scope` for narrow ctx.<exposeAs> typing.
1069
- (Runtime behavior is unchanged; the narrowed helper only refines TS types.)
1070
- ```
1071
-
1072
- 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).
1073
-
1074
- #### Multi-namespace features
1075
-
1076
- 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.
1077
-
1078
- ```text
1079
- src/features/interviews/.quickback/
1080
- ├── define-action.ts # generic — standard fallback
1081
- ├── define-action.interview-scope.ts # ctx.interview typed
1082
- └── define-action.event-scope.ts # ctx.event typed
1083
- ```
1084
-
1085
- #### Why per-namespace and not per-action
1086
-
1087
- 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.
1088
-
1089
- ## Read & Write Configuration
1090
-
1091
- Reads (`GET /` and `GET /:id`) live under `read:`; mutations live under top-level `create:`, `update:`, `delete:`, and `upsert:`. See [Read](/define/read) for the full read pipeline reference.
1092
-
1093
- ```typescript
1094
- read: {
1095
- // LIST + GET - GET /resource and GET /resource/:id
1096
- access: { roles: ["owner", "hiring-manager", "recruiter", "interviewer"] },
1097
- pageSize: 25, // Default page size
1098
- maxPageSize: 100, // Client can't exceed this
1099
- views: { // Per-view field projections
1100
- summary: {
1101
- fields: ['id', 'candidateId', 'jobId', 'stage'],
1102
- access: { roles: ["interviewer"] },
1103
- },
1104
- },
1105
- }
1106
-
1107
- create: {
1108
- // CREATE - POST /resource
1109
- access: { roles: ["owner", "hiring-manager", "recruiter"] },
1110
- defaults: { // Default values for new records
1111
- stage: 'applied',
1112
- },
1113
- },
1114
-
1115
- update: {
1116
- // UPDATE - PATCH /resource/:id
1117
- access: {
1118
- or: [
1119
- { roles: ["hiring-manager", "recruiter"] },
1120
- { roles: ["interviewer"], record: { stage: { equals: "interview" } } }
1121
- ]
1122
- },
1123
- },
1124
-
1125
- delete: {
1126
- // DELETE - DELETE /resource/:id
1127
- access: { roles: ["owner", "hiring-manager"] },
1128
- mode: "soft", // 'soft' (default) or 'hard'
1129
- },
1130
-
1131
- upsert: {
1132
- // PUT - PUT /resource/:id (only when generateId: false + guards: false)
1133
- access: { roles: ["hiring-manager", "sync-service"] },
1134
- }
1135
- ```
1136
-
1137
393
  ## Evaluation Order
1138
394
 
1139
395
  Generated `/:id` and batch handlers evaluate access in this fixed order:
@@ -1155,59 +411,6 @@ opaque 404 instead.
1155
411
  Function-form access (`access: async (ctx, record) => ...`) is opaque to
1156
412
  the pre-record phase and always passes there; it's fully evaluated post-record.
1157
413
 
1158
- ## List Filtering (Query Parameters)
1159
-
1160
- The LIST endpoint automatically supports filtering via query params:
1161
-
1162
- ```
1163
- GET /jobs?status=open # Exact match
1164
- GET /jobs?salaryMin.gt=50000 # Greater than
1165
- GET /jobs?salaryMin.gte=50000 # Greater than or equal
1166
- GET /jobs?salaryMax.lt=200000 # Less than
1167
- GET /jobs?salaryMax.lte=200000 # Less than or equal
1168
- GET /jobs?status.ne=closed # Not equal
1169
- GET /jobs?title.like=Engineer # Pattern match (LIKE %value%)
1170
- GET /jobs?status.in=open,draft # IN clause
1171
- ```
1172
-
1173
- | Operator | Query Param | SQL Equivalent |
1174
- |----------|-------------|----------------|
1175
- | Equals | `?field=value` | `WHERE field = value` |
1176
- | Not equals | `?field.ne=value` | `WHERE field != value` |
1177
- | Greater than | `?field.gt=value` | `WHERE field > value` |
1178
- | Greater or equal | `?field.gte=value` | `WHERE field >= value` |
1179
- | Less than | `?field.lt=value` | `WHERE field < value` |
1180
- | Less or equal | `?field.lte=value` | `WHERE field <= value` |
1181
- | Pattern match | `?field.like=value` | `WHERE field LIKE '%value%'` |
1182
- | In list | `?field.in=a,b,c` | `WHERE field IN ('a','b','c')` |
1183
-
1184
- ## Sorting & Pagination
1185
-
1186
- ```
1187
- GET /jobs?sort=createdAt&order=desc # Sort by field
1188
- GET /jobs?limit=25&offset=50 # Pagination
1189
- ```
1190
-
1191
- - **Default limit**: 50
1192
- - **Max limit**: 100 (or `maxPageSize` if configured)
1193
- - **Default order**: `asc`
1194
-
1195
- ## Delete Modes
1196
-
1197
- ```typescript
1198
- delete: {
1199
- access: { roles: ["owner", "hiring-manager"] },
1200
- mode: "soft", // Sets deletedAt/deletedBy, record stays in DB
1201
- }
1202
-
1203
- delete: {
1204
- access: { roles: ["owner", "hiring-manager"] },
1205
- mode: "hard", // Permanent deletion from database
1206
- }
1207
- ```
1208
-
1209
- `mode` on the single-record path is inherited by `DELETE /batch` unless `batch` names its own — so `mode: "hard"` above makes the whole resource hard-delete. That changes the schema: a hard-delete table must **not** declare `deletedAt` / `deletedBy` (via `...q.softDelete()` or literal Drizzle lines), and the firewall drops its `isNull(deletedAt)` predicate. See [Soft-delete fields](/define/schema#soft-delete-fields).
1210
-
1211
414
  ## Context Variables
1212
415
 
1213
416
  Use `$ctx.` prefix to reference context values in conditions: