@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
@@ -266,6 +266,46 @@ completeness uses the same route key as the emitted OpenAPI and MCP
266
266
  surfaces. The same normalization applies when a record resource path contains
267
267
  namespace parameters.
268
268
 
269
+ ### Masking action output (`outputMask`)
270
+
271
+ An action returns whatever `execute` returns. CRUD reads run every row
272
+ through the table's [masking](/define/masking) rules for the caller; an
273
+ action's result does not get that for free, because the compiler cannot tell
274
+ a row from any other object. Declare it:
275
+
276
+ ```typescript
277
+ // The action's own table: the record (or rows of it) is masked exactly like GET /guests/:id.
278
+ outputMask: 'source',
279
+
280
+ // Another table's rows, inside a wrapper: { pollId, ballots: [...] }.
281
+ outputMask: { table: 'votes', path: 'ballots' },
282
+ ```
283
+
284
+ The compiler applies the target table's generated mask function — the same
285
+ one the CRUD routes call — to the value at `path` (or to the whole result),
286
+ with the caller's roles. It handles a single row and an array of rows, on the
287
+ per-record route, the [bulk variant](#bulk-variant) (each result masked on
288
+ its own), and standalone actions.
289
+
290
+ It fails closed in three places:
291
+
292
+ - **Compile time.** An unknown table, a table that masks no columns (the
293
+ declaration would do nothing), or `'source'` on a standalone action with no
294
+ `record:` binding is a compile error. `outputMask` on a `stream` or `file`
295
+ action is too.
296
+ - **Runtime shape check.** The target must be a row of that table, or an
297
+ array of them, each carrying the table's primary key. A wrapper object, a
298
+ missing `path`, or an element that is not a row throws (the route answers
299
+ 500 and logs it) rather than returning the value unmasked — an object that
300
+ is not a row would otherwise pass through the mask function untouched.
301
+ - **`null` / `undefined`** carry no data and pass through.
302
+
303
+ `outputMask` and `output:` compose: the result is parsed through the
304
+ declared contract first, then masked. Without `outputMask`, a record-based
305
+ action keeps the older behaviour — its result is masked as one row of the
306
+ bound table when that table has masking rules, and anything else is returned
307
+ as-is.
308
+
269
309
  ### Configuration Options
270
310
 
271
311
  | Option | Required | Description |
@@ -274,7 +314,7 @@ namespace parameters.
274
314
  | `input` | Yes | Zod schema for request validation |
