@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
@@ -10,6 +10,36 @@ Quickback is a **backend compiler**. You write definition files, and Quickback c
10
10
  2. **Quickback compiles them** - Analyzes your definitions at build time
11
11
  3. **You get a production API** - `GET /jobs`, `POST /jobs`, `PATCH /jobs/:id`, `DELETE /jobs/:id`, batch operations, plus custom actions
12
12
 
13
+ ## Tenancy is not yours to model
14
+
15
+ **Workspace, team, tenant, account, org — they are all the Better Auth organization.** Quickback ships multi-tenancy; you never build it.
16
+
17
+ - **Don't** create a `workspaces` / `teams` / `tenants` table.
18
+ - **Don't** create a membership or `*_members` table.
19
+ - **Do** put `organizationId: q.scope("organization")` on every tenant-scoped table — the firewall is auto-derived from it.
20
+ - Membership and roles arrive on every request as `ctx.activeOrgId` and `ctx.roles`. You never query for them.
21
+ - Create a tenant with `POST /auth/v1/organization/create` and switch with `POST /auth/v1/organization/set-active` — not a custom action.
22
+
23
+ If your product calls it something else, that's a **label, not a schema decision** — the Account UI renames the organization surfaces for you (see [Account → Customization](/ui/account/customization)).
24
+
25
+ > **The expensive mistake**
26
+ >
27
+ > Hand-rolling a tenant table means re-implementing membership, roles, and invitations — and none of it is wired to `ctx`. Every access rule you then write against it fights the compiler, because `authz.relationships` cannot read Better Auth's tables.
28
+
29
+
30
+ ## The authorization ladder
31
+
32
+ Four rungs, in order. **Most apps never leave rung 1.** Climb only when the rung you're on genuinely can't express the rule — each one costs concepts, compile-time constraints, and per-request work.
33
+
34
+ | Rung | Reach for it when | Skip it when |
35
+ |---|---|---|
36
+ | **1. Org roles + firewall** | `organizationId: q.scope('organization')` plus `roles: ['member+']` / `['admin+']`. No `authz` block at all. | — this is the floor. It covers the large majority of apps end to end. |
37
+ | **2. Named rules** — [`authz.roles` / `authz.rules`](/define/authz-roles#centrally-defined-access-rules) | the same role expression repeats across many features and you want one source of truth | you have only a couple of repeats — inline them |
38
+ | **3. Relationships + areas** — [`authz.relationships`](/define/relationships), [feature areas](/define/areas) | membership lives in **your own** domain table (an attendee, a collaborator, an external reviewer), or a subtree shares a URL prefix **and** a per-row admission gate | org membership already answers it — that's rung 1 |
39
+ | **4. FGA** — [OpenFGA / Zanzibar](/define/fga) | you need a permission *graph*: derived, inherited, hierarchical, or public share links | a single hop answers it |
40
+
41
+ **Rung 3 is never the answer to "is this person in the org?"** A relationship's `from:` must be one of *your* feature tables — the compiler rejects one pointing at Better Auth's `organization_memberships`, `organizations`, or `user`. Org membership is rung 1, and it is already decided before your handler runs.
42
+
13
43
  ## File Structure
14
44
 
15
45
  Your definitions live in a `quickback/features/` folder organized by feature:
@@ -43,7 +73,7 @@ arbitrary depth):
43
73
 
44
74
  ```
45
75
  quickback/features/
46
- ├── workspace/ # AREA (has _area.ts)
76
+ ├── project/ # AREA (has _area.ts)
47
77
  │ ├── _area.ts # defineArea({...}) — prefix, via lanes, vocabulary
48
78
  │ ├── projects.ts # the area folder may itself be a feature
49
79
  │ └── tasks/ # child feature
@@ -52,8 +82,7 @@ quickback/features/
52
82
  └── billing/ # flat feature (unchanged)
53
83
  ```
54
84
 
