@quickback-dev/cli 0.70.27 → 0.70.38

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 (200) hide show
  1. package/dist/codex/AGENTS.md +290 -0
  2. package/dist/commands/build.d.ts +12 -0
  3. package/dist/commands/build.d.ts.map +1 -1
  4. package/dist/commands/build.js +69 -1
  5. package/dist/commands/build.js.map +1 -1
  6. package/dist/commands/build.test.d.ts.map +1 -0
  7. package/dist/commands/codex.d.ts +16 -0
  8. package/dist/commands/codex.d.ts.map +1 -0
  9. package/dist/commands/codex.js +159 -0
  10. package/dist/commands/codex.js.map +1 -0
  11. package/dist/commands/compile.d.ts +62 -0
  12. package/dist/commands/compile.d.ts.map +1 -0
  13. package/dist/commands/compile.js +830 -0
  14. package/dist/commands/compile.js.map +1 -0
  15. package/dist/commands/compile.test.d.ts.map +1 -0
  16. package/dist/commands/deploy.d.ts +9 -0
  17. package/dist/commands/deploy.d.ts.map +1 -1
  18. package/dist/commands/deploy.js +20 -2
  19. package/dist/commands/deploy.js.map +1 -1
  20. package/dist/commands/init.d.ts +6 -0
  21. package/dist/commands/init.d.ts.map +1 -0
  22. package/dist/commands/init.js +405 -0
  23. package/dist/commands/init.js.map +1 -0
  24. package/dist/commands/migrate-data.d.ts +12 -0
  25. package/dist/commands/migrate-data.d.ts.map +1 -0
  26. package/dist/commands/migrate-data.js +134 -0
  27. package/dist/commands/migrate-data.js.map +1 -0
  28. package/dist/commands/migrate.d.ts.map +1 -1
  29. package/dist/commands/migrate.js +11 -0
  30. package/dist/commands/migrate.js.map +1 -1
  31. package/dist/commands/migrate.test.d.ts.map +1 -0
  32. package/dist/commands/migrations.test.d.ts.map +1 -0
  33. package/dist/commands/push.test.d.ts.map +1 -0
  34. package/dist/commands/schema.test.d.ts.map +1 -0
  35. package/dist/commands/secrets.d.ts +27 -0
  36. package/dist/commands/secrets.d.ts.map +1 -0
  37. package/dist/commands/secrets.js +186 -0
  38. package/dist/commands/secrets.js.map +1 -0
  39. package/dist/docs/content.d.ts +7 -0
  40. package/dist/docs/content.d.ts.map +1 -0
  41. package/dist/docs/content.js +672 -0
  42. package/dist/docs/content.js.map +1 -0
  43. package/dist/docs/index.test.d.ts.map +1 -0
  44. package/dist/index.js +23 -3
  45. package/dist/index.js.map +1 -1
  46. package/dist/lib/access-manifest-diff.d.ts +87 -0
  47. package/dist/lib/access-manifest-diff.d.ts.map +1 -0
  48. package/dist/lib/access-manifest-diff.js +331 -0
  49. package/dist/lib/access-manifest-diff.js.map +1 -0
  50. package/dist/lib/action-harvest.test.d.ts.map +1 -0
  51. package/dist/lib/api-client.test.d.ts.map +1 -0
  52. package/dist/lib/artifact-routing.d.ts.map +1 -1
  53. package/dist/lib/artifact-routing.js +3 -0
  54. package/dist/lib/artifact-routing.js.map +1 -1
  55. package/dist/lib/artifact-routing.test.d.ts.map +1 -0
  56. package/dist/lib/auth.test.d.ts.map +1 -0
  57. package/dist/lib/compile-next-steps.test.d.ts.map +1 -0
  58. package/dist/lib/compiler-floor.test.d.ts.map +1 -0
  59. package/dist/lib/compiler-stubs.d.ts +2 -0
  60. package/dist/lib/compiler-stubs.d.ts.map +1 -1
  61. package/dist/lib/compiler-stubs.js +2 -0
  62. package/dist/lib/compiler-stubs.js.map +1 -1
  63. package/dist/lib/config-id-splice.test.d.ts.map +1 -0
  64. package/dist/lib/config-sync.test.d.ts.map +1 -0
  65. package/dist/lib/copy-public-assets.test.d.ts.map +1 -0
  66. package/dist/lib/copy-source-apps.test.d.ts.map +1 -0
  67. package/dist/lib/drizzle-meta-routing.test.d.ts.map +1 -0
  68. package/dist/lib/file-loader-typescript-fallback.test.d.ts.map +1 -0
  69. package/dist/lib/file-loader.d.ts +6 -0
  70. package/dist/lib/file-loader.d.ts.map +1 -1
  71. package/dist/lib/file-loader.js +17 -0
  72. package/dist/lib/file-loader.js.map +1 -1
  73. package/dist/lib/file-loader.test.d.ts.map +1 -0
  74. package/dist/lib/file-writer.test.d.ts.map +1 -0
  75. package/dist/lib/helpers.d.ts +39 -0
  76. package/dist/lib/helpers.d.ts.map +1 -0
  77. package/dist/lib/helpers.js +299 -0
  78. package/dist/lib/helpers.js.map +1 -0
  79. package/dist/lib/migrations/drizzle-prompts.test.d.ts.map +1 -0
  80. package/dist/lib/migrations/drizzle.test.d.ts.map +1 -0
  81. package/dist/lib/migrations/executor.test.d.ts.map +1 -0
  82. package/dist/lib/migrations/inventory.test.d.ts.map +1 -0
  83. package/dist/lib/migrations/lock.test.d.ts.map +1 -0
  84. package/dist/lib/migrations/paths.test.d.ts.map +1 -0
  85. package/dist/lib/migrations/plan.test.d.ts.map +1 -0
  86. package/dist/lib/migrations/postprocessors/index.test.d.ts.map +1 -0
  87. package/dist/lib/migrations/prompt-runner.test.d.ts.map +1 -0
  88. package/dist/lib/migrations/staging.test.d.ts.map +1 -0
  89. package/dist/lib/neon-canary.test.d.ts.map +1 -0
  90. package/dist/lib/neon-target.test.d.ts.map +1 -0
  91. package/dist/lib/neon.test.d.ts.map +1 -0
  92. package/dist/lib/ops-manifest.d.ts +76 -0
  93. package/dist/lib/ops-manifest.d.ts.map +1 -0
  94. package/dist/lib/ops-manifest.js +94 -0
  95. package/dist/lib/ops-manifest.js.map +1 -0
  96. package/dist/lib/prepare-output.test.d.ts.map +1 -0
  97. package/dist/lib/prepare-state-output.test.d.ts.map +1 -0
  98. package/dist/lib/release-and-pin.d.ts +34 -0
  99. package/dist/lib/release-and-pin.d.ts.map +1 -0
  100. package/dist/lib/release-and-pin.js +71 -0
  101. package/dist/lib/release-and-pin.js.map +1 -0
  102. package/dist/lib/schema-sync/index.test.d.ts.map +1 -0
  103. package/dist/lib/shell.d.ts +4 -1
  104. package/dist/lib/shell.d.ts.map +1 -1
  105. package/dist/lib/shell.js +8 -3
  106. package/dist/lib/shell.js.map +1 -1
  107. package/dist/lib/shell.test.d.ts.map +1 -0
  108. package/dist/lib/sweep-stale.d.ts +25 -0
  109. package/dist/lib/sweep-stale.d.ts.map +1 -0
  110. package/dist/lib/sweep-stale.js +179 -0
  111. package/dist/lib/sweep-stale.js.map +1 -0
  112. package/dist/lib/sweep-stale.test.d.ts.map +1 -0
  113. package/dist/lib/wrangler-resources.test.d.ts.map +1 -0
  114. package/dist/skill/docs/api/actions.md +2 -0
  115. package/dist/skill/docs/api/batch-operations.md +18 -4
  116. package/dist/skill/docs/api/crud.md +62 -0
  117. package/dist/skill/docs/api/errors.md +17 -2
  118. package/dist/skill/docs/configure/auth.md +49 -2
  119. package/dist/skill/docs/configure/bindings.md +15 -0
  120. package/dist/skill/docs/configure/domains.md +4 -0
  121. package/dist/skill/docs/configure/index.md +29 -11
  122. package/dist/skill/docs/configure/providers.md +1 -0
  123. package/dist/skill/docs/configure/tenancy.md +117 -0
  124. package/dist/skill/docs/define/access.md +19 -0
  125. package/dist/skill/docs/define/actions/access.md +76 -0
  126. package/dist/skill/docs/define/actions/defining.md +156 -1
  127. package/dist/skill/docs/define/actions/scoped-db.md +236 -9
  128. package/dist/skill/docs/define/areas.md +46 -0
  129. package/dist/skill/docs/define/authz-roles.md +10 -0
  130. package/dist/skill/docs/define/diagnostics.md +263 -0
  131. package/dist/skill/docs/define/encryption.md +34 -2
  132. package/dist/skill/docs/define/guards.md +13 -0
  133. package/dist/skill/docs/define/masking.md +77 -3
  134. package/dist/skill/docs/define/rate-limit.md +3 -3
  135. package/dist/skill/docs/define/schema.md +148 -7
  136. package/dist/skill/docs/define/scopes.md +79 -0
  137. package/dist/skill/docs/define/sealed-protocol.md +111 -9
  138. package/dist/skill/docs/define/transitions.md +39 -0
  139. package/dist/skill/docs/define/views.md +77 -3
  140. package/dist/skill/docs/platform/api-contract/index.md +4 -0
  141. package/dist/skill/docs/platform/auth/jwt-optimization.md +2 -0
  142. package/dist/skill/docs/platform/auth/plugins/aws-ses.md +4 -3
  143. package/dist/skill/docs/platform/auth/using-auth.md +6 -0
  144. package/dist/skill/docs/platform/database/d1.md +47 -0
  145. package/dist/skill/docs/platform/database/data-migrations.md +109 -0
  146. package/dist/skill/docs/platform/database/index.md +1 -0
  147. package/dist/skill/docs/platform/database/read-replication.md +257 -0
  148. package/dist/skill/docs/platform/database/using-d1.md +2 -1
  149. package/dist/skill/docs/platform/payments/one-off-checkout.md +6 -1
  150. package/dist/skill/docs/platform/push/index.md +2 -0
  151. package/dist/skill/docs/platform/realtime/partyserver-rooms.md +95 -9
  152. package/dist/skill/docs/platform/storage/using-r2.md +135 -19
  153. package/dist/skill/docs/start/deploy.md +38 -0
  154. package/dist/skill/docs/tooling/cli.md +120 -0
  155. package/dist/skill/docs/tooling/cloud-compiler/troubleshooting.md +13 -13
  156. package/dist/skill/docs/tooling/output.md +70 -2
  157. package/package.json +1 -1
  158. package/src/skill/docs/api/actions.md +2 -0
  159. package/src/skill/docs/api/batch-operations.md +18 -4
  160. package/src/skill/docs/api/crud.md +62 -0
  161. package/src/skill/docs/api/errors.md +17 -2
  162. package/src/skill/docs/configure/auth.md +49 -2
  163. package/src/skill/docs/configure/bindings.md +15 -0
  164. package/src/skill/docs/configure/domains.md +4 -0
  165. package/src/skill/docs/configure/index.md +29 -11
  166. package/src/skill/docs/configure/providers.md +1 -0
  167. package/src/skill/docs/configure/tenancy.md +117 -0
  168. package/src/skill/docs/define/access.md +19 -0
  169. package/src/skill/docs/define/actions/access.md +76 -0
  170. package/src/skill/docs/define/actions/defining.md +156 -1
  171. package/src/skill/docs/define/actions/scoped-db.md +236 -9
  172. package/src/skill/docs/define/areas.md +46 -0
  173. package/src/skill/docs/define/authz-roles.md +10 -0
  174. package/src/skill/docs/define/diagnostics.md +263 -0
  175. package/src/skill/docs/define/encryption.md +34 -2
  176. package/src/skill/docs/define/guards.md +13 -0
  177. package/src/skill/docs/define/masking.md +77 -3
  178. package/src/skill/docs/define/rate-limit.md +3 -3
  179. package/src/skill/docs/define/schema.md +148 -7
  180. package/src/skill/docs/define/scopes.md +79 -0
  181. package/src/skill/docs/define/sealed-protocol.md +111 -9
  182. package/src/skill/docs/define/transitions.md +39 -0
  183. package/src/skill/docs/define/views.md +77 -3
  184. package/src/skill/docs/platform/api-contract/index.md +4 -0
  185. package/src/skill/docs/platform/auth/jwt-optimization.md +2 -0
  186. package/src/skill/docs/platform/auth/plugins/aws-ses.md +4 -3
  187. package/src/skill/docs/platform/auth/using-auth.md +6 -0
  188. package/src/skill/docs/platform/database/d1.md +47 -0
  189. package/src/skill/docs/platform/database/data-migrations.md +109 -0
  190. package/src/skill/docs/platform/database/index.md +1 -0
  191. package/src/skill/docs/platform/database/read-replication.md +257 -0
  192. package/src/skill/docs/platform/database/using-d1.md +2 -1
  193. package/src/skill/docs/platform/payments/one-off-checkout.md +6 -1
  194. package/src/skill/docs/platform/push/index.md +2 -0
  195. package/src/skill/docs/platform/realtime/partyserver-rooms.md +95 -9
  196. package/src/skill/docs/platform/storage/using-r2.md +135 -19
  197. package/src/skill/docs/start/deploy.md +38 -0
  198. package/src/skill/docs/tooling/cli.md +120 -0
  199. package/src/skill/docs/tooling/cloud-compiler/troubleshooting.md +13 -13
  200. package/src/skill/docs/tooling/output.md +70 -2
