@quickback-dev/cli 0.12.0 → 0.14.2

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 (34) hide show
  1. package/dist/commands/create.d.ts.map +1 -1
  2. package/dist/commands/create.js +11 -3
  3. package/dist/commands/create.js.map +1 -1
  4. package/dist/docs/content.js +12 -12
  5. package/dist/docs/content.js.map +1 -1
  6. package/dist/index.js +1 -1
  7. package/dist/skill/docs/changelog.md +192 -1
  8. package/dist/skill/docs/compiler/config/auth.md +37 -0
  9. package/dist/skill/docs/compiler/definitions/access.md +164 -2
  10. package/dist/skill/docs/compiler/definitions/actions.md +145 -0
  11. package/dist/skill/docs/compiler/definitions/firewall.md +46 -0
  12. package/dist/skill/docs/compiler/definitions/index.md +2 -0
  13. package/dist/skill/docs/compiler/definitions/masking.md +11 -0
  14. package/dist/skill/docs/compiler/definitions/read.md +8 -7
  15. package/dist/skill/docs/compiler/definitions/views.md +100 -12
  16. package/dist/skill/docs/compiler/getting-started/full-example.md +12 -11
  17. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/crud.md +1 -2
  18. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/views-api.md +8 -13
  19. package/dist/templates/registry.d.ts.map +1 -1
  20. package/dist/templates/registry.js +14 -1
  21. package/dist/templates/registry.js.map +1 -1
  22. package/package.json +1 -1
  23. package/src/skill/docs/changelog.md +192 -1
  24. package/src/skill/docs/compiler/config/auth.md +37 -0
  25. package/src/skill/docs/compiler/definitions/access.md +164 -2
  26. package/src/skill/docs/compiler/definitions/actions.md +145 -0
  27. package/src/skill/docs/compiler/definitions/firewall.md +46 -0
  28. package/src/skill/docs/compiler/definitions/index.md +2 -0
  29. package/src/skill/docs/compiler/definitions/masking.md +11 -0
  30. package/src/skill/docs/compiler/definitions/read.md +8 -7
  31. package/src/skill/docs/compiler/definitions/views.md +100 -12
  32. package/src/skill/docs/compiler/getting-started/full-example.md +12 -11
  33. package/src/skill/docs/compiler/targets/hono-api/using-the-api/crud.md +1 -2
  34. package/src/skill/docs/compiler/targets/hono-api/using-the-api/views-api.md +8 -13
@@ -64,6 +64,7 @@ type FirewallPredicate =
64
64
  | { field: string; equals: string } // column = ctx.* (or literal)
65
65
  | { field: string; isNull: true } // column IS NULL
66
66
  | { field: string; in: string[] | string }// column IN (...)
67
+ | { field: string; via: string } // column IN (relationship subquery)
67
68
  | { exception: true }; // opt out of tenant scoping
68
69
 
69
70
  type FirewallConfig = ReadonlyArray<FirewallPredicate>;
@@ -74,6 +75,51 @@ firewallErrorMode?: 'reveal' | 'hide';
74
75
 
75
76
  Predicates are AND'd together. `firewallErrorMode` lives at the resource top level — it's a presentation-layer choice (403 vs 404), not a query-shape one.
76
77
 
