@quickback-dev/cli 0.66.17 → 0.66.19

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/build.d.ts.map +1 -1
  2. package/dist/commands/build.js +26 -20
  3. package/dist/commands/build.js.map +1 -1
  4. package/dist/index.js +1 -1
  5. package/dist/lib/action-harvest.d.ts +3 -2
  6. package/dist/lib/action-harvest.d.ts.map +1 -1
  7. package/dist/lib/action-harvest.js +3 -2
  8. package/dist/lib/action-harvest.js.map +1 -1
  9. package/dist/lib/compiler-stubs.d.ts +29 -8
  10. package/dist/lib/compiler-stubs.d.ts.map +1 -1
  11. package/dist/lib/compiler-stubs.js +29 -16
  12. package/dist/lib/compiler-stubs.js.map +1 -1
  13. package/dist/lib/file-writer.d.ts +9 -0
  14. package/dist/lib/file-writer.d.ts.map +1 -1
  15. package/dist/lib/file-writer.js +30 -5
  16. package/dist/lib/file-writer.js.map +1 -1
  17. package/dist/skill/docs/api/actions.md +10 -9
  18. package/dist/skill/docs/api/errors.md +14 -2
  19. package/dist/skill/docs/api/openapi.md +1 -1
  20. package/dist/skill/docs/api/query-params.md +7 -4
  21. package/dist/skill/docs/configure/auth.md +8 -4
  22. package/dist/skill/docs/configure/index.md +1 -1
  23. package/dist/skill/docs/define/access.md +16 -6
  24. package/dist/skill/docs/define/actions/defining.md +8 -1
  25. package/dist/skill/docs/define/actions/scoped-db.md +69 -8
  26. package/dist/skill/docs/define/changesets.md +8 -3
  27. package/dist/skill/docs/define/encryption.md +6 -3
  28. package/dist/skill/docs/define/escape-hatches.md +2 -2
  29. package/dist/skill/docs/define/fga.md +9 -4
  30. package/dist/skill/docs/define/firewall.md +15 -7
  31. package/dist/skill/docs/define/masking.md +1 -1
  32. package/dist/skill/docs/define/relationships.md +6 -3
  33. package/dist/skill/docs/define/schema.md +265 -7
  34. package/dist/skill/docs/define/scopes.md +15 -1
  35. package/dist/skill/docs/define/transitions.md +5 -0
  36. package/dist/skill/docs/define/views.md +9 -0
  37. package/dist/skill/docs/platform/api-contract/index.md +4 -2
  38. package/dist/skill/docs/platform/auth/api-keys.md +10 -1
  39. package/dist/skill/docs/platform/auth/jwt-optimization.md +10 -4
  40. package/dist/skill/docs/platform/auth/plugins/aws-ses.md +11 -4
  41. package/dist/skill/docs/platform/auth/plugins/index.md +4 -2
  42. package/dist/skill/docs/platform/auth/plugins/subscriptions.md +3 -3
  43. package/dist/skill/docs/platform/push/index.md +31 -23
  44. package/dist/skill/docs/platform/storage/r2.md +36 -4
  45. package/dist/skill/docs/platform/vector/embeddings.md +11 -76
  46. package/dist/skill/docs/platform/vector/index.md +1 -1
  47. package/dist/skill/docs/platform/vector/using-embeddings.md +10 -73
  48. package/dist/skill/docs/platform/webhooks/outbound.md +12 -8
  49. package/dist/skill/docs/tooling/cli.md +2 -2
  50. package/dist/skill/docs/tooling/cloud-compiler/authentication.md +1 -1
  51. package/dist/skill/docs/tooling/cloud-compiler/endpoints.md +2 -1
  52. package/dist/skill/docs/tooling/cloud-compiler/index.md +18 -3
  53. package/dist/skill/docs/tooling/cloud-compiler/local-compiler.md +7 -4
  54. package/dist/skill/docs/tooling/cloud-compiler/troubleshooting.md +1 -1
  55. package/dist/skill/docs/tooling/output.md +6 -2
  56. package/dist/skill/docs/ui/account/hooks.md +2 -2
  57. package/package.json +1 -1
  58. package/src/skill/docs/api/actions.md +10 -9
  59. package/src/skill/docs/api/errors.md +14 -2
  60. package/src/skill/docs/api/openapi.md +1 -1
  61. package/src/skill/docs/api/query-params.md +7 -4
  62. package/src/skill/docs/configure/auth.md +8 -4
  63. package/src/skill/docs/configure/index.md +1 -1
  64. package/src/skill/docs/define/access.md +16 -6
  65. package/src/skill/docs/define/actions/defining.md +8 -1
  66. package/src/skill/docs/define/actions/scoped-db.md +69 -8
  67. package/src/skill/docs/define/changesets.md +8 -3
  68. package/src/skill/docs/define/encryption.md +6 -3
  69. package/src/skill/docs/define/escape-hatches.md +2 -2
  70. package/src/skill/docs/define/fga.md +9 -4
  71. package/src/skill/docs/define/firewall.md +15 -7
  72. package/src/skill/docs/define/masking.md +1 -1
  73. package/src/skill/docs/define/relationships.md +6 -3
  74. package/src/skill/docs/define/schema.md +265 -7
  75. package/src/skill/docs/define/scopes.md +15 -1
  76. package/src/skill/docs/define/transitions.md +5 -0
  77. package/src/skill/docs/define/views.md +9 -0
  78. package/src/skill/docs/platform/api-contract/index.md +4 -2
  79. package/src/skill/docs/platform/auth/api-keys.md +10 -1
  80. package/src/skill/docs/platform/auth/jwt-optimization.md +10 -4
  81. package/src/skill/docs/platform/auth/plugins/aws-ses.md +11 -4
  82. package/src/skill/docs/platform/auth/plugins/index.md +4 -2
  83. package/src/skill/docs/platform/auth/plugins/subscriptions.md +3 -3
  84. package/src/skill/docs/platform/push/index.md +31 -23
  85. package/src/skill/docs/platform/storage/r2.md +36 -4
  86. package/src/skill/docs/platform/vector/embeddings.md +11 -76
  87. package/src/skill/docs/platform/vector/index.md +1 -1
  88. package/src/skill/docs/platform/vector/using-embeddings.md +10 -73
  89. package/src/skill/docs/platform/webhooks/outbound.md +12 -8
  90. package/src/skill/docs/tooling/cli.md +2 -2
  91. package/src/skill/docs/tooling/cloud-compiler/authentication.md +1 -1
  92. package/src/skill/docs/tooling/cloud-compiler/endpoints.md +2 -1
  93. package/src/skill/docs/tooling/cloud-compiler/index.md +18 -3
  94. package/src/skill/docs/tooling/cloud-compiler/local-compiler.md +7 -4
  95. package/src/skill/docs/tooling/cloud-compiler/troubleshooting.md +1 -1
  96. package/src/skill/docs/tooling/output.md +6 -2
  97. package/src/skill/docs/ui/account/hooks.md +2 -2