@@ -100,6 +100,38 @@ Two practical notes:
100
100
  - **Action responses**: rows returned from `db.insert(...).returning()` inside your own actions contain ciphertext — decrypt explicitly with `ctx.crypto.decrypt(value, { table, column })` if your action returns the field. Generated CRUD routes handle this automatically.
101
101
  - **No server-side equality lookups** on encrypted values (blind indexes are a roadmap item). If you need to filter by it, it probably shouldn't be encrypted — or it needs a separate non-sensitive derived column.
102
102
 
103
+ ## Secret columns — `q.secret()`
104
+
105
+ Some values are written once and only ever *used* by the server: a third-party client secret, a webhook URL that carries its own token. Nobody — not an admin, not the row's owner — needs to read them back. `q.secret()` is that column kind:
106
+
107
+ ```typescript
108
+ export default feature('integrations', {
109
+ columns: {
110
+ id: q.id(),
111
+ organizationId: q.scope('organization'), // required — keys are per-org
112
+ name: q.text().required(),
113
+ clientSecret: q.secret({ maxLength: 500 }),
114
+ ...q.audit(),
115
+ ...q.softDelete(),
116
+ },
117
+ read: { access: { roles: ['member+'] } },
118
+ create: { access: { roles: ['admin+'] } },
119
+ update: { access: { roles: ['admin+'] } },
120
+ });
121
+ ```
122
+
123
+ - **Encrypted at rest** with this envelope tier — same keys, chokepoint, `qbenc:` format, rules, and boot guard as `.encrypted()`.
124
+ - **Never returned.** The compiler gives the column a `masking` rule of `show: 'never'`, so CRUD, views, realtime, and changesets redact it (`[REDACTED]`; `null` stays `null`, so a client can tell whether one is set) for every role, the owner included. The read path does not even decrypt it. A `masking` entry of your own that would reveal it — `false`, or any `show` other than `'never'` — is a compile error.
125
+ - **Writable** through create, update, batch, and actions like any column. Clients send plaintext.
126
+ - **Readable server-side only through [`ctx.unmask(row, column)`](/define/actions/scoped-db#ctxunmask--reading-a-qsecret-column)** inside an action, which opens it with the row's organization key and records a best-effort audit entry. `ctx.crypto.decrypt` refuses secret columns.
127
+ - `.sealed()` and `.array()` on a secret are compile errors.
128
+
129
+ | | Stored as | Who reads plaintext |
130
+ |---|---|---|
131
+ | `.encrypted()` | envelope ciphertext | allowed roles, through every read path (masking composes on top) |
132
+ | `q.secret()` | envelope ciphertext | nobody through a read path; action code through `ctx.unmask` |
133
+ | `.sealed()` | client-sealed ciphertext | only a client holding a granted key — the server never can |
134
+
103
135
  ---
104
136
 
105
137
  # Sealed tier — end-to-end encryption
@@ -200,7 +232,7 @@ Behind that one call:
200
232
  5. **`/seal/v1/key`** (bearer that capability) passes three fail-closed gates — tenant, capability, live-grant — and returns the still-wrapped content key.
201
233
  6. The client unwraps the scope key, unwraps the content key, and decrypts. **None of this touches the server with a readable key.**
202
234
 
203
- Passkey reveal is the same call as `revealWithPasskey({ ..., getAssertion })`, where `getAssertion(nonce)` runs the WebAuthn ceremony.
235
+ Passkey reveal is the same call as `revealWithPasskey({ ..., getAssertion })`, where `getAssertion(nonce)` runs the WebAuthn ceremony. A PRF-capable passkey can also **replace the passphrase prompt**: the client wraps the passphrase-derived user master under the passkey's PRF output once (`wrapMasterWithPrf`), and from then on a single ceremony both proves the step-up and unlocks the keys (`revealWithPasskey({ ..., prfUnwrap })`). Sign-in passkeys are emitted PRF-capable at creation; native-app origins go in `encryption.seal.extraOrigins`. The derivation and envelope are specified in [Multi-factor unlock (passkey PRF)](/define/sealed-protocol#multi-factor-unlock-passkey-prf).
204
236
 
205
237
  ## Rules the compiler enforces
206
238
 
@@ -218,7 +250,7 @@ Sealed values are opaque references at rest, so they're fenced off from every su
218
250
  The sealed tier protects against **full Worker compromise** — leaked secrets, malicious or buggy server code, a coerced operator. All of them get ciphertext; the keys to read it never exist server-side. Its operating model is explicit:
219
251
 
220
252
  - **A reveal needs a real second factor.** The vault passphrase (or passkey) is separate from login and never leaves the client.
221
- - **Recovery is opt-in and zero-knowledge.** A key admin can enroll a scope key wrapped under a client-held recovery code through `/seal/v1/recovery/enroll`; `/recovery/use` returns only that opaque wrapped blob. If no recovery is enrolled and every reader loses their factor, the data is unrecoverable by design.
253
+ - **Recovery is opt-in and zero-knowledge.** A key admin can enroll a scope key wrapped under a client-held recovery factor through `/seal/v1/recovery/enroll` — a recovery code, or (`wrapMethod: 'prf-aesgcm'`) a hardware security key or shared vault passkey, one live row per method; `/recovery/use` returns only those opaque wrapped blobs. If no recovery is enrolled and every reader loses their factor, the data is unrecoverable by design.
222
254
  - **Rotation includes re-granting.** `/rotate` versions the scope key and returns the live-reader worklist and public keys so the key-admin client can wrap and grant the new private key without exposing it to the server.
223
255
  - **No server-side processing.** Your actions can't read, mask, search, or index a sealed value — it's plaintext only in a client that just revealed it. If the server needs to process the field, you want the envelope tier instead.
224
256
  - **Passkey rollout check.** The server verification path and nonce-bound
@@ -116,6 +116,19 @@ guards: {
116
116
 
117
117
  **If a field is not listed anywhere, it cannot be set by the client.**
118
118
 
119
+ ### Keys inside a JSON column
120
+
121
+ Guards work per column. A typed `q.json` column can also give its keys their own write tiers with [`q.json(schema, { keys })`](/define/schema#per-key-write-authority-keys). An `organizer` key follows the column's `createable` / `updatable` entry. A `platform` key is refused by every generic write with **422 `JSON_KEY_RESTRICTED`** (field and key named in `details.fields`), and a PATCH of the column keeps its stored value. Only an action whose caller matched its `access.userRole` lane, or one that lists the key in [`writes:`](/define/actions/defining#json-key-writes-and-requires), may change it. A `derivedFrom` key is never writable.
122
+
123
+ ```typescript
124
+ guards: {
125
+ createable: ["name", "settings"], // settings.theme (organizer) is writable here
126
+ updatable: ["name", "settings"], // settings.beta (platform) is not, on either route
127
+ }
128
+ ```
129
+
130
+ Leaving a JSON column in `updatable` with no `keys` makes every key of it client-writable, so declare `keys` whenever any part of the value is managed by the platform.
131
+
119
132
  ## System-Managed Fields (Always Protected)
120
133
 
121
134
  `GUARDS_CONFIG.systemManaged` rejects any field in this set from client input — even with `guards: false`. The set always includes the audit fields:
@@ -58,6 +58,7 @@ It also removes a bug class outright. When detection can never quietly supply a
58
58
  | :--- | :--- | :--- |
59
59
  | `GET /:id`, list, named views, `POST`, `PATCH`, `PUT`, batch | Masked per role | Returned in full |
60
60
  | Realtime frames + live-view deltas | Masked per-subscriber-role | Sent in full |
61
+ | Action results declaring [`outputMask`](/define/actions/defining#masking-action-output-outputmask) | Masked per role | Returned in full |
61
62
  | `?filter=` / `?sort=` | Only roles in the [query gate](#query-gate-filter--sort--search) | Unrestricted |
62
63
  | `?search=` | Dropped from the default searchable set | Searchable |
63
64
  | FK display label / `embeddings` / action egress scan | Blocked — see [Egress protection](#egress-protection) | Allowed |
@@ -214,13 +215,82 @@ masking: {
214
215
 
215
216
  ```typescript
216
217
  show: 'never' | {
217
- roles?: string[]; // Unmasked if user has any of these roles
218
- or?: 'owner'; // Unmasked if user is the record owner
218
+ roles?: string[]; // Unmasked if user has any of these roles
219
+ or?: 'owner' // …OR the user is the record owner
220
+ | { record: { /* … */ } }; // …OR the row's own state matches
219
221
  }
220
222
  ```
221
223
 
222
224
  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`.
223
225
 
226
+ ### Record-state masking
227
+
228
+ Some fields are secret only while the row is in a certain state: a poll's
229
+ voters until the poll closes, a roster entry until the attendee opts into the
230
+ directory. `or: { record: { … } }` reveals the field to every caller who can
231
+ read the row once the row's own columns match — OR'd with `roles`:
232
+
233
+ ```typescript
234
+ import { feature, q } from '@quickback/compiler';
235
+
236
+ export default feature('votes', {
237
+ columns: {
238
+ id: q.id(),
239
+ pollId: q.text().required(),
240
+ optionId: q.text().required(),
241
+ voterId: q.text().required(),
242
+ closedAt: q.timestamp().optional(),
243
+ organizationId: q.scope('organization'),
244
+ ...q.audit(),
245
+ ...q.softDelete(),
246
+ },
247
+ guards: { createable: ['pollId', 'optionId', 'voterId'], updatable: ['closedAt'] },
248
+ masking: {
249
+ // Admins always see the voter; everyone else once the ballot is closed.
250
+ voterId: {
251
+ type: 'redact',
252
+ show: { roles: ['admin'], or: { record: { closedAt: { notNull: true } } } },
253
+ },
254
+ },
255
+ read: { access: { roles: ['member', 'admin'] } },
256
+ create: { access: { roles: ['member', 'admin'] } },
257
+ update: { access: { roles: ['admin'] } },
258
+ delete: { access: { roles: ['admin'] }, mode: 'soft' },
259
+ });
260
+ ```
261
+
262
+ Conditions are on columns of the **same row**, and several conditions AND
263
+ together:
264
+
265
+ | Condition | Holds when |
266
+ |---|---|
267
+ | `{ notNull: true }` / `{ null: true }` | the column is set / empty |
268
+ | `{ equals: v }` / `{ notEquals: v }` | the column equals / differs from a literal (string, number, boolean) |
269
+ | `{ in: [...] }` / `{ notIn: [...] }` | the column is / is not one of the literals |
270
+ | `{ before: 'now' }` / `{ after: 'now' }` | a timestamp or date column is earlier / later than the request time |
271
+
272
+ It applies everywhere the field is masked, through one evaluator: `GET /:id`,
273
+ lists and named views, write responses, batch, [action
274
+ output](/define/actions/defining#masking-action-output-outputmask), realtime
275
+ frames and live-view deltas. The rule is about the row, not the caller, so
276
+ operands are literals — `$ctx.*` is a compile error (the caller axis is
277
+ `roles` and `or: 'owner'`).
278
+
279
+ It fails closed:
280
+
281
+ - A row whose projection **omits** a condition column never matches, so the
282
+ field stays masked. A named view that projects the field without its
283
+ condition columns is a compile error; a `?fields=` request that drops them
284
+ just gets the masked value.
285
+ - An unknown column or operator, `equals: null`, `before`/`after` on a column
286
+ that is not a timestamp or date, or a value other than `'now'` there is a
287
+ compile error. (`eq` is suggested as `equals`.)
288
+ - A condition on a column that is **itself masked** is a compile error:
289
+ revealing one field whenever another matches would disclose the other.
290
+ - The query gate does not change: `?filter=` / `?sort=` / `?search=` on the
291
+ column still follow `query.roles` (default `show.roles`), whatever state the
292
+ rows are in.
293
+
224
294
  ### `show: 'never'` — masked for everyone, deliberately
225
295
 
226
296
  ```typescript
@@ -236,6 +306,10 @@ Write `'never'` when nobody is the intent. Any other string is a compile error r
236
306
  > This does **not** add a `userRole` axis to masking. Gating a mask on Better Auth user roles (`sysadmin`, `appmanager`) is still refused at compile time. `'never'` only lets the deliberate case say so out loud; a mask that wants the same audience as a `userRole`-gated table still has to go through a gated view.
237
307
 
238
308
 
309
+ ### Masks derived from a realtime room
310
+
311
+ A [realtime room](/platform/realtime/partyserver-rooms#room-roles) whose binding declares `writeRoles` and is keyed by a non-PK column (`access.resource.key`, e.g. `yjsRoomId`) masks that column for you: `{ type: 'redact', show: { roles: <writeRoles> } }`, on every read path above. The binding owns that column's audience, so declaring `masking.<key>` on the table as well is a compile error.
312
+
239
313
  ### Relationship-aware field projection
240
314
 
241
315
  For relationship-specific field visibility, use a named view gated by the
@@ -252,7 +326,7 @@ compile-time refusal, never a silently ignored condition or a broader grant.
252
326
  [Named gates](/define/authz-roles#named-gates-authzrules) (`authz.rules`) follow the same discipline in `show:`:
253
327
 
254
328
  - A **who-only** gate expands like a named role (its flat role list; the owner-gated flat-role constraint above applies).
255
- - A gate carrying a **`record:`** predicate is a **compile error** — masking cannot evaluate record conditions, so the record dimension would be silently dropped.
329
+ - A gate carrying a **`record:`** predicate is a **compile error**. A gate's record predicate is ANDed with its roles; masking's record dimension is the OR arm [`or: { record }`](#record-state-masking) — the row's state reveals the field on its own — so state the condition there and reference a who-only rule in `show:`.
256
330
  - A gate carrying **firewall lanes** is a **compile error** — masking has no firewall array to satisfy, so the gate's row lanes would silently not apply. Reference a who-only rule (or inline the roles) in `show:`, and stamp the firewall gate on the resource's `firewall:` instead.
257
331
 
258
332
  **Supported patterns**, depending on intent:
@@ -108,7 +108,7 @@ Default-using resources collapse onto two shared bindings (`RL_1000_60`, `RL_200
108
108
 
109
109
  ## How requests are keyed
110
110
 
111
- Each handler composes a key as `<resource>:<op>:<userId>`. For routes that opt into PUBLIC access (no `userId`), the key falls back to the client's `cf-connecting-ip` header, then to the literal `'anon'` if that header is absent too.
111
+ Each handler composes a key as `<resource>:<op>:<identity>`. The identity is the caller's `userId`. A sessionless scope-only principal (for example an event pass, which has no `userId`) is keyed on its verified JWT subject, `scope:<kind>:<subjectId>`, so every pass holder gets their own bucket even when many of them share one network. Only callers with neither — routes that opt into PUBLIC access — fall back to the client's `cf-connecting-ip` header, then to the literal `'anon'` if that header is absent too.
112
112
 
113
113
  This means:
114
114
 
@@ -193,8 +193,8 @@ Set `rateLimit: false` to opt the action out of enforcement entirely.
193
193
 
194
194
  | Action kind | Key shape |
195
195
  |-------------|-----------|
196
- | Record-based | `<resource>:action:<actionName>:<userId\|cf-connecting-ip\|anon>` |
197
- | Standalone | `standalone:<path>:<userId\|cf-connecting-ip\|anon>` |
196
+ | Record-based | `<resource>:action:<actionName>:<userId\|scopeSubject\|cf-connecting-ip\|anon>` |
197
+ | Standalone | `standalone:<path>:<userId\|scopeSubject\|cf-connecting-ip\|anon>` |
198
198
 
199
199
  The `:action:` infix is what keeps `update` (resource bucket) and `approve` (action bucket) from sharing counters when they happen to land on the same binding name.
200
200
 
@@ -135,6 +135,7 @@ place for generated CRUD writes.
135
135
 
136
136
 
137
137
  - **Indexes and constraints:** column-level `.index()` / `.unique()` / `.check(expr)`, or table-level `indexes` / `unique` / `check` as a third arg to `q.table(name, cols, { indexes, unique, check })`. With `feature()`, pass `indexes`, `unique` and `check` as top-level keys alongside `columns` — the sugar forwards them into the same `q.table` opts. In the two-export form they go on `q.table`; on `defineTable(...)` they are a compile error, because they describe the table, not the resource. See [Constraints](#constraints--check-and-unique).
138
+ - **Race-safe write kinds (on `defineTable`):** `ledger: { grants, reserve }` makes the table the debits side of a balance served as `db.ledger.<name>` ([Ledgers](/define/actions/scoped-db#ledgers-dbledgername)); `idempotency: { rowToken, clientId? }` makes `POST /` and `POST /batch` replay a create whose row token is already stored ([Row-token idempotency](/api/crud#row-token-idempotency)).
138
139
 
139
140
  ### Column Types
140
141
 
@@ -142,6 +143,7 @@ place for generated CRUD writes.
142
143
  |---------|---------------------|----------|
143
144
  | `q.text()` | `text(...)` | `z.string()` |
144
145
  | `q.url()` | `text(...)` | `z.string().url({ protocol: /^https?$/ })` |
146
+ | `q.secret()` | `text(...)` (envelope-encrypted, never returned) | `z.string()` — see [Secret columns](/define/encryption#secret-columns--qsecret) |
145
147
  | `q.int()` | `integer(...)` | `z.number().int()` |
146
148
  | `q.bigint()` | `bigint(..., { mode: 'number' })` | `z.number().int()` within ±(2^53 − 1) |
147
149
  | `q.smallint()` | `smallint(...)` | `z.number().int()` within −32768..32767 |
@@ -155,6 +157,7 @@ place for generated CRUD writes.
155
157
  | `q.id()` | `text('id').primaryKey()` | `z.string()` |
156
158
  | `q.scope(kind)` | `text(...).notNull()` | `z.string()` |
157
159
  | `q.stamp({ fromScope, claim })` | `text(...).notNull()` (nullable with `optional: true`) | `z.string().optional()` |
160
+ | `q.storageKey({ bucket, key, mime, maxBytes })` | `text(...)` | never in a request body — written by `db.allocateUpload` only |
158
161
  | `.array()` on `q.text()` / `q.enum()` / `q.int()` / `q.uuid()` | `text(...).array()` etc. | `z.array(<element>)` |
159
162
 
160
163
  The Drizzle column is the Postgres form; on SQLite/D1 the compiler lowers it. The next section has the per-dialect storage for the exact-numeric, date, and array types.
@@ -172,6 +175,8 @@ In request bodies a column that is not `.required()` is `.optional().nullable()`
172
175
 
173
176
  Every rule is enforced on the generated create, update, and batch routes, described in OpenAPI, and read by the CMS form from the [schema registry](/ui/admin/schema-format). A misspelled option (`maxlength`) is a compile error, not a silent no-op. `q.url()` takes `sqlName` and `maxLength` only.
174
177
 
178
+ `q.secret()` is a write-only credential column — an API client secret, a webhook URL with an embedded token. It takes `sqlName`, `minLength`, `maxLength`, and `pattern`; it is encrypted at rest like `.encrypted()`, redacted on every read path for every role (owner included), and read server-side only through `ctx.unmask(row, column)`. The table needs a `q.scope('organization')` column. See [Secret columns](/define/encryption#secret-columns--qsecret).
179
+
175
180
  `q.url()` is `q.text()` plus an absolute-`http(s)`-URL check at the validation edge, so `javascript:` / `data:` / `ftp:` URIs and free-form strings are rejected before they ever land in storage or get rendered in the CMS.
176
181
 
177
182
  `q.id()` emits a plain text primary key. Actual ID assignment at insert time is driven by the provider's `generateId` setting (default `"uuid"`). This keeps q's output decoupled from any specific ID library.
@@ -208,6 +213,80 @@ The schema must be written inline from `z` and literals, because the compiler co
208
213
  - using `z` anywhere else in the table file
209
214
  - importing anything from `zod` other than `{ z }`
210
215
 
216
+ #### Per-key write authority (`keys`)
217
+
218
+ `createable` and `updatable` decide whether a client may write a column. One JSON column can mix keys a project member may change with keys only a platform operator may change (entitlements, plan features, feature flags). The second argument of `q.json(schema, opts)` can declare a tier for each key:
219
+
220
+ ```typescript title="quickback/features/projects/projects.ts"
221
+ import { feature, q } from "@quickback/compiler";
222
+ import { z } from "zod";
223
+
224
+ export default feature("projects", {
225
+ columns: {
226
+ id: q.id(),
227
+ name: q.text().required(),
228
+ settings: q.json(
229
+ z.object({
230
+ theme: z.string().optional(),
231
+ beta: z.boolean().optional(),
232
+ }),
233
+ {
234
+ keys: {
235
+ theme: { tier: "organizer" }, // ordinary: writable wherever `settings` is
236
+ beta: { tier: "platform" }, // generic writes refuse it
237
+ },
238
+ },
239
+ ).optional(),
240
+ organizationId: q.scope("organization"),
241
+ ...q.audit(),
242
+ ...q.softDelete(),
243
+ },
244
+ guards: { createable: ["name", "settings"], updatable: ["name", "settings"] },
245
+ read: { access: { roles: ["member"] } },
246
+ create: { access: { roles: ["member"] } },
247
+ update: { access: { roles: ["member"] } },
248
+ });
249
+ ```
250
+
251
+ | Option | Meaning |
252
+ |--------|---------|
253
+ | `sqlName` | SQL column name. The legacy positional form `q.json(schema, "col")` still works. |
254
+ | `keys.<key>.tier` | `"organizer"` (the default): an ordinary key. `"platform"`: see below. |
255
+ | `keys.<key>.derivedFrom` | The key is computed from another table and never stored. Requires `tier: "platform"` and a `z.boolean()` property. |
256
+
257
+ `keys` needs an inline `z.object({ ... })` value schema, and every key it lists must be a property of that schema. A key the schema doesn't declare, an unknown option, or a non-literal options object is a compile error.
258
+
259
+ **Platform keys.** Generic CRUD writes (POST, PATCH, PUT, the batch routes, and changeset ops) refuse a body that carries a platform key with **422 `JSON_KEY_RESTRICTED`**, and `details.fields` names it as `<column>.<key>`. A PATCH that replaces the column keeps the stored platform keys: `PATCH { settings: { theme: "dark" } }` leaves `beta` as it was. Platform keys are `readOnly` in the column's JSON Schema (OpenAPI, `api-types.gen.ts`, MCP).
260
+
261
+ Only an action can change a platform key, and only one of these actions:
262
+
263
+ - an action whose `access` names a `userRole` lane, when the caller's `user.role` matched it (`access: { userRole: ["operator"] }`);
264
+ - an action that names the key in [`writes:`](/define/actions/defining#json-key-writes-and-requires).
265
+
266
+ The [scoped `db`](/define/actions/scoped-db) enforces this rule, and so do handles from `unsafeDb.scopeTo(...)`. Any other action that writes the column gets 422 `JSON_KEY_RESTRICTED` if it changes or drops a platform key. Read-modify-write that carries the key over unchanged, such as `.set({ settings: { ...record.settings, theme } })`, is allowed. An insert may not set a platform key without the grant. An upsert's `onConflictDoUpdate({ set })` that touches the column is refused unless the action holds every grant, because the compiler cannot compare it against the stored row. The raw `unsafeDb` handle bypasses this check, as it bypasses the firewall.
267
+
268
+ **Derived keys.** `derivedFrom: { table, column, in, match? }` turns a key into a projection of another table. The key is `true` when a row of `table` that is linked to this row has `column` in the `in` set, and `false` otherwise. Soft-deleted rows don't count.
269
+
270
+ {/* doc-compile: skip — derivedFrom resolves against a second table (`plans`) the isolated fence does not declare; the tests/output-matrix/fixtures/json-key-tiers project compiles both. */}
271
+ ```typescript
272
+ settings: q.json(
273
+ z.object({ premiumExport: z.boolean().optional() }),
274
+ {
275
+ keys: {
276
+ premiumExport: {
277
+ tier: "platform",
278
+ // true while a `plans` row for this project is active or trialing
279
+ derivedFrom: { table: "plans", column: "status", in: ["active", "trialing"] },
280
+ },
281
+ },
282
+ },
283
+ ),
284
+ ```
285
+
286
+ - `table` is the other table's SQL name or export name, and `column` is a column of it.
287
+ - `match: { source, target }` links the rows: `source` is a column on this table, `target` a column on `table`. Omit it when `table` has exactly one `.references()` to this table. The compiler then infers the link (`plans.projectId → projects.id`). Zero or several references with no `match` is a compile error.
288
+ - A derived key is never stored and never writable. Every write path refuses it, actions with a grant included. CRUD reads (GET, list, views) and CRUD write responses fill it in from the source table. Realtime frames carry the stored value, which never holds a derived key. An action's [`requires:`](/define/actions/defining#json-key-writes-and-requires) also reads the source table, so the purchase or subscription row is the only source of truth.
289
+
211
290
  Under `generateId: "cuid"`, `"nanoid"`, or `"short"`, the `q.id()` default
212
291
  calls an npm helper (`createId` from `@paralleldrive/cuid2`, or `nanoid` /
213
292
  `customAlphabet` from `nanoid`). Don't import it in the table file, which may
@@ -328,6 +407,41 @@ columns: {
328
407
 
329
408
  **Idempotency (at-least-once).** The stamp rides inside the write, so it inherits the endpoint's replay semantics: a **keyed** replay (a repeated `Idempotency-Key` whose handler is skipped) neither re-writes nor re-stamps; a **keyless** retry re-writes and therefore re-stamps from the caller's then-current proven claim.
330
409
 
410
+ ### q.storageKey() — R2 object keys the compiler owns
411
+
412
+ `q.storageKey(...)` declares a column that holds an R2 object key. The compiler,
413
+ not the client, writes the key:
414
+
415
+ ```ts no-compile
416
+ r2Key: q.storageKey({
417
+ bucket: "MEDIA", // a bindings.r2Buckets binding
418
+ key: "media/{organizationId}/{eventId}/{uuid}.{ext}",
419
+ mime: ["image/*", "application/pdf"],
420
+ maxBytes: 10_000_000,
421
+ }),
422
+ ```
423
+
424
+ - **Never client-writable.** No generated write body (create, update, batch,
425
+ PUT, changeset) carries the column. Listing it in `guards.createable`,
426
+ `updatable`, `immutable` or `protected` is a compile error
427
+ (`STORAGE_KEY_GUARDED`).
428
+ - **Written only by `db.allocateUpload(table, { ...rowValues, ext, mime, size })`**
429
+ inside an action. It renders the key from the template, with `{column}`
430
+ values from the row, a fresh `{uuid}`, and `{ext}` from the call. It then
431
+ returns `{ row, putUrl, headers }`: a PUT signed for exactly the declared
432
+ `mime` and at most `maxBytes`.
433
+ - **Prefix-checked.** The row's prefix is the template up to `{uuid}` with the
434
+ row's own values (`media/org_abc/evt_1/`). Reads (`db.signDownload`), deletes,
435
+ and [tenant purge](/configure/tenancy) refuse a stored key outside it. Each
436
+ firewall tenant column (`organizationId`, `ownerId`, a scope column) must be a
437
+ placeholder before `{uuid}`. Each placeholder fills a whole path segment.
438
+ - **Deleted with the row.** A hard delete through the generated routes or the
439
+ action `db` deletes the object too.
440
+
441
+ The column takes `.required()`, `.optional()`, `.unique()` and `.index()`.
442
+ Other modifiers fail the compile. The template rules, the error codes, and the
443
+ full upload and download flow are in [Using R2 → Signed upload](/platform/storage/using-r2#signed-upload-large-or-confidential-files).
444
+
331
445
  ### Naming Convention
332
446
 
333
447
  By default, `q` picks the SQL column name from the JS key using the target database's conventional casing. Both `cloudflare-d1` and `neon` default to **`snake_case`** (`organizationId` → `organization_id`).
@@ -397,15 +511,23 @@ export default feature('line_items', {
397
511
  | `check: [{ name, sql }]` | `CONSTRAINT "<name>" CHECK (<sql>)` |
398
512
  | `unique: [{ columns }]` | `CREATE UNIQUE INDEX …` |
399
513
  | `unique: [{ columns, where: '…' }]` | `CREATE UNIQUE INDEX … WHERE …` (a partial unique index) |
514
+ | `unique: [{ columns, where: { deletedAt: null, status: 'active' } }]` | `CREATE UNIQUE INDEX … WHERE "deleted_at" IS NULL AND "status" = 'active'` |
400
515
  | `unique: [{ columns, whereNotDeleted: true }]` | `CREATE UNIQUE INDEX … WHERE "deleted_at" IS NULL` |
401
516
  | `unique: [{ columns, nullsNotDistinct: true }]` | `CONSTRAINT … UNIQUE NULLS NOT DISTINCT (…)`. Postgres 15+ only. |
402
517
 
403
518
  **How the SQL is written.** Column-level `.check(expr)` is appended to the
404
519
  quoted physical column name, as `"<column>" <expr>`. Write only what follows
405
520
  the column: `'> 0'`, `"IN ('draft', 'open')"`, `'BETWEEN 1 AND 5'`. The
406
- table-level `sql` and the unique `where` are complete expressions over the
521
+ table-level `sql` and a string unique `where` are complete expressions over the
407
522
  **physical (snake_case) column names**: `product_id`, not `productId`.
408
523
 
524
+ The **object form** of `where` takes the JS column names and renders the
525
+ physical ones for you, AND-joined. Each value is a literal: `null`
526
+ (`IS NULL`), `{ notNull: true }` (`IS NOT NULL`), a string, a finite number,
527
+ or a boolean (`= TRUE` / `= FALSE`, valid on Postgres and on the SQLite D1
528
+ ships). A key that is not a column of the table, or any other value, is a
529
+ compile error.
530
+
409
531
  **Nothing is translated per dialect.** The SQL must be valid for your
410
532
  database. `num_nonnulls(a, b, c) = 1` works on Postgres only. On D1, write
411
533
  `(a IS NOT NULL) + (b IS NOT NULL) + (c IS NOT NULL) = 1`. An invalid
@@ -424,6 +546,7 @@ from source, and it fails the compile on any of the following:
424
546
  - a value that isn't a literal
425
547
  - an unknown key
426
548
  - `where` together with `whereNotDeleted`
549
+ - an object `where` naming an unknown column, or a non-literal value
427
550
  - `nullsNotDistinct` on a partial unique
428
551
  - `whereNotDeleted` on a table without `...q.softDelete()`
429
552
  - `nullsNotDistinct` in a SQLite/D1 project, since SQLite always treats NULLs
@@ -452,8 +575,8 @@ created again. The insert returns `409 DB_UNIQUE_VIOLATION` against a row the
452
575
  caller can no longer see. Column-level `.unique()` has the same problem.
453
576
 
454
577
  On a soft-delete table, make the unique **partial**. `whereNotDeleted: true`
455
- adds `WHERE "deleted_at" IS NULL`, using the table's actual soft-delete column
456
- under your naming convention. Uniqueness then holds among live rows only, and
578
+ (or the object form `where: { deletedAt: null }`) adds `WHERE "deleted_at" IS NULL`,
579
+ using the table's actual soft-delete column under your naming convention. Uniqueness then holds among live rows only, and
457
580
  a deleted value can be reused. Restoring a soft-deleted row whose value a live
458
581
  row has since taken fails with a unique violation. That is the correct
459
582
  outcome, because the two rows would otherwise collide.
@@ -913,7 +1036,9 @@ The platform provides the pieces for an explicit policy:
913
1036
  - **Aggregate deletion** — use database foreign keys with
914
1037
  `onDelete: 'cascade'` for same-database ownership, and orchestrate
915
1038
  cross-database records, R2 objects, and external systems from an explicit
916
- offboarding action or queued job.
1039
+ offboarding action or queued job. For a whole organization,
1040
+ [`tenancy.purge`](/configure/tenancy) derives the table list from the
1041
+ firewall and deletes the rows' storage-key objects with them.
917
1042
  - **Encrypted data** — deleting an organization's wrapped DEK makes its
918
1043
  envelope-encrypted fields unreadable, provided no backup or export still
919
1044
  holds that row ([crypto-shredding](/define/encryption#per-organization-keys-blast-radius-and-crypto-shredding)
@@ -1123,9 +1248,25 @@ files sit at `features/<feature>/`. The thunk names a real binding; without
1123
1248
  the import the generated schema fails migration generation.
1124
1249
 
1125
1250
  Do this even when a column name appears obvious, such as `sessionId` beside a
1126
- `sessions` table. A matching `*Id` name is a useful compiler suggestion when a
1127
- relationship might be missing; it is not enough evidence to silently invent
1128
- one. CMS-ready schemas state the relationship explicitly.
1251
+ `sessions` table. A matching `*Id` name is not enough evidence to silently
1252
+ invent a relationship, so the compiler refuses the omission instead:
1253
+ [`SCHEMA_UNDECLARED_FK`](/define/diagnostics#schema-and-config-codes) fails the
1254
+ build when a `*Id` column names a feature table in the same database, is
1255
+ client-writable or used in a firewall / relationship arm, and declares no
1256
+ `.references()`. When the column genuinely is not a pointer into that table,
1257
+ say so with a reason:
1258
+
1259
+ {/* doc-compile: skip — one-key excerpt of a defineTable config */}
1260
+ ```typescript
1261
+ references: {
1262
+ cventEventId: { references: false, reason: 'Cvent-side id; no row in this database' },
1263
+ },
1264
+ ```
1265
+
1266
+ When both tables carry an org column, also declare
1267
+ [`match`](#match-a-referenced-rows-parent) on it —
1268
+ `SCHEMA_FK_MATCH_REQUIRED` warns until you do, or until you opt out with
1269
+ `references: { eventId: { match: false, reason: '…' } }`.
1129
1270
 
1130
1271
  ### Self-references
1131
1272
 
@@ -681,6 +681,76 @@ the matched row's PK too — so the arm above is **one arm that serves both** a
681
681
  logged-in attendee and a sessionless one. (It is distinct from
682
682
  `ctx.scope.event.id`, which is the *instance* — the event.)
683
683
 
684
+ ### `ctx.self` — the caller's own row
685
+
686
+ `subjectId` gives one firewall arm for both principals, but an action body
687
+ still needs the *row*: a logged-in attendee is found by `linkedUserId =
688
+ ctx.userId`, a pass holder by `id = ctx.scope.event.subjectId`, and every action
689
+ that touches "my" data repeats that branch. Declare it once on the role:
690
+
691
+ ```typescript
692
+ // quickback.config.ts
693
+ scopes: {
694
+ event: {
695
+ requestField: 'eventId',
696
+ roles: {
697
+ attendee: {
698
+ via: 'attendeeOf',
699
+ subject: 'both',
700
+ self: {
701
+ table: 'guests',
702
+ exposeAs: 'guest',
703
+ by: { session: 'linkedUserId', subject: 'id' }, // instance: 'eventId' (default: requestField)
704
+ recheck: { status: 'confirmed', deletedAt: null },
705
+ },
706
+ },
707
+ },
708
+ },
709
+ }
710
+ ```
711
+
712
+ Every action then sees **`ctx.self.guest`**, typed as the `guests` row or
713
+ `null` — one code path for both principals:
714
+
715
+ ```typescript
716
+ async execute({ ctx }) {
717
+ const me = ctx.self.guest; // same row for a session user and a pass holder
718
+ if (!me) throw new ActionError('Not an attendee of this event', 'NOT_ATTENDEE', 403);
719
+ }
720
+ ```
721
+
722
+ How it resolves, on **every** action request, before the action's access check:
723
+
724
+ - The caller must hold `scope:<kind>:<role>` for an instance
725
+ (`ctx.scope.<kind>` — from a scope token, or the namespace refresh). Anyone
726
+ else (an org admin admitted by a `{ roles }` lane) gets `null`: the lane
727
+ carries no self.
728
+ - One row of `self.table` is loaded, pinned to the caller —
729
+ `by.session = ctx.userId` for a Better Auth session, otherwise
730
+ `by.subject = ctx.scope.<kind>.subjectId` — to the instance
731
+ (`by.instance = ctx.scope.<kind>.id`), and to every `recheck` condition
732
+ (`null` = IS NULL, an array = one of), through the table's own firewall
733
+ (soft-delete applies; tenant scopes are skipped exactly as for a relationship
734
+ probe — the pins are the boundary).
735
+ - **`recheck` is a per-request re-proof.** A carried scope claim is trusted
736
+ between proofs (see [Revocation & TTL](#revocation--ttl)); when no row passes
737
+ the recheck, `ctx.self.<exposeAs>` is `null` **and the role is withdrawn
738
+ from `ctx.scope.<kind>.roles` for that request**, so every gate that relied
739
+ on it denies. A guest who stopped being `confirmed` loses the attendee role
740
+ at their next action, not at the token's TTL.
741
+
742
+ Defaults and checks (compile time):
743
+
744
+ | Key | Default | Required when |
745
+ |---|---|---|
746
+ | `by.session` | the relationship's `subject.column`, when `table` is its `from` table bound to `ctx.userId` | the role is user-provable (`subject: 'user' \| 'both'`) and `table` is another table. Rejected on `subject: 'supplied'`. |
747
+ | `by.subject` | `'id'` when `table` is the relationship's `from` table (`subjectId` is that row's PK) | the role is supplied-provable (`'supplied' \| 'both'`) and `table` is another table. Rejected on `subject: 'user'`. |
748
+ | `by.instance` | the scope's `requestField` | — |
749
+
750
+ `exposeAs` must be unique across every declared `self`. Refs can name the
751
+ caller's row as their ownership subject —
752
+ [`ownedVia: { …, subject: 'ctx.self.guest' }`](/define/actions/defining#id-arrays-parent-state-and-mine-through-a-junction).
753
+
684
754
  ### Realtime
685
755
 
686
756
  A scope-only token authorizes the realtime
@@ -717,9 +787,18 @@ ctx.scope?: Record<string, { id: string; roles?: string[]; subjectId?: string; [
717
787
  via: string;
718
788
  subKeys?: string[]; // 'col' → eq, 'col[]' → inArray
719
789
  subject?: 'user' | 'supplied' | 'both'; // who selects the conferring row (default 'user')
790
+ self?: { // ctx.self.<exposeAs> — the caller's own row
791
+ table: string;
792
+ exposeAs: string;
793
+ by?: { session?: string; subject?: string; instance?: string };
794
+ recheck?: Record<string, string | number | boolean | null | Array<string | number>>;
795
+ };
720
796
  }>;
721
797
  }
722
798
 
799
+ // ctx.self — present in actions when any scoped role declares `self`
800
+ ctx.self: { [exposeAs]: Row | null };
801
+
723
802
  // ctx.mintScope — present in actions when a `subject: 'supplied' | 'both'` role is declared
724
803
  ctx.mintScope(opts: { via: string; subject: string; setAuthToken?: boolean }):
725
804
  Promise<{ token: string; scope: { id: string; roles: string[]; subjectId?: string } }>;