275
315
  | `query` | No | Non-GET only. An inline `z.object({...})` of query-string parameters, validated apart from the JSON body and passed to `execute` as `query`. See [Query parameters on non-GET actions](/define/actions/record-and-standalone#query-parameters-on-non-get-actions) |
276
316
  | `output` | No | Portable Zod schema for the JSON success response. Generates action output types and constrains `execute`'s result. |
277
- | `access` | Yes | Access control (roles, record conditions, or function) |
317
+ | `access` | Yes | Access control (roles, record conditions, or function), or input-conditioned `arms` — see [Arms conditioned on input](/define/actions/access#arms-conditioned-on-input-accessarms) |
278
318
  | `execute` | Yes | Inline async arrow function (`async (ctx) => { … }`) |
279
319
  | `path` | Standalone only | Custom route path. Presence of `path` makes the action standalone. |
280
320
  | `method` | No | HTTP method: GET, POST, PUT, PATCH, DELETE (default: POST). GET actions parse `input` from query params; all other methods parse from the JSON body. See [GET vs POST for input](#get-vs-post-for-input). |
@@ -283,16 +323,72 @@ namespace parameters.
283
323
  | `allowRawSql` | No | Explicit compile-time opt-in for raw SQL in execute code |
284
324
  | `unsafe` | No | Unsafe raw DB mode. Object config (`reason`, `adminOnly`, `crossTenant`, `targetScope`). |
285
325
  | `transition` | No | State-machine policy enforcing the from/to pair. Lives on a record-based action, or on a standalone action paired with a `record:` binding. See [Transitions](/define/transitions) |
326
+ | `refs` | No | Scoped foreign-key inputs: load + firewall + 404 before `execute`, with `many`, `where`/`unmet`, and `ownedVia`. See [Refs](#refs-scoped-foreign-key-inputs) |
286
327
  | `record` | Standalone only | Feature-area transition adapter binding: `{ table, idFrom: "path.<param>", matchScope? }`. Binds + firewalls the record a `transition` operates on from a proven route param. See [Feature-area transition adapter](#feature-area-transition-adapter) |
287
328
  | `bulkVariant` | No | Auto-generate a `POST /:resource/batch/{action}` route alongside the per-record route (record-based actions). See [Bulk Variant](#bulk-variant) |
288
329
  | `webhook` | No | Standalone only. Compile-declared inbound signature verification (`standard-webhooks`, `hmac-sha256`, or `aws-sns`) that runs on the raw bytes **before** parse/access — see [Inbound webhooks](/platform/webhooks/inbound) |
289
330
  | `rawBody` | No | Standalone, non-GET only. Hand `execute` the request body as received (`rawBody: string`, bounded to 1 MiB) for signature schemes the compiler does not model — a per-organization secret stored in the database, a provider with its own canonicalisation. `input` still parses from the same bytes. Actions with `webhook:` receive `rawBody` automatically. The param is typed exactly that way: `rawBody: string` on those actions, absent on every other — see [Per-organization secrets](/platform/webhooks/inbound#per-organization-secrets-verify-in-the-action) |
290
331
  | `idempotency` | No | `'dedupe'` — PUBLIC-action opt-in for the `Idempotency-Key` header with dedupe-only semantics (duplicate ⇒ `409` reference; the cached body is never served to a second caller). Standalone actions with a **static** path only (a `:param` path is a compile error — the allowlist matches literal request paths) and the action's access must admit `PUBLIC`. Authenticated routes accept the header automatically — see [API contract](/platform/api-contract) |
291
332
  | `cms` | No | Pass-through metadata blob for CMS surfaces |
333
+ | `writes` | No | Platform-tier JSON keys this action may change: `{ '<column>' \| '<table>.<column>': ['<key>', …] }`. See [JSON key writes and requires](#json-key-writes-and-requires) |
334
+ | `requires` | No | A JSON key that must hold before `execute` runs, else 403 `ENTITLEMENT_REQUIRED`: `{ flag: '<key>' }` or `{ json: { column, key, truthy: true \| equals } }`, optionally `from: '<ref as>'`. See [JSON key writes and requires](#json-key-writes-and-requires) |
335
+ | `operator` | Standalone only | Operator lane: `{ target: { table, by: 'input.<field>', includeDeleted? } }` on a `userRole`-only action. Loads the target cross-tenant (404 when absent or soft-deleted), scopes `db` to its organization, passes the row as `target`, and audits every call against that tenant. Mutually exclusive with `unsafe`. See [Operator lane](/define/actions/scoped-db#operator-lane-operator) |
336
+ | `outputMask` | No | `'source'` or `{ table, path? }`. Masks the rows the action returns with that table's masking rules for the caller — see [Masking action output](#masking-action-output-outputmask) |
292
337
 
293
338
  `execute` must be an `async (ctx) => { … }` arrow function. `async function`
294
339
  declarations and non-async forms are rejected at parse time.
295
340
 
341
+ ## JSON key writes and requires
342
+
343
+ A typed JSON column can declare per-key write tiers with [`q.json(schema, { keys })`](/define/schema#per-key-write-authority-keys). Generic CRUD refuses its `platform` keys. Two action options work with those keys.
344
+
345
+ **`writes:` grants platform keys.** The scoped `db` lets an action change a platform key in one of two cases:
346
+
347
+ - the action's `access` names a `userRole` lane, and the caller's `user.role` matched one of those values. Every platform key is then open to the action;
348
+ - the action lists the key in `writes:`. Keys are `'<column>'` on the action's own table, or `'<table>.<column>'` for any table.
349
+
350
+ {/* doc-compile: skip — needs the keyed `projects` table from /define/schema; the tests/output-matrix/fixtures/json-key-tiers project compiles these actions. */}
351
+ ```typescript
352
+ // Platform operators: a userRole lane, so every platform key is open.
353
+ export default defineAction({
354
+ description: "Turn the beta key on or off",
355
+ input: z.object({ enabled: z.boolean() }),
356
+ access: { userRole: ["operator"] },
357
+ async execute({ db, record, input }) {
358
+ await db.update(projects)
359
+ .set({ settings: { ...(record.settings ?? {}), beta: input.enabled } })
360
+ .where(eq(projects.id, record.id));
361
+ return { beta: input.enabled };
362
+ },
363
+ });
364
+
365
+ // Org owners, granted exactly one platform key.
366
+ export default defineAction({
367
+ description: "Owners may grant beta",
368
+ input: z.object({ enabled: z.boolean() }),
369
+ access: { roles: ["owner"] },
370
+ writes: { settings: ["beta"] },
371
+ async execute({ db, record, input }) { /* same write */ },
372
+ });
373
+ ```
374
+
375
+ Any other action that changes or drops a platform key gets **422 `JSON_KEY_RESTRICTED`** from the write. Read-modify-write that carries the key over unchanged passes. `writes:` may name only platform keys. An organizer key needs no grant, and a `derivedFrom` key can never be written, so listing either is a compile error.
376
+
377
+ **`requires:` checks an entitlement before `execute`.** The check reads the action's record. On a standalone action, `from` must name one of its [`refs`](#refs-scoped-foreign-key-inputs). If the check fails, the route answers **403 `ENTITLEMENT_REQUIRED`** (`details: { column, key }`) and `execute` does not run.
378
+
379
+ {/* doc-compile: skip — fragments of action configs. */}
380
+ ```typescript
381
+ requires: { flag: "premiumExport" } // short form: the bound table's one keyed column, value === true
382
+ requires: { json: { column: "settings", key: "beta", truthy: true } } // any typed q.json column; `key` may be a path ("limits.sms")
383
+ requires: { json: { column: "settings", key: "tier", equals: "pro" } }
384
+ requires: { flag: "premiumExport", from: "project" } // reads the `project` ref row instead of the record
385
+ ```
386
+
387
+ - `flag` resolves against the one `q.json(..., { keys })` column on the bound table. If there are none or several, use the `json` form.
388
+ - `truthy` needs a `z.boolean()` at the key path. `equals` takes a string, number, boolean or `null` literal.
389
+ - A `derivedFrom` key is read from its source table, not from the stored column.
390
+ - `requires` is not supported with `bulkVariant: true`.
391
+
296
392
  ## Protected Fields
297
393
 
298
394
  Actions can modify fields that are protected from regular CRUD operations:
@@ -347,3 +443,62 @@ export default defineAction({
347
443
  - Ref keys must exist on the inline `z.object` input with agreeing
348
444
  optionality; `as` names can't shadow reserved context keys. Injected rows
349
445
  are the **unmasked** DB rows (masking remains a read-projection concern).
446
+ - Unknown keys on a ref are a compile error (a typo such as `idFrom` fails the
447
+ build instead of being ignored). The input field *is* the id source; there is
448
+ no `idFrom`.
449
+
450
+ ### Id arrays, parent state, and "mine through a junction"
451
+
452
+ Three more ref shapes cover what action bodies otherwise check by hand. Each is
453
+ independent and composes with `matchScope` / `matchWith`:
454
+
455
+ {/* doc-compile: skip — the refs name sibling tables (`bookings`, `booking_visitors`, `notices`) and a declared `ctx.self` that the isolated fence cannot declare; the whole project compiles in `tests/output-matrix/fixtures/refs-access-self`. */}
456
+ ```typescript
457
+ // features/sites/actions/confirmBookings.ts
458
+ export default defineAction({
459
+ description: "Confirm the caller's own bookings against a published notice.",
460
+ path: "/site/:siteId/bookings/confirm",
461
+ input: z.object({ bookingIds: z.array(z.string()).min(1).max(200), noticeId: z.string() }),
462
+ access: { roles: ["AUTHENTICATED"] },
463
+ refs: {
464
+ bookingIds: {
465
+ table: "bookings", as: "bookings",
466
+ many: true, // id array: every id must resolve
467
+ matchScope: "site", // checked per row
468
+ ownedVia: { // a junction row must link each one to the caller
469
+ junction: "booking_visitors",
470
+ refColumn: "bookingId", // junction column holding the ref's id
471
+ subjectColumn: "visitorId", // junction column holding the caller's identity
472
+ subject: "ctx.self.visitor", // which identity — see below
473
+ },
474
+ },
475
+ noticeId: {
476
+ table: "notices", as: "notice",
477
+ where: { status: "published" }, // parent-state rule on the loaded row
478
+ unmet: { code: "NOTICE_NOT_PUBLISHED", status: 409 },
479
+ },
480
+ },
481
+ execute: async ({ bookings, notice }) => { /* bookings: rows[], notice: row */ },
482
+ });
483
+ ```
484
+
485
+ | Key | Behaviour | Failure |
486
+ |---|---|---|
487
+ | `many: true` | The input field must be a `z.array(...)` (and an array field must declare `many: true`). Ids are deduplicated, loaded through the scoped db in slices under the driver's bind cap, and injected as a row array in first-occurrence input order. | **404** `REF_NOT_FOUND` (or your `notFound`) with `details.missing` — the ids that did not resolve inside the firewall. Out-of-tenant and nonexistent ids are indistinguishable. |
488
+ | `ownedVia` | One junction lookup (through the scoped db, in the same `Promise.all` as the loads) must find a row with `refColumn` = the ref's id and `subjectColumn` = the `subject` identity, for every loaded row. | **403** `REF_NOT_OWNED` (or `notOwned`) with `details.notOwned` on a `many` ref. A null subject (e.g. no self row) owns nothing. |
489
+ | `where` | Column → value on each loaded row: a literal is equality, `null` is IS NULL, an array is "one of". Keys are emitted as typed column references, so a misspelled column fails `tsc` in the generated project. | **409** `REF_CONDITION_UNMET` (or `unmet`), with `details.unmet` on a `many` ref. |
490
+
491
+ `ownedVia.subject` is required and names exactly one identity, so the compiler
492
+ never guesses between a session user id and a scope subject id:
493
+
494
+ | `subject` | Value |
495
+ |---|---|
496
+ | `"ctx.userId"` | The Better Auth session user |
497
+ | `"ctx.self.<exposeAs>"` | The id of the caller's own row — one identity for a session user **and** a pass holder (see [`ctx.self`](/define/scopes#ctxself--the-callers-own-row)) |
498
+ | `"ctx.scope.<kind>.subjectId"` | The scope claim's subject (the conferring row's PK) |
499
+
500
+ An undeclared `ctx.self.<exposeAs>` or scope kind is a compile error.
501
+
502
+ **Check order per ref:** absence (404) → `matchScope` / `matchWith` (400) →
503
+ `ownedVia` (403) → `where` (409). Ownership is checked before state so a caller
504
+ who does not own a row never learns its status.
@@ -378,21 +378,27 @@ non-cross-tenant `unsafeDb` still runs under the caller's RLS claims, so an
378
378
  insert the policy refuses comes back as 403 `FIREWALL_WRITE_DENIED`; on D1 it
379
379
  lands. That is the point of the escape hatch — and why it is audited.
380
380
 
381
- `unsafe` is the only sanctioned way around the scoped `db`. The compiler warns
382
- when a non-`unsafe` action — or a file it imports from the feature's `lib/`,
383
- the project's `lib/`, `hooks/` or `plugins/` (relative or `~/` imports) —
384
- reaches a raw database handle instead:
381
+ `unsafe` is the only sanctioned way around the scoped `db`. It is a **compile
382
+ error** (`ACTION_RAW_DB_WITHOUT_UNSAFE`) when a non-`unsafe` action reaches a
383
+ raw database handle instead. The check covers the action file and every file
384
+ it imports, transitively, from the feature's `lib/` and the project's `lib/`,
385
+ `hooks/`, or `plugins/` (relative or `~/` imports). A raw handle is any of:
385
386
 
386
387
  - `c.get('db')`
387
- - a database binding off the environment (`env.DB`, `c.env.HYPERDRIVE`, …)
388
+ - a database binding off the environment (`env.DB`, `c.env.HYPERDRIVE`,
389
+ `env.DB.prepare(…)`, …)
388
390
  - a drizzle driver import (`drizzle-orm/d1`, `drizzle-orm/postgres-js`, …)
391
+ - a call to `drizzle(…)`, `createDb()`, or `createAuthDb()`
389
392
  - `auth.$context` (Better Auth's adapter)
390
393
  - the action's own `unsafeDb`
391
394
 
392
- Each warning names the file, line, and handle. It is a warning for now and
393
- becomes a compile error in a future minor; declare `unsafe` (or
394
- `firewall: { exception: true }` for a deliberately unscoped action) if the
395
- access is intentional.
395
+ Each error names the action, file, line, and handle. If the access is
396
+ intentional, declare `unsafe: { reason: "…" }` so it is audited (or
397
+ `firewall: { exception: true }` for a deliberately unscoped action). To adopt
398
+ the check on an existing project, `compiler.securityContracts.failMode: "warn"`
399
+ downgrades it to a warning. Writes to Better Auth tables are a separate error,
400
+ `ACTION_AUTH_DB_WRITE`, that `unsafe` does not silence. See
401
+ [Diagnostics → source codes](/define/diagnostics#source-codes).
396
402
 
397
403
  Use object form for explicit policy and mandatory audit metadata:
398
404
 
@@ -448,6 +454,72 @@ request-scoped service-role boundary.
448
454
 
449
455
  Without unsafe mode, `unsafeDb` is `undefined` in the executor params.
450
456
 
457
+ ### Operator lane: `operator:`
458
+
459
+ A platform operator acting on **one** tenant — set a customer's plan, fix an
460
+ event's status, seed an organization — is not a cross-tenant query. Declare the
461
+ target instead of reaching for `unsafe`:
462
+
463
+ {/* doc-compile: skip — the `operator:` block is the point and it names `events`, a sibling table the fence does not declare; the gate compiles each fence as an isolated project. The whole project, with a runtime check of the audit row, compiles in `tests/output-matrix/fixtures/operator-lane`. */}
464
+ ```ts
465
+ // features/events/actions/setEventStatus.ts
466
+ import { z } from 'zod';
467
+ import { eq } from 'drizzle-orm';
468
+ import { defineAction, events } from '../.quickback/define-action';
469
+
470
+ export default defineAction({
471
+ description: "Platform operator: set an event's status in whichever tenant owns it",
472
+ path: '/events/operator/set-status',
473
+ input: z.object({ eventId: z.string(), status: z.enum(['draft', 'live', 'closed']) }),
474
+ access: { userRole: ['sysadmin'] },
475
+ operator: { target: { table: 'events', by: 'input.eventId' } }, // or table: 'organizations', by: 'input.organizationId'
476
+ async execute({ db, target, input }) {
477
+ // `db` is firewalled to target.organizationId — not the operator's own org.
478
+ const [row] = await db.update(events).set({ status: input.status })
479
+ .where(eq(events.id, target.id)).returning();
480
+ return row;
481
+ },
482
+ });
483
+ ```
484
+
485
+ Before `execute` runs, the route:
486
+
487
+ 1. Checks the `userRole` lane (403 otherwise). An unauthorized caller never triggers the lookup.
488
+ 2. Loads the target row by `input.<field>` — across tenants, on purpose (the raw handle on D1, the service-role handle on Postgres; Better Auth's organization table for `table: 'organizations'`).
489
+ 3. Answers **404 `OPERATOR_TARGET_NOT_FOUND`** when the row is absent or soft-deleted. Set `target: { …, includeDeleted: true }` to admit a soft-deleted row.
490
+ 4. Hands `execute` the row as `target` and a `db` equal to `unsafeDb.scopeTo({ organizationId })` — the target's `organizationId`, or the organization's own `id` when the target is `organizations`. Every statement after that is firewalled to the target tenant, and inserts are stamped with it. `unsafeDb` is not passed. On Postgres that `db` wraps the service-role handle, the same as `unsafeDb.scopeTo`: the firewall `WHERE` and insert stamps are the boundary, and RLS does not narrow it to the target tenant as a backstop.
491
+
492
+ Every call writes one audit row (`eventKind: 'operator_action'`) to the same
493
+ [`audit_events`](#unsafe-mode) table unsafe actions use, on denial, success and
494
+ error. A failed audit write fails the request (500 `ACCESS_AUDIT_LOG_FAILED`).
495
+
496
+ | Column | Value |
497
+ |---|---|
498
+ | `targetOrgId` | the **target's** organization (null when the request was denied before the target loaded) |
499
+ | `resource` | the target table (`events`, `organizations`) |
500
+ | `targetRecordId` | the requested id |
501
+ | `actorUserId` / `actorOrgId` | the operator and their own active org |
502
+ | `metadata.operator` | `{ targetTable, targetId }` |
503
+ | `metadata.input` | the action input, with every key named like a masked, `.encrypted()`, `.sealed()` or vault-ref column in the project replaced by `"[REDACTED]"` |
504
+
505
+ The return value is never stored.
506
+
507
+ The compiler refuses:
508
+
509
+ - `operator` without a `userRole`-only access lane — `access: { userRole: [...] }` and nothing else (no `roles`, `or`, `principals`).
510
+ - `operator` together with `unsafe`, `anchor`, `record` or `firewall` — one or the other.
511
+ - `operator` on a record action (no `path:`) or under an `authz.namespaces` prefix.
512
+ - `target.by` that is not `input.<field>` of a required field in an inline `z.object` input.
513
+ - `target.table` that is not an org-firewalled feature table (an org arm bound to `ctx.activeOrgId`) or `'organizations'`; `includeDeleted` on a table without soft delete.
514
+
515
+ A row in an org-firewalled table with no organization is refused with 500
516
+ `OPERATOR_TARGET_TENANT_UNRESOLVED` rather than run unscoped.
517
+
518
+ `emit:` and `invalidates:` on an operator action address the **target**
519
+ tenant's org room — the same organization the `db` is scoped to — never the
520
+ operator's own active org. A request whose `by` field is missing or empty is
521
+ rejected with 422 before the lookup.
522
+
451
523
  ### Raw SQL Policy
452
524
 
453
525
  By default, the compiler rejects raw SQL in action code. Use Drizzle query-builder syntax whenever possible.
@@ -475,6 +547,98 @@ Without `allowRawSql: true`, compilation fails with a loud error pointing to the
475
547
 
476
548
  The detector checks for SQL keywords in string arguments, so non-SQL method calls like `headers.get("X-Forwarded-For")` or `map.get("key")` will not trigger false positives.
477
549
 
550
+ ### Race-safe writes: `insertWhere`, `updateWhere`, `ledger`
551
+
552
+ D1 runs one statement at a time, but it has no transaction that spans two
553
+ statements. So "read, decide, then write" races another request: two votes
554
+ both see "no vote yet", two reservations both see "3 credits left". The
555
+ scoped `db` has three methods that put the decision inside the write, so
556
+ the database makes it once.
557
+
558
+ ```typescript
559
+ // One vote per voter, only while the poll is open — ONE statement:
560
+ // INSERT INTO votes (…) SELECT … WHERE EXISTS (open poll) AND NOT EXISTS (my vote)
561
+ const vote = await db.insertWhere(votes, { pollId, voterId: ctx.userId!, choice }, {
562
+ exists: { table: polls, where: and(eq(polls.id, pollId), eq(polls.status, "open")) },
563
+ notExists: { table: votes, where: and(eq(votes.pollId, pollId), eq(votes.voterId, ctx.userId!)) },
564
+ });
565
+ if (!vote) return { voted: false }; // the guard did not hold; nothing was written
566
+
567
+ // UPDATE votes SET choice = ? WHERE <where> AND EXISTS (open poll)
568
+ const changed = await db.updateWhere(votes, { choice }, {
569
+ where: and(eq(votes.pollId, pollId), eq(votes.voterId, ctx.userId!)),
570
+ exists: { table: polls, where: and(eq(polls.id, pollId), eq(polls.status, "open")) },
571
+ });
572
+ ```
573
+
574
+ | Method | Statement | Resolves to |
575
+ |---|---|---|
576
+ | `db.insertWhere(table, values, { exists?, notExists? })` | `INSERT … SELECT … WHERE [NOT] EXISTS (…)` | the inserted row, or `null` when the guard failed |
577
+ | `db.updateWhere(table, set, { where, exists?, notExists? })` | `UPDATE … WHERE <where> AND [NOT] EXISTS (…)` | the updated rows (`[]` when nothing matched) |
578
+
579
+ - **Everything the scoped `db` does still applies.** The row is built by the
580
+ ordinary insert path — scope columns stamped, audit columns hard-stamped,
581
+ firewall-on-write checked, trigger hooks run, encrypted columns encrypted —
582
+ and only the `VALUES` list becomes a guarded `SELECT`.
583
+ - **Probes are firewalled.** Each `exists` / `notExists` probe ANDs its own
584
+ table's firewall into its WHERE, so a guard can never test another
585
+ tenant's rows. Pass one probe or an array; at least one is required, and
586
+ every probe needs a `where` (a probe with no WHERE would test the whole
587
+ table). `updateWhere` refuses a missing `where`.
588
+ - **One row.** `insertWhere` takes a single values object.
589
+ - **Postgres.** Under `READ COMMITTED`, two concurrent `INSERT … WHERE NOT EXISTS`
590
+ statements can both succeed, so on Postgres the guarded statement runs after
591
+ `pg_advisory_xact_lock` in the same transaction (an interactive transaction,
592
+ or `db.batch()` on neon-http, which runs as one transaction). An
593
+ `updateWhere` with no probes needs no lock: an UPDATE re-checks its own
594
+ WHERE on the row it writes.
595
+
596
+ #### Ledgers: `db.ledger.<name>`
597
+
598
+ A ledger is a balance that must never go negative — credits, seats, quota,
599
+ stock. Declare it on the **debits** table; the grants table needs its own
600
+ `defineTable`:
601
+
602
+ {/* doc-compile: skip — a ledger spans two tables (credit_grants + credit_debits) in one feature; the docs gate compiles each fence as an isolated single-table project. The full shape is compiled by tests/output-matrix/fixtures/race-safe-writes. */}
603
+ ```typescript
604
+ // features/credits/credits.ts
605
+ export default defineTable(creditDebits, {
606
+ read: { access: { roles: ["owner", "admin"] } },
607
+ ledger: {
608
+ name: "credits", // db.ledger.credits (default: the table name)
609
+ grants: "creditGrants", // the grants table
610
+ reserve: { amountColumn: "amount", subjectColumn: "accountId", statusColumn: "status" },
611
+ },
612
+ });
613
+ ```
614
+
615
+ ```typescript
616
+ const reservation = await db.ledger.credits.reserve(input.accountId, 1, { purpose: "sms" });
617
+ if (!reservation) throw new ActionError("Not enough credits", "INSUFFICIENT_CREDITS", 402);
618
+ try {
619
+ await sendSms();
620
+ await db.ledger.credits.finalize(reservation.id);
621
+ } catch (err) {
622
+ await db.ledger.credits.release(reservation.id);
623
+ throw err;
624
+ }
625
+ ```
626
+
627
+ | Call | Statement | Resolves to |
628
+ |---|---|---|
629
+ | `reserve(subject, amount, values?)` | `INSERT INTO debits … WHERE Σ grants − Σ live debits >= amount` | the `reserved` debit, or `null` when the balance is short |
630
+ | `finalize(id)` | `UPDATE debits SET status = 'finalized' WHERE id = ? AND status = 'reserved'` | the row, or `null` if it was already settled |
631
+ | `release(id)` | `UPDATE debits SET status = 'released' WHERE id = ? AND status = 'reserved'` | the row, or `null` if it was already settled |
632
+ | `balance(subject)` | two firewalled sums | grants − (reserved + finalized) |
633
+
634
+ `amountColumn` and `subjectColumn` must exist on both tables; the debits table
635
+ also needs `id` and the status column (default `status`), which holds
636
+ `reserved` / `finalized` / `released`. Released debits do not count against the
637
+ balance; both sums are firewalled, and soft-deleted rows drop out of them like
638
+ every other read. `amount` must be a positive number (`400 LEDGER_INVALID_AMOUNT`
639
+ otherwise), and `values` may not set the subject, amount or status columns.
640
+ A missing table or column, or an unknown key, is a compile error.
641
+
478
642
  ## Sharing Code Between Actions
479
643
 
480
644
  For Zod schemas, helpers, or constants used across multiple actions in a
@@ -573,6 +737,7 @@ import type { Auth } from "better-auth";
573
737
  interface ActionExecutorParams {
574
738
  db: DrizzleDB; // Scoped database (auto-applies org/owner/soft-delete filters)
575
739
  unsafeDb?: DrizzleDB; // Unscoped database (only available when unsafe mode is enabled)
740
+ target?: TRow; // The loaded operator target (operator lane only — see Operator lane)
576
741
  ctx: AppContext; // User context (userId, roles, activeOrgId, activeTeamId, userRole)
577
742
  record?: TRecord; // The record (record-based only, undefined for standalone)
578
743
  input: TInput; // Validated input from Zod schema
@@ -688,11 +853,73 @@ Postgres audit columns take `Date` objects while SQLite takes ISO strings
688
853
  the parameter is typed as optional. `whereTransition` extends `whereRecord`
689
854
  with the transition's "from" precondition for transition actions.
690
855
 
856
+ #### `ctx.auth` — Better Auth users and members, org-bound
857
+
858
+ Changing a user — banning them, changing their role, deleting the account — through a raw `authDb` handle bypasses the revocation stamps used to invalidate outstanding JWTs. Use `ctx.auth` instead. It is hydrated on every request context in Cloudflare + Better Auth projects and typed on `execute`'s `ctx`:
859
+
860
+ ```typescript
861
+ // features/guests/actions/banMember.ts
862
+ import { z } from "zod";
863
+ import { defineAction } from "../.quickback/define-action";
864
+
865
+ export default defineAction({
866
+ description: "Ban a member of the active organization.",
867
+ path: "/members/ban",
868
+ input: z.object({ userId: z.string(), reason: z.string().optional() }),
869
+ access: { roles: ["owner", "admin"] },
870
+ async execute({ ctx, input }) {
871
+ await ctx.auth.ban(input.userId, input.reason);
872
+ return { banned: input.userId };
873
+ },
874
+ });
875
+ ```
876
+
877
+ | Method | Requires | Does |
878
+ |---|---|---|
879
+ | `ctx.auth.ban(userId, reason?)` | admin plugin | Sets `banned` + `banReason`, deletes every session. You cannot ban yourself. |
880
+ | `ctx.auth.setRole(userId, role, { orgId? })` | organization plugin | Sets the member's role in the active organization (`role` is typed to the declared organization roles). The last owner cannot be demoted (409). |
881
+ | `ctx.auth.deleteAccount(userId)` | — | Deletes the user's memberships, sessions, linked accounts, then the user. Deleting yourself is always allowed. |
882
+ | `ctx.auth.members.list(orgId?)` | organization plugin | The organization's members: `{ id, userId, organizationId, role, createdAt, user: { id, email, name, image } }`. |
883
+ | `ctx.auth.claims.backfill(opts?)` | [`auth.claims`](/configure/auth#authclaims--link-rows-to-the-account-that-verifies-their-email) | Links rows that predate their account. |
884
+
885
+ Every method writes through Better Auth's adapter with its schema mapping. `setRole` adds a database-enforced guard to that adapter update so concurrent calls cannot both demote the remaining owners; PostgreSQL calls serialize per organization. A stale membership or target platform-role read also fails with `409 AUTH_SURFACE_LAST_OWNER`, so reload before retrying. Organization endpoint lifecycle hooks are not invoked by this action surface; account methods use Better Auth's internal adapter where applicable. With `auth.jwt.revocationCheck: 'kv'` each write stamps `qbrev:user:<id>` (and `qbrev:member:<id>:<org>` for a role change), so outstanding JWTs die within seconds; if the stamp cannot be written the method throws `503 AUTH_REVOCATION_UNAVAILABLE` instead of reporting success. Platform roles (`user.role`) are not `ctx.auth`'s job: change them with Better Auth's `/admin/set-role`, which is on the [revocation kill list](/configure/auth#revocationcheck-none--kv--token-revocation-strategy) too.
886
+
887
+ **Who may act on whom.** The action's `access` decides who can call it; `ctx.auth` then bounds what the call can touch:
888
+
889
+ - An **operator** — a caller whose platform role is one of the admin plugin's `adminRoles` (`appmanager`, `sysadmin` by default) — may act on any user whose platform role ranks at or below its own, and may name another organization (`orgId`).
890
+ - **Everyone else is org-bound.** The target must be a member of the caller's active organization (otherwise `404 AUTH_SURFACE_NOT_FOUND` — nothing is learned about other tenants' users), must hold an organization role at or below the caller's (`auth.roleHierarchy`, default `member < admin < owner`), and must not be an operator. `setRole` may not assign a role above the caller's own. `ban` and `deleteAccount` change the whole account, so they also refuse a target who belongs to any other organization.
891
+
892
+ Errors are action errors: `401 AUTH_SURFACE_UNAUTHENTICATED` (no account caller), `403 AUTH_SURFACE_NO_ORG`, `403 AUTH_SURFACE_OUT_OF_SCOPE`, `403 AUTH_SURFACE_ROLE_CEILING`, `400 AUTH_SURFACE_INVALID_ROLE`, `400 AUTH_SURFACE_SELF`, `404 AUTH_SURFACE_NOT_FOUND`, `409 AUTH_SURFACE_LAST_OWNER`, `503 AUTH_REVOCATION_UNAVAILABLE`.
893
+
894
+ #### `ctx.unmask` — reading a `q.secret()` column
895
+
896
+ A [`q.secret()`](/define/encryption#secret-columns--qsecret) column is never returned by any read path, and the rows your action reads hold its ciphertext. `ctx.unmask(row, column)` is the one server-side read: it decrypts with the row's own organization key and records a best-effort `masked_reveal` audit entry.
897
+
898
+ ```typescript
899
+ // features/integrations/actions/checkSecret.ts
900
+ import { z } from "zod";
901
+ import { defineAction } from "../.quickback/define-action";
902
+
903
+ export default defineAction({
904
+ description: "Check an integration's client secret without revealing it.",
905
+ input: z.object({ candidate: z.string() }),
906
+ access: { roles: ["admin+"] },
907
+ async execute({ ctx, record, input }) {
908
+ const secret = await ctx.unmask(record, "clientSecret");
909
+ return { matches: secret === input.candidate };
910
+ },
911
+ });
912
+ ```
913
+
914
+ `column` is the property name when no other table has a secret column of that name, or `{ table, column }` (SQL table name + property name) — always accepted, and required for a shared name. The row must carry the column and its organization column; `null` unmasks to `null`.
915
+
691
916
  #### Reaching Better Auth tables (`authDb`)
692
917
 
693
918
  The scoped `db` is the **features** database. Better Auth tables never appear
694
919
  on it — that is by design. `AUTH_DB` is a separate Drizzle client.
695
920
 
921
+ **Changing a user or member — use [`ctx.auth`](#ctxauth--better-auth-users-and-members-org-bound), never a write on `authDb`.** A raw write skips Better Auth's hooks and leaves the user's JWTs alive.
922
+
696
923
  **Caller identity — use `ctx`, do not query `AUTH_DB`.** `ctx.userId`,
697
924
  `ctx.activeOrgId`, `ctx.roles`, and `ctx.userRole` are already on the request.
698
925
 
@@ -458,8 +458,54 @@ authz: {
458
458
  }
459
459
  ```
460
460
 
461
+ The gate records the admitting lane on `ctx.lane`; declare `lanes: 'all'` to also record every lane the caller satisfies on `ctx.lanes` — see [Recording every matched lane](#recording-every-matched-lane--lanes-all).
462
+
461
463
  Hydration is **per matched lane**: each lane fills `ctx.<its own exposeAs>` from its own `loads:` table, so lanes may load different tables into different keys. Both lanes above name `events` / `event`, so `ctx.event` is populated whichever fires. A lane declaring neither `loads:` nor `exposeAs:` is authorization-only — it opens the gate and hydrates nothing.
462
464
 
465
+ ### Recording every matched lane — `lanes: 'all'`
466
+
467
+ The gate stamps **`ctx.lane`** on every request it admits: the lane that let
468
+ the caller in — a relationship lane's name, `'roles'` for a `{ roles }` lane,
469
+ `'team'` for `{ team: true }`. The bulk-grant role check runs before the
470
+ relationship probes and short-circuits them, so an org admin who is *also* a
471
+ named organizer is admitted as `'roles'`, and nothing records the organizer
472
+ relationship. A body that needs to know ("may this admin also act as the
473
+ event's organizer?") would have to re-query it.
474
+
475
+ Declare `lanes: 'all'` and the gate also stamps **`ctx.lanes`** — every lane the
476
+ caller satisfies, in `via:` declaration order:
477
+
478
+ ```typescript
479
+ namespaces: {
480
+ eventScope: {
481
+ prefix: '/event/:eventId',
482
+ via: ['organizerOf', 'attendeeOf', { roles: ['admin', 'owner'] }],
483
+ lanes: 'all',
484
+ },
485
+ }
486
+ // An org owner who is also a named organizer:
487
+ // ctx.lane → 'roles' (the lane that admitted them)
488
+ // ctx.lanes → ['organizerOf', 'roles'] (everything they hold)
489
+ ```
490
+
491
+ - Every relationship lane is evaluated even when an earlier lane already opened
492
+ the gate. Probes the gate started are awaited, not re-run; only lanes the
493
+ gate skipped (the role arm matched) cost a query each.
494
+ - A probe that throws fails the request rather than silently dropping a lane —
495
+ `ctx.lanes.includes(...)` never lies by omission.
496
+ - With the default (`lanes: 'first'`) only `ctx.lane` is stamped; `ctx.lanes`
497
+ is absent, so code cannot mistake a partial list for a complete one.
498
+ - `ctx.lanes` is what decides a relationship arm in
499
+ [`access.arms`](/define/actions/access#arms-conditioned-on-input-accessarms)
500
+ and a `via:` rule in [`ctx.is`](/define/actions/access#asking-a-named-role-in-the-body-ctxis).
501
+ - The per-namespace helper types both: `ctx.lane` as the union of this
502
+ namespace's lane labels, `ctx.lanes` as an array of them.
503
+ - `lanes` is accepted on `authz.namespaces` entries and feature-area
504
+ `defineArea` gates. On a table-level `defineTable({ namespace })` it is a
505
+ compile error.
506
+ - The scope-claim refresh still stamps the role of the lane that **admitted**
507
+ the request (`ctx.lane`), not of every lane in `ctx.lanes`.
508
+
463
509
  ### Bulk-grant lanes
464
510
 
465
511
  Relationship lanes cover "specifically connected to this row." Bulk-grant lanes cover "anyone with this role / team membership in the row's tenant" — the case where an org admin or a team member should see every event in their scope without writing per-event relationship rows.
@@ -90,6 +90,16 @@ A named rule works in the `roles: [...]` array of every access surface. The comp
90
90
 
91
91
  Names that **aren't** declared in `authz.roles` — Better Auth roles, pseudo-roles like `AUTHENTICATED` — pass through untouched, so you can mix named rules and raw roles in the same array.
92
92
 
93
+ ### Checking a named role inside an action: `ctx.is`
94
+
95
+ Every `authz.roles` name is also a generated, typed predicate on the action
96
+ context: `ctx.is('eventStaff')` returns `true` when the caller satisfies the
97
+ rule on this request. The argument is typed as the union of declared names, and
98
+ the rule is expanded with the same passes `access.roles` uses — so a body
99
+ never re-derives a role set by hand. A `via:` arm is decided from the lanes a
100
+ namespace gate recorded (`lanes: 'all'`); see
101
+ [Asking a named role in the body](/define/actions/access#asking-a-named-role-in-the-body-ctxis).
102
+
93
103
  ### Beyond roles: named permissions
94
104
 
95
105
  For access that traverses the data graph (FK hops, SpiceDB-style permission composition), see [`authz.permissions` + `authz.arrows`](/define/permissions) — the same define-once-reference-by-name model, one level richer than `authz.roles`.