@quickback-dev/cli 0.70.31 → 0.70.40

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 (127) hide show
  1. package/dist/commands/build.d.ts +12 -0
  2. package/dist/commands/build.d.ts.map +1 -1
  3. package/dist/commands/build.js +69 -1
  4. package/dist/commands/build.js.map +1 -1
  5. package/dist/commands/deploy.d.ts +9 -0
  6. package/dist/commands/deploy.d.ts.map +1 -1
  7. package/dist/commands/deploy.js +20 -2
  8. package/dist/commands/deploy.js.map +1 -1
  9. package/dist/commands/migrate-data.d.ts +12 -0
  10. package/dist/commands/migrate-data.d.ts.map +1 -0
  11. package/dist/commands/migrate-data.js +134 -0
  12. package/dist/commands/migrate-data.js.map +1 -0
  13. package/dist/commands/migrate.d.ts.map +1 -1
  14. package/dist/commands/migrate.js +11 -0
  15. package/dist/commands/migrate.js.map +1 -1
  16. package/dist/commands/secrets.d.ts +27 -0
  17. package/dist/commands/secrets.d.ts.map +1 -0
  18. package/dist/commands/secrets.js +186 -0
  19. package/dist/commands/secrets.js.map +1 -0
  20. package/dist/index.js +23 -3
  21. package/dist/index.js.map +1 -1
  22. package/dist/lib/access-manifest-diff.d.ts +87 -0
  23. package/dist/lib/access-manifest-diff.d.ts.map +1 -0
  24. package/dist/lib/access-manifest-diff.js +331 -0
  25. package/dist/lib/access-manifest-diff.js.map +1 -0
  26. package/dist/lib/artifact-routing.d.ts.map +1 -1
  27. package/dist/lib/artifact-routing.js +3 -0
  28. package/dist/lib/artifact-routing.js.map +1 -1
  29. package/dist/lib/compiler-stubs.d.ts +2 -0
  30. package/dist/lib/compiler-stubs.d.ts.map +1 -1
  31. package/dist/lib/compiler-stubs.js +2 -0
  32. package/dist/lib/compiler-stubs.js.map +1 -1
  33. package/dist/lib/file-loader.d.ts +6 -0
  34. package/dist/lib/file-loader.d.ts.map +1 -1
  35. package/dist/lib/file-loader.js +17 -0
  36. package/dist/lib/file-loader.js.map +1 -1
  37. package/dist/lib/ops-manifest.d.ts +76 -0
  38. package/dist/lib/ops-manifest.d.ts.map +1 -0
  39. package/dist/lib/ops-manifest.js +94 -0
  40. package/dist/lib/ops-manifest.js.map +1 -0
  41. package/dist/lib/release-and-pin.d.ts +34 -0
  42. package/dist/lib/release-and-pin.d.ts.map +1 -0
  43. package/dist/lib/release-and-pin.js +71 -0
  44. package/dist/lib/release-and-pin.js.map +1 -0
  45. package/dist/lib/shell.d.ts +4 -1
  46. package/dist/lib/shell.d.ts.map +1 -1
  47. package/dist/lib/shell.js +8 -3
  48. package/dist/lib/shell.js.map +1 -1
  49. package/dist/skill/docs/api/actions.md +2 -0
  50. package/dist/skill/docs/api/batch-operations.md +18 -4
  51. package/dist/skill/docs/api/crud.md +62 -0
  52. package/dist/skill/docs/api/errors.md +17 -2
  53. package/dist/skill/docs/configure/auth.md +49 -2
  54. package/dist/skill/docs/configure/bindings.md +15 -0
  55. package/dist/skill/docs/configure/domains.md +4 -0
  56. package/dist/skill/docs/configure/index.md +29 -11
  57. package/dist/skill/docs/configure/tenancy.md +117 -0
  58. package/dist/skill/docs/define/access.md +19 -0
  59. package/dist/skill/docs/define/actions/access.md +76 -0
  60. package/dist/skill/docs/define/actions/defining.md +156 -1
  61. package/dist/skill/docs/define/actions/scoped-db.md +236 -9
  62. package/dist/skill/docs/define/areas.md +46 -0
  63. package/dist/skill/docs/define/authz-roles.md +10 -0
  64. package/dist/skill/docs/define/diagnostics.md +263 -0
  65. package/dist/skill/docs/define/encryption.md +32 -0
  66. package/dist/skill/docs/define/guards.md +13 -0
  67. package/dist/skill/docs/define/masking.md +77 -3
  68. package/dist/skill/docs/define/rate-limit.md +3 -3
  69. package/dist/skill/docs/define/schema.md +148 -7
  70. package/dist/skill/docs/define/scopes.md +79 -0
  71. package/dist/skill/docs/define/transitions.md +39 -0
  72. package/dist/skill/docs/define/views.md +77 -3
  73. package/dist/skill/docs/platform/api-contract/index.md +4 -0
  74. package/dist/skill/docs/platform/auth/jwt-optimization.md +2 -0
  75. package/dist/skill/docs/platform/auth/plugins/aws-ses.md +4 -3
  76. package/dist/skill/docs/platform/auth/using-auth.md +6 -0
  77. package/dist/skill/docs/platform/database/d1.md +47 -0
  78. package/dist/skill/docs/platform/database/data-migrations.md +109 -0
  79. package/dist/skill/docs/platform/database/read-replication.md +142 -7
  80. package/dist/skill/docs/platform/payments/one-off-checkout.md +6 -1
  81. package/dist/skill/docs/platform/push/index.md +2 -0
  82. package/dist/skill/docs/platform/realtime/partyserver-rooms.md +95 -9
  83. package/dist/skill/docs/platform/storage/using-r2.md +135 -19
  84. package/dist/skill/docs/start/deploy.md +38 -0
  85. package/dist/skill/docs/tooling/cli.md +120 -0
  86. package/dist/skill/docs/tooling/cloud-compiler/troubleshooting.md +13 -13
  87. package/dist/skill/docs/tooling/output.md +70 -2
  88. package/package.json +1 -1
  89. package/src/skill/docs/api/actions.md +2 -0
  90. package/src/skill/docs/api/batch-operations.md +18 -4
  91. package/src/skill/docs/api/crud.md +62 -0
  92. package/src/skill/docs/api/errors.md +17 -2
  93. package/src/skill/docs/configure/auth.md +49 -2
  94. package/src/skill/docs/configure/bindings.md +15 -0
  95. package/src/skill/docs/configure/domains.md +4 -0
  96. package/src/skill/docs/configure/index.md +29 -11
  97. package/src/skill/docs/configure/tenancy.md +117 -0
  98. package/src/skill/docs/define/access.md +19 -0
  99. package/src/skill/docs/define/actions/access.md +76 -0
  100. package/src/skill/docs/define/actions/defining.md +156 -1
  101. package/src/skill/docs/define/actions/scoped-db.md +236 -9
  102. package/src/skill/docs/define/areas.md +46 -0
  103. package/src/skill/docs/define/authz-roles.md +10 -0
  104. package/src/skill/docs/define/diagnostics.md +263 -0
  105. package/src/skill/docs/define/encryption.md +32 -0
  106. package/src/skill/docs/define/guards.md +13 -0
  107. package/src/skill/docs/define/masking.md +77 -3
  108. package/src/skill/docs/define/rate-limit.md +3 -3
  109. package/src/skill/docs/define/schema.md +148 -7
  110. package/src/skill/docs/define/scopes.md +79 -0
  111. package/src/skill/docs/define/transitions.md +39 -0
  112. package/src/skill/docs/define/views.md +77 -3
  113. package/src/skill/docs/platform/api-contract/index.md +4 -0
  114. package/src/skill/docs/platform/auth/jwt-optimization.md +2 -0
  115. package/src/skill/docs/platform/auth/plugins/aws-ses.md +4 -3
  116. package/src/skill/docs/platform/auth/using-auth.md +6 -0
  117. package/src/skill/docs/platform/database/d1.md +47 -0
  118. package/src/skill/docs/platform/database/data-migrations.md +109 -0
  119. package/src/skill/docs/platform/database/read-replication.md +142 -7
  120. package/src/skill/docs/platform/payments/one-off-checkout.md +6 -1
  121. package/src/skill/docs/platform/push/index.md +2 -0
  122. package/src/skill/docs/platform/realtime/partyserver-rooms.md +95 -9
  123. package/src/skill/docs/platform/storage/using-r2.md +135 -19
  124. package/src/skill/docs/start/deploy.md +38 -0
  125. package/src/skill/docs/tooling/cli.md +120 -0
  126. package/src/skill/docs/tooling/cloud-compiler/troubleshooting.md +13 -13
  127. package/src/skill/docs/tooling/output.md +70 -2