@@ -121,19 +121,20 @@ Same format as record-based actions. The difference is no record lookup or firew
121
121
  ### Security Flow
122
122
 
123
123
  1. **Authentication** — Required (401)
124
- 2. **Organization check** — For org-scoped resources, user must have an active organization (403)
124
+ 2. **Organization check** — For org-scoped resources, user must have an active organization (403). Uppercase pseudo-roles (`PUBLIC`, `AUTHENTICATED`, …) skip this check — not the firewall in step 4
125
125
  3. **Access** — Role-based check (403)
126
- 4. **Scoped DB** — The `db` passed to the handler is auto-scoped based on table columns (org isolation, owner filtering, soft delete)
126
+ 4. **Scoped DB** — The `db` passed to the handler applies each table's firewall, the same `WHERE` its CRUD routes use
127
127
  5. **Input validation** — Zod schema validation (400)
128
128
 
129
129
  ### Scoped Database
130
130
 
131
- All actions (both standalone and record-based) receive a **scoped `db`** instance that automatically enforces security based on the table's columns:
131
+ All actions (both standalone and record-based) receive a **scoped `db`** that applies each table's generated firewall — org, owner, team, scope, and `via:` arms plus the soft-delete filter — exactly as CRUD does:
132
132
 
133
- - Tables with `organizationId` — org isolation (`WHERE organizationId = ?`)
134
- - Tables with `ownerId` — owner isolation (`WHERE ownerId = ?`)
135
- - Tables with `deletedAt` — soft delete filter (`WHERE deletedAt IS NULL`)
136
- - `INSERT` operations auto-inject `organizationId` and `ownerId` from context
133
+ - `SELECT` / `UPDATE` / `DELETE` get the table's firewall `WHERE`, AND-merged with yours.
134
+ - `INSERT` stamps every claim column the firewall binds (`organizationId`, `ownerId`, …) from context.
135
+ - A caller without a claim the table's firewall requires reads and writes nothing there; an `INSERT` fails with 403 `FIREWALL_CLAIM_MISSING`. The action's `db` type rejects such tables at compile time when its `access` can't guarantee the claim.
136
+
137
+ Full semantics: [Scoped Database](/define/actions/scoped-db).
137
138
 
138
139
  #### `userId` vs `ownerId` on feature tables
139
140
 
@@ -157,10 +158,10 @@ Better Auth's own internal tables (`session`, `account`, `member`, `passkey`, `s
157
158
  ```typescript
158
159
  // Your handler receives a scoped db — no manual filtering needed
159
160
  execute: async ({ db, ctx, input }) => {
160
- // This query automatically includes WHERE organizationId = ? AND ownerId = ? AND deletedAt IS NULL
161
+ // This query automatically includes the applications firewall (e.g. organizationId = ?) AND deletedAt IS NULL
161
162
  const items = await db.select().from(applications).where(eq(applications.stage, 'interview'));
162
163
 
163
- // Inserts automatically include organizationId and ownerId
164
+ // Inserts automatically stamp the firewall's claim columns (e.g. organizationId)
164
165
  await db.insert(applications).values({ candidateId: input.candidateId, jobId: input.jobId, stage: 'applied' });
165
166
 
166
167
  return items;
@@ -16,7 +16,7 @@ The generated API returns structured error responses with consistent fields acro
16
16
  | `405` | Method Not Allowed | The path is a real route, but not for this verb — the response carries an `Allow` header listing the methods it does accept |
17
17
  | `409` | Conflict | Unique constraint hit, or a duplicate [`Idempotency-Key`](/platform/api-contract#idempotency-key) still in flight |
18
18
  | `412` | Precondition Failed | `If-Match` revision mismatch — [changesets](/define/changesets) and plain single-record `PATCH`/`PUT`/`DELETE` |
19
- | `422` | Unprocessable | `Idempotency-Key` reused with a different request or principal |
19
+ | `422` | Unprocessable | `Idempotency-Key` reused with a different request or principal, or a stored encrypted value will not decrypt (`ENCRYPTION_UNREADABLE`) |
20
20
  | `428` | Precondition Required | `If-Match` sent where it can't anchor: no revision column, a batch endpoint (single-resource precondition), or the POST changeset variant |
21
21
  | `429` | Too Many Requests | Rate limit exceeded |
22
22
  | `500` | Internal Error | Uncaught throw — generic body, full error server-side |
@@ -94,7 +94,7 @@ Missing or invalid authentication tokens.
94
94
  | Code | Description |
95
95
  |------|-------------|
96
96
  | `AUTH_MISSING` | No Authorization header provided |
97
- | `AUTH_INVALID_TOKEN` | Token is malformed or invalid |
97
+ | `AUTH_INVALID_TOKEN` | Token is malformed or invalid — including a Quickback-minted JWT that no longer verifies (rotated key, tampered, revoked). Presented-and-bad is always `401`, never treated as no credential |
98
98
  | `AUTH_EXPIRED` | Token has expired |
99
99
  | `AUTH_RATE_LIMITED` | Too many auth attempts |
100
100
  | `AUTH_REVOCATION_UNAVAILABLE` | **503, retryable.** Only with [`revocationCheck: 'kv'`](/configure/auth#revocationcheck-none--kv--token-revocation-strategy): the bearer's signature verified, but its revocation state could not be read (KV binding missing or unreachable), so it was not trusted. Retry, or authenticate with a session cookie |
@@ -124,6 +124,13 @@ Firewall filtering is transparent — the query is scoped by `WHERE organization
124
124
  | `FIREWALL_USER_ISOLATION` | Record belongs to another user |
125
125
  | `FIREWALL_SOFT_DELETED` | Record has been soft deleted |
126
126
 
127
+ Inside an action, an `INSERT` through the [scoped `db`](/define/actions/scoped-db)
128
+ into a table whose firewall requires a claim the caller does not carry (no
129
+ `activeOrgId` for an org-scoped table, say) fails with **403**
130
+ `FIREWALL_CLAIM_MISSING`, `layer: "action"`, and
131
+ `details: { table, column, claim }` — the row is never written into whatever
132
+ tenant the body named.
133
+
127
134
  For security-hardened deployments, set `firewallErrorMode: 'hide'` at the **top
128
135
  level of the resource definition** (not inside `firewall:` — it was lifted off
129
136
  when `firewall` became a predicate array) to return opaque **404 Not Found**
