@quickback-dev/cli 0.66.6 → 0.66.8

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 (50) hide show
  1. package/dist/commands/build.d.ts +0 -1
  2. package/dist/commands/build.d.ts.map +1 -1
  3. package/dist/commands/build.js +0 -1
  4. package/dist/commands/build.js.map +1 -1
  5. package/dist/index.js +1 -1
  6. package/dist/lib/api-client.d.ts +1 -1
  7. package/dist/lib/api-client.d.ts.map +1 -1
  8. package/dist/lib/api-client.js +13 -8
  9. package/dist/lib/api-client.js.map +1 -1
  10. package/dist/lib/api-client.test.js +47 -0
  11. package/dist/lib/api-client.test.js.map +1 -1
  12. package/dist/lib/file-writer.d.ts +1 -1
  13. package/dist/lib/file-writer.d.ts.map +1 -1
  14. package/dist/lib/file-writer.js +2 -3
  15. package/dist/lib/file-writer.js.map +1 -1
  16. package/dist/lib/migrations/drizzle.d.ts.map +1 -1
  17. package/dist/lib/migrations/drizzle.js +6 -1
  18. package/dist/lib/migrations/drizzle.js.map +1 -1
  19. package/dist/lib/migrations/drizzle.test.js +7 -0
  20. package/dist/lib/migrations/drizzle.test.js.map +1 -1
  21. package/dist/lib/migrations/executor.d.ts.map +1 -1
  22. package/dist/lib/migrations/executor.js +4 -0
  23. package/dist/lib/migrations/executor.js.map +1 -1
  24. package/dist/lib/migrations/postprocessors/better-auth-upgrade.d.ts +7 -0
  25. package/dist/lib/migrations/postprocessors/better-auth-upgrade.d.ts.map +1 -0
  26. package/dist/lib/migrations/postprocessors/better-auth-upgrade.js +149 -0
  27. package/dist/lib/migrations/postprocessors/better-auth-upgrade.js.map +1 -0
  28. package/dist/skill/docs/define/actions/index.md +6 -0
  29. package/dist/skill/docs/define/actions/scoped-db.md +88 -41
  30. package/dist/skill/docs/define/transitions.md +11 -0
  31. package/dist/skill/docs/define/triggers.md +4 -0
  32. package/dist/skill/docs/platform/auth/index.md +37 -0
  33. package/dist/skill/docs/platform/database/d1.md +2 -2
  34. package/dist/skill/docs/platform/database/neon.md +246 -55
  35. package/dist/skill/docs/platform/queues/handlers.md +12 -0
  36. package/dist/skill/docs/platform/schedules/index.md +3 -1
  37. package/dist/skill/docs/tooling/cloud-compiler/endpoints.md +10 -0
  38. package/dist/skill/docs/tooling/cloud-compiler/troubleshooting.md +16 -0
  39. package/package.json +1 -1
  40. package/src/skill/docs/define/actions/index.md +6 -0
  41. package/src/skill/docs/define/actions/scoped-db.md +88 -41
  42. package/src/skill/docs/define/transitions.md +11 -0
  43. package/src/skill/docs/define/triggers.md +4 -0
  44. package/src/skill/docs/platform/auth/index.md +37 -0
  45. package/src/skill/docs/platform/database/d1.md +2 -2
  46. package/src/skill/docs/platform/database/neon.md +246 -55
  47. package/src/skill/docs/platform/queues/handlers.md +12 -0
  48. package/src/skill/docs/platform/schedules/index.md +3 -1
  49. package/src/skill/docs/tooling/cloud-compiler/endpoints.md +10 -0
  50. package/src/skill/docs/tooling/cloud-compiler/troubleshooting.md +16 -0
@@ -74,11 +74,17 @@ intersected with the same authority context: a single or shared hydration
74
74
  target is required, while targets selected by distinct relationship lanes are
75
75
  optional and must be narrowed by the handler.
76
76
 
77
- For tables queried by authored actions, `resource.databaseAccess` adds an
78
- independent Postgres RLS policy without adding HTTP surface. It never mounts a
79
- read/CRUD route and never adds an OpenAPI operation. The action remains the API
80
- layer where validation, state transitions, side effects, and business logic
81
- belong; `databaseAccess` is only the database's row-level upper bound.
77
+ For tables queried by authored actions, `resource.databaseAccess` opens a
78
+ **delegated-principal lane** at the database: an independent Postgres RLS policy
79
+ with no HTTP surface. It never mounts a read/CRUD route and never adds an
80
+ OpenAPI operation. The action remains the API layer where validation, state
81
+ transitions, side effects, and business logic belong; `databaseAccess` is only
82
+ the database's row-level upper bound.
83
+
84
+ It exists for one reason. A delegated principal has no `userId`, no active
85
+ organization, and no membership roles, so the table's ordinary firewall
86
+ predicate — `organizationId = ctx.activeOrgId` — can never match for it. The
87
+ lane is the row rule that CAN: the principal's own verified claims.
82
88
 
83
89
  {/* doc-compile: skip — provider prerequisite: `resource.databaseAccess` compiles only on Cloudflare + Neon `connectionMode: "hyperdrive"` (RLS + transaction-local claims), and the gate's harness is D1. The file is otherwise whole and compiles on a Neon project. */}
