@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
@@ -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`.
@@ -60,6 +60,7 @@ compile.
60
60
  | `AUTHZ_NOT_OVER_RESOURCE` | warn | A `not` whose operand resolves to a **resource (SQL) site** — `NOT EXISTS` over a nullable join can silently pass (the null-trap). The site resolution is conservative, so this stays advisory. |
61
61
  | `AUTHZ_RECORD_PREDICATE_NOT_ON_LIST` | warn | A **constant** `read.access.record` predicate (`status: { equals: "published" }`, `id: { equals: "never" }`). `access.record` runs against a loaded row on `GET /:id` only — `GET /`, `POST /batch`, and the MCP list tool stop at the role gate, so the rows still list. Omit `read` to hide a resource; use the firewall to filter. `$ctx`-relative predicates are the per-record shape and stay silent. |
62
62
  | `AUTHZ_PUSHDOWN_COST` | info | Per-permission report: how many SQL subqueries the permission lowers to, plus the max recursive-CTE depth. Advisory, never fails a build. |
63
+ | `AUTHZ_ROOM_ACCESS_INHERITED` | warn | A resource-backed [realtime room](/platform/realtime/partyserver-rooms#room-roles) with no `access.roles` (connections gated on the table's CRUD `read.access`, so narrowing the room means narrowing CRUD reads) or no `access.writeRoles` (every admitted caller may write). Declare both on the binding. Printed while the config is checked, before the analyzer runs, so `QUICKBACK_AUTHZ_STRICT` does not promote it and there is nothing to override. |
63
64
 
64
65
  A few codes are reserved in the diagnostic enum for the milestones that emit
65
66
  them and don't fire on a shipped config today: `AUTHZ_UNBOUNDED_RECURSION`
@@ -102,6 +103,65 @@ surface is separately guarded today by the IR's unbound-route invariant — a
102
103
  hard error that predates this promotion and owns that surface; one subject,
103
104
  one error.)
104
105
 
106
+ ## Schema and config codes
107
+
108
+ These read the lowered project — each table's resolved create/update field
109
+ sets, its firewall arms, `authz.relationships`, and each action's access —
110
+ and flag the shapes that silently skip a security mechanism Quickback
111
+ already has. They run on every compile.
112
+
113
+ | Code | Default | What it catches | Opt-out |
114
+ |---|---|---|---|
115
+ | `SCHEMA_UNDECLARED_FK` | **error** | A `*Id` / `*_id` column that names a feature table in the same database (`eventId` → `events` or `event`), is client-writable (in the effective `createable` / `updatable` set) **or** sits in a firewall or `authz.relationships` arm, and declares no [`.references()`](/define/schema#references). Without it no [firewalled FK check](/define/firewall#foreign-key-referential-checks) runs, so a caller can point the row at another tenant's parent. Never fires for auth-owned ids (`userId`, `ownerId`, `organizationId`, `teamId`, `memberId`, audit ids) or when no matching feature table exists. | `references: { eventId: { references: false, reason: '…' } }` in `defineTable` |
116
+ | `SCHEMA_FK_MATCH_REQUIRED` | warn | A declared FK where the child **and** its target both carry an org column, with no [`match`](/define/schema#match-a-referenced-rows-parent) on the org column. A `match` on another parent column counts when that column is itself org-matched. | `references: { eventId: { match: false, reason: '…' } }` in `defineTable` |
117
+ | `SCHEMA_JSON_UNGUARDED` | warn | A JSON column (`q.json`, `json` / `jsonb`) clients can write with no `keys` policy — anyone who may update the row may set every key of the document. | `// quickback-allow SCHEMA_JSON_UNGUARDED: <reason>` in the table file |
118
+ | `ACTION_PUBLIC_WITHOUT_RATELIMIT` | warn | An action whose access admits `PUBLIC` with no explicit [`rateLimit`](/define/rate-limit#actions) (it shares the project-default write bucket, keyed by client IP), or with `rateLimit: false`. | `// quickback-allow ACTION_PUBLIC_WITHOUT_RATELIMIT: <reason>` in the action file |
119
+
120
+ Why two defaults:
121
+
122
+ - `SCHEMA_UNDECLARED_FK` is an **error** because the fix is always
123
+ available (`.references()` works on q-DSL and raw Drizzle columns alike)
124
+ and the gap is a cross-tenant write.
125
+ - `SCHEMA_FK_MATCH_REQUIRED` is a **warning** because `match` can only be
126
+ written on a q-DSL column — on a raw Drizzle table the only way to clear an
127
+ error would be an opt-out that misstates intent — and generated CRUD writes
128
+ already run the firewalled FK check. The remaining gap is action-side
129
+ writes, which the `match` trigger backstops. Under
130
+ `QUICKBACK_AUTHZ_STRICT=true` it, and the other two warnings, fail the
131
+ build.
132
+
133
+ Every opt-out needs a non-empty `reason`. The compiler rejects an opt-out
134
+ without one, a `references` entry it does not recognise, or one naming a
135
+ column the table does not have.
136
+
137
+ {/* doc-compile: skip — excerpt of a defineTable config; `guests` and its columns are elided */}
138
+ ```ts
139
+ export default defineTable(guests, {
140
+ references: {
141
+ cventEventId: { references: false, reason: 'Cvent-side id; no row in this database' },
142
+ partnerEventId: { match: false, reason: 'guests may be invited to a partner org event' },
143
+ },
144
+ // ...
145
+ });
146
+ ```
147
+
148
+ ### Migration window
149
+
150
+ The error honours `compiler.securityContracts.failMode`. While you add the
151
+ missing declarations, set it to `'warn'` and every finding prints, marked as
152
+ downgraded, without failing the build:
153
+
154
+ ```ts
155
+ export default defineConfig({
156
+ compiler: { securityContracts: { failMode: 'warn' } },
157
+ // ...
158
+ });
159
+ ```
160
+
161
+ `failMode: 'warn'` also downgrades the
162
+ [security contract](/tooling/output#security-contract-report-and-signature)
163
+ checks, so treat it as temporary.
164
+
105
165
  ## The override surface
106
166
 
107
167
  Every promoted finding can be explicitly accepted — per finding, with a
@@ -156,6 +216,209 @@ A high subquery count or a deep recursive CTE (from a recursive
156
216
  [arrow](/define/arrows)) is a signal to reconsider the rule —
157
217
  not an error, but worth a look.
158
218
 
219
+ ## Source codes
220
+
221
+ The checks above read the policy graph. These read your **authored source**:
222
+ action files, the feature `lib/` files, and the project's `lib/`, `hooks/`,
223
+ `plugins/`, `email-templates/`, and `middlewares/` files. They catch code that
224
+ goes around a pillar instead of through it. The analysis is syntactic (no
225
+ type checker), it runs on every compile, and it renders on the
226
+ `[quickback:source]` channel:
227
+
228
+ ```
229
+ [quickback:source] ACTION_RAW_DB_WITHOUT_UNSAFE: action "listMyEvents" reaches a raw database handle (drizzle(env.DB)) without declaring `unsafe` — the firewall does not apply to it and no audit row is written.
230
+ at site=action listMyEvents features/user-profiles/actions/listMyEvents.ts:61:20
231
+ hint: Use the scoped `db`, or declare `unsafe: { reason: "…" }` on the action and use `unsafeDb` (audited).
232
+ opt-out: // quickback-allow ACTION_RAW_DB_WITHOUT_UNSAFE: <reason>
233
+ ```
234
+
235
+ | Code | Tier | Scope | What it catches |
236
+ |---|---|---|---|
237
+ | `ACTION_RAW_DB_WITHOUT_UNSAFE` | **error** | action files, and every project file they import | A raw database handle reached by an action with no `unsafe:` declaration. |
238
+ | `ACTION_AUTH_DB_WRITE` | **error** | action files, and every project file they import | An insert, update, or delete against a Better Auth table that does not go through Better Auth. |
239
+ | `ACTION_ROLE_CHECK_IN_BODY` | warn | the `execute` function of action files | A role check written in the handler body instead of in the declared `access`. |
240
+ | `ENV_UNDECLARED` | **error** | every authored file (Cloudflare runtime) | An `env.X` read where nothing declares `X`. |
241
+ | `TEMPLATE_UNESCAPED` | **error** | every authored file | A `${}` value in an HTML template literal that is not escaped. |
242
+ | `SOURCE_ALLOW_INVALID` | **error** | — | A `quickback-allow` directive with no reason, an unknown code, or nothing left to suppress. |
243
+
244
+ "Every project file they import" is transitive. It follows relative imports
245
+ and the `~/` alias through the feature `lib/` and the project `lib/`,
246
+ `hooks/`, and `plugins/` files. A finding in a shared file names the action
247
+ that reached it. Packages from `node_modules` are not followed.
248
+
249
+ ### `ACTION_RAW_DB_WITHOUT_UNSAFE`
250
+
251
+ It fires on these, in an action that has no `unsafe:`:
252
+
253
+ - `c.get('db')`
254
+ - a database binding read off the environment: `env.DB`, `c.env.AUTH_DB`,
255
+ `env.HYPERDRIVE`, and so on. That includes `env.DB.prepare(…)`.
256
+ - a drizzle driver import (`drizzle-orm/d1`, `drizzle-orm/postgres-js`, …)
257
+ - a call to `drizzle(…)`, `createDb()`, or `createAuthDb()`
258
+ - `auth.$context` (Better Auth's adapter)
259
+ - the action's own `unsafeDb`. This only fires in the action file. An imported
260
+ helper may receive `unsafeDb` from an `unsafe` caller.
261
+
262
+ **Opt-out:** declare `unsafe: { reason: "…" }` on the action (or `unsafe: true`,
263
+ or `firewall: { exception: true }` on a deliberately unscoped action), so the
264
+ call is audited. See [Unsafe mode](/define/actions/scoped-db#unsafe-mode). A
265
+ `quickback-allow` directive also works when a raw handle is in a shared file
266
+ the action imports but does not call.
267
+
268
+ ### `ACTION_AUTH_DB_WRITE`
269
+
270
+ It fires on `.insert(T)`, `.update(T)`, and `.delete(T)` when `T` is:
271
+
272
+ - a table imported from the generated auth schema (`…/auth/schema`,
273
+ `…/auth-schema`), by name or through a namespace (`authSchema.user`,
274
+ `const { member } = authSchema`), or
275
+ - anything, when the receiver is the auth database handle (`authDb`,
276
+ `c.get("authDb")`, `AUTH_DB`).
277
+
278
+ It also fires on raw SQL strings that write a Better Auth table:
279
+ `INSERT INTO <t> (…|VALUES|SELECT)`, `UPDATE <t> SET`, `DELETE FROM <t>
280
+ WHERE`. The table names are `user`, `session`, `account`, `verification`,
281
+ `organization`, `member`, `invitation`, `team`, `teamMember`, `apikey`,
282
+ `passkey`, `twoFactor`, `jwks`, and the subscriptions and OAuth plugin tables,
283
+ under both the singular (D1) and plural (Postgres) spellings. A project table
284
+ with the same name is excluded. Reads are never flagged.
285
+
286
+ The check runs whether or not the action is `unsafe`. `unsafe` lets an action
287
+ read across tenants. It does not let it bypass Better Auth's hooks, session
288
+ revocation, or `qbrev` stamping. Use Better Auth for writes: `auth.api.*` on
289
+ the action's `auth` parameter.
290
+
291
+ **Opt-out:** `// quickback-allow ACTION_AUTH_DB_WRITE: <reason>`.
292
+
293
+ ### `ACTION_ROLE_CHECK_IN_BODY`
294
+
295
+ Inside `execute` only, it fires on:
296
+
297
+ - a membership test on a roles array: `ctx.roles.includes(…)`,
298
+ `(ctx.roles ?? []).some(…)`, and `every`, `indexOf`, `find`, `findIndex`,
299
+ `has` on anything named `roles`, `userRoles`, or `memberRoles`.
300
+ - an equality comparison (`===`, `!==`, `==`, `!=`) between a role literal and
301
+ the caller's role. A caller's role is an expression rooted at `ctx` whose
302
+ last name contains `role` (`ctx.userRole`, `ctx.member?.role`), or a bare
303
+ local with such a name (`role`). `input.role` and `row.role` are data and are
304
+ not flagged.
305
+ - `['admin', 'owner'].includes(<caller role>)` and `switch (<caller role>)`
306
+ with role-literal cases.
307
+
308
+ A role literal is `owner`, `admin`, `member`, any name in `auth.roleHierarchy`
309
+ or `authz.roles`, or any role named in any action's `access`.
310
+
311
+ It is a warning: role checks in the body still run. The problem is that the
312
+ declared `access` and the route manifest stop describing who can call the
313
+ action. Move the gate into `access` (an `anyOf` arm per caller class), or name
314
+ the role set once in `authz.roles`.
315
+
316
+ **Opt-out:** `// quickback-allow ACTION_ROLE_CHECK_IN_BODY: <reason>`. Use it
317
+ for response shaping that is not a gate.
318
+
319
+ ### `ENV_UNDECLARED`
320
+
321
+ It fires on `env.X`, `(env as any).X`, `env["X"]`, and `const { X } = env`,
322
+ where the environment is `env`, `c.env`, `ctx.env`, or `this.env`.
323
+ `process.env` and `import.meta.env` are not checked. `X` is declared if it is:
324
+
325
+ - a member of the generated `CloudflareBindings` interface (`src/env.d.ts`):
326
+ the compiler's own bindings plus everything under `bindings`, including
327
+ `bindings.vars` and `bindings.secrets`, or
328
+ - provided by the generated `wrangler.toml`: `[vars]` and per-environment
329
+ `[env.<target>.vars]`, every `binding = "…"`, and the
330
+ `[*.secrets] required` lists.
331
+
332
+ This is the same set wrangler deploys with, so an `ENV_UNDECLARED` read is
333
+ `undefined` at runtime unless something outside the config sets it.
334
+
335
+ **Fix:** declare it: `bindings: { secrets: [{ name: "X" }] }` or
336
+ `bindings: { vars: { X: "…" } }`. **Opt-out**, for a value set outside the
337
+ config (for example `wrangler deploy --var`):
338
+ `// quickback-allow ENV_UNDECLARED: <reason>`. On a non-Cloudflare runtime
339
+ the check does not run.
340
+
341
+ ### `TEMPLATE_UNESCAPED`
342
+
343
+ A template literal counts as HTML when any of these is true:
344
+
345
+ 1. its literal text contains a tag: `<p`, `</div`, `<!DOCTYPE`.
346
+ 2. it is passed directly to a function whose name contains `html`
347
+ (`c.html(…)`, `sendHtml(…)`), or bound to a variable, property, or
348
+ assignment target whose name ends in `html` (`html`, `bodyHtml`,
349
+ `innerHTML`; not `htmlR2Key`).
350
+ 3. the file is under an `email-templates/` or `templates/` directory, and the
351
+ template is not bound to a name containing `subject`, `text`, or `plain`.
352
+
353
+ Each `${}` value in an HTML template must be one of these:
354
+
355
+ - a call to an escaping function: `esc(…)`, or any name containing `escape`
356
+ or `sanitize` (`escapeHtml`, `escapeAttr`, `sanitizeUrl`)
357
+ - a `.replace` / `.replaceAll` chain whose patterns together cover `&` and `<`
358
+ (`s.replace(/[&<>"']/g, …)`)
359
+ - a template tagged with a tag whose name contains `html`, `escape`, or
360
+ `sanitize` (`` html`…` ``). An escaping tag also exempts the template itself.
361
+ - a literal; arithmetic, comparison, or a unary expression; `x.length`;
362
+ `Number(…)`, `parseInt(…)`, `parseFloat(…)`, `Math.*(…)`, `.toFixed(…)`;
363
+ `encodeURIComponent(…)`, `encodeURI(…)`
364
+ - a nested template, a `cond ? a : b`, `a && b`, `a || b`, `a ?? b`, or
365
+ `a + b` whose parts are all allowed
366
+ - `xs.map(cb).join(…)`, or `[…].join(…)`, where every value `cb` returns
367
+ (or every element) is allowed. `cb` can be an escaping function
368
+ (`.map(escapeHtml)`).
369
+ - a same-file binding whose every value is allowed: a `const`, or a
370
+ `let`/`var` when its initializer and every `=` / `+=` to it in the
371
+ declaring block are allowed
372
+ - a call to a same-file function whose every `return` is allowed. Recursive
373
+ renderers are fine.
374
+
375
+ Anything else is unescaped: function parameters, values imported from another
376
+ module, and property reads such as `input.name`. One finding is reported per
377
+ template and lists the offending values. A helper whose own template is
378
+ reported is not reported again where it is used.
379
+
380
+ **Fix:** escape the value at the interpolation, or build the markup with an
381
+ escaping `html` tag. **Opt-out**, for a value that is already markup (a
382
+ fragment from another module's renderer, a server-built constant):
383
+ `// quickback-allow TEMPLATE_UNESCAPED: <reason>` on the line where the
384
+ template starts, or above it.
385
+
386
+ ### Opting out: `quickback-allow`
387
+
388
+ Every source code has the same opt-out: a comment that names the code and
389
+ gives a reason.
390
+
391
+ ```ts
392
+ // quickback-allow TEMPLATE_UNESCAPED: badgeSvg is rendered server-side from a fixed icon set
393
+ const badge = `<div class="badge">${input.badgeSvg}</div>`;
394
+
395
+ const showBilling = ctx.roles?.includes("owner"); // quickback-allow ACTION_ROLE_CHECK_IN_BODY: response shaping, not a gate
396
+ ```
397
+
398
+ - `// quickback-allow <CODE>: <reason>` covers findings of `<CODE>` on the
399
+ same line or the line below it.
400
+ - `// quickback-allow-file <CODE>: <reason>`, anywhere in a file, covers every
401
+ `<CODE>` finding in that file.
402
+ - `/* … */` comments work too.
403
+
404
+ An allowed finding does not print; the directive in the source is the record.
405
+ `SOURCE_ALLOW_INVALID` (an error) fires when a directive:
406
+
407
+ - has no reason,
408
+ - names an unknown code, or
409
+ - suppresses nothing, because the finding was fixed or the file is outside
410
+ the code's scope. Remove the directive.
411
+
412
+ ### Migration window: `failMode: "warn"`
413
+
414
+ Source-code errors fail the compile by default. To adopt them on an existing
415
+ project, set
416
+ [`compiler.securityContracts.failMode`](/configure#security-contract-reports-and-signing) to
417
+ `"warn"`. Every source error, including `SOURCE_ALLOW_INVALID`, then prints as
418
+ a warning marked `downgraded by compiler.securityContracts.failMode = "warn"`,
419
+ and the compile continues. The same switch governs the generated-output
420
+ security contracts. `ACTION_ROLE_CHECK_IN_BODY` is a warning in both modes.
421
+
159
422
  ## See also
160
423
 
161
424
  - [Permissions](/define/permissions) — the `anyOf` / `allOf` /