@quickback-dev/cli 0.34.3 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/docs/content.d.ts.map +1 -1
  2. package/dist/docs/content.js +35 -5
  3. package/dist/docs/content.js.map +1 -1
  4. package/dist/index.js +1 -1
  5. package/dist/skill/SKILL.md +3 -3
  6. package/dist/skill/agents/quickback-specialist/AGENT.md +3 -3
  7. package/dist/skill/docs/changelog.md +442 -0
  8. package/dist/skill/docs/compiler/definitions/arrows.md +269 -0
  9. package/dist/skill/docs/compiler/definitions/diagnostics.md +136 -0
  10. package/dist/skill/docs/compiler/definitions/feature.md +3 -3
  11. package/dist/skill/docs/compiler/definitions/fga.md +314 -0
  12. package/dist/skill/docs/compiler/definitions/firewall.md +93 -6
  13. package/dist/skill/docs/compiler/definitions/permissions.md +145 -0
  14. package/dist/skill/docs/compiler/definitions/scopes.md +339 -0
  15. package/dist/skill/docs/compiler/definitions/views.md +66 -0
  16. package/dist/skill/docs/stack/realtime/durable-objects.md +43 -0
  17. package/dist/skill/docs/stack/realtime/live-views.md +168 -0
  18. package/dist/skill/docs/stack/realtime/partyserver-rooms.md +22 -2
  19. package/package.json +1 -1
  20. package/src/skill/SKILL.md +3 -3
  21. package/src/skill/agents/quickback-specialist/AGENT.md +3 -3
  22. package/src/skill/docs/changelog.md +442 -0
  23. package/src/skill/docs/compiler/definitions/arrows.md +269 -0
  24. package/src/skill/docs/compiler/definitions/diagnostics.md +136 -0
  25. package/src/skill/docs/compiler/definitions/feature.md +3 -3
  26. package/src/skill/docs/compiler/definitions/fga.md +314 -0
  27. package/src/skill/docs/compiler/definitions/firewall.md +93 -6
  28. package/src/skill/docs/compiler/definitions/permissions.md +145 -0
  29. package/src/skill/docs/compiler/definitions/scopes.md +339 -0
  30. package/src/skill/docs/compiler/definitions/views.md +66 -0
  31. package/src/skill/docs/stack/realtime/durable-objects.md +43 -0
  32. package/src/skill/docs/stack/realtime/live-views.md +168 -0
  33. package/src/skill/docs/stack/realtime/partyserver-rooms.md +22 -2