55
- Area projects must declare `requires: ['feature-areas']` in `quickback.config.ts`.
56
- See [Feature areas](/define/areas) for the full model.
85
+ An area gates a **row inside a tenant** (this project, this event, this location) — it is not how you get multi-tenancy, which you already have. Area projects must declare `requires: ['feature-areas']` in `quickback.config.ts`. See [Feature areas](/define/areas) for the full model.
57
86
 
58
87
  **Table files** use `feature()` to combine schema and security config in one call:
59
88
 
@@ -220,7 +220,7 @@ compile-time refusal, never a silently ignored condition or a broader grant.
220
220
 
221
221
  ### Named gates in masking
222
222
 
223
- [Named gates](/define/access#named-gates-authzrules) (`authz.rules`) follow the same discipline in `show:`:
223
+ [Named gates](/define/authz-roles#named-gates-authzrules) (`authz.rules`) follow the same discipline in `show:`:
224
224
 
225
225
  - A **who-only** gate expands like a named role (its flat role list; the owner-gated flat-role constraint above applies).
226
226
  - A gate carrying a **`record:`** predicate is a **compile error** — masking cannot evaluate record conditions, so the record dimension would be silently dropped.
@@ -140,5 +140,5 @@ type PermissionLeaf =
140
140
  the `from` table's own firewall (tenant scope + soft-delete) is AND'd into
141
141
  each subquery, exactly as with a `via:` arm.
142
142
  - See [Scopes & capability grants](/define/scopes) for scoped
143
- roles and [Access — relationships](/define/access#authz-relationships)
143
+ roles and [Access — relationships](/define/relationships#authzrelationships)
144
144
  for the relationship shape.
@@ -62,7 +62,7 @@ export default defineTable(customers, {
62
62
  | `GET /api/v1/{resource}/:id` | `read.access` |
63
63
  | `GET /api/v1/{resource}/views/{name}` | `read.views[name].access` (falls back to `read.access`) |
64
64
 
65
- Each `access` block takes a `roles: [...]` array. When the same role expression recurs across reads/views/CRUD, define it once in `authz.roles` and reference it by name — see [Centrally defined access rules](/define/access#centrally-defined-access-rules).
65
+ Each `access` block takes a `roles: [...]` array. When the same role expression recurs across reads/views/CRUD, define it once in `authz.roles` and reference it by name — see [Centrally defined access rules](/define/authz-roles#centrally-defined-access-rules).
66
66
 
67
67
  Single-record `GET /:id` inherits `read.access` automatically — there's no
68
68
  separate `read.get` block. If you need different access for single records,
@@ -268,3 +268,105 @@ the **root row only** — read the aggregate back with `?include=<relation>`.
268
268
  - [Access](/define/access) — Roles, record conditions, and combinators
269
269
  - [Firewall](/define/firewall) — Tenant scoping and `firewallErrorMode`
270
270
  - [Views API](/api/views) — Calling views from clients
271
+
272
+ ## Read & Write Configuration
273
+
274
+ 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.
275
+
276
+ ```typescript
277
+ read: {
278
+ // LIST + GET - GET /resource and GET /resource/:id
279
+ access: { roles: ["owner", "hiring-manager", "recruiter", "interviewer"] },
280
+ pageSize: 25, // Default page size
281
+ maxPageSize: 100, // Client can't exceed this
282
+ views: { // Per-view field projections
283
+ summary: {
284
+ fields: ['id', 'candidateId', 'jobId', 'stage'],
285
+ access: { roles: ["interviewer"] },
286
+ },
287
+ },
288
+ }
289
+
290
+ create: {
291
+ // CREATE - POST /resource
292
+ access: { roles: ["owner", "hiring-manager", "recruiter"] },
293
+ defaults: { // Default values for new records
294
+ stage: 'applied',
295
+ },
296
+ },
297
+
298
+ update: {
299
+ // UPDATE - PATCH /resource/:id
300
+ access: {
301
+ or: [
302
+ { roles: ["hiring-manager", "recruiter"] },
303
+ { roles: ["interviewer"], record: { stage: { equals: "interview" } } }
304
+ ]
305
+ },
306
+ },
307
+
308
+ delete: {
309
+ // DELETE - DELETE /resource/:id
310
+ access: { roles: ["owner", "hiring-manager"] },
311
+ mode: "soft", // 'soft' (default) or 'hard'
312
+ },
313
+
314
+ upsert: {
315
+ // PUT - PUT /resource/:id (only when generateId: false + guards: false)
316
+ access: { roles: ["hiring-manager", "sync-service"] },
317
+ }
318
+ ```
319
+
320
+ ## List Filtering (Query Parameters)
321
+
322
+ The LIST endpoint automatically supports filtering via query params:
323
+
324
+ ```
325
+ GET /jobs?status=open # Exact match
326
+ GET /jobs?salaryMin.gt=50000 # Greater than
327
+ GET /jobs?salaryMin.gte=50000 # Greater than or equal
328
+ GET /jobs?salaryMax.lt=200000 # Less than
329
+ GET /jobs?salaryMax.lte=200000 # Less than or equal
330
+ GET /jobs?status.ne=closed # Not equal
331
+ GET /jobs?title.like=Engineer # Pattern match (LIKE %value%)
332
+ GET /jobs?status.in=open,draft # IN clause
333
+ ```
334
+
335
+ | Operator | Query Param | SQL Equivalent |
336
+ |----------|-------------|----------------|
337
+ | Equals | `?field=value` | `WHERE field = value` |
338
+ | Not equals | `?field.ne=value` | `WHERE field != value` |
339
+ | Greater than | `?field.gt=value` | `WHERE field > value` |
340
+ | Greater or equal | `?field.gte=value` | `WHERE field >= value` |
341
+ | Less than | `?field.lt=value` | `WHERE field < value` |
342
+ | Less or equal | `?field.lte=value` | `WHERE field <= value` |
343
+ | Pattern match | `?field.like=value` | `WHERE field LIKE '%value%'` |
344
+ | In list | `?field.in=a,b,c` | `WHERE field IN ('a','b','c')` |
345
+
346
+ ## Sorting & Pagination
347
+
348
+ ```
349
+ GET /jobs?sort=createdAt&order=desc # Sort by field
350
+ GET /jobs?limit=25&offset=50 # Pagination
351
+ ```
352
+
353
+ - **Default limit**: 50
354
+ - **Max limit**: 100 (or `maxPageSize` if configured)
355
+ - **Default order**: `asc`
356
+
357
+ ## Delete Modes
358
+
359
+ ```typescript
360
+ delete: {
361
+ access: { roles: ["owner", "hiring-manager"] },
362
+ mode: "soft", // Sets deletedAt/deletedBy, record stays in DB
363
+ }
364
+
365
+ delete: {
366
+ access: { roles: ["owner", "hiring-manager"] },
367
+ mode: "hard", // Permanent deletion from database
368
+ }
369
+ ```
370
+
371
+ `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).
372
+
@@ -0,0 +1,313 @@
1
+ # Relationship-Based Authorization - authz.relationships
2
+
3
+ **[Rung 3](/define#the-authorization-ladder).** Use a relationship when membership lives
4
+ in **your own** domain table — an attendee, a collaborator, an external reviewer who
5
+ isn't in your org.
6
+
7
+ > **Not for org membership**
8
+ >
9
+ > "Is this person in the organization?" is **[rung 1](/define/access)**, not a relationship.
10
+ > A relationship's `from:` must be one of *your* feature tables — the compiler rejects one
11
+ > pointing at Better Auth's `organization_memberships`, `organizations`, or `user`. Org
12
+ > membership is already decided before your handler runs and is available as `ctx.roles`.
13
+ >
14
+ > A relationship's `where:` also takes **scalar equality only** (`string | number |
15
+ > boolean`). `where: { role: ['admin','owner'] }` is not valid — declare one relationship
16
+ > per role, or use org roles.
17
+
18
+
19
+ ## Relationship-based authorization
20
+
21
+ 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.
22
+
23
+ ### `authz.relationships`
24
+
25
+ Declare relationships once in `quickback.config.ts`:
26
+
27
+ ```typescript
28
+ // quickback.config.ts
29
+ import { defineConfig } from '@quickback/compiler';
30
+
31
+ export default defineConfig({
32
+ // ...providers...
33
+ authz: {
34
+ relationships: {
35
+ guestOf: {
36
+ from: 'event_guests', // table name string
37
+ subject: { column: 'userId', equals: 'ctx.userId' }, // caller side
38
+ resource: { column: 'eventId' }, // resource side
39
+ where: { status: 'confirmed' }, // optional filter
40
+ },
41
+ },
42
+ roles: {
43
+ guest: { via: 'guestOf' },
44
+ // Composite: any guest OR an org owner/admin
45
+ eventStaff: {
46
+ or: [
47
+ { via: 'guestOf' },
48
+ { roles: ['admin', 'owner'] },
49
+ ],
50
+ },
51
+ },
52
+ },
53
+ });
54
+ ```
55
+
56
+ ### Using relationship-roles in resources
57
+
58
+ 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.
59
+
60
+ #### Supported relationship-role surfaces
61
+
62
+ | Surface | Status | Notes |
63
+ |---|---|---|
64
+ | `firewall:` `via:` predicate | ✓ Supported | Subquery composes as outermost AND |
65
+ | `crud.*.access` `roles: ['guest']` | ✓ Supported | Inline async lookup per request |
66
+ | `read.access` / `read.views.*.access` `roles: ['guest']` | ✓ Supported | Same inline path |
67
+ | **Standalone** `actions.<name>.access` `roles: ['guest']` | ✓ Supported | Inline gate; the surface exposes `resource.column` as a path param or input field |
68
+ | **Record-based** `actions.<name>.access` `roles: ['guest']` | ✓ Supported | Inline lookup uses the already-loaded, firewalled record |
69
+ | Namespace `via` lanes | ✓ Supported | Hoisted middleware resolves once and can hydrate `ctx.<exposeAs>` |
70
+ | `masking.<field>.show` `roles: ['guest']` | Build-time refusal | Use a relationship-gated view for field projection; per-row async masking is not approximated |
71
+
72
+ Relationship roles are therefore available across CRUD, reads, standalone
73
+ actions, record-based actions, and namespace mounts. Masking is the one
74
+ different execution surface: list masking must stay synchronous and batched, so
75
+ the compiler rejects a relationship-bearing `masking.show` rule and points to a
76
+ relationship-gated view instead. It never drops the relationship arm or turns
77
+ it into a broader role grant.
78
+
79
+ ### Standalone actions: surface keys and `loads` / `exposeAs` (v0.19+)
80
+
81
+ 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.
82
+
83
+ Pair the relationship with `loads` + `exposeAs` to hydrate the loaded resource onto `ctx`:
84
+
85
+ ```typescript
86
+ authz: {
87
+ relationships: {
88
+ attendeeOf: {
89
+ from: 'guests',
90
+ subject: { column: 'userId', equals: 'ctx.userId' },
91
+ resource: { column: 'eventId' },
92
+ where: { status: 'confirmed' },
93
+ loads: 'events', // ← v0.19+: load matching event row
94
+ exposeAs: 'event', // ← onto ctx.event for the action body
95
+ },
96
+ },
97
+ roles: {
98
+ attendee: { via: 'attendeeOf' },
99
+ },
100
+ }
101
+ ```
102
+
103
+ The resolver (v0.20):
104
+
105
+ 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.
106
+ 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.
107
+ 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.
108
+ 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.
109
+ 5. Assigns the loaded row to `ctx.event` for the action body.
110
+
111
+ **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.
112
+
113
+ ### Conditional tenant preconditions (v0.20+)
114
+
115
+ Standalone actions in features with org/team-scoped tables previously emitted unconditional preconditions:
116
+
117
+ ```ts
118
+ if (!ctx.activeOrgId) return c.json(AccessErrors.noOrg(), 403);
119
+ if (!ctx.activeTeamId) return c.json(AccessErrors.noTeam(), 403);
120
+ ```
121
+
122
+ These ran **before** the relationship resolver, which 403'd attendees whose sessions don't carry an active tenant claim (the canonical event-attendee shape).
123
+
124
+ 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.
125
+
126
+ 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.
127
+
128
+ ### Requirement on the relationship's `from` table
129
+
130
+ For the v0.20 tenant-stamping to work, the relationship's `from` table must carry tenant columns:
131
+
132
+ - For org stamping: an `organizationId` column (or whatever spelling the project's auth-provider defaults pick).
133
+ - For team stamping: a `teamId` column.
134
+
135
+ When the `from` table has **neither**, the compiler emits a `[quickback:authz]` warning at compile time:
136
+
137
+ ```
138
+ Relationship "X" at authz.relationships.X has no organization or team columns
139
+ on its `from` table ("guests"). Action "Y" will compile, but downstream
140
+ scoped-db queries inside execute() may 403 because ctx.activeOrgId /
141
+ activeTeamId cannot be stamped from the match row. Either add the tenant
142
+ column to "guests", or set firewall: { exception: true } on the action.
143
+ ```
144
+
145
+ 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.
146
+
147
+ The body can then trust `ctx.event` and drop the hand-rolled `SELECT … FROM guests WHERE …` boilerplate:
148
+
149
+ ```ts
150
+ // features/chat/actions/getInbox.ts
151
+ import { z } from "zod";
152
+ import { defineAction } from "../.quickback/define-action";
153
+
154
+ export default defineAction({
155
+ description: "List the caller's chat inbox for one event they attend.",
156
+ path: '/chat/get-inbox',
157
+ input: z.object({ eventId: z.number().int().positive() }),
158
+ access: { roles: ['admin', 'member', 'attendee'] }, // attendee is a relationship-role
159
+ execute: async ({ db, ctx, input }) => {
160
+ // No hand-rolled attendance check needed — the resolver already ran.
161
+ // ctx.event is the loaded events row. Typed as `any` here because the
162
+ // hand-rolled `roles: ['attendee']` action gates per-action, not per-
163
+ // namespace — see "Narrow ctx.<exposeAs> typing" below for the typed
164
+ // import flip available when the same hydration runs through a
165
+ // namespace mount.
166
+ const event = ctx.event as typeof events.$inferSelect;
167
+ // … domain logic only.
168
+ },
169
+ });
170
+ ```
171
+
172
+ `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.).
173
+
174
+ ### Action firewall escape hatch (v0.19+)
175
+
176
+ `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:
177
+
178
+ {/* 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. */}
179
+ ```ts
180
+ // features/admin/actions/crossTenantReport.ts
181
+ import { z } from "zod";
182
+ import { defineAction } from "../.quickback/define-action";
183
+
184
+ export default defineAction({
185
+ description: "Report activity across every tenant for a date range (sysadmin only).",
186
+ path: '/admin/cross-tenant-report',
187
+ input: z.object({ since: z.string(), until: z.string() }),
188
+ firewall: { exception: true },
189
+ unsafe: { reason: 'cross-tenant audit', adminOnly: true, targetScope: 'all' },
190
+ access: { roles: ['SYSADMIN'] },
191
+ execute: async ({ unsafeDb, ctx }) => { /* cross-org query */ },
192
+ });
193
+ ```
194
+
195
+ `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.
196
+
197
+ ### Recommended pattern: gate at the firewall layer
198
+
199
+ 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:
200
+
201
+ ```typescript
202
+ // features/sessions/sessions.ts
203
+ firewall: [
204
+ { field: 'organizationId', equals: 'ctx.activeOrgId' },
205
+ { field: 'eventId', via: 'guestOf' }, // ← row visibility
206
+ ],
207
+ read: {
208
+ access: { roles: ['admin', 'member'] }, // ← who can hit the route
209
+ views: {
210
+ cms: { access: { roles: ['admin', 'member'] }, fields: [...] },
211
+ guest: { access: { roles: ['member', 'admin'] }, fields: [...] },
212
+ },
213
+ },
214
+ ```
215
+
216
+ 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.
217
+
218
+ ### Cross-tenant "my events" dashboards are NOT this
219
+
220
+ 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.
221
+
222
+ For cross-tenant aggregation, use one of:
223
+
224
+ - **User-scoped firewall**: `firewall: { owner: { column: 'userId' } }` — a flat per-user table.
225
+ - **A standalone action that walks the relationship table itself** — see worked example below.
226
+
227
+ Don't reach for relationship-roles first and then get confused when the tenant firewall blocks. The two patterns serve different problems.
228
+
229
+ #### Worked example: `GET /my-events` standalone action
230
+
231
+ 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:
232
+
233
+ ```ts
234
+ // features/dashboard/actions/myEvents.ts
235
+ import { z } from 'zod';
236
+ import { eq, and, inArray } from 'drizzle-orm';
237
+ import { defineAction } from '../.quickback/define-action';
238
+ import { events } from '../../events/events';
239
+ import { guests } from '../../guests/guests';
240
+
241
+ export default defineAction({
242
+ description: "List events the caller is a confirmed guest of, across all tenants.",
243
+ path: '/my-events',
244
+ method: 'GET',
245
+ input: z.object({}),
246
+ // Any signed-in user. Row visibility comes from the query, not the role.
247
+ access: { roles: ['AUTHENTICATED'] },
248
+ async execute({ db, ctx }) {
249
+ // 1. Find every event the caller has a confirmed guest row for.
250
+ const guestRows = await db
251
+ .select({ eventId: guests.eventId })
252
+ .from(guests)
253
+ .where(
254
+ and(
255
+ eq(guests.userId, ctx.userId!),
256
+ eq(guests.status, 'confirmed'),
257
+ // guests.organizationId is NOT filtered here — that's the whole
258
+ // point of the cross-tenant lane. The relationship row's org is
259
+ // ambient information that this action explicitly traverses.
260
+ )
261
+ );
262
+
263
+ if (guestRows.length === 0) return { events: [] };
264
+
265
+ // 2. Pull the matching events. NOTE: this query also bypasses
266
+ // `events.organizationId` scope — by design — so explicitly filter
267
+ // out soft-deleted rows yourself if your `events` table uses them.
268
+ const eventIds = guestRows.map((r) => r.eventId);
269
+ const rows = await db
270
+ .select()
271
+ .from(events)
272
+ .where(inArray(events.id, eventIds));
273
+
274
+ return { events: rows };
275
+ },
276
+ });
277
+ ```
278
+
279
+ Why this is a standalone action and not a CRUD route:
280
+
281
+ - **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.
282
+ - **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.
283
+ - **Audit-logged automatically.** Standalone actions are mandatorily audit-logged in the runtime — the cross-tenant traversal is recorded with `ctx.userId`, IP, and timing.
284
+
285
+ Two important guardrails when you write one of these:
286
+
287
+ 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.
288
+ 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.
289
+
290
+ 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.
291
+
292
+ ### Compile-time refusals (consolidated)
293
+
294
+ The validator and resolver reject:
295
+
296
+ - Unknown key in `authz` block (typo guard — `realtionships` would otherwise silently produce a permanently-denied role).
297
+ - 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.
298
+ - Cycle in role composition (`a → b → a`).
299
+ - Relationship `from` references unknown table.
300
+ - Relationship-role used on a resource missing the `resource.column`.
301
+ - Relationship table with `firewall: { exception: true }` (would let cross-tenant grants slip through).
302
+ - `lowering: 'session'` (reserved for v2 — staleness/invalidation ergonomics not yet shipped).
303
+ - `+` hierarchy suffix on a relationship-role name (terminal, like pseudo-roles).
304
+ - Relationship-backed rules in `masking.show` (use a relationship-gated view
305
+ for field projection; action access is fully supported).
306
+
307
+
308
+ ## Outgrown this?
309
+
310
+ When several actions share a path prefix *and* this gate, hoist it into a
311
+ [feature area](/define/areas#namespace-mounts-hoisted-relationship-middleware) so the
312
+ resolver runs once per request. When you need a permission *graph* — derived, inherited,
313
+ hierarchical, or public share links — that's [rung 4 → FGA](/define/fga).
@@ -210,7 +210,7 @@ caller missing the claim gets a fail-closed **403**, never a `NULL` row.
210
210
  ## Namespace scope-claim refresh
211
211
 
212
212
  A scope is normally minted at `POST /scope/v1/enter`. When you also mount a
213
- [namespace](/define/access#namespace-mounts-hoisted-relationship-middleware)
213
+ [namespace](/define/areas#namespace-mounts-hoisted-relationship-middleware)
214
214
  that gates `/event/:eventId/*` on the **same** relationship, the namespace
215
215
  resolver can refresh `ctx.scope.<kind>` in memory for the duration of that
216
216
  request — so an attendee hitting `/event/evt_123/announce` gets
@@ -135,7 +135,7 @@ Events are only delivered to subscribers who fall within the broadcast's audienc
135
135
 
136
136
  ### Named rules and gates in `requiredRoles`
137
137
 
138
- Declared [`authz.roles`](/define/access#centrally-defined-access-rules) and [`authz.rules` gates](/define/access#named-gates-authzrules) can appear in `realtime.requiredRoles`. The compiler lowers them to flat static role names at build time, because the WebSocket ticket handshake has no DB in hand:
138
+ Declared [`authz.roles`](/define/authz-roles#centrally-defined-access-rules) and [`authz.rules` gates](/define/authz-roles#named-gates-authzrules) can appear in `realtime.requiredRoles`. The compiler lowers them to flat static role names at build time, because the WebSocket ticket handshake has no DB in hand:
139
139
 
140
140
  - A named role lowers to its composing static roles; relationship (`via:`) arms contribute nothing at the handshake (the row-stream firewall enforces that dimension later) and emit a warning.
141
141
  - A **who-only gate** lowers as its `who`. A gate carrying `record:` or `firewall` arms is undecidable at the handshake — it contributes nothing, with a warning.
@@ -157,6 +157,26 @@ POST /storage/v1/bucket
157
157
  > bytes land.
158
158
 
159
159
 
160
+ > **The read policy covers metadata, not just bytes.** `readScope` and
161
+ > `readRoles` are applied on every route that can reveal an object — downloads,
162
+ > `GET /object` listings, and `POST /url` lookups alike. Being a member of the
163
+ > owning organization is not sufficient on its own.
164
+ >
165
+ > - **Listing** (`GET /object`) returns only objects in buckets you may read.
166
+ > The filter is applied in the query, so `limit` and `offset` page over your
167
+ > readable set — you never receive a short page because rows were removed
168
+ > after the fact. Naming a bucket you cannot read returns `403`
169
+ > `ACCESS_ROLE_REQUIRED`; with no `bucket` filter, unreadable buckets are
170
+ > simply absent.
171
+ > - **URL lookup** (`POST /url`) returns `404` when the bucket policy denies
172
+ > you — the same response as an object that does not exist. This is
173
+ > deliberate: a `403` would confirm that the id or key you supplied resolves
174
+ > to a real object, letting a caller enumerate objects they cannot read.
175
+ >
176
+ > For `readScope: "user"` buckets, both routes additionally require that you own
177
+ > the object.
178
+
179
+
160
180
  ### Role-Based Access
161
181
 
162
182
  You can restrict operations to specific roles:
@@ -389,6 +409,25 @@ After compiling:
389
409
  | `allowedTypes` | `string[]` | Images only | Allowed MIME types (managed mode) |
390
410
  | `publicDomain` | `string` | - | Custom domain for files worker (managed mode) |
391
411
 
412
+ ### How the size limit is enforced
413
+
414
+ `maxFileSize` (and a bucket's `fileSizeLimit`) is enforced against bytes that
415
+ actually arrive, not against what the client claims:
416
+
417
+ - **Through-Worker uploads** (`POST /object/...`) are read through a byte
418
+ counter that aborts the moment the limit is crossed, so nothing over-limit
419
+ reaches R2. `Content-Length` is still checked first — it cheaply turns away
420
+ honest oversized clients — but it is optional and client-supplied, so it is
421
+ never the enforcement point.
422
+ - **Presigned uploads** go straight from the client to R2, and the signature
423
+ binds the content type, not the length. The `size` you declare at presign
424
+ time is therefore advisory. `POST /confirm/...` HEADs the object, compares
425
+ the real size against the bucket limit, and **deletes an over-limit object**
426
+ rather than recording it — otherwise the declared-size check could be
427
+ sidestepped by simply never calling confirm.
428
+
429
+ Both paths answer `413` with the actual and permitted byte counts.
430
+
392
431
  ## Security Model
393
432
 
394
433
  - **Upload security**: Enforced by API worker (auth middleware, org check, role check)
@@ -15,12 +15,13 @@ The `:provider` parameter identifies which service sent the webhook (e.g., `stri
15
15
  ```
16
16
  External Service → POST /webhooks/v1/inbound/stripe
17
17
  │
18
- ├─ 1. Verify signature (HMAC-SHA256)
19
- ├─ 2. Parse event (provider-specific)
20
- ├─ 3. Deduplicate via externalId
21
- ├─ 4. Store in webhook_events table
22
- ├─ 5. Enqueue for async processing
23
- └─ 6. Return 200 OK immediately
18
+ ├─ 1. Read body, capped at 1 MiB (413 if exceeded)
19
+ ├─ 2. Verify signature (HMAC-SHA256)
20
+ ├─ 3. Parse event (provider-specific)
21
+ ├─ 4. Deduplicate via externalId
22
+ ├─ 5. Store in webhook_events table
23
+ ├─ 6. Enqueue for async processing
24
+ └─ 7. Return 200 OK immediately
24
25
 
25
26
  Queue Consumer
26
27
  │
@@ -29,6 +30,16 @@ External Service → POST /webhooks/v1/inbound/stripe
29
30
  └─ 3. Update status → 'processed' or 'failed'
30
31
  ```
31
32
 
33
+ > **The body cap comes before signature verification, deliberately.** The
34
+ > signature *is* the authentication on this route, and it cannot be checked
35
+ > until the body has been read — so the read itself carries the limit.
36
+ > Without it, an unsigned caller would choose how much the Worker buffers,
37
+ > hashes, stores and enqueues before being turned away. Bodies over 1 MiB get
38
+ > `413`, distinct from the `401` an invalid signature returns.
39
+ >
40
+ > The same cap applies to actions declaring `webhook:` verification.
41
+
42
+
32
43
  The API returns `200 OK` immediately after enqueuing. Your handler logic runs asynchronously via the queue consumer, so external services don't time out waiting for your processing to complete.
33
44
 
34
45
  ## Registering Handlers