@quickback-dev/cli 0.34.2 → 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,339 @@
1
+ # Scopes & Capability Grants
2
+
3
+ Org membership answers *"which tenant is this caller in?"* Scopes answer a different question: *"this caller isn't an org member, but they're a **confirmed attendee of event E** — let them see exactly E's rows, as exactly the role they hold, and nothing else."*
4
+
5
+ A **scope** is a tenant axis whose value is established by a **relationship you prove once** (at `POST /scope/v1/enter`) and then carry in a signed JWT claim — verified cryptographically on every later request with **no database round-trip**. It's the REST/JWT twin of the realtime ws-ticket.
6
+
7
+ ## When to use it
8
+
9
+ Reach for a scope when a principal must touch a bounded slice of an instance **without being an org member**:
10
+
11
+ - **Event attendee** — reads their event's announcements / sessions, not the org.
12
+ - **Shuttle driver** — sees only the passengers on *their* bus (a row slice), can DM them.
13
+ - **F&B vendor** — reads dietary *counts*, zero attendee rows.
14
+ - **Visiting nurse / carrier / contractor** — one patient's meds, one carrier's shipments.
15
+
16
+ Each is *event-scoped* but a **distinct least-privilege role**. Org members are unaffected — they keep their normal tenant access.
17
+
18
+ ## The model
19
+
20
+ ### 1. Declare relationships + scopes
21
+
22
+ A scope **kind** (`event`) declares named **roles**, each conferred by a relationship whose `from` row carries the role (and optionally a **sub-key** for row slicing):
23
+
24
+ ```typescript
25
+ // quickback.config.ts
26
+ authz: {
27
+ relationships: {
28
+ attendeeOf: { from: 'guests', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { status: 'confirmed' } },
29
+ organizerOf: { from: 'staff', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { role: 'organizer' } },
30
+ shuttleDriverOf: { from: 'staff', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { role: 'shuttleDriver' } },
31
+ },
32
+ scopes: {
33
+ event: {
34
+ requestField: 'eventId', // the body field the client sends to /enter
35
+ roles: {
36
+ attendee: { via: 'attendeeOf' },
37
+ organizer: { via: 'organizerOf' },
38
+ shuttleDriver: { via: 'shuttleDriverOf', subKeys: ['shuttleId'] }, // row-slice sub-key
39
+ },
40
+ },
41
+ },
42
+ }
43
+ ```
44
+
45
+ ### 2. Enter the scope
46
+
47
+ ```http
48
+ POST /scope/v1/enter (session OR existing JWT auth)
49
+ { "eventId": "evt_123" }
50
+ ```
51
+
52
+ The server probes **every declared role** for the proposed instance (one DB touch), and mints the proven roles + sub-keys into a signed JWT `scope` claim, returned via the `set-auth-token` header and the body:
53
+
54
+ ```jsonc
55
+ // a shuttle driver who is also a confirmed guest
56
+ "scope": { "event": { "id": "evt_123", "roles": ["attendee", "shuttleDriver"], "shuttleId": "shA" } }
57
+ ```
58
+
59
+ The client sends that JWT as `Authorization: Bearer …` on subsequent requests. The auth middleware verifies the signature and sets `ctx.scope` — **no DB**. The claim is carried forward on every authed call (rolling refresh) until you `enter` a different instance.
60
+
61
+ > **Invariant:** the client only *proposes* the instance id (from the URL). The server proves membership before signing. No client-asserted scope is ever trusted.
62
+
63
+ ### 3. Gate the pillars
64
+
65
+ Scoped roles are referenced everywhere a pillar takes a role as the namespaced identifier **`scope:<kind>:<role>`**:
66
+
67
+ ```typescript
68
+ // features/guests/guests.ts — the manifest, row-sliced + PII-masked
69
+ export default feature('guests', {
70
+ columns: { /* … eventId, shuttleId, email, … */ },
71
+ // org staff see the whole event; a shuttle driver sees only their bus
72
+ firewall: {
73
+ any: [
74
+ { field: 'organizationId', equals: 'ctx.activeOrgId' },
75
+ { all: [
76
+ { field: 'eventId', equals: 'ctx.scope.event' },
77
+ { field: 'shuttleId', equals: 'ctx.scope.event.shuttleId' }, // sub-key row slice
78
+ ] },
79
+ ],
80
+ },
81
+ masking: {
82
+ email: { type: 'email', show: { roles: ['admin', 'scope:event:organizer'] } }, // hidden from the driver
83
+ },
84
+ read: {
85
+ views: {
86
+ manifest: {
87
+ fields: ['id', 'nameAtInvite', 'shuttleId', 'pickupLocation'],
88
+ access: { roles: ['admin', 'scope:event:organizer', 'scope:event:shuttleDriver'] },
89
+ },
90
+ },
91
+ },
92
+ });
93
+ ```
94
+
95
+ | Pillar | How it reads the scoped role |
96
+ |--------|------------------------------|
97
+ | **Firewall** (rows) | `all`/`any` arms keyed on `ctx.scope.<kind>` (+ sub-keys) — see [Firewall](/compiler/definitions/firewall) |
98
+ | **Access** (verbs/views) | `access.roles: ['scope:event:shuttleDriver']` on CRUD, actions, and views |
99
+ | **Masking** (fields) | `masking.<col>.show.roles` includes / excludes `scope:event:<role>` |
100
+
101
+ ## The org / scope split (security)
102
+
103
+ **Scoped roles never merge into `ctx.roles`.** A `scope:*` identifier matches **only** the verified scope claim (`ctx.scope.<kind>.roles`); a bare org role (`admin`, `member`) matches **only** `ctx.roles`. The compiler enforces the split so an externally-provisioned `shuttleDriver` can **never** satisfy an `admin` gate by string coincidence, and a tampered scope claim can't impersonate an org role. This is the precondition for admitting limited outside users at all.
104
+
105
+ ## Sub-keys (row slicing)
106
+
107
+ A role's `subKeys` name columns on the relationship's `from` row that are projected into the claim. A firewall arm then slices on them:
108
+
109
+ ```typescript
110
+ { field: 'shuttleId', equals: 'ctx.scope.event.shuttleId' }
111
+ ```
112
+
113
+ Because sub-key arms compose with `all`, an **absent** sub-key denies (`sql\`1 = 0\``) rather than widening — a driver can never see *all* shuttles by simply lacking the claim. The scope accessor is always emitted null-safe (`ctx.scope?.event?.shuttleId`), so an org caller who never entered the scope hits a clean deny, not a 500.
114
+
115
+ ### Set-valued sub-keys
116
+
117
+ A driver may cover **more than one** bus. Append a `[]` marker to the
118
+ sub-key name to project **every** matched `from` row's value into the claim
119
+ as a `string[]`:
120
+
121
+ ```typescript
122
+ roles: {
123
+ shuttleDriver: { via: 'shuttleDriverOf', subKeys: ['shuttleId[]'] }, // set-valued
124
+ }
125
+ ```
126
+
127
+ The `[]` is a marker only — it's stripped from the column name (the
128
+ relationship's `from` row still reads `shuttleId`). At `/scope/v1/enter` the
129
+ proven rows union their values, so the claim carries an array:
130
+
131
+ ```jsonc
132
+ "scope": { "event": { "id": "evt_123", "roles": ["shuttleDriver"], "shuttleId": ["shA", "shC"] } }
133
+ ```
134
+
135
+ The matching firewall arm — written exactly as for the scalar case
136
+ (`{ field: 'shuttleId', equals: 'ctx.scope.event.shuttleId' }`) — is
137
+ **rewritten by the compiler** to an `inArray` row-slice:
138
+
139
+ ```sql
140
+ WHERE shuttle_id IN (ctx.scope?.event?.shuttleId ?? [])
141
+ ```
142
+
143
+ The `?? []` default makes an absent claim lower to `inArray(col, [])` — a
144
+ clean DENY, never a malformed SQL fragment or a 500. A scalar sub-key (no
145
+ `[]` marker) is untouched and keeps lowering to `eq`. You write the same
146
+ `equals` arm either way; declaring `shuttleId[]` vs `shuttleId` in the scope
147
+ role is the only switch.
148
+
149
+ ## Auto-stamping the scope column on insert (`q.scope`)
150
+
151
+ `q.scope('organization')` auto-stamps the tenant column on write, the same
152
+ way `q.scope('owner')` stamps `ownerId`. A relationship-derived kind works
153
+ identically: `q.scope('event')` auto-stamps the column from the **verified
154
+ scope claim** (`ctx.scope.event.id`) on insert — no need to pass `eventId`
155
+ in the request body:
156
+
157
+ ```typescript
158
+ export const eventNotes = q.table('event_notes', {
159
+ id: q.id(),
160
+ eventId: q.scope('event'), // INSERT autofill from ctx.scope.event.id
161
+ body: q.text().required(),
162
+ organizationId: q.scope('organization'), // INSERT autofill from ctx.activeOrgId
163
+ });
164
+ ```
165
+
166
+ The stamp is **insert-only** and null-safe — the generated CREATE handler
167
+ writes `eventId: ctx.scope?.event?.id`, so it never binds `undefined`. It
168
+ does **not** add a read-time `WHERE` filter (that's the firewall's job; a
169
+ read scoped to `eventId = ctx.scope.event.id` would be wrong here). Infra
170
+ kinds map to their session fields (`organization` → `ctx.activeOrgId`,
171
+ `owner` → `ctx.userId`, `team` → `ctx.activeTeamId`); any other kind maps to
172
+ `ctx.scope.<kind>.id`.
173
+
174
+ ## Namespace scope-claim refresh
175
+
176
+ A scope is normally minted at `POST /scope/v1/enter`. When you also mount a
177
+ [namespace](/compiler/definitions/access#namespace-mounts-hoisted-relationship-middleware)
178
+ that gates `/event/:eventId/*` on the **same** relationship, the namespace
179
+ resolver can refresh `ctx.scope.<kind>` in memory for the duration of that
180
+ request — so an attendee hitting `/event/evt_123/announce` gets
181
+ `ctx.scope.event = { id: 'evt_123', roles: ['attendee'] }` without a separate
182
+ `enter` round-trip. The refresh runs **after** the gate (the gate proves the
183
+ relationship; the refresh stamps the proven role from the path param).
184
+
185
+ This is a strictly-guarded convenience, and it stamps **per matched lane**. The
186
+ resolver records which `via:` lane opened the gate (first-match-wins) and stamps
187
+ **only that lane's** scope role — an attendee who matched `attendeeOf` gets
188
+ `roles: ['attendee']`; an organizer who matched `organizerOf` gets
189
+ `roles: ['organizer']`. A caller can never receive a role they didn't prove this
190
+ request.
191
+
192
+ - **Relationship lanes** each confer their own scope role, stamped only when that exact lane matched — so a **multi-lane `via:`** (e.g. `via: ['attendeeOf', 'organizerOf']`) refreshes the matched lane's role, not an ambiguous union.
193
+ - A **bulk-grant lane** (`{ roles: [...] }` or `{ team: true }`) confers **no** scope role — it opens the gate via the caller's org role *without* proving any relationship, so there is nothing to stamp (stamping one would forge it). The gate still passes; the caller is simply authorized by their org role.
194
+
195
+ The refresh described so far is in-memory and single-request. To also hand the
196
+ caller a **persisted** scope token, opt the namespace into `mintScope` — see
197
+ below.
198
+
199
+ ### Gotcha: a namespace only emits its resolver when it claims a standalone action
200
+
201
+ This is the single most common surprise (it has tripped up a customer): **a
202
+ namespace emits its resolver — and therefore the scope refresh and the
203
+ [`mintScope`](#mintscope-mint-the-scope-token-from-the-namespace-resolver)
204
+ mint — only when at least one STANDALONE action's `path:` falls under the
205
+ namespace prefix.**
206
+
207
+ A standalone action declares its own `path:` (e.g.
208
+ `path: '/event/:eventId/home'`), so the compiler can match it against the
209
+ namespace prefix and hoist it into the synthetic namespace routes file.
210
+ **Record-based actions are different** — they mount under their resource's CRUD
211
+ routes (`/api/v1/guests/:id/checkin`), which live *outside* the
212
+ `/event/:eventId` prefix. They never match the prefix, so they never get
213
+ claimed.
214
+
215
+ A namespace that contains **only** record-based actions is therefore **inert**:
216
+ nothing matches the prefix, no synthetic routes file is emitted, and so there
217
+ is **no resolver, no scope refresh, and no mint** — even though the namespace
218
+ is declared and validates cleanly. The middleware you expected to gate
219
+ `/event/:eventId/*` simply isn't there.
220
+
221
+ The fix is to give the namespace at least one standalone action under the
222
+ prefix. In `q-events`, `eventHome` exists precisely for this — a standalone
223
+ `GET /event/:eventId/home` that pulls the resolver (and the §5.3 mint) into
224
+ existence:
225
+
226
+ ```typescript
227
+ // features/events/actions/eventHome.ts
228
+ export default defineAction({
229
+ path: '/event/:eventId/home', // ← standalone path UNDER the namespace prefix
230
+ method: 'GET',
231
+ input: z.object({}),
232
+ access: { roles: ['scope:event:attendee', 'scope:event:organizer', 'manager+'] },
233
+ async execute({ db, ctx, c }) { /* … */ },
234
+ });
235
+ ```
236
+
237
+ With that action present, the `eventScope` resolver is emitted, runs the
238
+ `attendeeOf` probe once per `/event/:eventId/*` request, stamps
239
+ `ctx.scope.event`, and (because the namespace sets `mintScope: true`) mints the
240
+ scope token. Without a standalone action under the prefix, none of that fires.
241
+
242
+ ## `mintScope` — mint the scope token from the namespace resolver
243
+
244
+ A scope is normally minted by an explicit `POST /scope/v1/enter` round-trip.
245
+ Setting **`mintScope: true`** on a namespace folds that mint into the
246
+ namespace resolver: on a successful relationship probe the resolver MINTS a
247
+ persisted scope JWT and returns it via the `set-auth-token` header — so a
248
+ native client hitting `/event/:eventId/*` gets a scope token **without ever
249
+ calling `/scope/v1/enter`**.
250
+
251
+ ```typescript
252
+ // quickback.config.ts
253
+ authz: {
254
+ relationships: {
255
+ attendeeOf: {
256
+ from: 'guests',
257
+ subject: { column: 'linkedUserId', equals: 'ctx.userId' },
258
+ resource: { column: 'eventId' },
259
+ where: { status: 'confirmed' },
260
+ loads: 'guests',
261
+ exposeAs: 'guest',
262
+ },
263
+ },
264
+ namespaces: {
265
+ eventScope: {
266
+ prefix: '/event/:eventId',
267
+ via: ['attendeeOf'], // one or more lanes — mints the matched lane's role
268
+ mintScope: true, // ← fold the scope-token mint into the resolver
269
+ },
270
+ },
271
+ }
272
+ ```
273
+
274
+ A confirmed attendee then hits the standalone action under the prefix:
275
+
276
+ ```http
277
+ GET /api/v1/event/evt_123/home
278
+ Authorization: Bearer <existing-jwt>
279
+
280
+ 200 OK
281
+ set-auth-token: <new-scoped-jwt> ← carries scope.event.roles = ["attendee"]
282
+ ```
283
+
284
+ The client stores the `set-auth-token` value and sends it as the bearer on
285
+ every subsequent `/event/:eventId/*` request. The JWT carries
286
+ `scope.event = { id: 'evt_123', roles: ['attendee'] }`, so the scoped-role
287
+ access checks (`scope:event:attendee`) pass with no DB touch and no second
288
+ `enter` call.
289
+
290
+ `mintScope` is **opt-in per namespace** and defaults to `false`. With it off,
291
+ the resolver does the in-memory `ctx.scope.<kind>` refresh only (the section
292
+ above); subsequent requests must still call `/scope/v1/enter` for a persisted
293
+ token.
294
+
295
+ ### Per-matched-lane minting (forging safety)
296
+
297
+ The mint stamps the scope role of **whichever lane matched**, gated on the
298
+ first-match-wins probe — the *same* per-lane discipline as the in-memory stamp,
299
+ applied here with higher stakes: a minted token **persists for its whole TTL**,
300
+ so it can only ever carry the role the caller actually proved this request.
301
+
302
+ - A **multi-lane `via:`** (e.g. `via: ['attendeeOf', 'organizerOf']`) mints the matched lane's role — `attendeeOf` → `scope.event.roles = ['attendee']`, `organizerOf` → `['organizer']`. The resolver records which lane opened the gate, so there is no ambiguity.
303
+ - A **bulk-grant lane** (`{ roles: [...] }` or `{ team: true }`) mints **no** scope role — it opens the gate via the caller's org role without proving a relationship. The gate passes; the caller carries their org role, not a minted scope role.
304
+
305
+ > The realtime [ws-ticket](/stack/realtime/durable-objects#namespace-backed-tickets-per-matched-lane) can authorize through this same namespace `via:`, issuing a per-matched-lane WebSocket ticket — so the socket gate and the REST gate stay identical.
306
+
307
+ In every suppressed case the gate still authorizes the request; only the mint
308
+ (and the in-memory refresh) are skipped, and those callers obtain a scope
309
+ token through `/scope/v1/enter` as usual. Flipping `mintScope: true` can never
310
+ forge a scope role — the guard, not the flag, is the gate.
311
+
312
+ ### TTL and best-effort semantics
313
+
314
+ - **TTL is the scope-token TTL** — `auth.jwt.expiresIn` (default 180s), **clamped to a hard ≤180s ceiling** at the mint site. A longer-lived scope token would widen the post-revocation replay window past the spec bound, so the clamp is non-negotiable.
315
+ - **The mint is gated by the same proven-relationship guard as the in-memory stamp.** It runs *after* the gate has granted access, reading the instance id from the proven path param (`:eventId`) — never from request input — so the minted `scope:<kind>:<role>` is backed by exactly the proof `/scope/v1/enter` requires. The token is **byte-identical** to one `/scope/v1/enter` would produce: same shared mint helper, same carry-forward of any *other* verified scope kinds already on the incoming token (the freshly-proven kind takes precedence; siblings survive the re-mint).
316
+ - **The mint is best-effort.** A mint failure (e.g. a missing signing secret) **never fails the request** — the in-memory stamp already authorized it; the caller simply doesn't receive a refreshed token on that response and can fall back to `/scope/v1/enter`.
317
+
318
+ ## Revocation & TTL
319
+
320
+ The scope claim is trusted for the JWT TTL (default 180s, `auth.jwt.expiresIn`) — identical to how `orgId` / `role` claims already behave. Removing a guest/staff row takes effect within one TTL (the next `enter` won't re-mint the role). Immediate revocation (`auth.jwt.revocationCheck: 'kv'`) is on the roadmap.
321
+
322
+ ## Reference
323
+
324
+ ```typescript
325
+ // AppContext (generated lib/types.ts)
326
+ ctx.scope?: Record<string, { id: string; roles?: string[]; [subKey: string]: string | string[] | undefined }>;
327
+
328
+ // authz.scopes.<kind>
329
+ {
330
+ requestField: string; // body field carrying the instance id
331
+ roles: Record<string, { via: string; subKeys?: string[] }>; // 'col' → eq, 'col[]' → inArray
332
+ }
333
+ ```
334
+
335
+ - `requestField` must equal every role-relationship's `resource.column`.
336
+ - Each relationship's `from` table must exist and ship a generated firewall (it can't be `exception`).
337
+ - A `subKeys` entry ending in `[]` is **set-valued** (lowers to `inArray`, minted as `string[]`); without the marker it's scalar (`eq`, minted as `string`).
338
+ - `q.scope('<kind>')` auto-stamps the column from `ctx.scope.<kind>.id` on insert.
339
+ - Generated route: `POST /scope/v1/enter` (mounted only when `authz.scopes` is declared).
@@ -312,6 +312,72 @@ the metric from the user's filters would surprise.
312
312
  - No raw SQL `expr:` form. Column references only — declare a generated
313
313
  column or write a custom action if you need arithmetic.
314
314
 
315
+ ## Aggregate-only views
316
+
317
+ A normal view returns rows *and* (optionally) aggregations. An
318
+ **aggregate-only** view returns the rollup and **nothing else** — no
319
+ `data[]`, no field selection. Set `aggregateOnly: true`:
320
+
321
+ ```typescript
322
+ read: {
323
+ views: {
324
+ 'dietary-rollup': {
325
+ aggregateOnly: true,
326
+ fields: [], // must be empty/absent
327
+ kMin: 5, // k-anonymity bucket size
328
+ access: { roles: ['scope:event:fnb', 'admin'] },
329
+ aggregations: {
330
+ dietaryRollup: { fn: 'groupBy', field: 'dietaryNotes' },
331
+ totalGuests: { fn: 'sum', field: 'guestCount' },
332
+ headcount: { fn: 'count' },
333
+ },
334
+ },
335
+ },
336
+ }
337
+ ```
338
+
339
+ The response carries only `aggregations`:
340
+
341
+ ```json
342
+ {
343
+ "view": "dietary-rollup",
344
+ "aggregations": {
345
+ "dietaryRollup": { "vegan": 18, "gluten-free": 12, "(none)": 143 },
346
+ "totalGuests": 184,
347
+ "headcount": 173
348
+ }
349
+ }
350
+ ```
351
+
352
+ This lets a vendor see *"12 guests need a gluten-free meal"* without ever
353
+ reading the roster. The endpoint is gated **independently** of the base
354
+ collection and the per-row views — reading the rollup grants zero row or
355
+ field access.
356
+
357
+ **Constraints (compile-time):**
358
+
359
+ - Requires a non-empty `aggregations` map.
360
+ - `fields` must be empty or absent — field selection is disabled, and
361
+ `?fields=` cannot coax row-level data out.
362
+ - Only the view's `query.filterable` allowlist is honored. `query.searchable`
363
+ and `query.sortable` are rejected (no `?search=`, no `?sort=`, no
364
+ free-form `?<col>=` outside the allowlist).
365
+
366
+ ### `kMin` — k-anonymity suppression
367
+
368
+ `kMin` (default `5`) protects against re-identification through small
369
+ buckets ("1 guest, allergy = shellfish"):
370
+
371
+ - `groupBy` buckets with fewer than `kMin` rows collapse into a single
372
+ `"(other)"` bucket carrying their summed count.
373
+ - A scalar `count` / `sum` / `avg` / `min` / `max` / `count_distinct`
374
+ computed over a filtered set smaller than `kMin` rows returns the literal
375
+ string `"(suppressed)"` instead of a number.
376
+
377
+ `kMin` is only meaningful on `aggregateOnly: true` views. It's ignored on
378
+ row-returning views, where the aggregations ride alongside the rows and the
379
+ row firewall already governs disclosure.
380
+
315
381
  ## Response Format
316
382
 
317
383
  View responses include metadata about the view:
@@ -60,6 +60,49 @@ providers: {
60
60
 
61
61
  That tells `/broadcast/v1/ws-ticket` to authenticate with Better Auth, verify the `attendee` relationship role against `body.eventId`, and mint a short-lived ticket scoped to the resolved `events:<id>` lane.
62
62
 
63
+ ### Namespace-backed tickets (per-matched-lane)
64
+
65
+ The single-`role` form above authorizes the ticket through **one** relationship.
66
+ When the room is gated by an [authz namespace](/compiler/definitions/scopes#mintscope-mint-the-scope-token-from-the-namespace-resolver)
67
+ with a **multi-lane `via:`** — e.g. an event reachable by attendees, organizers,
68
+ contractors, *and* org admins — point the ticket at the namespace instead, and it
69
+ authorizes through the namespace's full `via` (per-matched-lane):
70
+
71
+ ```typescript
72
+ realtime: {
73
+ wsTicket: {
74
+ namespace: "eventScope", // authorize via this namespace's full multi-lane `via`
75
+ requestField: "eventId",
76
+ scopeTable: "events",
77
+ },
78
+ },
79
+ ```
80
+
81
+ `/broadcast/v1/ws-ticket` now runs the **same first-match-wins gate** the
82
+ namespace uses, and issues the ticket for whichever lane matched:
83
+
84
+ | Caller matched via | Ticket role |
85
+ |---|---|
86
+ | `attendeeOf` (relationship lane) | `attendee` |
87
+ | `organizerOf` | `organizer` |
88
+ | `contractorOf` | `contractor` |
89
+ | `{ roles: ["admin","owner"] }` (bulk lane) | the caller's **org/membership roles** — no scope role |
90
+
91
+ This closes the gap where the single-`role` form denied (`403`) an org admin who
92
+ could legitimately reach the room through the bulk lane but isn't a confirmed
93
+ attendee — their realtime socket now opens.
94
+
95
+ > **`scopeTable` must be tenant-scoped.** Before minting, the route loads the
96
+ > `scopeTable` row by `requestField` through *its own firewall* — so a ticket can
97
+ > only target a room whose resource resolves under the caller's tenant (an org-A
98
+ > admin requesting an org-B `eventId` gets `403`, not a cross-tenant socket). Because
99
+ > the room *is* the data — there is no firewall between a ticket and a Durable
100
+ > Object room — the compiler **rejects at build time** a namespace-backed
101
+ > `wsTicket` whose `scopeTable` has `firewall: { exception: true }` or a non-tenant
102
+ > (literal-only) firewall with no org/owner/team isolation. Use a tenant-scoped
103
+ > `scopeTable`.
104
+
105
+
63
106
  ## When auto-broadcast fires (and when you call it manually)
64
107
 
65
108
  Quickback emits auto-broadcasts in **only one place**: the generated CRUD route handlers (`POST /` create, `PATCH /:id` update, `DELETE /:id` delete) for resources with `realtime.enabled` (or covered by `dbConfig.realtime: true`'s project-level default). Those handlers wrap each successful write with a `realtime.insert / update / delete` call before responding.
@@ -0,0 +1,168 @@
1
+ # Live Views
2
+
3
+ A **live view** is a named *surface*: a root row plus the related data a screen
4
+ shows around it — forward foreign-key display values and reverse-FK child
5
+ collections. When a client subscribes to a live view, the open surface stays
6
+ whole in realtime: any write to the root row **or** a related row that shares a
7
+ foreign key is pushed as a `view_changes` delta the client splices in place.
8
+
9
+ This is the difference from table-level [`postgres_changes`](/stack/realtime/using-realtime)
10
+ broadcasts, which are single-row, single-table. A person-detail screen that
11
+ shows a `people` row plus rows from a normalized `phone_numbers` table would
12
+ otherwise have to stitch together separate per-table events and figure out that
13
+ a `phone_numbers` insert with `personId = X` belongs to the person it has open.
14
+ Live views do that mapping for you.
15
+
16
+ > Live views ride the realtime Broadcaster. You must have realtime enabled
17
+ > (`providers.database.config.realtime: true`). Declaring a view without
18
+ > realtime is a compile-time error.
19
+
20
+ ## Defining a view
21
+
22
+ Views live in `services/views/<name>.ts`:
23
+
24
+ ```typescript
25
+ // services/views/person-detail.ts
26
+ import { defineView } from 'quickback';
27
+
28
+ export default defineView({
29
+ name: 'person-detail',
30
+ root: 'people',
31
+ include: [
32
+ { relation: 'companyId' }, // forward FK → company display value
33
+ { relation: 'phone_numbers' }, // reverse FK → phoneNumbers[] collection
34
+ ],
35
+ });
36
+ ```
37
+
38
+ - **`root`** — the table the surface is keyed by. Must be a `defineTable`
39
+ resource (its firewall + read access gate the surface).
40
+ - **`include[].relation`** — a forward-FK column on the root (`companyId`), or
41
+ the name of a child table that references the root (`phone_numbers`). The
42
+ compiler auto-detects the direction from the foreign-key graph; pass
43
+ `kind: 'forward' | 'reverse'` to disambiguate.
44
+ - **`as`** — the response key the related data is spliced under. Defaults to a
45
+ derived name: forward strips a trailing `Id` (`companyId` → `company`),
46
+ reverse uses the child table name (`phone_numbers` → `phoneNumbers`).
47
+ - **`fields`** — optional column projection on the included table.
48
+
49
+ The materialized surface looks like:
50
+
51
+ ```jsonc
52
+ {
53
+ "id": "person_123",
54
+ "name": "Ada Lovelace",
55
+ "email": "ad***@example.com", // masked per the people table's masking config
56
+ "company": "Analytical Engines", // forward display value
57
+ "phoneNumbers": [ // reverse-FK child collection
58
+ { "id": "ph_1", "number": "+1..." }
59
+ ]
60
+ }
61
+ ```
62
+
63
+ Every included table is read through **its own** `firewall` and `masking` — a
64
+ subscriber only ever sees related rows they're already allowed to read, masked
65
+ exactly as they would be on a normal read.
66
+
67
+ ## Reading a surface
68
+
69
+ The compiler generates a read endpoint per view:
70
+
71
+ ```http
72
+ GET /api/v1/views/person-detail/person_123
73
+ → { "data": { ...surface }, "seq": 7 }
74
+ ```
75
+
76
+ `seq` is the surface's current monotonic sequence — the client uses it to detect
77
+ dropped deltas. A `404` is returned when the caller can't read the root row
78
+ (indistinguishable from "doesn't exist", closing the id-probe channel).
79
+
80
+ ## Subscribing (client)
81
+
82
+ The built-in CMS and Account SPAs ship a `useView` hook:
83
+
84
+ ```tsx
85
+ import { useView } from '~/lib/realtime/use-view';
86
+
87
+ function PersonDetail({ personId }: { personId: string }) {
88
+ const { data, connected, loading } = useView('person-detail', personId);
89
+ // `data` stays live: editing the person merges into the root; adding a phone
90
+ // appends to data.phoneNumbers; deleting one removes it — no refetch.
91
+ }
92
+ ```
93
+
94
+ Under the hood `useView` uses a **subscribe-then-snapshot** flow so no change
95
+ slips through the gap between reading the surface and the socket going live:
96
+
97
+ 1. Requests a **view-scoped ws-ticket** (`POST /broadcast/v1/ws-ticket` with
98
+ `{ view, rootId }`) — gated by the same root firewall as the read endpoint —
99
+ and opens a WebSocket scoped to `view:<view>:<rootId>`.
100
+ 2. Once the socket is open, fetches the full surface via
101
+ `GET /api/v1/views/<view>/:rootId`. Deltas arriving during that fetch are
102
+ **buffered**, then replayed after the snapshot applies (the route reads the
103
+ `seq` baseline *before* materializing, so the snapshot is at least as fresh
104
+ as `seq`, and replay is idempotent — collections key by row `id`).
105
+ 3. Applies `view_changes` deltas in place (the **hybrid-delta** model):
106
+ - `target: 'root'` + `UPDATE` → shallow-merge into the surface root
107
+ - `target: 'root'` + `DELETE` → surface cleared
108
+ - `target: 'collection'` → append / replace-by-key / remove-by-key on `data[as]`
109
+ - `delta.resync` → refetch the surface (the stricter-child path above)
110
+ 4. Tracks `seq`. A gap (`seq !== last + 1`) or a WebSocket reconnect triggers a
111
+ full **resync** — the safety net that heals any dropped delta (Cloudflare D1
112
+ has no transactions, so emit is best-effort by design). If the server can't
113
+ read the baseline it returns `seq: null`; the client then adopts the first
114
+ delta's `seq` instead of treating it as `0`, so a transient read error never
115
+ spirals into a resync loop. Overlapping resyncs are token-guarded so a slow
116
+ earlier fetch can't clobber a newer surface.
117
+
118
+ To subscribe from a custom client, request a ticket with `{ view, rootId }` and
119
+ connect to `…/broadcast/v1/websocket?ws_ticket=<ticket>`. Messages are:
120
+
121
+ ```jsonc
122
+ {
123
+ "type": "view_changes",
124
+ "view": "person-detail",
125
+ "rootId": "person_123",
126
+ "seq": 8,
127
+ "delta": { "target": "collection", "op": "INSERT", "as": "phoneNumbers",
128
+ "key": "ph_2", "row": { "id": "ph_2", "number": "+1..." } }
129
+ }
130
+ ```
131
+
132
+ ## How changes are captured
133
+
134
+ Deltas are emitted from the **write chokepoint** — the same wrapper that injects
135
+ audit fields wraps every `db.insert/update/delete`. Because CRUD routes *and*
136
+ action handlers write through that db, both emit deltas; there's no separate
137
+ hook to wire. A write taps its result and, when it used `.returning()`, fans a
138
+ delta to each affected surface. Soft deletes (an `UPDATE` that sets `deletedAt`)
139
+ are emitted as `DELETE` so the row leaves the surface.
140
+
141
+ ## Security
142
+
143
+ - The **subscribe gate** reuses the view materializer: a ticket is only minted
144
+ when the caller can read the root row.
145
+ - Each included table's `firewall` + `masking` apply on both the initial
146
+ materialize and the live deltas (masking is applied per subscriber role at
147
+ fanout), so the two are consistent.
148
+ - **Stricter-child guard.** When a reverse-FK child's firewall is *stricter*
149
+ than the root's (e.g. an owner-scoped note under an org-scoped person), the
150
+ raw child row is **never broadcast**. Instead the server emits a *resync
151
+ signal* and the client refetches the surface through the materializer, which
152
+ applies the child's own firewall per subscriber. Row-bearing deltas are sent
153
+ only when the child is no stricter than the root.
154
+ - **Masking fails closed.** A mask type the Broadcaster can't replicate —
155
+ notably `type: 'custom'`, whose function is stripped during codegen — is
156
+ fully redacted (`[REDACTED]`) in deltas rather than passed through.
157
+ - **Projection parity.** An include's `fields` projection is applied to deltas
158
+ too, so a delta never carries a column the surface deliberately omits.
159
+
160
+ ## v1 limitations
161
+
162
+ - **Depth-1 includes only.** Nested includes are a compile-time error — flatten
163
+ the surface or split into multiple views.
164
+ - **Forward includes** (e.g. a company name on a person) are materialized into
165
+ the surface and refreshed on resync, but a change to the *referenced parent*
166
+ does not push a live delta — it surfaces on the next resync/reconnect.
167
+ - **Writes without `.returning()`** (and raw action writes that don't return
168
+ rows) don't push a live delta; resync-on-reconnect heals the surface.