84
90
  ```typescript
@@ -95,49 +101,81 @@ export const attendanceEvidence = q.table('attendanceEvidence', {
95
101
  });
96
102
 
97
103
  export default defineTable(attendanceEvidence, {
98
- // Ordinary account CRUD remains organization-scoped.
104
+ // The ACCOUNT lane: ordinary organization-scoped CRUD. This is the firewall,
105
+ // and the firewall is the only pillar that lowers to SQL.
99
106
  firewall: [
100
107
  { field: "organizationId", equals: "ctx.activeOrgId" },
101
108
  ],
102
109
 
103
- // Authored actions can use their caller-scoped db under one of two exact
104
- // row lanes. Sibling arms OR; fields in each arm AND.
110
+ // The DELEGATE lane: the event delegate has no active organization, so the
111
+ // firewall above can never admit it. Its rows are the ones its own claims
112
+ // name. Fields inside one arm AND; sibling `or` arms are independent lanes.
105
113
  databaseAccess: {
106
114
  select: {
107
- or: [
108
- {
109
- roles: ["AUTHENTICATED"],
110
- record: {
111
- organizationId: { equals: "$ctx.activeOrgId" },
112
- },
113
- },
114
- {
115
- principals: ["event_delegate"],
116
- record: {
117
- eventId: { equals: "$ctx.principal.claims.eventId" },
118
- personId: { equals: "$ctx.principal.claims.personId" },
119
- },
120
- },
121
- ],
115
+ principals: ["event_delegate"],
116
+ record: {
117
+ eventId: { equals: "$ctx.principal.claims.eventId" },
118
+ personId: { equals: "$ctx.principal.claims.personId" },
119
+ },
122
120
  },
123
121
  },
124
122
  });
125
123
  ```
126
124
 
127
- `databaseAccess` supports `select`, `insert`, `update`, and `delete` with a
128
- purpose-built, SQL-pushable rule language: `principals`, `roles`, recursive
129
- `or`/`and`, and record `equals` against a DB-visible account or principal
130
- context value. Application-only values such as `userRole`, functions, and
131
- request/body fields stay at the action access layer; the compiler refuses them
132
- inside database RLS rather than pretending PostgreSQL can evaluate them.
133
-
134
- Every authorization path must contain at least one nonempty record equality.
135
- A principal-only or role-only leaf is rejected; every `or` arm must be bounded.
136
- An `and` group is bounded when at least one child bounds every expansion (for
137
- example, a principal child AND an event-id record child). A node cannot mix
138
- leaf fields with `or`/`and`, because the boolean node is the complete rule.
139
- This mandatory shape prevents an action declaration from accidentally granting
140
- the delegated principal an entire table.
125
+ ### One lane, one policy
126
+
127
+ The compiler emits exactly **one** permissive policy per table with a lane,
128
+ `<table>_principal_scope`, whose `USING` is the OR over the declared principal
129
+ arms. Two principal types on the same table are two arms of that one policy,
130
+ not two policies.
131
+
132
+ Its **command is the lane's declared reach**:
133
+
134
+ | Declared | Emitted |
135
+ |----------|---------|
136
+ | `select` only | `FOR SELECT`, `USING` only — the lane reads and cannot write |
137
+ | any of `insert` / `update` / `delete` | `FOR ALL`, with the same predicate as `WITH CHECK` |
138
+
139
+ Whether a delegate may write is a property of the lane, declared once by the
140
+ author, so the database enforces it as the policy's command. Which *verb* a
141
+ caller may reach is still the API's decision — RLS is the lane backstop, not a
142
+ per-operation access matrix.
143
+
144
+ The policy is **permissive**, and PostgreSQL ORs permissive policies together,
145
+ so the lane opens *beside* the table's `<table>_scope` firewall policy rather
146
+ than narrowing it. That is the point — the delegated caller has no active
147
+ organization — but it means a `databaseAccess` arm is never a place to write a
148
+ restriction: a row that satisfies the arm is reachable even when the table
149
+ firewall would not have matched it, and even when it is soft-deleted.
150
+ Restrictions belong in `firewall`. The restrictive `<table>_deny_anon` and
151
+ `<table>_principal_fence` policies remain the only arms that cap every lane.
152
+
153
+ ### What the compiler refuses, and why
154
+
155
+ `databaseAccess` lowers **only** `principals` + `record`, plus recursive
156
+ `or`/`and` over those. Two shapes that used to be spellable here are now
157
+ compile errors:
158
+
159
+ - **`roles`, anywhere.** Authored roles are enforced by the API and never reach
160
+ SQL (generated RLS is a backstop, not a second copy of `access`), so a role
161
+ arm here promised an authorization the database did not enforce. `roles` is
162
+ absent from the `DatabaseAccessRule` type as well, so an editor rejects it
163
+ before the compiler does.
164
+ - **A `record` equality with no `principals` gate.** That is an owner or tenant
165
+ rule, and those go in `firewall` — the one pillar that lowers to SQL. If the
166
+ owner boundary must hold at the database, author it as a firewall arm.
167
+
168
+ Both produce: *databaseAccess lowers only delegated-principal lanes (principals
169
+ + record). Account-lane scope belongs in firewall; roles are enforced by the
170
+ API.*
171
+
172
+ Every authorization path must also contain at least one record equality. A
173
+ principal-only leaf is rejected; every `or` arm must be bounded on its own,
174
+ because each is an independent lane. An `and` group is one lane whose children
175
+ may split the principal gate and the row bound between them. A node cannot mix
176
+ leaf fields with `or`/`and`, because the boolean node is the complete rule. This
177
+ mandatory shape is what stops a lane declaration from quietly granting a
178
+ delegated principal an entire table.
141
179
 