@@ -225,9 +232,14 @@ Surfaced when a SQL write fails *post-validation* — most often a `NOT NULL` or
225
232
  | `DB_UNIQUE_VIOLATION` | 409 | Unique constraint hit |
226
233
  | `DB_INSERT_FAILED` | 500 | INSERT failed for an unrecognized reason |
227
234
  | `DB_UPDATE_FAILED` | 500 | UPDATE failed for an unrecognized reason |
235
+ | `ENCRYPTION_UNREADABLE` | 422 | A stored [`.encrypted()`](/define/encryption) value will not decrypt |
228
236
 
229
237
  The `details.column` field is only present when the driver's error message identified the offending column (SQLite/D1 do; some PG variants don't).
230
238
 
239
+ `ENCRYPTION_UNREADABLE` always carries `details: { table, column, id }` — the
240
+ row whose stored ciphertext is malformed or was not written under the caller's
241
+ organization key. Rewriting the field repairs the row.
242
+
231
243
  ## Batch Errors
232
244
 
233
245
  Batch operations can return:
@@ -23,7 +23,7 @@ The generated spec documents every route the compiler produces:
23
23
  - Views
24
24
  - Actions (including standalone actions)
25
25
  - Auth routes (`/api/auth/**`)
26
- - Storage, embeddings, and webhook routes (when configured)
26
+ - Storage and webhook routes (when configured)
27
27
 
28
28
  Each endpoint includes request/response schemas derived from your Drizzle column types, access control metadata, and error responses.
29
29
 
@@ -89,7 +89,7 @@ currently wired into the emitted route.
89
89
  - `count` — number of records returned on this page
90
90
  - `page` / `pageSize` — derived from `?offset=` and `?limit=`
91
91
  - `hasMore` — whether more rows exist in the queried direction. Without `?total=true` it comes from a `limit + 1` over-fetch probe, so it never lies on a final page that exactly fills the limit; with `?total=true` it is page arithmetic (`page < totalPages`).
92
- - `nextCursor` / `prevCursor` — opaque keyset cursors; pass them back as `?starting_after=` and `?ending_before=`. Either can be `null`.
92
+ - `nextCursor` / `prevCursor` — keyset cursors; pass them back as `?starting_after=` and `?ending_before=`. Treat them as opaque, but they are encoded, not encrypted: they carry the boundary row's sort-key values. Either can be `null` — including when the sort includes a [masked](/define/masking) column the caller may sort by (`query.roles`) but not see (`show.roles`); page with `?offset=` in that case.
93
93
  - `total` / `totalPages` — present **only** when the request passed `?total=true` (see below)
94
94
 
95
95
  There is no `limit` or `offset` member in `pagination`.
@@ -133,7 +133,10 @@ When the multi-sort format is detected (comma or `-` prefix), the `order` parame
133
133
 
134
134
  A client-supplied `?sort=` naming an unknown column — or one outside a view's
135
135
  `query.sortable` — returns `400`, for the same reason unknown filters do: rows
136
- would come back in some other order that reads as the requested one. A view's
136
+ would come back in some other order that reads as the requested one. Array
137
+ columns, and `q.decimal()` columns on D1 (stored as `TEXT`, so they would sort
138
+ as strings), are never sortable — see
139
+ [Decimals, dates, 64-bit integers, and arrays](/define/schema#decimals-dates-64-bit-integers-and-arrays). A view's
137
140
  own `defaultSort` fallback is config, not caller input, and is never rejected.
138
141
 
139
142
  ## Field Selection
@@ -231,8 +234,8 @@ This request:
231
234
  | `search` | LIST, VIEW | Search text across all text columns |
232
235
  | `field=value` | LIST, VIEW | Filter by exact match |
233
236
  | `field.op=value` | LIST, VIEW | Filter with operator (gt, gte, lt, lte, ne, like, in) |
234
- | `starting_after` | LIST, VIEW | Opaque keyset cursor — rows strictly after the boundary |
235
- | `ending_before` | LIST, VIEW | Opaque keyset cursor — rows strictly before the boundary |
237
+ | `starting_after` | LIST, VIEW | Keyset cursor (from `nextCursor`) — rows strictly after the boundary |
238
+ | `ending_before` | LIST, VIEW | Keyset cursor (from `prevCursor`) — rows strictly before the boundary |
236
239
  | `include` | LIST, VIEW, GET | FK-graph embedding (allowlisted — see below) |
237
240
  | `fields[<fk>]` | LIST, VIEW, GET | Sparse fields for an embedded include target |
238
241
 
@@ -62,7 +62,7 @@ Those two knobs — `expiresIn` and `revocationCheck` — cover the vast majorit
62
62
  1. The browser SPA gets a JWT via the `set-auth-token` response header on every authenticated call.
63
63
  2. On subsequent requests the SPA sends `Authorization: Bearer <jwt>`.
64
64
  3. The auth middleware's **fast-path** verifies the signature only — no DB query, no session lookup. `AppContext` is reconstructed from JWT claims.
65
- 4. If verification fails (or no JWT is present), the middleware falls back to session auth.
65
+ 4. If no JWT is present, the middleware falls back to session auth. If a JWT **this project minted** fails to verify (rotated key, expired, tampered, revoked), the request is refused with `401 AUTH_INVALID_TOKEN` / `AUTH_EXPIRED` — never downgraded to "unauthenticated" — so clients can re-mint on 401 alone.
66
66
  5. After successful session auth, a fresh JWT is minted and returned via `set-auth-token`. The cycle continues.
67
67
 
68
68
  The fast-path is intentionally stateless: it trusts the claims for the full TTL. **Stolen or pre-revocation tokens are valid until they expire.** That's the trade-off the fast-path makes — and the reason `expiresIn` and `revocationCheck` are the two most-tuned knobs below: the first bounds the window, the second shrinks it to seconds.
@@ -89,6 +89,8 @@ Default `quickback:<project name>` — a compile-time constant, so every worker
89
89
 
90
90
  Set this when other services need to distinguish JWTs minted by this Worker from other issuers. The compiler bakes the issuer into both the mint side (added to claims) and the verify side (rejects tokens with mismatched `iss`).
91
91
 
92
+ It must differ from the OAuth provider's issuer (`oauth.issuerUrl`, default `BETTER_AUTH_URL` + `/auth/v1`) — the middleware tells a Quickback token from an OAuth access token by `iss`, so the compiler rejects an issuer equal to the OAuth one, or any URL whose path is the auth base path.
93
+
92
94
  ### `audience?: string` — `aud` claim
93
95
 
94
96
  Default `quickback:<project name>` (the same constant as `issuer`).
@@ -102,8 +104,10 @@ Both knobs are gone. Tokens are signed with Better Auth's JWKS keyring (EdDSA),
102
104
  ### `GET /auth/v1/token` — mint an identity JWT
103
105
 
104
106
  Better Auth's jwt plugin endpoint. Session-authenticated callers (cookie or
105
- session-token bearer) mint a short-lived JWT carrying `sub`, `sid`, `orgId`,
107
+ session-token bearer) mint a short-lived JWT carrying `sub`, `sid`, `ict`, `orgId`,
106
108
  `role`, `userRole`, `tiers`, `email`, `name`, plus the pinned `iss` / `aud`.