@@ -0,0 +1,314 @@
1
+ # FGA - Relationship-Based Access (Zanzibar)
2
+
3
+ The **FGA pillar** brings [OpenFGA](https://openfga.dev) / Google Zanzibar
4
+ **Relationship-Based Access Control (ReBAC)** to Quickback. You declare an
5
+ authorization model in the OpenFGA modeling DSL, store relationship tuples in a
6
+ compiler-owned table, and resolve graph-shaped permission checks at request
7
+ time — no external authorization service, all inside your Worker.
8
+
9
+ It is **opt-in** and sits alongside the role-based [Access](/compiler/definitions/access)
10
+ pillar and the lightweight [`authz.relationships`](/compiler/definitions/access#relationship-roles)
11
+ join-roles. Use whichever fits:
12
+
13
+ | Need | Use |
14
+ | --- | --- |
15
+ | "Admins can edit, members can read" | [Access](/compiler/definitions/access) roles |
16
+ | "The caller has a row linking them to this record" | [`authz.relationships`](/compiler/definitions/access) |
17
+ | "A recruiter is automatically a viewer; a folder's viewer can view its docs; share publicly" | **FGA** |
18
+
19
+ ## When you need a permission *graph*
20
+
21
+ Roles and one-hop relationship joins can't express:
22
+
23
+ - **Derived** permissions — an `editor` is automatically a `viewer`.
24
+ - **Hierarchical** permissions — a document inherits viewers from its folder.
25
+ - **Group** permissions — every member of `team:eng` is a viewer.
26
+ - **Per-record grants** — assign one person to one record without a global role.
27
+ - **Public sharing** — make one object viewable by everyone, with a share link.
28
+
29
+ These are exactly what Zanzibar's *userset rewrites* and *tuple-to-userset*
30
+ relations solve, and what the FGA pillar gives you.
31
+
32
+ ## The model
33
+
34
+ Declare it with `authz.fga.model` in `quickback.config.ts`, using the OpenFGA
35
+ modeling DSL verbatim (the same text the OpenFGA CLI and VS Code extension
36
+ use):
37
+
38
+ ```typescript
39
+ // quickback.config.ts
40
+ export default defineConfig({
41
+ // ...
42
+ authz: {
43
+ fga: {
44
+ model: `
45
+ model
46
+ schema 1.1
47
+
48
+ type user
49
+
50
+ type organization
51
+ relations
52
+ define member: [user]
53
+
54
+ type job
55
+ relations
56
+ define org: [organization]
57
+ define hiring_manager: [user]
58
+ define recruiter: [user] or hiring_manager
59
+ define viewer: [user, user:*] or recruiter or member from org
60
+ define can_manage: recruiter
61
+
62
+ type application
63
+ relations
64
+ define job: [job]
65
+ define viewer: viewer from job
66
+ define editor: can_manage from job
67
+ `,
68
+ },
69
+ },
70
+ });
71
+ ```
72
+
73
+ The compiler **parses and validates** the model at compile time — every type,
74
+ relation, and `from` reference must resolve, or the compile fails loud.
75
+
76
+ ### DSL reference
77
+
78
+ | Syntax | Meaning |
79
+ | --- | --- |
80
+ | `define viewer: [user]` | Direct assignment — a stored tuple grants `viewer`. |
81
+ | `define viewer: [user, user:*]` | `user:*` = **type-bound public access** (everyone). |
82
+ | `define viewer: [team#member]` | A **userset** — every `member` of a `team` is a `viewer`. |
83
+ | `define viewer: [user] or editor` | **Union** — `editor`s are also `viewer`s (derived). |
84
+ | `define viewer: editor and member` | **Intersection** — must be both. |
85
+ | `define viewer: editor but not blocked` | **Exclusion**. |
86
+ | `define viewer: viewer from parent` | **Tuple-to-userset** — inherit `viewer` from the `parent` object. |
87
+
88
+ ## Tuples
89
+
90
+ A **relationship tuple** is `(user, relation, object)` — e.g.
91
+ `(user:anne, recruiter, job:123)`. Tuples live in a compiler-owned,
92
+ **organization-scoped** `fga_tuples` table that the compiler emits and migrates
93
+ for you (a Check never reads another tenant's tuples).
94
+
95
+ Write them three ways:
96
+
97
+ ```typescript
98
+ // 1. In an action / handler via ctx.fga
99
+ await ctx.fga.write([
100
+ { user: 'user:' + input.userId, relation: 'recruiter', object: 'job:' + record.id },
101
+ ]);
102
+
103
+ // 2. Over the REST API (admin / write-role gated)
104
+ // POST /api/v1/fga/v1/write
105
+ // { "writes": [{ "user": "user:anne", "relation": "recruiter", "object": "job:123" }] }
106
+
107
+ // 3. A public share link (see Public sharing below)
108
+ ```
109
+
110
+ ## Checking access
111
+
112
+ ### `ctx.fga` in handlers and actions
113
+
114
+ Every authenticated request gets an org-scoped `ctx.fga` client:
115
+
116
+ ```typescript
117
+ const allowed = await ctx.fga.check('user:' + ctx.userId, 'can_manage', 'job:' + jobId);
118
+ const myJobs = await ctx.fga.listObjects('user:' + ctx.userId, 'viewer', 'job'); // ['job:1', ...]
119
+ const tree = await ctx.fga.expand('job:123', 'viewer'); // debug the userset tree
120
+ ```
121
+
122
+ ### The `access: { fga }` arm — secure by construction
123
+
124
+ Enforce a Check declaratively on a resource operation. The compiler fetches the
125
+ record and emits an inline `ctx.fga.check(...)` gate:
126
+
127
+ ```typescript
128
+ export default feature('jobs', {
129
+ // ...
130
+ // Org owners/admins can edit any job, OR anyone with the FGA `can_manage`
131
+ // relation on THIS specific job — without an org-wide admin role.
132
+ update: {
133
+ access: {
134
+ or: [
135
+ { roles: ['owner', 'admin'] },
136
+ { fga: { relation: 'can_manage', object: 'job:{id}' } },
137
+ ],
138
+ },
139
+ },
140
+ });
141
+ ```
142
+
143
+ `object` is a template — `{field}` tokens interpolate the fetched record's
144
+ columns (`job:{id}` → `job:${record.id}`). On per-record operations
145
+ (`GET /:id`, `update`, `delete`, and record-based actions) the compiler emits
146
+ the inline check. It is **fail-closed**: if the check can't run, access is
147
+ denied.
148
+
149
+ ### Filtering a collection by an FGA relation
150
+
151
+ On `read.access` (and named views) the `fga` arm does more than gate the
152
+ per-record `GET /:id` — it **filters the collection `GET /`** too. The compiler
153
+ resolves the caller's authorized object ids via the engine's `ListObjects` and
154
+ injects an `inArray(id, …)` into the list query *before* it runs, so the row
155
+ page, `total`, and `hasMore` all stay correct (no fetch-then-drop that would
156
+ break pagination):
157
+
158
+ ```typescript
159
+ export default feature('jobs', {
160
+ // ...
161
+ read: {
162
+ // Collection GET / returns only jobs the caller is a `viewer` of;
163
+ // GET /:id enforces the same relation per record.
164
+ access: { fga: { relation: 'viewer', object: 'job:{id}' } },
165
+ },
166
+ });
167
+ ```
168
+
169
+ Three access shapes are supported on a collection-filtering arm:
170
+
171
+ | Access shape | Collection behavior |
172
+ | --- | --- |
173
+ | `{ fga }` | Always filter to the FGA-authorized ids. |
174
+ | `{ or: [{ roles }, { fga }] }` | If the role arm passes, return all firewall-scoped rows (no FGA filter); otherwise filter to the authorized ids. |
175
+ | `{ and: [{ roles }, { fga }] }` | If the role arm fails, return an empty page; otherwise filter to the authorized ids. |
176
+
177
+ Deeper nesting (an `fga` arm under multi-level `and`/`or`, or multiple
178
+ conflicting `fga` arms) is a **compile error** that points you at
179
+ `POST /fga/v1/list-objects` to filter manually.
180
+
181
+ **The cap.** The authorized id set is bounded by `authz.fga.listObjects.maxIds`
182
+ (default **1000**). If a caller's authorized set exceeds the cap, the collection
183
+ request fails with a hard **422 `FGA_LIST_TOO_LARGE`** whose hint points to
184
+ `POST /fga/v1/list-objects` for paginated enumeration — never a silent partial
185
+ page. Raise the cap or paginate via the API for collections that legitimately
186
+ authorize more than `maxIds` rows per caller.
187
+
188
+ ## Public sharing
189
+
190
+ The FGA pillar is also Quickback's public-sharing mechanism — two
191
+ complementary tools.
192
+
193
+ ### Type-bound public access (`user:*`)
194
+
195
+ A model relation that lists `user:*` (e.g. `define viewer: [user, user:*] …`)
196
+ can be granted to *everyone* by writing one tuple:
197
+
198
+ ```typescript
199
+ await ctx.fga.write([{ user: 'user:*', relation: 'viewer', object: 'job:' + id }]);
200
+ ```
201
+
202
+ Now every Check for `viewer` on that object passes.
203
+
204
+ ### Share links
205
+
206
+ Enable signed, unauthenticated share links:
207
+
208
+ ```typescript
209
+ authz: {
210
+ fga: {
211
+ model: `...`,
212
+ sharing: {
213
+ enabled: true,
214
+ // The dedicated public route (always mounted): GET /share/v1/:token
215
+ route: '/share',
216
+ // Optional vanity base URL (also add it to your runtime `routes`).
217
+ baseUrl: 'https://share.acme.dev',
218
+ // Tokens never expire by default; set a TTL in seconds to expire them.
219
+ ttlSeconds: 0,
220
+ // Public projection: what a `job:<id>` share link may reveal, no login.
221
+ resources: {
222
+ job: { table: 'jobs', fields: ['id', 'title', 'department', 'status'] },
223
+ },
224
+ },
225
+ },
226
+ }
227
+ ```
228
+
229
+ - **Mint** a link: `POST /api/v1/fga/v1/share` `{ "object": "job:123", "relation": "viewer" }`
230
+ (write-role gated) → `{ token, url }`. Minting **writes the `(user:*, relation,
231
+ object)` tuple** (making the object publicly viewable per the model) and then
232
+ signs the link. If the relation has no `user:*` arm in the model, minting
233
+ fails with a 400 rather than handing back a dead link.
234
+ - **Resolve** a link: `GET /share/v1/:token` — **no authentication**. The route
235
+ verifies the HMAC, then **checks the stored grant** (no contextual shortcut):
236
+ the object must still have the granted `user:*` relation right now. Only then
237
+ does it return the configured public projection. Nothing else leaks — the
238
+ token is scoped to exactly that object and relation.
239
+ - **Revoke** a link: delete the `(user:*, relation, object)` tuple (via
240
+ `POST /fga/v1/write` `deletes`, or your own action). The next `GET` Check
241
+ fails and the link stops returning content — revocation is real, not just
242
+ token expiry.
243
+
244
+ ### The share URL: route, base URL, or both
245
+
246
+ You get **both** by default:
247
+
248
+ - A **dedicated route** on the API origin — `…/share/v1/:token` — always
249
+ available when sharing is enabled.
250
+ - An optional **vanity base URL** (`share.<your-domain>`). Set
251
+ `sharing.baseUrl` and add the host to your runtime `routes`:
252
+
253
+ ```typescript
254
+ providers: {
255
+ runtime: defineRuntime('cloudflare', {
256
+ routes: [
257
+ { pattern: 'api.acme.dev', custom_domain: true },
258
+ { pattern: 'share.acme.dev', custom_domain: true }, // share base URL
259
+ ],
260
+ }),
261
+ },
262
+ ```
263
+
264
+ Minted links then use `https://share.acme.dev/v1/:token`; otherwise they use
265
+ the API origin + the dedicated route.
266
+
267
+ ## REST API
268
+
269
+ When `authz.fga` is set, the compiler mounts an OpenFGA-compatible surface at
270
+ `/api/v1/fga/v1`, all tenant-scoped to `ctx.activeOrgId`:
271
+
272
+ | Endpoint | Body | Returns |
273
+ | --- | --- | --- |
274
+ | `POST /check` | `{ user, relation, object, contextual_tuples? }` | `{ allowed }` |
275
+ | `POST /list-objects` | `{ user, relation, type }` | `{ objects }` |
276
+ | `POST /expand` | `{ relation, object }` | `{ tree }` |
277
+ | `POST /read` | `{ object?, relation?, user? }` | `{ tuples }` |
278
+ | `POST /write` | `{ writes?, deletes? }` | `{ ok }` (write-role) |
279
+ | `POST /share` | `{ object, relation, ttlSeconds? }` | `{ token, url }` (write-role) |
280
+
281
+ `writeRoles` (default `['admin']`) controls who can write tuples and mint share
282
+ links. Pseudo-roles and `+` hierarchy suffixes are honored.
283
+
284
+ ## How it resolves
285
+
286
+ The embedded engine resolves a Check by walking the model: direct tuples,
287
+ type-bound public access (`user:*`), userset subjects (`team:eng#member`),
288
+ computed usersets (union / intersection / exclusion), and tuple-to-userset
289
+ (`viewer from parent`), plus request-scoped **contextual tuples**. It has cycle
290
+ detection and a configurable resolution-depth cap (`authz.fga.maxDepth`,
291
+ default 25).
292
+
293
+ The engine **enforces the model's direct type restrictions at check time**: a
294
+ stored tuple whose subject shape isn't allowed for the relation is inert. So a
295
+ `user:*` tuple on a relation declared `[user]` (no wildcard) can never grant
296
+ access, even if it was written out-of-band — the model is the ceiling.
297
+
298
+ ## Limitations (v0.35)
299
+
300
+ - `access: { fga }` covers **per-record** operations (`GET /:id`, `update`,
301
+ `delete`, record-based actions) and **collection filtering** on
302
+ `read.access` / views (see
303
+ [Filtering a collection](#filtering-a-collection-by-an-fga-relation)). It is
304
+ **not valid on `create`** (no record yet — rejected at compile) or
305
+ **standalone actions** (use `ctx.fga.check` in `execute`).
306
+ - **Collection filtering is bounded** by `authz.fga.listObjects.maxIds`
307
+ (default 1000). A caller authorized for more rows than the cap gets a hard
308
+ **422 `FGA_LIST_TOO_LARGE`**, not a partial page — paginate via
309
+ `POST /fga/v1/list-objects` for those cases. Only the bare/`or`/`and`-with-roles
310
+ shapes are filtered; deeper nesting is a compile error.
311
+ - **Conditional tuples** (CEL conditions / ABAC) — the schema reserves the
312
+ columns, but condition evaluation is not yet wired.
313
+ - `ListObjects` enumerates candidate objects from tuples and Checks each — a
314
+ reverse-index optimization is a planned follow-up.
@@ -61,11 +61,14 @@ When you omit the `firewall:` block entirely, the compiler scans the schema for
61
61
 
62
62
  ```typescript
63
63
  type FirewallPredicate =
64
- | { field: string; equals: string } // column = ctx.* (or literal)
65
- | { field: string; isNull: true } // column IS NULL
66
- | { field: string; in: string[] | string }// column IN (...)
67
- | { field: string; via: string } // column IN (relationship subquery)
68
- | { exception: true }; // opt out of tenant scoping
64
+ | { field: string; equals: string; optional?: boolean } // column = ctx.* (or literal)
65
+ | { field: string; isNull: true } // column IS NULL
66
+ | { field: string; in: string[] | string; optional?: boolean } // column IN (...)
67
+ | { field: string; via: string } // column IN (relationship subquery)
68
+ | { field?: string; permission: string } // named authz.permissions reference (v0.35+)
69
+ | { all: FirewallPredicate[] } // AND group (v0.35+)
70
+ | { any: FirewallPredicate[] } // OR group (v0.35+)
71
+ | { exception: true }; // opt out of tenant scoping
69
72
 
70
73
  type FirewallConfig = ReadonlyArray<FirewallPredicate>;
71
74
 
@@ -73,7 +76,41 @@ type FirewallConfig = ReadonlyArray<FirewallPredicate>;
73
76
  firewallErrorMode?: 'reveal' | 'hide';
74
77
  ```
75
78
 
76
- Predicates are AND'd together. `firewallErrorMode` lives at the resource top level — it's a presentation-layer choice (403 vs 404), not a query-shape one.
79
+ The top-level array is AND'd together. `firewallErrorMode` lives at the resource top level — it's a presentation-layer choice (403 vs 404), not a query-shape one.
80
+
81
+ ## Boolean groups: `all` / `any` (v0.35+)
82
+
83
+ A flat array can only express AND. To grant access through **either** of two independent paths — "an org member **OR** an event attendee" — nest an `any` group. The top-level array stays sugar for `all`, so every existing firewall is byte-identical.
84
+
85
+ ```typescript
86
+ firewall: {
87
+ any: [
88
+ { field: 'organizationId', equals: 'ctx.activeOrgId' }, // org-member grant
89
+ { field: 'eventId', equals: 'ctx.scope.event' }, // attendee grant (token-verified)
90
+ ],
91
+ }
92
+ ```
93
+
94
+ Null-safe scope semantics make this safe (these apply **inside `all`/`any` groups**, opt-in via the new syntax):
95
+
96
+ - A **scope** arm (`ctx.activeOrgId`, `ctx.activeTeamId`, `ctx.scope.*`) whose claim is **absent never binds `undefined`** (the classic 500 / "match every row" trap). In an `any` group an absent arm **drops**; if **every** arm drops, the group denies with `sql\`1 = 0\`` (the empty-guard) — never a full-table read. In an `all` group an absent required scope **denies** the group.
97
+ - Mark an arm `{ optional: true }` to **drop-instead-of-deny** when absent inside an `all` group (the teamless rest-of-org slice — `ctx.activeTeamId` is implicitly optional).
98
+ - **Owner** (`ctx.userId`) and **soft-delete** (`isNull deletedAt`) are always present / always AND'd — never relaxed.
99
+
100
+ ```typescript
101
+ // (org OR event) AND owner AND not-deleted
102
+ firewall: {
103
+ all: [
104
+ { any: [
105
+ { field: 'organizationId', equals: 'ctx.activeOrgId' },
106
+ { field: 'eventId', equals: 'ctx.scope.event' },
107
+ ] },
108
+ { field: 'ownerId', equals: 'ctx.userId' },
109
+ ],
110
+ }
111
+ ```
112
+
113
+ The `ctx.scope.*` arms are how **relationship-derived scopes** (attendees, shuttle drivers, vendors) reach event-scoped rows without org membership — see [Scopes & capability grants](/compiler/definitions/scopes).
77
114
 
78
115
  ## Relationship-based scoping (`via:`)
79
116
 
@@ -120,6 +157,56 @@ Key properties:
120
157
 
121
158
  See [Access — relationships](/compiler/definitions/access#authz-relationships) for the full `authz.relationships` shape and role-binding patterns.
122
159
 
160
+ ## Named permissions (`{ permission }`)
161
+
162
+ A `via:` arm references **one** relationship. When the same grant rule —
163
+ "organizer **or** confirmed attendee" — recurs across several resources,
164
+ name it **once** under `authz.permissions` and reference it from any
165
+ firewall with a `{ permission }` arm. See [Permissions](/compiler/definitions/permissions)
166
+ for the full DSL.
167
+
168
+ ```typescript
169
+ // quickback.config.ts
170
+ authz: {
171
+ relationships: { organizerOf: { /* … */ }, attendeeOf: { /* … */ } },
172
+ permissions: {
173
+ 'event:view': { anyOf: ['organizerOf', 'attendeeOf'] },
174
+ },
175
+ }
176
+
177
+ // features/sessions/sessions.ts
178
+ firewall: [
179
+ { field: 'organizationId', equals: 'ctx.activeOrgId' },
180
+ { field: 'eventId', permission: 'event:view' },
181
+ ]
182
+ ```
183
+
184
+ The compiler lowers `{ permission }` to the same `all` / `any` relationship
185
+ subqueries the expression names — `anyOf` becomes an OR of subqueries,
186
+ `allOf` an AND. `field` is the resource-side column those subqueries
187
+ constrain (the same column you'd put on a `via:` arm).
188
+
189
+ A permission referenced from a firewall can also resolve an
190
+ [**arrow**](/compiler/definitions/arrows) — an `{ arrowRef, permission }`
191
+ leaf that traverses a foreign key to inherit authority from a parent object
192
+ ("org admins of the event's org can see its announcements", "anyone who
193
+ administers an ancestor folder can read this one"). An arrow leaf lowers to
194
+ an FK-hop subquery (non-recursive) or a bounded `WITH RECURSIVE` CTE
195
+ (self-FK hierarchy), tenant-constrained at every row.
196
+
197
+ **M1 limit — firewall arms must be SQL-pushable.** A firewall runs as a
198
+ WHERE clause, so a permission referenced from one may only resolve to
199
+ relationship subqueries. A permission whose expression contains a
200
+ **claim-site leaf** (`{ role }`, `{ scopeRole }`, `{ pseudoRole }`) or a
201
+ `not` is rejected at compile time when referenced from a firewall — those
202
+ shapes are valid in the DSL but reserved for future claim/runtime
203
+ enforcement sites. Use a role gate on `read.access` / `crud.*.access` for
204
+ membership checks.
205
+
206
+ The compile-time analyzer additionally flags a referenced permission that can
207
+ never be satisfied, an arm shadowed by a broader one, and the SQL / CTE cost
208
+ of each permission — see [Diagnostics](/compiler/definitions/diagnostics).
209
+
123
210
  ## Context Sources
124
211
 
125
212
  When `equals` references the request context, use these standard sources:
@@ -0,0 +1,145 @@
1
+ # Permissions
2
+
3
+ A `via:` arm references **one** relationship. A `roles: [...]` array ORs a
4
+ flat list of role names. When the *same* grant rule recurs across several
5
+ resources — "organizer **or** confirmed attendee", "admin **and not**
6
+ suspended" — name it once under `authz.permissions` and reference it
7
+ everywhere by name. A permission is a **named boolean expression** over the
8
+ authorization primitives you've already declared.
9
+
10
+ ## Declaring permissions
11
+
12
+ Permissions live in `quickback.config.ts` alongside `authz.relationships`:
13
+
14
+ ```typescript
15
+ // quickback.config.ts
16
+ import { defineConfig } from '@quickback/compiler';
17
+
18
+ export default defineConfig({
19
+ // ...providers...
20
+ authz: {
21
+ relationships: {
22
+ organizerOf: { from: 'event_staff', subject: { column: 'userId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { role: 'organizer' } },
23
+ attendeeOf: { from: 'event_guests', subject: { column: 'userId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { status: 'confirmed' } },
24
+ },
25
+ permissions: {
26
+ 'event:view': { anyOf: ['organizerOf', 'attendeeOf'] },
27
+ 'event:manage': { allOf: ['organizerOf', { not: 'suspendedFromEvent' }] },
28
+ 'org:admin': { anyOf: [{ role: 'admin' }, { role: 'owner' }] },
29
+ },
30
+ },
31
+ });
32
+ ```
33
+
34
+ ## The expression DSL
35
+
36
+ A permission is a tree of three combinators over **leaves**:
37
+
38
+ | Combinator | Meaning |
39
+ |---|---|
40
+ | `{ anyOf: [...] }` | union — satisfied if **any** arm holds |
41
+ | `{ allOf: [...] }` | intersection — satisfied only if **all** arms hold |
42
+ | `{ not: <expr> }` | exclusion — satisfied if the operand does **not** hold |
43
+
44
+ A bare leaf (no combinator) is a one-arm permission — the replacement for a
45
+ single `via:`.
46
+
47
+ ### Leaves
48
+
49
+ A leaf names one authorization primitive. The common case is a bare string;
50
+ object forms are the unambiguous escape hatch.
51
+
52
+ | Leaf | Resolves to |
53
+ |---|---|
54
+ | `'organizerOf'` (bare string, no prefix) | a declared **relationship** |
55
+ | `{ relationRef: 'organizerOf' }` | a declared relationship (explicit) |
56
+ | `{ permissionRef: 'event:view' }` | **another permission** (composition) |
57
+ | `{ role: 'admin' }` | an org-membership role (`ctx.roles`) |
58
+ | `{ scopeRole: { kind: 'event', role: 'organizer' } }` | a [scoped role](/compiler/definitions/scopes) |
59
+ | `{ pseudoRole: 'AUTHENTICATED' }` | `PUBLIC` / `AUTHENTICATED` / `INTERNAL` / … |
60
+ | `{ arrowRef: 'eventOrg', permission: 'org:admin' }` | an [FK-traversal arrow](/compiler/definitions/arrows) — resolve the row's FK to its target object and require a permission there |
61
+
62
+ String sugar for the prefixed forms is also accepted inside an expression:
63
+ `'permission:event:view'`, `'scope:event:organizer'`, `'role:admin'`. A bare
64
+ string with no recognized prefix is always a relationship reference.
65
+
66
+ ## Referencing a permission
67
+
68
+ A resource references a permission from its `firewall` with a
69
+ `{ permission }` arm. `field` is the resource-side column the lowered
70
+ subqueries constrain — the same column a `via:` arm would carry:
71
+
72
+ ```typescript
73
+ // features/sessions/sessions.ts
74
+ firewall: [
75
+ { field: 'organizationId', equals: 'ctx.activeOrgId' },
76
+ { field: 'eventId', permission: 'event:view' },
77
+ ]
78
+ ```
79
+
80
+ The compiler **lowers** the permission to the equivalent firewall arms:
81
+ `anyOf` becomes an OR of relationship subqueries (`any`), `allOf` becomes an
82
+ AND (`all`), and `{ permissionRef }` inlines the referenced permission's
83
+ arms. The result is byte-identical to writing those `via:` arms by hand — the
84
+ permission is just the named, reusable spelling.
85
+
86
+ See [Firewall — named permissions](/compiler/definitions/firewall#named-permissions-permission)
87
+ for how the arm sits inside a firewall.
88
+
89
+ ## M1 limits
90
+
91
+ Permissions are richer than what a firewall can enforce today. The DSL
92
+ accepts the full shape so configs are forward-compatible, but a firewall
93
+ runs as a SQL `WHERE` clause, so a permission referenced from a firewall
94
+ must be **SQL-pushable**. Two cases are rejected at compile time when
95
+ referenced from a firewall:
96
+
97
+ - **Claim-site leaves.** `{ role }`, `{ scopeRole }`, and `{ pseudoRole }`
98
+ are decided from the request's verified claims, not from a row subquery.
99
+ A permission containing one of these can't lower to a `WHERE` clause, so
100
+ referencing it from a firewall is a compile error. Gate membership on
101
+ `read.access` / `crud.*.access` instead, where role checks belong.
102
+ - **`not`.** A `not` whose operand resolves to a SQL (relationship) site is
103
+ rejected — `NOT IN (subquery)` over a nullable set is the classic
104
+ null-trap (a `NULL` row silently passes). It's representable in the DSL for
105
+ future claim/runtime sites but errors in a firewall in M1.
106
+
107
+ These shapes (`{ role }`, `not`, typed caveats) remain in the DSL because
108
+ they're the enforcement surfaces of later milestones (claim-site and runtime
109
+ checks). M1 ships the SQL-pushable subset: relationship and `{ permissionRef }`
110
+ leaves under `anyOf` / `allOf`. FK-traversal arrows (`{ arrowRef, permission }`)
111
+ are now shipped and **are** firewall-pushable — see
112
+ [Arrows](/compiler/definitions/arrows).
113
+
114
+ The compile-time analyzer flags permissions that can never be satisfied,
115
+ arms shadowed by a broader arm, a `not` over a SQL site (the null-trap), and
116
+ the subquery / CTE cost of each rule — see
117
+ [Diagnostics](/compiler/definitions/diagnostics).
118
+
119
+ ## Reference
120
+
121
+ ```typescript
122
+ // authz.permissions.<name>
123
+ type PermissionExpr =
124
+ | PermissionLeaf
125
+ | { anyOf: PermissionExpr[] }
126
+ | { allOf: PermissionExpr[] }
127
+ | { not: PermissionExpr };
128
+
129
+ type PermissionLeaf =
130
+ | string // relationship name (bare) or prefixed sugar
131
+ | { relationRef: string }
132
+ | { permissionRef: string }
133
+ | { role: string } // claim-site — not firewall-pushable (M1)
134
+ | { scopeRole: { kind: string; role: string } } // claim-site — not firewall-pushable (M1)
135
+ | { pseudoRole: string } // claim-site — not firewall-pushable (M1)
136
+ | { arrowRef: string; permission: string }; // FK-traversal arrow — see Arrows
137
+ ```
138
+
139
+ - Referenced from a firewall as `{ field, permission: '<name>' }`.
140
+ - Relationship leaves carry every property of the underlying relationship —
141
+ the `from` table's own firewall (tenant scope + soft-delete) is AND'd into
142
+ each subquery, exactly as with a `via:` arm.
143
+ - See [Scopes & capability grants](/compiler/definitions/scopes) for scoped
144
+ roles and [Access — relationships](/compiler/definitions/access#authz-relationships)
145
+ for the relationship shape.