142
180
  The supported equality sources are `ctx.userId`, `ctx.activeOrgId`,
143
181
  `ctx.activeTeamId`, `ctx.principal.actor.id`, optional principal session/family
@@ -145,10 +183,19 @@ ids, and `ctx.principal.claims.<name>` (with or without a leading `$`). The
145
183
  record keys are Drizzle/JavaScript table field names; Quickback resolves them
146
184
  through the table metadata and quotes the exact physical PostgreSQL identifier,
147
185
  so a field such as `eventId: text("event-id")` is safe. Unknown fields fail the
148
- compile. `ADMIN` and the app-only `INTERNAL` marker are forbidden on this DB
149
- surface, while `SYSADMIN` retains its explicit `cms.sysadmin` prerequisite. The
150
- feature is rejected outside Cloudflare + Neon Hyperdrive because those targets
151
- cannot guarantee request-scoped Postgres claims.
186
+ compile. Application-only values — `userRole`, functions, request/body fields —
187
+ stay at the action access layer; the compiler refuses them rather than
188
+ pretending PostgreSQL can evaluate them. The feature is rejected outside
189
+ Cloudflare + Neon Hyperdrive because no other target can guarantee
190
+ request-scoped Postgres claims.
191
+
192
+ > **Upgrading.** The four per-operation `<table>_database_<op>` policies are
193
+ > retired. One appended `quickback_rls` migration drops them on every table and
194
+ > creates the single `<table>_principal_scope` where a lane is declared —
195
+ > append-only, like every other security migration. A `databaseAccess` block that
196
+ > still carries `roles` (or a principal-less `record`) fails the compile with the
197
+ > message above; move the account arm to `firewall` and keep the principal arm.
198
+
152
199
 
153
200
  ### Scoped relational-query safety
154
201
 
@@ -15,6 +15,17 @@ Two declaration sites:
15
15
  idempotency, and compiler-applied writes, for an action you are writing
16
16
  anyway.
17
17
 
18
+ Both work on **any table in the feature** — the primary and its siblings
19
+ alike. A sibling table's transitions synthesize to
20
+ `actions/<table>/<name>.ts`, bound to that table, importing the generated
21
+ per-table helper (`.quickback/define-action.<table>`), and mount at
22
+ `POST /<table>/:id/<name>` exactly like a primary's. So a status machine on a
23
+ child table (`reservations` inside `features/sessions/`) does not force the
24
+ table into its own feature — group related tables freely. Never replace
25
+ declared transitions with hand-written per-verb actions: you lose the
26
+ generated routes, the `guards.protected` integration, and the CMS
27
+ affordances.
28
+
18
29
  ## Two lines per state change
19
30
 