@@ -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 } }>;
@@ -127,6 +127,45 @@ Semantics:
127
127
  writes into a `q.timestamp()` column as-is, on every database and every
128
128
  `db` handle — see [Column types](/define/schema#decimals-dates-64-bit-integers-and-arrays).
129
129
 
130
+ ### Concurrency: the guard is in the UPDATE
131
+
132
+ D1 has no transaction across statements, so a transition that read the row
133
+ and then wrote it by id would let two concurrent requests both succeed (two
134
+ scanners checking in one guest). The compiler-applied write never does that:
135
+ the UPDATE itself carries the state it checked.
136
+
137
+ ```sql
138
+ -- field transition (close: open → closed)
139
+ UPDATE tickets SET status = 'closed', modified_at = ?, …
140
+ WHERE <firewall> AND id = ? AND status = 'open' -- the from-state it read
141
+ RETURNING *;
142
+
143
+ -- stamp-only transition (checkIn, guard: { checkedInAt: { null: true } })
144
+ UPDATE guests SET checked_in_at = ?, checked_in_by_id = ?, …
145
+ WHERE <firewall> AND id = ? AND status = 'confirmed' AND checked_in_at IS NULL
146
+ RETURNING *;
147
+ ```
148
+
149
+ The WHERE pins the exact value the pre-check saw (a compare-and-set), which is
150
+ stricter than `status IN (<every from-state>)`: if a twin moved the row
151
+ between two legal source states, the stale request loses instead of acting on
152
+ a row it never checked. When two requests race:
153
+
154
+ - one UPDATE matches and wins (`200`);
155
+ - the other sees the new state in its pre-check (`409
156
+ ACCESS_ACTION_NOT_ALLOWED_FOR_STATE` / `onIllegal`), or matches no row at the
157
+ UPDATE (`409 ACCESS_TRANSITION_LOST`);
158
+ - with `idempotent: "noop"`, a request that loses to a twin that already
159
+ reached the target answers `{ success: true, unchanged: true }`, exactly as
160
+ if it had arrived second.
161
+
162
+ This holds for every table-level transition (the compiler always applies the
163
+ write) and every action-level `transition` with `stamp`, `clears`,
164
+ `applyBefore: true` or no `execute`. A hand-written `execute` that does its own
165
+ write must use `whereTransition(table)` in its WHERE and throw
166
+ `TransitionLostError` on an empty `RETURNING` — a write by `whereRecord` alone
167
+ is the race.
168
+
130
169
  ### On a feature-area route
131
170
 
132
171
  A transition normally lives on a table-bound record action (`POST /:id/{action}`).
@@ -318,11 +318,12 @@ Response now carries the aggregations alongside `data`:
318
318
  | `count` | optional | `COUNT(*)` if omitted, `COUNT(field)` (non-null) if given | `{ fn: 'count' }` |
319
319
  | `count_distinct` | required | scalar number | `{ fn: 'count_distinct', field: 'sourceId' }` |
320
320
  | `groupBy` | required | `{ value: count }` map | `{ fn: 'groupBy', field: 'status' }` |
321
+ | `rollup` | — (`groupBy`, `count`, `sum`) | array of bucket rows | `{ fn: 'rollup', groupBy: 'optionId', count: true, sum: ['weight'] }` |
321
322
 
322
323
  `groupBy` always returns a count map keyed by the distinct values of `field`.
323
- `NULL` values bucket under the literal string `"(none)"`. Other rollup
324
- functions (`groupBy` + `sum` of another column) are deferred to a future
325
- release.
324
+ `NULL` values bucket under the literal string `"(none)"`. To sum other
325
+ columns per bucket, use a [declared rollup](#declared-rollups-fn-rollup) on
326
+ an aggregate-only view.
326
327
 
327
328
  ### Filter and firewall inheritance
328
329
 
@@ -427,6 +428,79 @@ buckets ("1 guest, allergy = shellfish"):
427
428
  row-returning views, where the aggregations ride alongside the rows and the
428
429
  row firewall already governs disclosure.
429
430
 
431
+ ### Declared rollups (`fn: 'rollup'`)
432
+
433
+ A rollup is the grouped aggregate an action would otherwise compute in
434
+ JavaScript — and actions can't run raw aggregates. It emits one firewalled
435
+ `SELECT <groupBy>, COUNT(*), SUM(<col>)… GROUP BY <groupBy>` over the view's
436
+ filtered set, and each returned row carries the bucket and its totals — never
437
+ a row id or a subject. A caller who may not read individual ballots can read
438
+ the tally if the view's `access` admits them:
439
+
440
+ ```typescript
441
+ import { feature, q } from '@quickback/compiler';
442
+
443
+ export default feature('votes', {
444
+ columns: {
445
+ id: q.id(),
446
+ pollId: q.text().required(),
447
+ optionId: q.text().required(),
448
+ weight: q.int().default(1).required(),
449
+ organizationId: q.scope('organization'),
450
+ ...q.audit(),
451
+ ...q.softDelete(),
452
+ },
453
+ guards: { createable: ['pollId', 'optionId', 'weight'], updatable: [] },
454
+ read: {
455
+ access: { roles: ['admin'] }, // individual ballots: admins only
456
+ views: {
457
+ tally: {
458
+ aggregateOnly: true,
459
+ fields: [],
460
+ kMin: 1, // a poll tally may show single votes
461
+ access: { roles: ['member', 'admin'] },
462
+ query: { filterable: ['pollId'] },
463
+ aggregations: {
464
+ tally: { fn: 'rollup', groupBy: 'optionId', count: true, sum: ['weight'] },
465
+ },
466
+ },
467
+ },
468
+ },
469
+ create: { access: { roles: ['member', 'admin'] } },
470
+ update: { access: { roles: ['admin'] } },
471
+ delete: { access: { roles: ['admin'] }, mode: 'soft' },
472
+ });
473
+ ```
474
+
475
+ `GET /api/v1/votes/views/tally?pollId=p1` returns:
476
+
477
+ ```json
478
+ {
479
+ "view": "tally",
480
+ "aggregations": {
481
+ "tally": [
482
+ { "optionId": "opt_a", "count": 12, "sum": { "weight": 15 } },
483
+ { "optionId": "opt_b", "count": 7, "sum": { "weight": 7 } }
484
+ ]
485
+ }
486
+ }
487
+ ```
488
+
489
+ - `groupBy` names one column; `count: true` adds the bucket size; `sum` lists
490
+ numeric columns, returned under `sum`. At least one of `count` / `sum`.
491
+ - Only on `aggregateOnly: true` views — a rollup is its own surface, gated by
492
+ its own `access`, never a side-channel of a row view. `kMin` applies:
493
+ buckets smaller than k fold into one `"(other)"` row, and a non-empty set
494
+ smaller than k returns `"(suppressed)"`.
495
+ - **The bucket may not identify a subject.** Grouping by the primary key, the
496
+ owner column, a `q.stamp()` identity column, `createdBy` / `modifiedBy` /
497
+ `deletedBy`, a reference to the auth user table, or an encrypted column is
498
+ a compile error — one bucket per subject is a per-subject read.
499
+ - A masked `groupBy` or `sum` column needs every role that can reach the view
500
+ to be in its masking query roles (the `groupBy` / `min` / `max` rule
501
+ above), and at request time a caller who may not query one of them gets
502
+ `"(suppressed)"`.
503
+
430
504
  ## Response Format
431
505
 
432
506
  View responses include metadata about the view:
@@ -84,6 +84,10 @@ caller-generated UUID, ≤ 255 chars) to make the write safe to retry:
84
84
  - Keys expire after **24 hours** (Stripe semantics); 5xx and `Set-Cookie`
85
85
  responses release the lock instead of caching.
86
86
 
87
+ The key is per **request**. For "this client-side record exists exactly
88
+ once" across sessions and devices, store a per-**row** token instead — see
89
+ [Row-token idempotency](/api/crud#row-token-idempotency).
90
+
87
91
  **Claims are bound to the calling principal.** A replay from a different
88
92
  principal — another user, another scope subject, a delegated machine
89
93
  principal, or a legacy row with no principal — is refused with a `422`
@@ -125,6 +125,8 @@ There is no same-second gap: markers are epoch milliseconds (written `m<ms>`), t
125
125
  Revocation stamps are written **automatically** on:
126
126
 
127
127
  - user ban
128
+ - the target of the admin plugin's `/admin/set-role`, `/admin/remove-user`, `/admin/update-user`, and `/admin/revoke-user-sessions`
129
+ - every [`ctx.auth`](/define/actions/scoped-db#ctxauth--better-auth-users-and-members-org-bound) write (ban, role change, account deletion)
128
130
  - org-member removal and member role change (Better Auth `organizationHooks`)
129
131
  - `UPDATE` / `DELETE` of scope-conferring relationship rows
130
132
 
@@ -80,16 +80,17 @@ const esc = (v: string) =>
80
80
  .replace(/"/g, '&quot;').replace(/'/g, '&#39;');
81
81
 
82
82
  export default function welcomeTemplate({ otp, name, appName, appUrl }: Input) {
83
- const greeting = name ? `Hi ${name},` : 'Hi,';
83
+ // Plain text: TEMPLATE_UNESCAPED skips names containing `text`, `subject`, or `plain`.
84
+ const greetingText = name ? `Hi ${name},` : "Hi,";
84
85
  return {
85
86
  subject: `Welcome to ${appName} — set your password`,
86
87
  html: `
87
88
  <h1>Welcome to ${esc(appName)}</h1>
88
- <p>${esc(greeting)} your account is ready. Use this code to set your password and sign in:</p>
89
+ <p>${esc(greetingText)} your account is ready. Use this code to set your password and sign in:</p>
89
90
  <p style="font-size:32px;letter-spacing:8px"><b>${esc(otp)}</b></p>
90
91
  <p>Visit <a href="${esc(appUrl)}/set-password">${esc(appUrl)}/set-password</a> to finish setup.</p>
91
92
  `,
92
- text: `${greeting}\n\nYour ${appName} code: ${otp}\n\nFinish setup at ${appUrl}/set-password`,
93
+ text: `${greetingText}\n\nYour ${appName} code: ${otp}\n\nFinish setup at ${appUrl}/set-password`,
93
94
  };
94
95
  }
95
96
  ```
@@ -114,6 +114,12 @@ export default defineConfig({
114
114
  - The column set is fixed. Sessions, accounts and credentials are never returned.
115
115
  - `roles` is required, and the organization plugin must be enabled — otherwise the compile fails.
116
116
 
117
+ ## Changing users from actions — `ctx.auth`
118
+
119
+ Action code that bans a user, changes a member's role, deletes an account, or lists an organization's members uses `ctx.auth` — typed, bound to the caller's active organization, written through Better Auth's adapter, and stamping the `qbrev:user` [revocation entry](/configure/auth#revocationcheck-none--kv--token-revocation-strategy) so outstanding JWTs die. Never write the auth tables through `authDb`. Full reference: [`ctx.auth`](/define/actions/scoped-db#ctxauth--better-auth-users-and-members-org-bound).
120
+
121
+ Rows addressed to an email before the account exists (invitations, guest lists) can be linked automatically when the account verifies that email: [`auth.claims`](/configure/auth#authclaims--link-rows-to-the-account-that-verifies-their-email).
122
+
117
123
  ## Related
118
124
 
119
125
  - [Auth Overview](/platform/auth) — Setup and configuration
@@ -225,6 +225,53 @@ binding name unchanged across environments; only the stateful identifiers —
225
225
  `database_id`, queue names, bucket names (and optionally `database_name`) —
226
226
  are per-environment.
227
227
 
228
+ ### Inheriting from another target (`extends`)
229
+
230
+ A staging target is usually production with different identities. Instead of
231
+ copying production's block, extend it and list only what differs:
232
+
233
+ {/* doc-compile: skip — excerpt of the `environments` block; `production` is the entry shown above. */}
234
+ ```typescript title="quickback/quickback.config.ts"
235
+ environments: {
236
+ production: { /* … as above … */ },
237
+ staging: {
238
+ extends: "production",
239
+ name: "my-app-staging",
240
+ domain: "api-staging.example.com",
241
+ worker: {
242
+ env: "staging",
243
+ vars: { BETTER_AUTH_URL: "https://api-staging.example.com" },
244
+ bindings: {
245
+ d1: {
246
+ auth: { databaseId: "…" },
247
+ features: { databaseId: "…" },
248
+ },
249
+ },
250
+ },
251
+ },
252
+ },
253
+ ```
254
+
255
+ The compiler resolves `extends` before anything else reads the config. The
256
+ validator, the `[env.*]` emitter, the hostname resolver, and the ops manifest
257
+ all see one complete target, so the generated `[env.staging]` stanza is as
258
+ complete as a hand-written one. The rules:
259
+
260
+ - **Objects merge key by key, arrays and scalars replace.** In the example,
261
+ `worker.vars` keeps production's other vars and overrides
262
+ `BETTER_AUTH_URL`. `requiredSecrets`, `workersDev`, `previewUrls`,
263
+ `placement` and the email binding are inherited unchanged.
264
+ - **Identity and state are never inherited.** `name`, `domain` / `domains`,
265
+ `filesWorker`, `branch`, `worker.env`, and the stateful bindings `d1`, `kv`,
266
+ `hyperdrive`, `queues`, `r2Buckets` and `rateLimits` must be restated. If
267
+ any were inherited, a staging deploy would run on production's script,
268
+ hostnames, or data. If one is missing, the usual per-target errors name it
269
+ (for example, *must declare bindings.d1.features.databaseId*). When
270
+ production gains a new database role, every child that has not restated it
271
+ fails the compile, so a staging target cannot silently drift.
272
+ - **Chains are allowed. A cycle or an unknown parent is a compile error** that
273
+ names the chain (`staging → preview → staging`).
274
+
228
275
  ### Queues and R2 buckets per target
229
276
 
230
277
  Queue names and R2 bucket names are stateful, so repeating the primary value