109
+ An `x-api-key` cannot mint here — it stands in for a session only on
110
+ `GET /auth/v1/get-session`.
107
111
  Two invariants:
108
112
 
109
113
  - **`orgId` is only ever signed beside a membership `role`**, and the verifier
@@ -123,7 +127,7 @@ Default `'none'`.
123
127
 
124
128
  | Value | Behavior | Cost per verify |
125
129
  |---|---|---|
126
- | `'none'` | No revocation check. Stolen / pre-revocation tokens valid until TTL expires (scope claims: until the carry-forward cap). Use a low `expiresIn` to bound the replay window. | 0 |
130
+ | `'none'` | No revocation check. Stolen / pre-revocation tokens valid until TTL expires (scope claims: until the carry-forward cap; org / role claims riding a scope token: until their identity proof `ict` passes the same cap — `/scope/v1/enter` and the refresh never restart it). Use a low `expiresIn` to bound the replay window. | 0 |
127
131
  | `'kv'` | Fast-path checks per-principal revocation timestamps in the project's existing `KV` binding before trusting a verified token. Fails closed: an unreadable store means the bearer is not trusted. | 2+ KV reads (~5-15ms, edge-cached) |
128
132
 
129
133
  `'kv'` (**Cloudflare runtime only**) keeps the fast-path stateless against the auth DB (still 0 D1 queries). There is nothing extra to provision — entries ride the `KV` binding every project already has, prefixed `qbrev:` and self-expiring after the maximum token lifetime, so the store never accumulates.