20
31
  ```typescript
@@ -78,6 +78,10 @@ the next migrate.
78
78
  - `OLD.column` / `NEW.column` references use **SQL column names**
79
79
  (`deleted_at`, not `deletedAt`) and are validated against the table at
80
80
  compile time.
81
+ - Bare `CASE ... END` expressions, including nested cases, are supported.
82
+ For example: `SELECT CASE WHEN NEW.total < 0 THEN RAISE(ABORT, 'invalid total') END;`.
83
+ That `END` closes the expression; authored `BEGIN ... END` trigger frames
84
+ are rejected.
81
85
  - Optional `when:` is a SQL expression guard (`WHEN` clause).
82
86
  - To reject a write, `SELECT RAISE(ABORT, 'message');` — this is the only
83
87
  trigger form that blocks *every* write path, including raw SQL.
@@ -62,3 +62,40 @@ Roles are used throughout the security layers — in [Access](/define/access) ru
62
62
 
63
63
  - [Plugins](/platform/auth/plugins) — Email OTP, passkeys, magic links, and more
64
64
  - [Security](/platform/auth/security) — Cookies, rate limiting, cross-domain auth
65
+
66
+ ## Compiler-managed auth versions and upgrades
67
+
68
+ The compiler pins Better Auth, its schema CLI, and the generated companion
69
+ packages to **1.7.2**. Recompile and install the emitted dependencies together;
70
+ remove older Better Auth overrides from `build.dependencies`. An incompatible
71
+ override is rejected because it would run a different auth version from the
72
+ one that generated your schema.
73
+
74
+ For an existing project, retain its `quickback/drizzle` migration history and
75
+ use the updated CLI when recompiling. The CLI generates the upgrade locally;
76
+ migration history stays on your machine. Apply the newly generated auth migration before
77
+ starting the updated Worker. Existing migration SQL is preserved. The upgrade
78
+ adds the current JWT/OAuth schema, including JWKS `alg`/`crv` and resource-bound
79
+ grants, and backfills account identities without resetting credentials.
80
+
81
+ Automatic account backfill covers password, SIWE, Google, Apple, Facebook,
82
+ Line, GitHub, and compiler-managed Cloudflare accounts. Unknown/custom provider
83
+ identities and duplicate identities must be resolved with an explicit migration;
84
+ the generated migration fails before replacing existing account rows. Custom
85
+ foreign keys into SQLite's account table also require an explicit migration.
86
+ Rehearse the migration against a database copy, and stop old auth writers during
87
+ the cutover so they cannot write the previous account shape.
88
+
89
+ Existing OAuth grants without a recorded resource set are revoked during the
90
+ upgrade; clients must authorize again. Client registrations and ordinary
91
+ sessions are retained. The compiler maps its audience configuration into the
92
+ 1.7 `resources` option and preserves the previous global resource allowlist
93
+ for clients (`enforcePerClientResources: false`). Authorization-code and refresh
94
+ grants still bind resources and reject widening to an unauthorized resource.
95
+ Projects opting into per-client resource restrictions must link their clients
96
+ to resources using the OAuth provider's resource administration APIs.
97
+
98
+ The bundled Account UI uses `signIn.social` and `linkSocial` for generic OAuth
99
+ providers, including Cloudflare. Their callback is now
100
+ `/auth/v1/callback/cloudflare`; update the registered redirect URI when upgrading
101
+ an existing Cloudflare login integration.
@@ -395,7 +395,7 @@ For all Quickback-generated code, D1's application-layer security provides equiv
395
395
  2. **Generated code enforces rules** - All CRUD and Action endpoints automatically apply firewall, access, guards, and masking.
396
396
  3. **Single entry point** - Every request flows through your API where security is enforced.
397
397
 
398
- Unlike Neon, where PostgreSQL RLS provides database-level enforcement (protecting data even if application code has bugs), D1's security comes from architecture: the database is inaccessible except through your Worker, and all generated routes apply the four security pillars. The trade-off is that **custom routes you write outside Quickback must manually apply security** — there is no database-level safety net.
398
+ Unlike Neon, where PostgreSQL RLS provides a database-level backstop (protecting tenant scope, soft delete and lane admission even if application code has bugs — roles, status, transitions and masking stay with the API either way, see [Row Level Security](/platform/database/neon#row-level-security)), D1's security comes from architecture: the database is inaccessible except through your Worker, and all generated routes apply the four security pillars. The trade-off is that **custom routes you write outside Quickback must manually apply security** — there is no database-level safety net.
399
399
 
400
400
  ### Comparison with Neon RLS
401
401
 
@@ -403,7 +403,7 @@ Unlike Neon, where PostgreSQL RLS provides database-level enforcement (protectin
403
403
  |----------|------|-----|
404
404
  | CRUD endpoints | ✅ Secure (RLS + App) | ✅ Secure (App) |
405
405
  | Actions | ✅ Secure (RLS + App) | ✅ Secure (App) |
406
- | Manual routes | ✅ RLS still protects | ⚠️ Must apply firewall |
406
+ | Manual routes | ✅ RLS still fences tenant scope, soft delete and lane admission — not roles | ⚠️ Must apply firewall |
407
407
  | External DB access | ⚠️ Possible with credentials | ✅ Not possible |
408
408
  | Dashboard queries | Via the Neon console | ⚠️ Admin only (audit logged) |
409
409
 
@@ -390,6 +390,46 @@ commands with their current definitions. An existing project whose `build`
390
390
  script still runs `auth:schema` therefore converges to the TypeScript-only
391
391
  build, while unrelated custom scripts remain intact.
392
392
 
393
+ ### Better Auth's tables stay vanilla Better Auth
394
+
395
+ Better Auth's own API is the authorization gate for its tables. Quickback does
396
+ not reimplement that gate in SQL — no policy re-derives membership, checks a
397
+ role, or splits by verb. What the compiler adds is the same **backstop** every
398
+ feature table gets, so a leaked `DATABASE_URL` or a mis-scoped handle cannot
399
+ read another user's or another organization's auth rows:
400
+
401
+ | Policy | Kind | On which tables |
402
+ |--------|------|-----------------|
403
+ | `<table>_deny_anon` | RESTRICTIVE `FOR ALL` | Every managed table |
404
+ | `quickback_service_role_all` | permissive `FOR ALL` | Every table in the `auth` schema, created by the role bootstrap |
405
+ | `<table>_scope` | permissive **`FOR SELECT`** | Only tables with a caller-readable scope column |
406
+
407
+ **Reads are tenant/self scoped; writes go through Better Auth only.** The scope
408
+ policy is `FOR SELECT` with a `USING` clause and no `WITH CHECK`, so the caller
409
+ lane can read these rows and change none of them — a handle cannot set its own
410
+ `member.role`. Better Auth's adapter always stamps the service marker, so every
411
+ write it makes runs on the service lane. The predicate:
412
+
413
+ | Table | Scope |
414
+ |-------|-------|
415
+ | `user` | `id = auth.user_id()` |
416
+ | `session`, `account`, `passkey` | `user_id = auth.user_id()` |
417
+ | `apikey` | `reference_id = auth.user_id()` — Better Auth's apikey table has no `user_id` |
418
+ | `organization` | `id = public.get_active_org_id()` |
419
+ | `member`, `invitation`, `team` | `organization_id = public.get_active_org_id()` |
420
+ | `team_member` | `team_id = public.get_active_team_id()` |
421
+
422
+ Everything else is **service-only** — deny-anon plus the bootstrap lane is the
423
+ entire policy set, and no caller-scoped handle can read a row either: `verification`,
424
+ `jwks`, the Better Auth rate-limit counters, `device_code`, the
425
+ `oauth_*` provider tables and the `agent_*` / `approval_request` agent-auth
426
+ tables. Better Auth's own adapter always stamps the service marker, so its
427
+ reads and writes never consult any of this; the policies exist for the handles
428
+ that are *not* Better Auth.
429
+
430
+ A table with no obvious scope column is service-only by construction. The
431
+ compiler will not invent a predicate for one — it fails closed.
432
+
393
433
  ## Migrations
394
434
 
395
435
  Neon uses PostgreSQL migrations, distinct from D1's SQLite migrations. One
@@ -481,9 +521,24 @@ role authority.
481
521
 
482
522
  ## Row Level Security
483
523
 
484
- Quickback emits RLS policies from your `firewall` and `access` config. Neon's
485
- policies read the transaction-local claims described above via `auth.user_id()`
486
- and the `get_active_org_id()` / `has_any_role()` helpers.
524
+ Generated RLS is a **backstop, not a second copy of `access`**. Every database
525
+ call goes through the API, and the API owns roles, status, transitions and
526
+ masking. RLS exists so that a bug in a custom route, or a handle that escaped
527
+ its scope, cannot cross a tenant, resurrect a soft-deleted row, or read another
528
+ owner's row. It is the floor under the application, not a second application.
529
+
530
+ Quickback lowers your `firewall` config — and only your `firewall` config —
531
+ into policies that read the transaction-local claims described above through
532
+ `auth.user_id()`, `get_active_org_id()`, `get_active_team_id()`, `get_scope()`
533
+ and the `get_principal_*()` helpers. Each feature table gets exactly four
534
+ policies:
535
+
536
+ | Policy | Kind | What it does |
537
+ |--------|------|--------------|
538
+ | `<table>_deny_anon` | RESTRICTIVE `FOR ALL` | Blocks any query carrying neither a stamped user id, nor a verified delegated/scope principal, nor the service marker |
539
+ | `<table>_service_role` | permissive `FOR ALL` | Admits Worker-internal contexts — see [Background jobs and cross-tenant actions](#background-jobs-and-cross-tenant-actions) |
540
+ | `<table>_principal_fence` | RESTRICTIVE `FOR ALL` | Caps every permissive policy, so no policy can broaden a request that carries the wrong principal type |
541
+ | `<table>_scope` | permissive `FOR ALL` | The firewall scope predicate. `USING` also requires `deleted_at IS NULL` on soft-deletable tables; `WITH CHECK` is the scope predicate alone, so a row can be soft-deleted but never resurrected |
487
542
 
488
543
  ```typescript