78
+ ## Relationship-based scoping (`via:`)
79
+
80
+ For relationship authorization — "this user can see rows X if they have a confirmed `event_guests` row pointing at X" — declare the relationship under `authz.relationships` in `quickback.config.ts`, then reference it from `firewall:` with a `via:` predicate:
81
+
82
+ ```typescript
83
+ // quickback.config.ts
84
+ authz: {
85
+ relationships: {
86
+ guestOf: {
87
+ from: 'event_guests', // table name
88
+ subject: { column: 'userId', equals: 'ctx.userId' }, // caller side
89
+ resource: { column: 'eventId' }, // resource side
90
+ where: { status: 'confirmed' }, // optional row filter
91
+ },
92
+ },
93
+ }
94
+
95
+ // features/sessions/sessions.ts
96
+ firewall: [
97
+ { field: 'organizationId', equals: 'ctx.activeOrgId' },
98
+ { field: 'eventId', via: 'guestOf' },
99
+ ]
100
+ ```
101
+
102
+ Compiles to:
103
+
104
+ ```sql
105
+ WHERE sessions.organizationId = ?
106
+ AND sessions.eventId IN (
107
+ SELECT eventId FROM event_guests
108
+ WHERE userId = ?
109
+ AND status = 'confirmed'
110
+ AND <event_guests' own firewall — tenant scope + soft-delete>
111
+ )
112
+ ```
113
+
114
+ Key properties:
115
+
116
+ - **Firewall stays the outermost AND.** A guest of an event in another tenant is still blocked by your tenant predicate. Relationship-based scoping never bypasses tenant isolation.
117
+ - **The relationship table's own firewall is AND'd into the subquery.** Soft-deleting a `event_guests` row revokes access immediately; cross-tenant relationship rows can't grant access.
118
+ - **Anonymous callers fail closed.** `ctx.userId` is null-guarded; the subquery short-circuits to `WHERE 1 = 0` for unauthenticated requests.
119
+ - **The relationship table must be tenant-scoped** (`firewall: { exception: true }` is rejected at compile time on relationship tables).
120
+
121
+ See [Access — relationships](/compiler/definitions/access#authz-relationships) for the full `authz.relationships` shape and role-binding patterns.
122
+
77
123
  ## Context Sources
78
124
 
79
125
  When `equals` references the request context, use these standard sources:
@@ -110,6 +110,8 @@ The firewall controls **which records** a user can see. It automatically adds WH
110
110
 
111
111
  No manual configuration needed - Quickback applies smart rules based on your schema.
112
112
 
113
+ For relationship-based row visibility (e.g. "user can see this event because they have a confirmed `event_guests` row pointing at it"), declare the relationship under `authz.relationships` and reference it from the firewall with a `via:` predicate. See [Firewall → Relationship-based scoping](/compiler/definitions/firewall#relationship-based-scoping-via).
114
+
113
115
  [Learn more about Firewall →](/compiler/definitions/firewall)
114
116
 
115
117
  ### 2. Access (CRUD Permissions)
@@ -139,6 +139,17 @@ show: {
139
139
 
140
140
  The `'owner'` condition compares against the owner column declared via `q.scope('owner')` (or auto-detected from a `userId` / `ownerId` column). If no owner scope is present, it falls back to `createdBy`.
141
141
 
142
+ ### Relationship-roles in masking (v1 limitation)
143
+
144
+ Relationship-roles declared under `authz.roles` (e.g. `guest: { via: 'guestOf' }`) are **not yet supported in `show:` clauses**. The compiler refuses to build with a clear error message because async, db-aware mask functions plus a batched relationship matcher (to avoid N+1 on list responses) are required to ship safely — that pipeline has not yet landed. The runtime evaluator fails closed on unrecognized arms, so silent grants are impossible.
145
+
146
+ **Workarounds**, depending on intent:
147
+
148
+ - **Gate on BA roles only**: keep masking simple and put the relationship check at the access layer instead — `read.views.<v>.access: { roles: ['guest'] }` returns a curated field projection that excludes the sensitive column entirely for non-staff callers, without involving masking.
149
+ - **Move the field into a view that's gated by the relationship-role at access**: same pattern — column-level security via field projection rather than per-row masking.
150
+
151
+ A future async-mask pipeline with batched lookups will lift this limitation; the schema slot is reserved so the v2 add will be non-breaking.
152
+
142
153
  ## Query Gate (filter / sort / search)
143
154
 
144
155
  Masking has a second concern beyond hiding values in the response: a non-admin caller could enumerate masked PII via the query string — e.g. `?filter=email:like:%@target.com` — and infer presence even when the response payload is redacted. The `query` allowlist closes this:
@@ -53,8 +53,7 @@ export default defineTable(customers, {
53
53
  |----------|------|
54
54
  | `GET /api/v1/{resource}` | `read.access` |
55
55
  | `GET /api/v1/{resource}/:id` | `read.access` |
56
- | `GET /api/v1/{resource}?view={name}` | `read.views[name].access` (falls back to `read.access`) |
57
- | `GET /api/v1/{resource}/views/{name}` | Same — explicit path form of the `?view=` dispatch |
56
+ | `GET /api/v1/{resource}/views/{name}` | `read.views[name].access` (falls back to `read.access`) |
58
57
 
59
58
  Single-record `GET /:id` inherits `read.access` automatically — there's no
60
59
  separate `read.get` block. If you need different access for single records,
@@ -145,10 +144,10 @@ read: {
145
144
  }
146
145
  ```
147
146
 
148
- Both endpoint shapes are emitted automatically:
147
+ Named views are emitted at dedicated path routes:
149
148
 
150
- - Query-string dispatch: `GET /api/v1/jobs?view=internal`
151
- - Explicit path: `GET /api/v1/jobs/views/internal`
149
+ - `GET /api/v1/jobs/views/internal`
150
+ - If `read.defaultView` is set, bare `GET /api/v1/jobs` resolves to that view.
152
151
 
153
152
  ## Migrating from `crud.list` / `crud.get`
154
153
 
@@ -161,7 +160,7 @@ DSL v2 rejects both at compile time. The migration is mechanical:
161
160
  | `crud.list.maxPageSize` | `read.maxPageSize` |
162
161
  | `crud.list.fields: [...]` | Move to a named view under `read.views` |
163
162
  | `crud.get.access` | `read.access` (or record-level conditions) |
164
- | `crud.get.fields: [...]` | Move to a named view; clients call `?view=...` |
163
+ | `crud.get.fields: [...]` | Move to a named view; clients call `/views/{name}` |
165
164
  | Top-level `views: {...}` | `read.views: {...}` |
166
165
 
167
166
  Example before/after:
@@ -197,7 +196,9 @@ crud: {
197
196
  ```
198
197
 
199
198
  Clients that previously hit `GET /:id` to retrieve only summary fields now
200
- call `GET /:id?view=summary`.
199
+ move that projection to a named collection view such as
200
+ `GET /api/v1/jobs/views/summary`. Single-record `GET /:id` always returns the
201
+ full masked record.
201
202
 
202
203
  ## Read-Only Resources
203
204
 
@@ -75,20 +75,18 @@ export default defineTable(candidates, {
75
75
 
76
76
  ## Generated Endpoints
77
77
 
78
- Each view generates **two** equivalent GET endpoints — pick whichever is more ergonomic for your client:
78
+ Each named view generates a dedicated GET endpoint:
79
79
 
80
80
  ```
81
81
  GET /api/v1/candidates # Full read - read.access fields
82
- GET /api/v1/candidates?view=pipeline # Query-string dispatch
83
- GET /api/v1/candidates/views/pipeline # Explicit path form
84
- GET /api/v1/candidates?view=full # hiring-manager/recruiter only
82
+ GET /api/v1/candidates/views/pipeline # interviewer/recruiter/etc.
83
+ GET /api/v1/candidates/views/full # hiring-manager/recruiter only
85
84
  GET /api/v1/candidates/views/report # report fields
86
85
  ```
87
86
 
88
- The `?view=` query-string form is convenient when the rest of your client
89
- already builds collection URLs and you only need to swap the projection.
90
- The `/views/{name}` path form is better when you want a stable URL per
91
- projection.
87
+ If `read.defaultView` is set, bare `GET /api/v1/candidates` can also resolve
88
+ to that named view. Without `defaultView`, bare `GET /api/v1/candidates`
89
+ returns `VIEW_REQUIRED` once views are declared.
92
90
 
93
91
  ## Query Parameters
94
92
 
@@ -227,6 +225,93 @@ read: {
227
225
  | `/views/full` | interviewer | Yes | `j***@c******.com` |
228
226
  | `/views/full` | recruiter | Yes | `jane@company.com` |
229
227
 
228
+ ## Aggregations
229
+
230
+ Views can declare pre-computed aggregations that run alongside the row
231
+ query and surface as `aggregations: { ... }` on the response. This avoids a
232
+ custom standalone action for every "count of X grouped by Y" dashboard
233
+ tile — the firewall and view filters already in place drive the metric.
234
+
235
+ ```typescript
236
+ read: {
237
+ access: { roles: ['owner', 'admin', 'member'] },
238
+ views: {
239
+ pipeline: {
240
+ fields: ['id', 'jobId', 'candidateId', 'status', 'appliedAt'],
241
+ aggregations: {
242
+ totalApplications: { fn: 'count' },
243
+ byStatus: { fn: 'groupBy', field: 'status' },
244
+ },
245
+ },
246
+ },
247
+ }
248
+ ```
249
+
250
+ Response now carries the aggregations alongside `data`:
251
+
252
+ ```json
253
+ {
254
+ "data": [/* paginated rows */],
255
+ "view": "pipeline",
256
+ "pagination": { "count": 50, "page": 1, "pageSize": 50, "hasMore": true },
257
+ "aggregations": {
258
+ "totalApplications": 173,
259
+ "byStatus": {
260
+ "applied": 102,
261
+ "screening": 41,
262
+ "interview": 18,
263
+ "offer": 7,
264
+ "rejected": 5
265
+ }
266
+ }
267
+ }
268
+ ```
269
+
270
+ ### Supported aggregation functions
271
+
272
+ | `fn` | `field` | Returns | Example |
273
+ |---|---|---|---|
274
+ | `sum` | required, numeric | scalar number | `{ fn: 'sum', field: 'guestCount' }` |
275
+ | `avg` | required, numeric | scalar number | `{ fn: 'avg', field: 'salary' }` |
276
+ | `min` | required | scalar number | `{ fn: 'min', field: 'price' }` |
277
+ | `max` | required | scalar number | `{ fn: 'max', field: 'price' }` |
278
+ | `count` | optional | `COUNT(*)` if omitted, `COUNT(field)` (non-null) if given | `{ fn: 'count' }` |
279
+ | `count_distinct` | required | scalar number | `{ fn: 'count_distinct', field: 'sourceId' }` |
280
+ | `groupBy` | required | `{ value: count }` map | `{ fn: 'groupBy', field: 'status' }` |
281
+
282
+ `groupBy` always returns a count map keyed by the distinct values of `field`.
283
+ `NULL` values bucket under the literal string `"(none)"`. Other rollup
284
+ functions (`groupBy` + `sum` of another column) are deferred to a future
285
+ release.
286
+
287
+ ### Filter and firewall inheritance
288
+
289
+ Aggregations always run over the **same** filtered, firewalled set as the
290
+ row query. Pagination is intentionally ignored — you get the value over
291
+ every matching record, not just the current page.
292
+
293
+ In practice: a request like
294
+ `GET /applications/views/pipeline?status=applied&jobId=job_123&limit=10`
295
+ returns the first 10 applied rows for that job, AND `byStatus` reflects
296
+ only that filtered set (which will be `{ applied: <total> }` since the
297
+ filter pinned the status). This is the only consistent default — divorcing
298
+ the metric from the user's filters would surprise.
299
+
300
+ ### Constraints (compile-time)
301
+
302
+ - `field` must reference a real column on the table.
303
+ - `sum`/`avg` require numeric column types (`int`, `real`, `decimal`,
304
+ `numeric`, `bigint`). Non-numeric columns are rejected at compile time.
305
+ - The same masking opt-out gate that governs `query.{filterable, sortable,
306
+ searchable}` applies to aggregations: the view's roles must satisfy the
307
+ masking rule, otherwise the aggregation is rejected. (A `sum(salary)`
308
+ leaks structure across the masked set even when the row payload is
309
+ redacted.)
310
+ - Aggregation names cannot collide with the reserved response fields
311
+ `data`, `pagination`, `view`.
312
+ - No raw SQL `expr:` form. Column references only — declare a generated
313
+ column or write a custom action if you need arithmetic.
314
+
230
315
  ## Response Format
231
316
 
232
317
  View responses include metadata about the view:
@@ -238,15 +323,18 @@ View responses include metadata about the view:
238
323
  { "id": "cnd_456", "name": "John Smith", "source": "referral" }
239
324
  ],
240
325
  "view": "pipeline",
241
- "fields": ["id", "name", "source"],
242
326
  "pagination": {
243
- "limit": 50,
244
- "offset": 0,
245
- "count": 2
327
+ "count": 2,
328
+ "page": 1,
329
+ "pageSize": 50,
330
+ "hasMore": false
246
331
  }
247
332
  }
248
333
  ```
249
334
 
335
+ When the view declares `aggregations`, the response also includes an
336
+ `aggregations: { ... }` field. See [Aggregations](#aggregations).
337
+
250
338
  ## Complete Example
251
339
 
252
340
  ```typescript
@@ -253,16 +253,17 @@ import { AuthErrors, AccessErrors, GuardErrors } from '../../lib/errors';
253
253
 
254
254
  const app = new Hono();
255
255
 
256
- // GET /candidates?view=<name> — unified read handler dispatched by ?view
256
+ // GET /candidates/views/:viewName — named view projection
257
257
  const READ_ACCESS = { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] };
258
258
 
259
- app.get('/', async (c) => {
259
+ app.get('/views/:viewName', async (c) => {
260
260
  const ctx = c.get('ctx');
261
261
  const db = c.get('db');
262
262
 
263
+ const viewName = c.req.param('viewName');
263
264
  const params = Object.fromEntries(new URL(c.req.url).searchParams);
264
- const view = VIEWS_CONFIG[params.view as keyof typeof VIEWS_CONFIG];
265
- if (!view) return c.json({ error: 'View required', code: 'VIEW_REQUIRED' }, 400);
265
+ const view = VIEWS_CONFIG[viewName as keyof typeof VIEWS_CONFIG];
266
+ if (!view) return c.json({ error: 'Unknown view', code: 'VIEW_NOT_FOUND' }, 400);
266
267
 
267
268
  // Per-view access gate (falls back to read-level access)
268
269
  if (!await evaluateAccess(view.access ?? READ_ACCESS, ctx)) {
@@ -273,7 +274,7 @@ app.get('/', async (c) => {
273
274
  const results = await db.select(/* projected fields */).from(candidates)
274
275
  .where(buildFirewallConditions(ctx));
275
276
 
276
- return c.json({ data: maskCandidates(results, ctx), view: params.view });
277
+ return c.json({ data: maskCandidates(results, ctx), view: viewName });
277
278
  });
278
279
 
279
280
  // POST /candidates - Create with guards
@@ -383,10 +384,10 @@ Views control **which fields are returned**. Masking controls **what values are
383
384
 
384
385
  | Endpoint | Role | `phone` in response? | `phone` value |
385
386
  |----------|------|--------------------|-------------|
386
- | `/candidates?view=pipeline` | interviewer | No | N/A |
387
- | `/candidates?view=pipeline` | recruiter | No | N/A |
388
- | `/candidates?view=full` | interviewer | No | N/A (no access) |
389
- | `/candidates?view=full` | recruiter | Yes | `555-123-4567` |
387
+ | `/candidates/views/pipeline` | interviewer | No | N/A |
388
+ | `/candidates/views/pipeline` | recruiter | No | N/A |
389
+ | `/candidates/views/full` | interviewer | No | N/A (no access) |
390
+ | `/candidates/views/full` | recruiter | Yes | `555-123-4567` |
390
391
 
391
392
  ### Guards Enforcement
392
393
 
@@ -417,8 +418,8 @@ POST /candidates
417
418
  | `POST` | `/candidates` | hiring-manager, recruiter |
418
419
  | `PATCH` | `/candidates/:id` | hiring-manager, recruiter |
419
420
  | `DELETE` | `/candidates/:id` | hiring-manager |
420
- | `GET` | `/candidates?view=pipeline` | owner, hiring-manager, recruiter, interviewer |
421
- | `GET` | `/candidates?view=full` | hiring-manager, recruiter |
421
+ | `GET` | `/candidates/views/pipeline` | owner, hiring-manager, recruiter, interviewer |
422
+ | `GET` | `/candidates/views/full` | hiring-manager, recruiter |
422
423
 
423
424
  ---
424
425
 
@@ -75,8 +75,7 @@ Calls a client makes:
75
75
  ```bash
76
76
  GET /jobs # Collection — gated by read.access
77
77
  GET /jobs/:id # Single — gated by read.access (with ID-probe defense)
78
- GET /jobs?view=summary # View dispatch
79
- GET /jobs/views/summary # Explicit view path
78
+ GET /jobs/views/summary # Named view projection
80
79
  ```
81
80
 
82
81
  ### ID-probe defense on `/:id`
@@ -4,14 +4,14 @@ Views provide named column projections that limit which fields are returned in A
4
4
 
5
5
  ## Endpoints
6
6
 
7
- Views are dispatched two equivalent ways:
7
+ Named views are queried through a dedicated path endpoint:
8
8
 
9
9
  ```
10
- GET /api/v1/{resource}?view={view-name} # Query-string dispatch
11
- GET /api/v1/{resource}/views/{view-name} # Explicit path
10
+ GET /api/v1/{resource}/views/{view-name}
12
11
  ```
13
12
 
14
- Both forms are emitted automatically and behave identically.
13
+ If you set `read.defaultView`, bare `GET /api/v1/{resource}` can still resolve
14
+ to that view. Named views themselves are addressed via `/views/{view-name}`.
15
15
 
16
16
  ## Example
17
17
 
@@ -39,11 +39,6 @@ export default defineTable(candidates, {
39
39
  ### Request
40
40
 
41
41
  ```bash
42
- # Query-string form
43
- curl '/api/v1/candidates?view=pipeline' \
44
- -H "Authorization: Bearer <token>"
45
-
46
- # Path form (equivalent)
47
42
  curl /api/v1/candidates/views/pipeline \
48
43
  -H "Authorization: Bearer <token>"
49
44
  ```
@@ -57,11 +52,11 @@ curl /api/v1/candidates/views/pipeline \
57
52
  { "id": "cand_002", "name": "Bob Martinez", "source": "referral" }
58
53
  ],
59
54
  "view": "pipeline",
60
- "fields": ["id", "name", "source"],
61
55
  "pagination": {
62
- "limit": 50,
63
- "offset": 0,
64
- "count": 2
56
+ "count": 2,
57
+ "page": 1,
58
+ "pageSize": 50,
59
+ "hasMore": false
65
60
  }
66
61
  }
67
62
  ```