@@ -132,7 +136,7 @@ A token is rejected when its mint timestamp (`iat`/`iatMs`, or the scope claim's
132
136
 
133
137
  | Key | Revokes | Written automatically on |
134
138
  |---|---|---|
135
- | `qbrev:sid:<sessionId>` | every JWT minted from one Better Auth session (tokens carry the minting session as `sid`) | `POST /sign-out` and `POST /revoke-session` (Better Auth endpoint hooks) — a lost device's token dies with its session while the user's other devices keep theirs |
139
+ | `qbrev:sid:<sessionId>` | every JWT minted from one Better Auth session (tokens carry the minting session as `sid` — including scope tokens from `/scope/v1/enter`, namespace mints and their refreshes) | `POST /sign-out` and `POST /revoke-session` (Better Auth endpoint hooks) — a lost device's token dies with its session while the user's other devices keep theirs |
136
140
  | `qbrev:user:<userId>` | every JWT for the user | user ban (`databaseHooks.user.update.after` — flipping `banned` stamps the key and, when outbound webhooks are enabled, emits a `user.banned` event); `revoke-sessions`, `revoke-other-sessions`, `change-password` with `revokeOtherSessions`, and `delete-user` (endpoint hooks). Call `revokeUserTokens` for custom flows |
137
141
  | `qbrev:member:<userId>:<orgId>` | the user's org-membership claims | member removal / role change (Better Auth `organizationHooks`) |
138
142
  | `qbrev:scope:<userId>:<kind>:<id>` | the user's carried scope claim | UPDATE/DELETE of a scope-conferring relationship row (audit-wrapper chokepoint + the single DELETE route) |
@@ -135,7 +135,7 @@ export default defineConfig({
135
135
 
136
136
  `routes` is atomic across every surface: feature routes move to `/api/v2/*`,
137
137
  Better Auth to `/auth/v2/*`, realtime to `/broadcast/v2`, and generated
138
- OpenAPI, MCP tool calls, OAuth discovery, `llms.txt`, schema/embeddings routes,
138
+ OpenAPI, MCP tool calls, OAuth discovery, `llms.txt`, schema routes,
139
139
  and dedicated-domain shortcuts follow. When CMS or Account is enabled Quickback
140
140
  bakes those paths into the SPA build and injects them at runtime. Quickback
141
141
  does not expose a mixed v1/v2 URL surface from one compiled Worker.
@@ -208,6 +208,8 @@ Quickback ships seven reserved UPPERCASE markers. Six are real pseudo-roles hand
208
208
 
209
209
  You can mix pseudo-roles with real roles in the same list — they're OR'd together.
210
210
 
211
+ Pseudo-roles skip the Access layer's active-organization precondition — they do **not** skip the Firewall. Row scoping still comes from each table's firewall, in CRUD routes and inside an action's scoped `db` alike: an `AUTHENTICATED` caller with no active org reads nothing from an org-scoped table. See [Scoped Database](/define/actions/scoped-db).
212
+
211
213
  #### `PUBLIC` — unauthenticated access
212
214
 
213
215
  Use `roles: ["PUBLIC"]` for public-facing endpoints like contact forms, public listings, or webhooks. Skips both the auth gate and the role check.
@@ -441,17 +443,25 @@ declaratively (`roles`, `userRole`, `record`, `or`, `and`).
441
443
 
442
444
  ### Collection routes honour `access.record` too
443
445
 
444
- `GET /`, the per-view lists, and the generated MCP list tool fold the same
445
- `record:` predicates into the query's `WHERE`, arm for arm, so a list can never
446
- return a row the caller could not `GET` one at a time:
446
+ `GET /`, the per-view lists, `?total`, `?search`, view aggregations, and the
447
+ generated MCP list tool fold the same arms into the query's `WHERE`, arm for
448
+ arm, so a list can never return a row the caller could not `GET` one at a time:
447
449
 
448
450
  - Each `or` arm whose role / `userRole` gates admit the caller contributes its
449
451
  `record` predicates as one AND-group; the groups are OR'd together.
450
- - An admitted arm with **no** `record` block lifts the constraint for the
451
- whole list (that arm would admit every row on `GET /:id` as well).
452
+ - A [relationship-role](/define/relationships) arm contributes
453
+ `<resource.column> IN (<relationship subquery>)` — only rows the caller is
454
+ related to — and an [`fga`](/define/fga#filtering-a-collection-by-an-fga-relation)
455
+ arm contributes membership in the caller's `ListObjects` id set. Both compose
456
+ with `record:` siblings like any other arm; neither lifts the constraint.
457
+ - An admitted arm with **no** `record` block (and no relationship / `fga`
458
+ arm) lifts the constraint for the whole list (that arm would admit every
459
+ row on `GET /:id` as well).
452
460
  - A `$ctx.` value that is absent for the caller (no `activeOrgId`, no
453
461
  `scope`) makes that arm unsatisfiable — it denies, never matches.
454
- - A predicate on a column the table does not have yields no rows.
462
+ - A `record:` predicate on a column the table does not declare, or a
463
+ relationship whose `resource.column` the table does not declare, is a
464
+ **compile error** — the list could never be filtered by it.
455
465
  - No admitted arm at all → `403` from the role gate, as before.
456
466
 
457
467
  `POST /batch` runs the same per-record check single `POST` does
@@ -118,7 +118,14 @@ evaluates project code. The output contract feeds OpenAPI and
118
118
  **Every action input must produce a schema.** A failed harvest fails the
119
119
  compile, naming the exact action, whether
120
120
  bundling or evaluation failed, and the underlying local error. Output remains
121
- optional.
121
+ optional. A successful harvest reports its denominator —
122
+ `✔ Resolved 12 of 12 action input schema(s)`.
123
+
124
+ The count covers the action files **you wrote**. Actions the compiler generates
125
+ from a table's [`transitions:`](/define/transitions) have no file in your tree,
126
+ so the CLI never harvests them: they take no input, and the compiler emits
127
+ their strict schema (`{ "type": "object", "properties": {},
128
+ "additionalProperties": false }`) itself.
122
129
 
123
130
  **Why it fails instead of degrading.** The compiler's static fallback parser
124
131
  reads your Zod as text and can only produce `type` and `properties`. It never
@@ -2,16 +2,61 @@
2
2
 
3
3
  ## Scoped Database
4
4
 
5
- All actions receive a **scoped `db`** instance that automatically enforces security:
5
+ All actions receive a **scoped `db`** that applies each table's **firewall** —
6
+ the same generated `WHERE` clause the table's CRUD routes use:
7
+
8
+ | Operation | What the scoped `db` adds |
9
+ |-----------|---------------------------|
10
+ | `SELECT` | the table's firewall (org / owner / team / scope / `via:` arms) AND soft-delete filter |
11
+ | `UPDATE` / `DELETE` | the same firewall `WHERE`, AND-merged with yours |
12
+ | `INSERT` | every required claim column the firewall binds (e.g. `organizationId` from `ctx.activeOrgId`), overwriting any value you passed |
13
+
14
+ It is not a guess from column names. `any:` groups, `optional` arms, scope
15
+ (`ctx.scope.*`) and `via:` relationship arms, the null-claim deny, the
16
+ `cms.sysadmin` cross-tenant escape, and `firewall: { exception: true }` all
17
+ behave exactly as they do on CRUD — including custom per-table predicates such
18
+ as `{ field: 'linkedUserId', equals: 'ctx.userId' }`.
19
+
20
+ **Access decides whether the handler runs; the firewall still decides which
21
+ rows it touches.** An action admitted by an uppercase marker (`PUBLIC`,
22
+ `AUTHENTICATED`, `SCOPED`, …) skips the Access layer's active-org
23
+ precondition, but not the firewall: a caller without the claim a table's
24
+ firewall requires reads and writes **nothing** in that table (`1 = 0`), and an
25
+ `INSERT` into it fails with **403 `FIREWALL_CLAIM_MISSING`** rather than
26
+ landing in whatever tenant the request body named.
27
+
28
+ - **Scope principals** reach rows through the table's `ctx.scope.*` arms, as on CRUD.
29
+ - **Delegated principals** named in a table's [`databaseAccess`](#delegated-principals-and-databaseaccess) lane keep the soft-delete filter; their row bound is the lane's RLS policy.
30
+ - **Tables with no `defineTable`** (Better Auth tables, bare Drizzle tables) get column rules instead — `organizationId = ctx.activeOrgId`, `ownerId = ctx.userId`, `teamId = ctx.activeTeamId` (team only narrows when another rule binds), plus `deletedAt IS NULL` — and a missing claim denies.
31
+
32
+ ### Caught at compile time
33
+
34
+ The action's `db` is typed against its own `access`. A table whose firewall
35
+ requires a claim that some caller your `access` admits may lack — an
36
+ `AUTHENTICATED` or `PUBLIC` action reading an org-scoped table, a
37
+ `scope:<kind>:<role>` action reading a table with no `ctx.scope.<kind>` arm —
38
+ is a `tsc` error on the `from(...)`, `insert(...)`, `update(...)` or
39
+ `delete(...)` call, instead of a query that silently matches nothing:
40
+
41
+ ```text
42
+ Property '"QUICKBACK: this action's access admits callers that lack a claim this
43
+ table's firewall requires … Fix: require an org role, add a scope or relationship
44
+ access arm that supplies the claim, or declare the action unsafe and use unsafeDb"'
45
+ is missing in type …
46
+ ```
6
47
 
7
- | Operation | Org Scoping | Owner Scoping | Soft Delete Filter | Auto-inject on INSERT |
8
- |-----------|-------------|---------------|--------------------|-----------------------|
9
- | `SELECT` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |
10
- | `INSERT` | n/a | n/a | n/a | `organizationId`, `ownerId` from ctx |
11
- | `UPDATE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |
12
- | `DELETE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |
48
+ Every alternative in `access` is checked on its own:
49
+ `or: [{ roles: ['member'] }, { roles: ['scope:application:applicant'] }]` may read a table whose firewall is
50
+ `any: [org arm, ctx.scope.application arm]`, because each lane satisfies one arm.
51
+ A record action's own table is always accepted — the route loaded `record`
52
+ through its firewall. Tables with no `defineTable`, subqueries and raw `sql`
53
+ sources are not gated. Anchored actions get the same treatment for reads:
54
+ `select().from(t)` only accepts tables in the anchor's reach.
13
55
 
14
- Scoping is duck-typed at runtime — tables with an `organizationId` column get org scoping, tables with `ownerId` get owner scoping, tables with `deletedAt` get soft delete filtering.
56
+ Not gated at the type level: joins (`leftJoin(t)` and friends) and `$count` —
57
+ both still go through the runtime firewall rules above (`$count` is scoped;
58
+ a joined table is not re-filtered, so join only through foreign keys you own).
59
+ `db.with(...)` is blocked outright.
15
60
 
16
61
  ```typescript
17
62
  async execute({ db, ctx, input }) {
@@ -232,6 +277,22 @@ predicate in the `WHERE` (for example,
232
277
 
233
278
  Actions that need to bypass scoped DB filters (for example, platform-level support operations) can enable unsafe mode.
234
279
 
280
+ `unsafe` is the only sanctioned way around the scoped `db`. The compiler warns
281
+ when a non-`unsafe` action — or a file it imports from the feature's `lib/`,
282
+ the project's `lib/`, `hooks/` or `plugins/` (relative or `~/` imports) —
283
+ reaches a raw database handle instead:
284
+
285
+ - `c.get('db')`
286
+ - a database binding off the environment (`env.DB`, `c.env.HYPERDRIVE`, …)
287
+ - a drizzle driver import (`drizzle-orm/d1`, `drizzle-orm/postgres-js`, …)
288
+ - `auth.$context` (Better Auth's adapter)
289
+ - the action's own `unsafeDb`
290
+
291
+ Each warning names the file, line, and handle. It is a warning for now and
292
+ becomes a compile error in a future minor; declare `unsafe` (or
293
+ `firewall: { exception: true }` for a deliberately unscoped action) if the
294
+ access is intentional.
295
+
235
296
  Use object form for explicit policy and mandatory audit metadata:
236
297
 
237
298
  ```typescript
@@ -396,9 +396,14 @@ placeholders must be mapped `payload` keys; an unresolvable placeholder is a
396
396
  compile error, and a null placeholder value at runtime skips the push
397
397
  (fail-closed — nobody gets a blank notification).
398
398
 
399
- Fan-out: a scope-keyed delivery targets subscriptions tagged
400
- `scope:<room key>`; an `organizationId` + `userIdFrom` delivery targets that
401
- user's devices; profile roles AND-compose as a `role:` tag filter. Delivery
399
+ Fan-out: a scope-keyed delivery reaches devices carrying the
400
+ instance-bound scope role tag `scope:<kind>:<instance>#<role>` for each
401
+ `scope:<kind>:<role>` in the profile's roles, where the room placeholder is
402
+ that kind's `requestField` (org roles on a scope room reach no device — they
403
+ are never stamped on subscriptions). An `organizationId` + `userIdFrom`
404
+ delivery targets that user's devices only while they hold one of the profile's
405
+ org roles in that organization, resolved from membership at send time. A
406
+ profile whose roles can reach no device is a compile error. Delivery
402
407
  rides the `PUSH_FANOUT_QUEUE` after commit — at-least-once, best-effort,
403
408
  never rolling back the changeset. A delivery that resolves to no audience
404
409
  pushes to nobody, mirroring the ws broadcast lane exactly.
@@ -25,11 +25,14 @@ That one modifier changes what a database breach means: a leaked D1 backup, expo
25
25
 
26
26
  - **`org_data_keys`** — one row per organization holding a random 256-bit data key (DEK), stored **wrapped** under the `ENCRYPTION_KEK` worker secret. Created lazily on the org's first encrypted write.
27
27
  - **Write path** — every write (CRUD routes, batch routes, and `db.insert`/`db.update` inside your actions) flows through the same chokepoint, which AES-256-GCM-encrypts the column before anything else sees it. Audit snapshots, webhook payloads, and realtime deltas therefore carry ciphertext by construction.
28
- - **Read path** — generated routes decrypt behind the firewall and then apply masking, so authorized callers see plaintext and everyone else sees the redaction — never ciphertext.
28
+ - **Plaintext in, from clients** — CRUD, batch, and changeset request bodies reject a value that starts with `qbenc:` (400). Clients send plaintext; the `qbenc:` prefix is reserved for stored ciphertext. Action code can still write `ctx.crypto.encrypt()` output directly — the chokepoint passes ciphertext through untouched.
29
+ - **Read path** — generated routes decrypt behind the firewall and then apply masking, so authorized callers see plaintext and everyone else sees the redaction — never ciphertext. A stored value that will not decrypt fails the request with `422` [`ENCRYPTION_UNREADABLE`](/api/errors), naming the table, column, and row id — never a silent `null`.
29
30
  - **`ctx.crypto`** — explicit `await ctx.crypto.decrypt(value)` / `ctx.crypto.encrypt(value)` for action code that processes the field server-side (building a manifest, sending an email). Scoped to the caller's active organization. `ctx.crypto` is only hydrated for authenticated requests — inside schedules, queue consumers, email handlers, and `PUBLIC` actions it is undefined. There, import the primitives directly: `import { encryptValue, decryptValue } from '../lib/encryption'` and call `decryptValue(env, db, organizationId, stored)`. Writes through the `withInternalContext` handle still encrypt automatically.
30
31
  - **Boot guard** — a project with encrypted columns refuses to serve without `ENCRYPTION_KEK` (503 `MISSING_ENV`), instead of silently storing plaintext.
31
32
 
32
- Values at rest look like `qbenc:1:<keyVersion>:<iv>:<ciphertext>` — the prefix makes accidental plaintext detectable, and the embedded key version supports rotation with lazy re-encryption on write.
33
+ Values at rest look like `qbenc:1:<keyVersion>:<iv>:<ciphertext>` — the prefix makes accidental plaintext detectable, and the embedded key version is recorded for future key rotation. Rotation is not built yet: every value is written and read under the org's single current DEK.
34
+
35
+ Each wrapped DEK is bound to its organization (AES-GCM additional data), so a wrapped key copied into another org's `org_data_keys` row fails to unwrap. Rows written before this binding are still read and are rewrapped the first time they load (on D1; on Neon the request connection has no `UPDATE` on `org_data_keys`, so legacy rows stay in the older format until a service-role pass).
33
36
 
34
37
  ## Setup
35
38
 
@@ -54,7 +57,7 @@ Encrypted columns **may** appear in view projections and responses — they decr
54
57
 
55
58
  ## Per-organization keys: blast radius and crypto-shredding
56
59
 
57
- Each organization's data is encrypted under its own DEK, so one compromised key never exposes another tenant. Deleting an org's `org_data_keys` row makes every encrypted value it ever wrote **permanently unreadable** — the cleanest possible GDPR-erasure and offboarding story.
60
+ Each organization's data is encrypted under its own DEK, so one compromised key never exposes another tenant. Deleting an org's `org_data_keys` row makes every encrypted value it wrote unreadable **with the current `ENCRYPTION_KEK`** — provided no copy of that wrapped key survives elsewhere (database backups, point-in-time restore, exports). Shredding is a manual, service-role delete today; there is no generated shred or rotation endpoint. After a delete, the next encrypted write for that org creates a fresh DEK, and reads of the old values fail with `ENCRYPTION_UNREADABLE`.
58
61
 
59
62
  ## What this tier does and doesn't claim
60
63
 
@@ -5,10 +5,10 @@
5
5
  compiled to Drizzle. It turns
6
6
 
7
7
  ```
8
- feature(name, { columns, indexes, unique, ...rest })
8
+ feature(name, { columns, indexes, unique, check, ...rest })
9
9
  ```
10
10
 
11
- into `q.table(name, columns, { indexes, unique })` plus `defineTable(name, rest)`,
11
+ into `q.table(name, columns, { indexes, unique, check })` plus `defineTable(name, rest)`,
12
12
  passing every other key through verbatim. Both forms produce byte-identical output.
13
13
 
14
14
  `defineTable()` is **not deprecated**. It is the layer underneath, and it is what you
@@ -178,17 +178,22 @@ export default feature('jobs', {
178
178
  });
179
179
  ```
180
180
 
181
- Three access shapes are supported on a collection-filtering arm:
181
+ The `fga` arm composes with its siblings exactly like any other access arm —
182
+ each `or` arm that admits the caller contributes a filter, and the filters are
183
+ OR'd:
182
184
 
183
185
  | Access shape | Collection behavior |
184
186
  | --- | --- |
185
187
  | `{ fga }` | Always filter to the FGA-authorized ids. |
186
188
  | `{ or: [{ roles }, { fga }] }` | If the role arm passes, return all firewall-scoped rows (no FGA filter); otherwise filter to the authorized ids. |
187
189
  | `{ and: [{ roles }, { fga }] }` | If the role arm fails, return an empty page; otherwise filter to the authorized ids. |
190
+ | `{ or: [{ roles, record }, { fga }] }` | Rows matching the `record:` predicate **or** the authorized ids — the `record:` sibling is never dropped. |
188
191
 
189
- Deeper nesting (an `fga` arm under multi-level `and`/`or`, or multiple
190
- conflicting `fga` arms) is a **compile error** that points you at
191
- `POST /fga/v1/list-objects` to filter manually.
192
+ Nesting depth and the number of `fga` arms are unrestricted. The `object`
193
+ template must be `"<type>:{<idColumn>}"` with `idColumn` a declared column of
194
+ the table — anything else is a **compile error** (it could not be mapped back
195
+ to rows). For shapes you'd rather filter yourself, enumerate ids with
196
+ `POST /fga/v1/list-objects`.
192
197
 
193
198
  **The cap.** The authorized id set is bounded by `authz.fga.listObjects.maxIds`
194
199
  (default **1000**). If a caller's authorized set exceeds the cap, the collection
@@ -137,7 +137,7 @@ Null-safe scope semantics make this safe (these apply **inside `all`/`any` group
137
137
 
138
138
  - 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.
139
139
  - **An `any` group with an org arm tenant-binds its scope and relationship arms.** Beside `{ field: 'organizationId', equals: 'ctx.activeOrgId' }`, a `ctx.scope.*` arm, a `via:` arm, or a `{ permission }` arm is emitted as `scope-arm AND (organizationId = ctx.activeOrgId OR the caller has no org claim)`. A caller with **no** org claim (a scope-only or relationship principal) is unaffected; a caller who carries org B's membership *and* a scope claim or relationship row on an org-A instance cannot ride the scope arm into org A's rows. Owner arms (`ctx.userId`), team arms, and literal `in` lists are not tenant-bound. An org claim and a scope claim in one request are therefore always the same tenant — or the scope arm yields nothing.
140
- - 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).
140
+ - 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). An optional arm only drops while a **non-optional** tenant arm still bounds the query; a sole optional arm denies when its claim is absent, exactly like the team rule below.
141
141
  - **Owner** (`ctx.userId`) and **soft-delete** (`isNull deletedAt`) are always present / always AND'd — never relaxed.
142
142
 
143
143
  > **`ctx.activeTeamId` is implicitly optional only while another tenant arm
@@ -151,6 +151,12 @@ Null-safe scope semantics make this safe (these apply **inside `all`/`any` group
151
151
  > return no `WHERE` at all, and any authenticated caller would read every
152
152
  > tenant's rows.
153
153
  >
154
+ > The same rule holds for the flat array and for `all:` groups, for
155
+ > `{ optional: true }` arms, and for the Postgres RLS policy the compiler
156
+ > emits alongside the API firewall: a sole team or optional arm lowers to
157
+ > strict `team_id = <claim>` (a NULL claim matches no row), never
158
+ > `claim IS NULL OR …`.
159
+ >
154
160
  > This matters because `ctx.activeTeamId` is absent in ordinary
155
161
  > configurations: the Better Auth teams plugin is opt-in, and the external auth
156
162
  > provider does not supply the claim at all. Note that soft-delete and literal
@@ -223,17 +229,19 @@ WHERE sessions.organizationId = ?
223
229
  SELECT eventId FROM event_guests
224
230
  WHERE userId = ?
225
231
  AND status = 'confirmed'
226
- AND <event_guests' own firewall — tenant scope + soft-delete>
232
+ AND <event_guests' soft-delete predicates — NOT its tenant scope>
227
233
  )
228
234
  ```
229
235
 
230
236
  Key properties:
231
237
 
232
238
  - **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.
233
- - **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.
239
+ - **Only the relationship table's soft-delete predicates are AND'd into the subquery — not its tenant scope.** Soft-deleting an `event_guests` row revokes access immediately. The tenant scope is deliberately skipped: a guest of another tenant's event has no `activeOrgId` for it to match, so applying it would lock out exactly the callers relationships exist for. A relationship row is trusted because of two invariants instead:
240
+ 1. **FK integrity on `resource.column`.** Declare it as a foreign key (`eventId: q.text().references(() => ({ table: 'events', column: 'id' }))`). Creates, and any update that changes it, then check the target through its own firewall ([Foreign-Key Referential Checks](#foreign-key-referential-checks)) — a row can't name another tenant's instance.
241
+ 2. **Write-gating on the relationship table.** Whoever can create or edit its rows can confer the relationship, so gate its `create`/`update` access as tightly as the access it grants — and guard `resource.column` against update (`guards: { immutable: ['eventId'] }`) so an existing row can't be repointed at all.
234
242
  - **Anonymous callers fail closed.** `ctx.userId` is null-guarded; the subquery short-circuits to `WHERE 1 = 0` for unauthenticated requests.
235
243
  - **The relationship table must be tenant-scoped** (`firewall: { exception: true }` is rejected at compile time on relationship tables).
236
- - **The relationship table needs its own `defineTable`.** That `<event_guests' own firewall>` line in the SQL above is the table's generated firewall helper — a bare Drizzle export has none, so a `from:` table with no `export default defineTable(...)` is a compile error naming the table.
244
+ - **The relationship table needs its own `defineTable`.** That `<event_guests' soft-delete predicates>` line in the SQL above comes from the table's generated firewall helper — a bare Drizzle export has none, so a `from:` table with no `export default defineTable(...)` is a compile error naming the table.
237
245
 
238
246
  See [Access — relationships](/define/relationships#authzrelationships) for the full `authz.relationships` shape and role-binding patterns.
239
247
 
@@ -510,7 +518,7 @@ export default defineTable(records, {
510
518
 
511
519
  ### Foreign-Key Referential Checks
512
520
 
513
- Generated `POST /` and `POST /batch` handlers validate every foreign-key column against the **target table's** firewall before inserting. If a record references a row that the caller can't see (wrong org, soft-deleted, or non-existent), the request fails with:
521
+ Every generated write handler — `POST /`, `POST /batch`, `PATCH /:id`, `PATCH /batch`, `PUT /:id` (both its update and create paths), `PUT /batch`, and the root of a [changeset](/define/changesets) — validates foreign-key columns against the **target table's** firewall before writing. Creates check every FK in the body; updates check every FK whose value **changes** (a value equal to the stored one costs no query). If a record references a row that the caller can't see (wrong org, soft-deleted, or non-existent), the request fails with:
514
522
 
515
523
  ```json
516
524
  {
@@ -521,9 +529,9 @@ Generated `POST /` and `POST /batch` handlers validate every foreign-key column
521
529
  }
522
530
  ```
523
531
 
524
- This closes a cross-tenant injection vector: even if an attacker knows a foreign tenant's row ID, they cannot attach a child record to it, and they cannot trigger a cross-tenant cascade delete. The check uses the target table's `buildXFirewallConditions(ctx)` helper, so it honors whatever firewall predicates the target declared (organization, owner, team, custom). FKs to tables with `{ exception: true }` get a plain existence check (still verifies the row exists, doesn't tenant-scope it).
532
+ This closes a cross-tenant injection vector: even if an attacker knows a foreign tenant's row ID, they cannot attach a child record to it — at creation or by repointing an existing row later — and they cannot trigger a cross-tenant cascade delete. The check uses the target table's `buildXFirewallConditions(ctx)` helper, so it honors whatever firewall predicates the target declared (organization, owner, team, custom). FKs to tables with `{ exception: true }` get a plain existence check (still verifies the row exists, doesn't tenant-scope it). A [self-reference](/define/schema#self-references) (`parentId: q.text().references('self')`) is checked against the table's own firewall the same way.
525
533
 
526
- The check runs after guards but before the insert, so it appears as `layer: "validation"` in error responses. Status code is `400`, not `404` — returning `404` would leak existence of out-of-scope rows.
534
+ The check runs after guards but before the write, so it appears as `layer: "validation"` in error responses. Status code is `400`, not `404` — returning `404` would leak existence of out-of-scope rows.
527
535
 
528
536
  ### Pre-Record ID-Probe Defense
529
537
 
@@ -278,7 +278,7 @@ masking: {
278
278
  }
279
279
  ```
280
280
 
281
- `query` is a single role gate that covers `?filter`, `?sort`, and `?search` uniformly. When omitted, it inherits from `show.roles` — "if you can see it, you can query it" — which is the right shape for almost all PII.
281
+ `query` is a single role gate that covers `?filter`, `?sort`, `?search`, and [view aggregations](/define/views#constraints-compile-time) uniformly, evaluated per caller with the same role rule as access (org roles, `scope:<kind>:<role>`, pseudo-roles). When omitted, it inherits from `show.roles` — "if you can see it, you can query it" — which is the right shape for almost all PII. Sorting by a masked column you may query but not see returns `null` pagination cursors (a cursor encodes the boundary row's sort values); `?offset=` paging still works. An aggregation over a masked column the caller may not query returns `"(suppressed)"`; `groupBy` / `min` / `max` on a masked column additionally require every role that can reach the view to be a query role, at build time.
282
282
 
283
283
  A view can opt back in for a higher-privileged role pair by listing the column in its own `query.{filterable,searchable,sortable}` allowlist. The compiler validates at build time that the view's access roles intersect the masking `query.roles` (or `show.roles` when `query` is omitted), so the opt-in can never reach a caller who'd see the value masked.
284
284
 
@@ -69,6 +69,9 @@ export default defineConfig({
69
69
  >
70
70
  > ```typescript
71
71
  > // features/conversations/conversation_members.ts
72
+ > import { sqliteTable, text } from 'drizzle-orm/sqlite-core';
73
+ > import { defineTable } from '@quickback/compiler';
74
+ >
72
75
  > export const conversation_members = sqliteTable('conversation_members', {
73
76
  > id: text('id').primaryKey(),
74
77
  > userId: text('user_id').notNull(),
@@ -105,7 +108,7 @@ Resource definitions reference declared roles by name in `roles: [...]` arrays e
105
108
  |---|---|---|
106
109
  | `firewall:` `via:` predicate | ✓ Supported | Subquery composes as outermost AND |
107
110
  | `crud.*.access` `roles: ['guest']` | ✓ Supported | Inline async lookup per request |
108
- | `read.access` / `read.views.*.access` `roles: ['guest']` | ✓ Supported | Same inline path |
111
+ | `read.access` / `read.views.*.access` `roles: ['guest']` | ✓ Supported | `GET /:id`: same inline path. Collections (`GET /`, views, `?total`, `?search`, aggregations, MCP list): rows filtered by `<resource.column> IN (<relationship subquery>)`, OR'd with sibling arms. The table must declare `resource.column`, and multi-hop (`hops`) relationships are refused here — scope those with a firewall `via:` |
109
112
  | **Standalone** `actions.<name>.access` `roles: ['guest']` | ✓ Supported | Inline gate; the surface exposes `resource.column` as a path param or input field |
110
113
  | **Record-based** `actions.<name>.access` `roles: ['guest']` | ✓ Supported | Inline lookup uses the already-loaded, firewalled record |
111
114
  | Namespace `via` lanes | ✓ Supported | Hoisted middleware resolves once and can hydrate `ctx.<exposeAs>` |
@@ -145,12 +148,12 @@ authz: {
145
148
  The resolver:
146
149
 
147
150
  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.
148
- 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.
151
+ 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 soft-delete predicates AND-applied — **not** its tenant scope (a cross-tenant attendee has no `activeOrgId` to match; see [Firewall — relationships](/define/firewall#relationship-based-scoping-via) for the two invariants that make the row trustworthy instead: FK integrity on `resource.column`, and write-gating on the relationship table). If neither role nor relationship qualifies → 403.
149
152
  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.
150
153
  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.
151
154
  5. Assigns the loaded row to `ctx.event` for the action body.
152
155
 
153
- **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.
156
+ **What each query enforces.** The relationship match applies the `from` table's soft-delete only; the loaded resource runs under its full firewall, bound to the tenant stamped from the matched row — so a relationship row can only open an instance in its own tenant. The relationship row's existence is the proof that the caller is authorized; its tenant columns are the source of the stamped claim. That makes the row's integrity load-bearing: declare `resource.column` as a foreign key and guard it against update (`guards: { immutable: ['eventId'] }`), and gate who may write the relationship table as tightly as the access it confers.
154
157
 
155
158
  ### Conditional tenant preconditions
156
159