489
544
  firewall: [
@@ -492,17 +547,86 @@ firewall: [
492
547
  ```
493
548
 
494
549
  ```sql
495
- CREATE POLICY "documents_select" ON documents FOR SELECT
550
+ CREATE POLICY "documents_scope"
551
+ ON "app"."documents" FOR ALL
552
+ TO quickback
496
553
  USING (
497
554
  organization_id = public.get_active_org_id()
498
- AND (public.is_admin() OR user_id = auth.user_id())
555
+ AND deleted_at IS NULL
556
+ )
557
+ WITH CHECK (
558
+ organization_id = public.get_active_org_id()
499
559
  );
500
560
  ```
501
561
 
502
- Every feature table also gets a restrictive `deny_anon` policy (blocks queries
503
- with neither a stamped user id nor a delegated principal) and a `service_role`
504
- policy (admits Worker-internal contexts — see
505
- [Background jobs and cross-tenant actions](#background-jobs-and-cross-tenant-actions)).
562
+ Exception tables (`firewall: [{ exception: true }]`) keep their permissive
563
+ `<table>_all` policy, and SYSTEM tables — idempotency keys, the webhook store,
564
+ Better Auth rate-limit counters, subscriptions, file metadata — stay
565
+ service-role only.
566
+
567
+ Better Auth's own tables carry the same backstop, in its two- or three-policy
568
+ form: see [Better Auth's tables stay vanilla Better
569
+ Auth](#better-auths-tables-stay-vanilla-better-auth).
570
+
571
+ ### What is deliberately not in SQL
572
+
573
+ Roles, status, transitions, masking and per-operation access are **not**
574
+ lowered into policies. That is a decision, not a gap:
575
+
576
+ - **Roles.** `access.roles` names your application's vocabulary. Mirroring it
577
+ into SQL made every role rename append a security migration, and left two
578
+ enforcement points that could disagree — with the SQL copy being the one
579
+ nobody reads. The API is the single gate.
580
+ - **Status and transitions.** A policy sees one row and no request context, so
581
+ it cannot express "an archived invoice may only move to `restored`, by the
582
+ route that logs the transition". A half-expressed rule in SQL is worse than
583
+ no rule in SQL.
584
+ - **Masking.** Masking shapes a response. RLS decides which rows a caller may
585
+ touch, never which columns come back redacted.
586
+ - **Per-operation access.** One `FOR ALL` scope policy is the same fence for
587
+ every verb. Four near-identical policies only made the tenant predicate
588
+ harder to read and easier to get subtly wrong in exactly one of them.
589
+
590
+ The consequence is intentional: at the **SQL layer**, a caller whose
591
+ organization role is `member` can update a same-org row. The route they would
592
+ have to call still refuses them, and anything reaching the database outside a
593
+ generated route holds a caller-scoped handle whose tenant is already fenced.
594
+
595
+ The compiler enforces the shape at compile time. `QB-RLS-SCOPE-POLICY` requires
596
+ all four policies, requires a tenant/owner/scope predicate in the scope policy's
597
+ `USING` clause, and **fails the build if any policy body calls `has_any_role`**.
598
+ Opt out with `compiler.securityContracts.rls.requireScopePolicy: false` —
599
+ `requireCrudPolicies` is the pre-016 name for the same key and is still honoured.
600
+
601
+ ### Upgrading an existing database
602
+
603
+ An existing project gets **one appended `quickback_rls` security migration** on
604
+ its next compile. It runs `DROP POLICY IF EXISTS` on the retired names before
605
+ creating the new ones, so the upgrade is append-only: prior migration files keep
606
+ their bytes and their journal hashes, and a second unchanged compile appends
607
+ nothing.
608
+
609
+ Apply it with the **setup-owner credential**, not `quickback_admin`. The
610
+ security migration reissues the helper functions, and PostgreSQL refuses that to
611
+ a role that does not own them (`42501 must be owner of function ...`) — the same
612
+ requirement that already applies to any changed security or bootstrap SQL.
613
+
614
+ The same migration also drops the five helper functions the generated policies
615
+ no longer reference — `has_any_role`, `has_org_role`, `get_user_role`,
616
+ `is_owner` and `is_org_member` — after the policy statements that stop
617
+ referencing them. Membership is proven by the Worker and stamped as the request
618
+ org, so nothing re-derives it in SQL.
619
+
620
+ The retired names include the per-verb auth-table policies
621
+ (`users_select`, `members_insert`, …) that older projects carry. They are
622
+ dropped, so an upgraded database converges on the narrower set rather than
623
+ keeping a wider policy nobody emits any more.
624
+
625
+ One leftover worth knowing: the redundant `idx_<table>_<column>` index the
626
+ compiler used to infer alongside an index your schema already declared is no
627
+ longer emitted, but an append-only security migration does not drop an index an
628
+ older journal created. New databases get one index; existing ones keep the
629
+ duplicate until you drop it yourself.
506
630
 
507
631
  ### Delegated principal RLS
508
632
 
@@ -534,60 +658,103 @@ database context uses the same resolved union plus separate compiler-internal
534
658
  cannot appear in an action `AppContext`, and a delegated action context cannot
535
659
  carry account/org/team/membership fields.
536
660
 
537
- `resource.databaseAccess` emits operation-specific, RLS-only policies for
538
- authored actions and support tables. It does not mount generic routes or
539
- OpenAPI operations. Every authorization path must include at least one
540
- SQL-lowerable record equality; any unbounded OR arm or principal/role-only leaf
541
- fails compilation. This lets an organization account lane and a disjoint
542
- event/person delegated lane share a table without weakening either:
661
+ `resource.databaseAccess` opens a **delegated-principal lane** at the database:
662
+ RLS only, no generic routes and no OpenAPI operations. It exists because a
663
+ delegated principal has no account identity — no `userId`, no active
664
+ organization, no membership roles — so the table's ordinary firewall predicate
665
+ can never match for it. The lane is the row rule that can: the principal's own
666
+ verified claims, read through `get_principal_claim()`.
543
667
 
544
668
  ```typescript
669
+ // The account lane is the FIREWALL. The delegate lane is databaseAccess.
670
+ firewall: [
671
+ { field: "organizationId", equals: "ctx.activeOrgId" },
672
+ ],
545
673
  databaseAccess: {
546
674
  select: {
547
- or: [
548
- {
549
- roles: ["AUTHENTICATED"],
550
- record: { organizationId: { equals: "$ctx.activeOrgId" } },
551
- },
552
- {
553
- principals: ["event_delegate"],
554
- record: {
555
- eventId: { equals: "$ctx.principal.claims.eventId" },
556
- personId: { equals: "$ctx.principal.claims.personId" },
557
- },
558
- },
559
- ],
675
+ principals: ["event_delegate"],
676
+ record: {
677
+ eventId: { equals: "$ctx.principal.claims.eventId" },
678
+ personId: { equals: "$ctx.principal.claims.personId" },
679
+ },
560
680
  },
561
681
  }
562
682
  ```
563
683
 
564
- Postgres combines the record comparisons inside each arm with AND. Restrictive
565
- per-operation principal fences also cap every permissive policy, so a public,
566
- firewall-exception, or old permissive policy cannot admit the wrong principal
567
- type. The action still owns all application behavior; these policies only
568
- constrain which rows its caller-scoped `db` or transaction may touch.
684
+ That emits exactly **one** permissive policy on the table:
685
+
686
+ ```sql
687
+ CREATE POLICY "attendance_evidence_principal_scope"
688
+ ON "app"."attendance_evidence" FOR SELECT TO quickback
689
+ USING (public.get_principal_type() = 'event_delegate'
690
+ AND "event_id" = public.get_principal_claim('eventId')
691
+ AND "person_id" = public.get_principal_claim('personId'));
692
+ ```
693
+
694
+ Several principal types on one table are several OR arms of that same policy,
695
+ never several policies. Postgres ANDs the record comparisons inside each arm.
696
+
697
+ The policy's **command is the lane's declared reach**: `FOR SELECT` with no
698
+ `WITH CHECK` when only `databaseAccess.select` is declared, `FOR ALL` with the
699
+ same predicate as `WITH CHECK` as soon as any of `insert` / `update` / `delete`
700
+ is. Whether a delegate lane may write is a property of the lane, declared once
701
+ by the author, so the database enforces it as the policy's command; WHICH verb
702
+ a caller may reach is still the API's decision.
703
+
704
+ The lane lowers `principals` + `record` and nothing else. Two shapes are
705
+ compile errors, with the same message: **`roles` anywhere** (authored roles are
706
+ enforced by the API and never reach SQL, so a role arm here promised an
707
+ authorization the database did not enforce), and **a `record` equality with no
708
+ `principals` gate** (that is an owner/tenant rule, and those belong in
709
+ `firewall`, the one pillar that lowers to SQL). Every authorization path must
710
+ still carry at least one SQL-lowerable record equality; an unbounded `or` arm
711
+ or a principal-only leaf fails the compile.
712
+
713
+ The policy is **permissive**, and PostgreSQL ORs permissive policies together,
714
+ so `databaseAccess` opens a lane *beside* `<table>_scope` rather than narrowing
715
+ it — that is the point (the delegated caller has no active organization, so the
716
+ tenant predicate can never match), but it means a `databaseAccess` arm is never
717
+ a place to write a restriction. A row that satisfies the arm is reachable even
718
+ when the table firewall would not have matched it, and even when it is
719
+ soft-deleted. Write the restriction in `firewall`; the restrictive
720
+ `<table>_deny_anon` and `<table>_principal_fence` policies are the only arms
721
+ that cap every lane. The fence also means a table admits a principal type only
722
+ where its `access` (or its lane) names that type — a `ctx.principal.claims.*`
723
+ firewall arm on a table whose access names no principal is unreachable.
724
+
725
+ > **Upgrading.** The four per-operation `<table>_database_<op>` policies are
726
+ > retired. One appended `quickback_rls` migration drops them on every table and
727
+ > creates the single `<table>_principal_scope` where a lane is declared —
728
+ > append-only, like every other security migration, so no applied file changes.
729
+
569
730
 
570
731
  ### Firewall patterns
571
732
 
733
+ Every pattern is the same one `FOR ALL` scope policy with a different
734
+ predicate — no per-operation variants, no role arms.
735
+
572
736
  **Organization-scoped:**
573
737
 
574
738
  ```sql
575
- CREATE POLICY "projects_select" ON projects FOR SELECT
576
- USING (organization_id = public.get_active_org_id());
739
+ CREATE POLICY "projects_scope" ON "app"."projects" FOR ALL TO quickback
740
+ USING (organization_id = public.get_active_org_id())
741
+ WITH CHECK (organization_id = public.get_active_org_id());
577
742
  ```
578
743
 
579
- **User-scoped:**
744
+ **User-scoped** (`owner_id`, the auto-firewalled ownership column):
580
745
 
581
746
  ```sql
582
- CREATE POLICY "preferences_select" ON preferences FOR SELECT
583
- USING (user_id = auth.user_id());
747
+ CREATE POLICY "preferences_scope" ON "app"."preferences" FOR ALL TO quickback
748
+ USING (owner_id = auth.user_id())
749
+ WITH CHECK (owner_id = auth.user_id());
584
750
  ```
585
751
 
586
- **Public tables:**
752
+ **Exception tables** (`firewall: [{ exception: true }]`) — no scope predicate,
753
+ so the restrictive deny-anon policy is the only fence left:
587
754
 
588
755
  ```sql
589
- CREATE POLICY "categories_deny_anon" ON categories FOR ALL TO anon USING (false);
590
- CREATE POLICY "categories_all" ON categories FOR ALL TO authenticated USING (true) WITH CHECK (true);
756
+ CREATE POLICY "categories_all" ON "app"."categories" FOR ALL TO quickback
757
+ USING (true) WITH CHECK (true);
591
758
  ```
592
759
 
593
760
  ### Helper functions
@@ -597,11 +764,21 @@ CREATE POLICY "categories_all" ON categories FOR ALL TO authenticated USING (tru
597
764
  | `auth.user_id()` | Reads the verified user id from the transaction-local `request.jwt.claim.sub` setting |
598
765
  | `get_active_org_id()` | Reads the request-scoped org from the transaction-local `request.jwt.claim.org_id` setting |
599
766
  | `get_active_team_id()` | Reads the request-scoped team from `request.jwt.claim.team_id` (teams mode) |
600
- | `has_any_role(roles[])` | Checks if the user has any specified role in the request org |
601
- | `has_org_role(role)` | Checks for a single specific role |
602
- | `is_org_member()` | Checks org membership in the request org |
603
- | `is_owner(owner_id)` | Checks record ownership against `auth.user_id()` |
604
- | `is_admin()` | Checks the `auth.admins` table (admin mode) |
767
+ | `is_admin()` | Checks the `auth.admins` table (admin mode). No scope policy calls it. |
768
+
769
+ There is no role-lookup helper and no membership helper. Roles are the API's
770
+ gate, not SQL's: `QB-RLS-SCOPE-POLICY` fails the build if any policy body calls
771
+ `has_any_role`. Membership is Better Auth's gate: the Worker proves it once and
772
+ stamps the active organization, and policies compare against that stamp.
773
+
774
+ `is_admin()` is no part of that gate either. Enabling the admin plugin does
775
+ **not** widen any scope policy: "admin" is a role, and a scope policy is the
776
+ firewall predicate, full stop. An admin's cross-tenant read goes through the
777
+ API on the service lane — an `unsafe: { crossTenant: true }` action stamps
778
+ `quickback.service_role`, which `<table>_service_role` admits — not by SQL
779
+ re-deriving admin from `auth.admins`. Older databases carry the previous
780
+ `(public.is_admin() OR (…))` form until the new security migration replaces
781
+ those policies; it does, in the same append-only pass.
605
782
 
606
783
  All helpers are TEXT-typed to match Better Auth's prefixed ids (`org_abc123`).
607
784
  The request org/team scope is passed by the Worker **per transaction**, not read
@@ -612,14 +789,27 @@ SQL-side access is revoked immediately. Fail closed.
612
789
 
613
790
  The only compiler-owned support tables the RLS layer reads live in
614
791
  `src/db/rls-support.schema.ts`: a `profiles` table (populated by the
615
- `sync_profile_display_name()` trigger and protected by the `profiles_*`
616
- policies) and, when admin/sysadmin helpers are emitted, an `admins` table (read
792
+ `sync_profile_display_name()` trigger and protected by `profiles_deny_anon`
793
+ plus a self-scoped, read-only `profiles_scope`) and, when admin/sysadmin helpers are
794
+ emitted, an `admins` table (read
617
795
  by `is_admin()` / `is_sysadmin()`). Better Auth's own `sessions` table may still
618
796
  carry an `active_organization_id`, but Quickback RLS never reads it.
619
797
 
620
798
  RLS coverage includes Better Auth's own tables — including those the compiler
621
799
  force-enables (organization, admin, `apikeys`; plus the OAuth/agent table
622
- families when those surfaces are on, locked to service-role only).
800
+ families when those surfaces are on, which are service-only). Database-backed
801
+ Better Auth rate-limit counters also receive both `ENABLE` and `FORCE ROW LEVEL
802
+ SECURITY`. Only the internal auth service context can read or change those
803
+ counters; ordinary caller claims grant no access. See [Better Auth's tables
804
+ stay vanilla Better Auth](#better-auths-tables-stay-vanilla-better-auth) for
805
+ the exact policy set per table.
806
+ Cloudflare uses database counters by default. Explicit memory storage or
807
+ inactive rate limiting does not generate policies for a missing counter table.
808
+
809
+ For existing databases, recompile and apply the newly appended security
810
+ migration using the **setup-owner credential**, as required for changed
811
+ security/bootstrap SQL, to protect existing counters. Applied migration files stay unchanged
812
+ and existing counter rows are preserved.
623
813
 
624
814
  ## Background jobs and cross-tenant actions
625
815
 
@@ -847,16 +1037,17 @@ Hyperdrive owns the shared connection pool.
847
1037
 
848
1038
  > Postgres authorizes `SELECT … FOR UPDATE` as both a read and a write: the row
849
1039
  > must pass its `SELECT` **and** `UPDATE` policies. This matters for delegated
850
- > principals because Quickback emits a restrictive update fence for every table.
851
- > A principal with `databaseAccess.select` but no matching
852
- > `databaseAccess.update` can read an eligible row, but cannot lock it with
1040
+ > principals because a lane that declares only `databaseAccess.select` emits a
1041
+ > `FOR SELECT` policy — by design, since read-only is what the author declared.
1042
+ > Such a principal can read an eligible row but cannot lock it with
853
1043
  > `.for("update")`.
854
1044
  >
855
1045
  > Keep read-only eligibility and reference-table lookups as ordinary scoped
856
1046
  > selects. Lock the mutable grant, capacity, or redemption row that the action is
857
- > authorized to update. If an action legitimately must lock another table,
858
- > declare a narrowly bounded `databaseAccess.update` rule for that principal;
859
- > do not broaden or bypass the generated principal fence.
1047
+ > authorized to update. If an action legitimately must lock another table, declare
1048
+ > a narrowly bounded `databaseAccess.update` rule for that principal — which makes
1049
+ > its one lane policy `FOR ALL` with the same predicate as `WITH CHECK`. Do not
1050
+ > broaden the predicate or bypass the generated principal fence.
860
1051
 
861
1052
 
862
1053
  **Security is preserved, unchanged.** The verified caller claims run as the