@quickback-dev/cli 0.14.2 → 0.16.0
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.
- package/dist/commands/compile.d.ts.map +1 -1
- package/dist/commands/compile.js +40 -2
- package/dist/commands/compile.js.map +1 -1
- package/dist/docs/content.js +5 -5
- package/dist/docs/content.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/lib/copy-public-assets.d.ts +34 -0
- package/dist/lib/copy-public-assets.d.ts.map +1 -0
- package/dist/lib/copy-public-assets.js +118 -0
- package/dist/lib/copy-public-assets.js.map +1 -0
- package/dist/lib/copy-public-assets.test.d.ts +2 -0
- package/dist/lib/copy-public-assets.test.d.ts.map +1 -0
- package/dist/lib/copy-public-assets.test.js +151 -0
- package/dist/lib/copy-public-assets.test.js.map +1 -0
- package/dist/skill/docs/changelog.md +158 -0
- package/dist/skill/docs/compiler/config/index.md +18 -0
- package/dist/skill/docs/compiler/config/output.md +34 -0
- package/dist/skill/docs/compiler/definitions/access.md +16 -2
- package/dist/skill/docs/compiler/definitions/firewall.md +27 -0
- package/dist/skill/docs/compiler/definitions/schema.md +9 -0
- package/package.json +1 -1
- package/src/skill/docs/changelog.md +158 -0
- package/src/skill/docs/compiler/config/index.md +18 -0
- package/src/skill/docs/compiler/config/output.md +34 -0
- package/src/skill/docs/compiler/definitions/access.md +16 -2
- package/src/skill/docs/compiler/definitions/firewall.md +27 -0
- package/src/skill/docs/compiler/definitions/schema.md +9 -0
|
@@ -317,6 +317,40 @@ src/apps/ # Root assets directory
|
|
|
317
317
|
|
|
318
318
|
On custom domains, each SPA is served at root (`/`) via hostname-based routing. On the unified domain, CMS is at `/cms/` and Account is at `/account/`.
|
|
319
319
|
|
|
320
|
+
### Static Assets (`quickback/public/`)
|
|
321
|
+
|
|
322
|
+
Anything you drop under `quickback/public/` is copied verbatim into `src/apps/` on every compile. The compiler does not parse, template, or otherwise touch these files — they are bytes that ride past it into the Cloudflare ASSETS binding.
|
|
323
|
+
|
|
324
|
+
```
|
|
325
|
+
quickback/public/ # Source — checked into your repo
|
|
326
|
+
├── favicon.ico
|
|
327
|
+
├── robots.txt
|
|
328
|
+
├── og/
|
|
329
|
+
│ └── og-image.png
|
|
330
|
+
└── pdfs/
|
|
331
|
+
└── whitepaper.pdf
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
After compile:
|
|
335
|
+
|
|
336
|
+
```
|
|
337
|
+
src/apps/ # Destination — written by the CLI
|
|
338
|
+
├── favicon.ico # Served at https://your-domain/favicon.ico
|
|
339
|
+
├── robots.txt # Served at /robots.txt
|
|
340
|
+
├── og/og-image.png # Served at /og/og-image.png
|
|
341
|
+
├── pdfs/whitepaper.pdf
|
|
342
|
+
├── cms/ # Compiler-emitted SPA (don't shadow)
|
|
343
|
+
└── account/ # Compiler-emitted SPA (don't shadow)
|
|
344
|
+
```
|
|
345
|
+
|
|
346
|
+
Notes:
|
|
347
|
+
|
|
348
|
+
- The folder is optional. If it doesn't exist, this step is a no-op.
|
|
349
|
+
- Files removed from `quickback/public/` disappear from `src/apps/` on the next compile — `src/` is wiped and rewritten each run.
|
|
350
|
+
- Hidden entries (`.DS_Store`, `.git/`, dotfiles) are skipped.
|
|
351
|
+
- A file in `quickback/public/` that would overwrite a compiler-emitted path (e.g. `quickback/public/cms/index.html`) fails the compile with a clear error rather than silently shadowing the SPA shell.
|
|
352
|
+
- Binaries (images, fonts, PDFs) are copied byte-for-byte — there is no string round-trip.
|
|
353
|
+
|
|
320
354
|
### Generated Wrangler Assets Config
|
|
321
355
|
|
|
322
356
|
The compiler always generates `run_worker_first = true` when SPAs are enabled — the Worker handles all SPA routing (per hostname and per path prefix):
|
|
@@ -60,7 +60,7 @@ crud: {
|
|
|
60
60
|
The `+` suffix expands at compile time — `"member+"` becomes `["member", "admin", "owner"]` in the generated code. You can mix hierarchical and exact roles: `roles: ["member+", "finance"]` expands to `["member", "admin", "owner", "finance"]`.
|
|
61
61
|
|
|
62
62
|
- Roles without `+` are exact matches (no expansion)
|
|
63
|
-
- Pseudo-roles (`PUBLIC`, `AUTHENTICATED`, `USER`, `ADMIN`) cannot use the `+` suffix — they're terminal markers
|
|
63
|
+
- Pseudo-roles (`PUBLIC`, `AUTHENTICATED`, `USER`, `ADMIN`, `SYSADMIN`) cannot use the `+` suffix — they're terminal markers
|
|
64
64
|
- Using `+` with a role not in the hierarchy throws a compile error
|
|
65
65
|
- Using `+` without configuring `auth.roleHierarchy` throws a compile error
|
|
66
66
|
|
|
@@ -131,7 +131,7 @@ When `roles` and `userRole` both appear in a single `Access` node, they're combi
|
|
|
131
131
|
|
|
132
132
|
### Pseudo-roles
|
|
133
133
|
|
|
134
|
-
Quickback ships
|
|
134
|
+
Quickback ships five UPPERCASE role markers that are **not backed by a Better Auth role column** — they're system-level shortcuts handled directly by the compiler. The casing carries the boundary: UPPERCASE = pseudo-role (no plugin context required), lowercase = real role from a plugin's table (e.g. `members.role` from the org plugin).
|
|
135
135
|
|
|
136
136
|
| Role | Auth gate | Compile-time requirement | Runtime check |
|
|
137
137
|
|------|-----------|-------------------------|---------------|
|
|
@@ -139,6 +139,7 @@ Quickback ships four UPPERCASE role markers that are **not backed by a Better Au
|
|
|
139
139
|
| `AUTHENTICATED` | required | none | `ctx.authenticated === true` |
|
|
140
140
|
| `USER` | required | resource firewall **must** scope by `userId` | `ctx.authenticated` AND (`ctx.userRole` is unset OR `ctx.userRole === "user"`) |
|
|
141
141
|
| `ADMIN` | required | Better Auth admin plugin **must** be enabled | `ctx.authenticated && ctx.userRole === "admin"` |
|
|
142
|
+
| `SYSADMIN` | required | `cms: { sysadmin: true }` **must** be set on the project | `ctx.authenticated && ctx.userRole === "sysadmin"` |
|
|
142
143
|
|
|
143
144
|
You can mix pseudo-roles with real roles in the same list — they're OR'd together.
|
|
144
145
|
|
|
@@ -220,6 +221,19 @@ read: { access: { roles: ["ADMIN"] } }
|
|
|
220
221
|
|
|
221
222
|
Without the admin plugin you get a compile error pointing you to either enable the plugin or use lowercase `roles: ["admin"]` (the org-membership admin role).
|
|
222
223
|
|
|
224
|
+
#### `SYSADMIN` — cross-tenant DB-admin tier
|
|
225
|
+
|
|
226
|
+
Use `roles: ["SYSADMIN"]` for endpoints that should only be reachable by platform sysadmins — the cross-tenant DB-admin tier introduced in v0.15.0. Compiles to `ctx.userRole === "sysadmin"`. **Requires `cms: { sysadmin: true }` on the project config**; without that flag, using `SYSADMIN` fails the compile so the role can't sit as dead code.
|
|
227
|
+
|
|
228
|
+
```typescript
|
|
229
|
+
// Cross-tenant audit dashboard, sysadmin-only
|
|
230
|
+
read: { access: { roles: ["SYSADMIN"] } }
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
`SYSADMIN` is a strict superset of `ADMIN` — at runtime, the universal-bypass shortcuts in `evaluateAccess` admit `userRole === 'sysadmin'` anywhere they admit `userRole === 'admin'`. The distinction matters for one thing only: **the firewall escape hatch**. When `cms.sysadmin: true`, every `buildFirewallConditions` emits an `if (ctx.userRole === 'sysadmin') return undefined;` (or just the soft-delete predicate when present) at the top — so sysadmins see every tenant's rows, not just their own org's. That escape hatch does NOT fire for `userRole === 'admin'`; admins still go through the firewall like everyone else.
|
|
234
|
+
|
|
235
|
+
This separation exists so Better Auth admin-plugin powers (user management, impersonation) and DB-admin powers (cross-tenant data inspection) stay decoupled. A user can have `user.role === 'admin'` without DB-level cross-tenant access; a user can have `user.role === 'sysadmin'` without org-membership context. See [CMS Configuration](/compiler/config#cms-configuration) for the `cms.sysadmin` flag, the cross-tenant `/admin/v1/sysadmin/organizations` endpoint, and the SPA's "All organizations" sentinel.
|
|
236
|
+
|
|
223
237
|
#### Mixing pseudo-roles with real roles
|
|
224
238
|
|
|
225
239
|
Pseudo-roles and lowercase real roles compose with OR:
|
|
@@ -159,6 +159,33 @@ When the `firewall:` block is omitted, the compiler scans the schema for known s
|
|
|
159
159
|
|
|
160
160
|
So `firewall: [{ exception: true }]` on the default configuration returns `isNull(<table>.deletedAt)` from `buildFirewallConditions()` — no tenant filter, soft-delete filter still applied.
|
|
161
161
|
|
|
162
|
+
## Sysadmin Escape Hatch
|
|
163
|
+
|
|
164
|
+
When `cms: { sysadmin: true }` is set on the project (introduced in v0.15.0), every `buildFirewallConditions()` emits a runtime branch that drops tenant scopes for `ctx.userRole === 'sysadmin'` callers while keeping the soft-delete predicate:
|
|
165
|
+
|
|
166
|
+
```typescript
|
|
167
|
+
// Generated for an org-scoped table when cms.sysadmin: true
|
|
168
|
+
export function buildFirewallConditions(ctx: AppContext): SQL | undefined {
|
|
169
|
+
if (ctx.userRole === 'sysadmin') {
|
|
170
|
+
return isNull(invoices.deletedAt); // tenant predicate dropped, soft-delete kept
|
|
171
|
+
}
|
|
172
|
+
return and(
|
|
173
|
+
eq(invoices.organizationId, ctx.activeOrgId!),
|
|
174
|
+
isNull(invoices.deletedAt),
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
The escape branch is **only** emitted when:
|
|
180
|
+
|
|
181
|
+
- `cms.sysadmin: true` is set on the project config
|
|
182
|
+
- The table has at least one tenant-scope predicate (org / owner / team / `via:` relationship). Tables with no tenant scopes already return what a sysadmin would see, so the runtime check would be dead code.
|
|
183
|
+
- The firewall does not declare `{ exception: true }` (no tenant scopes to drop).
|
|
184
|
+
|
|
185
|
+
**Sysadmin is distinct from admin.** `userRole === 'admin'` callers still go through the firewall normally — only `userRole === 'sysadmin'` triggers the bypass. Admins keep their existing universal-bypass at the *access* layer (cross-org reads on per-record routes via `?organizationId=`), but the firewall's row predicate remains in force. Sysadmin is opt-in, configured per-project, and intended for the cross-tenant CMS DB-admin tier — see [CMS Configuration](/compiler/config#cms-configuration).
|
|
186
|
+
|
|
187
|
+
If your project doesn't set `cms.sysadmin: true`, the escape branch is never emitted and the role value is functionally inert.
|
|
188
|
+
|
|
162
189
|
## Common Patterns
|
|
163
190
|
|
|
164
191
|
```typescript
|
|
@@ -309,6 +309,15 @@ These internal tables still participate in the database schema and migrations
|
|
|
309
309
|
|
|
310
310
|
The compiler automatically injects the four **[audit fields](#audit-fields)** (`createdAt`/`createdBy`/`modifiedAt`/`modifiedBy`), the soft-delete pair (`deletedAt`/`deletedBy`, when soft delete is enabled), and **`organizationId`** into child/junction tables when the parent feature is org-scoped. This ensures cascade soft deletes and scoped queries work correctly without manual column definitions.
|
|
311
311
|
|
|
312
|
+
> **`id` is currently NOT auto-injected — declare it yourself**
|
|
313
|
+
>
|
|
314
|
+
> Unlike audit fields, the `id` column is your responsibility today. The CRUD/action route generators, FK probing, access checks, and OpenAPI emission all assume every queryable table has a single string-typed `id` column. Tables that omit it — or use a non-`id` single PK (`userId.primaryKey()`) or a compound `primaryKey({ columns: [...] })` constraint — parse fine but produce broken generated code downstream.
|
|
315
|
+
>
|
|
316
|
+
> Use `q.id()` (preferred) or `id: text("id").primaryKey()` / `id: integer("id").primaryKey({ autoIncrement: true })` on every table that participates in routes. For internal tables marked `// @quickback-internal`, the constraint doesn't apply.
|
|
317
|
+
>
|
|
318
|
+
> This asymmetry is being closed in **v0.14.8** — `injectIdField` will run unconditionally alongside audit injection, including on junction tables. See the [v0.14.7 changelog](/docs/changelog#coming-next--id-field-auto-injection-v0148) for the migration plan.
|
|
319
|
+
|
|
320
|
+
|
|
312
321
|
## Audit Fields
|
|
313
322
|
|
|
314
323
|
Quickback adds four audit columns to **every table** (including child/junction tables without `defineTable`) — never declare them in your schemas:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@quickback-dev/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.16.0",
|
|
4
4
|
"description": "CLI for Quickback — define your backend in TypeScript, compile to a fully wired Cloudflare Worker (or Bun / Node) with auth, database, migrations, security, CMS, and Account UI.",
|
|
5
5
|
"author": "Kardoe Incorporated <paul@kardoe.com>",
|
|
6
6
|
"license": "MIT",
|
|
@@ -4,6 +4,164 @@ Release notes for the Quickback compiler, CLI, and platform.
|
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
+
## v0.15.0 — May 7, 2026
|
|
8
|
+
|
|
9
|
+
### Sysadmin tier — cross-tenant DB-admin role for the CMS
|
|
10
|
+
|
|
11
|
+
A new opt-in `cms: { sysadmin: true }` flag turns the CMS into a Supabase-style cross-tenant DB-admin tool gated by `user.role === 'sysadmin'`. Distinct from `'admin'` so Better Auth admin-plugin powers (user management, impersonation) and DB-admin powers stay decoupled. Off by default — projects without the feature get zero behavior change.
|
|
12
|
+
|
|
13
|
+
When enabled, the compiler emits a `SYSADMIN` pseudo-role (fifth marker alongside `PUBLIC` / `AUTHENTICATED` / `USER` / `ADMIN`); a firewall escape hatch in every `buildFirewallConditions` that drops tenant scopes for `ctx.userRole === 'sysadmin'` while preserving soft-delete; a true cross-tenant `/admin/v1/sysadmin/organizations` endpoint that selects directly from the auth-schema `organization` table; and a relaxed cross-tenant guard that skips the `ORG_REQUIRED` 400 for sysadmins on list routes — that's how the SPA's "All organizations" sentinel reaches the firewall escape end-to-end.
|
|
14
|
+
|
|
15
|
+
The CMS SPA gains a two-mode design: org admins keep the existing membership-based switcher (Better Auth's `setActiveOrganization`); sysadmins get a `SysadminOrgSelector` that loads from the cross-tenant endpoint, defaults to "All organizations" (omits the org filter on reads), and pins selected tenants via `?organizationId=` on every API call (sysadmins have no member rows, so `setActive` would 403). A new `OrgGate` component handles no-active-org cases for org users — auto-pick when there's exactly one membership, full-frame picker for multiple, empty state for zero — so sessions that lost their active org don't dead-end.
|
|
16
|
+
|
|
17
|
+
Refusing to compile `roles: ["SYSADMIN"]` without `cms.sysadmin: true` keeps the role from sitting as dead code. RLS providers (Neon, Supabase) emit `false` for `SYSADMIN` today; per-table RLS policy emit is a follow-up.
|
|
18
|
+
|
|
19
|
+
### Durable Object `[[migrations]]` order is now preserved across recompiles
|
|
20
|
+
|
|
21
|
+
Cloudflare's migration system is append-only — every deploy must include previously-deployed migration tags in their original order, with new ones appended last. CF rejects deploys with `code: 10061` when the order shifts. The compiler used to iterate `bindings.durableObjects` in config order at emit time, so a user inserting a new DO into the middle of the array bumped every later auto-migration into the wrong slot, breaking deploys for projects with multiple DOs (caught by AttendVIP).
|
|
22
|
+
|
|
23
|
+
The CLI now sends the project's existing `wrangler.toml` (when present) in `existingFiles` alongside the drizzle meta. The compiler parses migration tags from it via `parseExistingMigrationTags`, then emits auto-generated DO `[[migrations]]` blocks in two phases: deployed entries first (preserving the existing wrangler.toml order), net-new entries appended last in `bindings.durableObjects` config order. Reordering DOs in the config array no longer reshuffles deployed migrations; inserting a new DO anywhere in the array always appends its migration block last. First compiles (no existing wrangler.toml) keep the current config-order behavior — no behavior change for new projects. User-declared `bindings.durableObjectMigrations` (historical entries) are unaffected; they continue to emit first.
|
|
24
|
+
|
|
25
|
+
### Standalone-action wrapper no longer 403s `AUTHENTICATED`-only routes on org-scoped projects
|
|
26
|
+
|
|
27
|
+
Standalone actions (`standalone: true`) on org-scoped projects emitted an unconditional `if (!ctx.activeOrgId) return 403 ACCESS_NO_ORG` gate before role checking. For an action declared `access: { roles: ["AUTHENTICATED"] }`, this contradicted the access rule itself: a signed-in user with no active org (e.g. just signed up but not yet joined an organization, or a token-auth caller) was the exact caller `AUTHENTICATED` was supposed to admit. Found by AttendVIP — every recompile re-introduced the bug because the fix lived in handler-side patches, not the generator. The standalone wrapper now skips the org gate when the access tree references any pseudo-role anywhere, including under `or:`/`and:` arms.
|
|
28
|
+
|
|
29
|
+
### Queue handler emit no longer drops the `queue` export when there are no embeddings
|
|
30
|
+
|
|
31
|
+
`compiler.ts` emits `src/queue-consumer.ts` whenever `embeddingFeatures.length > 0 || queueHandlers.length > 0`, but the worker entry only checked `hasEmbeddings`. Projects with custom queue handlers under `services/queues/*` and no embeddings got the consumer file generated and then no entry-point wiring — wrangler bound the queue to a missing handler at deploy time. Caught against AttendVIP's `sendCancelEmail` queue handler. `MainAppOptions` and `CloudflareMainAppOptions` gain a `hasQueueHandlers` flag; `generateQueueImport` and `generateCloudflareExport` now gate on `hasEmbeddings || hasQueueHandlers`.
|
|
32
|
+
|
|
33
|
+
### `quickback/public/` — static-asset passthrough into `src/apps/`
|
|
34
|
+
|
|
35
|
+
A new opt-in folder. Anything you drop under `quickback/public/` is copied verbatim into `src/apps/` on every compile, where the wrangler `[assets]` binding (`directory = "src/apps"`) already serves it. So `quickback/public/robots.txt` becomes reachable at `https://your-domain/robots.txt`, `quickback/public/og/og-image.png` at `/og/og-image.png`, and so on. Favicons, `robots.txt`, OG images, marketing PDFs, sitemap fragments, `.well-known/` files — anything you'd previously have had to post-process into `src/apps/` after each compile.
|
|
36
|
+
|
|
37
|
+
The compiler does **not** parse, template, or otherwise touch these files. They ride past it as bytes — the CLI does the copy after `writeFilesWithMerge`, using `fs.copyFile` so binaries (PNGs, fonts, PDFs) stay byte-perfect rather than being corrupted by the utf-8 string channel the compiler manifest uses for source files. The compiler API contract is unchanged; nothing round-trips through `compile.quickback.dev`.
|
|
38
|
+
|
|
39
|
+
Rules:
|
|
40
|
+
|
|
41
|
+
- **Optional.** If the folder doesn't exist, the step is a no-op.
|
|
42
|
+
- **Stale-cleaned.** `src/` is wiped and rewritten each compile, so files removed from `quickback/public/` disappear from `src/apps/` automatically on the next run.
|
|
43
|
+
- **Hidden entries skipped.** `.DS_Store`, `.git/`, dotfiles — none of these were intentional drops; including them would break worker asset bindings.
|
|
44
|
+
- **Collisions fail loud.** A file in `quickback/public/` whose path would shadow a compiler-emitted manifest entry — e.g. `quickback/public/cms/index.html` against the SPA shell — fails the compile with the offending paths listed, rather than silently overwriting and producing a confused-looking SPA build. Move or rename the offending file.
|
|
45
|
+
|
|
46
|
+
The change is contained to the CLI: `packages/cli/src/lib/copy-public-assets.ts` (helper + `PublicAssetCollisionError`) and one block in `packages/cli/src/commands/compile.ts`. Test coverage in `copy-public-assets.test.ts` walks the missing-folder, single-file, nested-tree, binary-preservation, hidden-entry, single-collision, multi-collision, empty-folder, and split-output cases — nine tests, byte-level assertions on the binary path.
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
## v0.14.7 — May 7, 2026
|
|
51
|
+
|
|
52
|
+
### Four more codegen bugs caught by AttendVIP — generated output now typechecks for projects with non-`id` PKs and DO-only features
|
|
53
|
+
|
|
54
|
+
Filed after AttendVIP's `tsc` reported 230 errors against the generated `src/`. Triage split them into six patterns; four are surgical and ship here. The other two (TS2769 ×156 + TS2339 ×~50) trace to a deeper assumption — every queryable table has a string-typed `id` column — and are deferred to v0.14.8 along with the agreed `id` auto-inject design (see *Coming next* below).
|
|
55
|
+
|
|
56
|
+
**1. Duplicate `guests` import in routes that use relationship-roles (`TS2300`).** The relationship-import injector (`generators/feature-generator.ts`) added `import { <table>, buildFirewallConditions as build<Table>FirewallConditions } from './<table>.resource'` whenever it detected a relationship-table reference in the routes file — without checking that the table binding was already imported from `./schema` upstream. So `guests.routes.ts` ended up with `guests` declared twice. Fix: scan the existing import block, only add identifiers that aren't already in scope (drop the binding from the new import line, or skip the line entirely if both binding and alias are imported).
|
|
57
|
+
|
|
58
|
+
**2. `db` referenced before declaration in single-record + bulk action handlers (`TS2448` / `TS2304`).** `record-based.ts:195,541` baked `firewallClause = ...buildFirewallConditions(ctx, db)...` and used the same string in two places: (a) the outer pre-fetch `await unsafeDb.select().from(table).where(firewallClause)` — where `db` doesn't exist yet (`db = createScopedDb(unsafeDb, ctx)` is declared later for handler scope), and (b) inside `processBatch` where `db` is created from the tx/handle param. The outer use threw at typecheck (`'db' is used before its declaration`); at runtime it would have been a `ReferenceError`. Fix: pass `unsafeDb` (the in-scope handle) to `buildFirewallConditions` in both `firewallClause` definitions. The helper only uses its `db` arg for relationship-role subqueries (when `via:` is in play); either handle is a valid Drizzle client for that lookup.
|
|
59
|
+
|
|
60
|
+
**3. PartyServer realtime gates passed 1 arg to a 2-arg `buildFirewall_X` (`TS2554`).** `optional-routes.ts` emitted `buildFirewall_<feature>(ctx as any)` in the WebSocket-upgrade gate for every Durable Object that declared `access: { resource }`. After v0.14.4 made `buildFirewallConditions(ctx, db)` 2-arg whenever the resource has any `via:` predicate, this gate stopped compiling for any DO whose target feature uses relationship-roles. AttendVIP's `event-pages` DO sits on `event_pages` (admin via `guestOf`), which is exactly that case. Fix: the gate already constructs `db = drizzle(c.env.<binding>)` for its own `db.select(...).limit(1)` — pass that same `db` into the firewall call. Mirrored in both the single-resource and multi-resource gate branches.
|
|
61
|
+
|
|
62
|
+
**4. Durable-object-only features dropped their `lib/` files from output (`TS2307`).** `compiler.ts:546` only ran the feature-walker (and copied `featureLibFiles` to output) when the feature had at least one action file. AttendVIP's `user-profiles/` declares a single DO source under `lib/UserGateway.ts` and zero `actions/` — perfectly valid (per-user realtime gateway, the Slack/Linear pattern), but the walker skipped the feature entirely. The compile finished without error, then `index.ts` tried to import `./features/user-profiles/lib/UserGateway` and `tsc` 404'd the module. `event-pages/PageRoom.ts` worked only because that feature happens to also have `actions/`. Fix: run the discovery + lib-copy path whenever the feature has either actions OR lib files. Copying `lib/` files when the feature has at least one of either is the safe reading of the original intent.
|
|
63
|
+
|
|
64
|
+
**Drops ~20 of the 230 attendvip errors** (TS2300 ×2, TS2448 ×11, TS2304 ×6, TS2554 ×2 from the realtime gate, TS2307 ×1 — depending on cache state). The remaining 210 are TS2769 (numeric-ID arrays where the column is `integer`, not `text`) and TS2339 (`.id` referenced on tables that have a non-`id` PK or a compound PK) — both downstream of the same root: `id` is currently *not* auto-injected, only audit columns are.
|
|
65
|
+
|
|
66
|
+
### Account auth: emailOtp on AWS SES drops the magic-link companion (OTP-only)
|
|
67
|
+
|
|
68
|
+
The compiler used to auto-wire `createComboAuthSendVerificationOTP` from `@quickback-dev/better-auth-combo-auth` whenever a project used `emailOtp` with the `aws-ses` email provider — sign-in / sign-up / verify emails carried *both* a 6-digit OTP and a clickable magic link, with `useComboAuthEmail: true` in the SES config. This was on by default for every account-app project that picked AWS SES.
|
|
69
|
+
|
|
70
|
+
Two reasons to drop the magic-link half:
|
|
71
|
+
|
|
72
|
+
1. **Mail-client URL prefetching can burn the OTP before the human sees the email.** Outlook Safe Links, Gmail mobile, corporate proxies, and security scanners all eagerly fetch URLs in incoming mail; the magic link's `?data=...` payload includes the OTP server-side, so the first GET completes the sign-in (consuming the one-time code) and the user clicking through 30 seconds later gets a "code already used" failure.
|
|
73
|
+
2. **Two sign-in surfaces are harder to support.** The account SPA's `/welcome` and `/email-otp` routes only render the OTP form; the magic-link arm bypasses that UI entirely. One canonical entry point (enter the code) keeps the account flow legible.
|
|
74
|
+
|
|
75
|
+
The compiler now emits a plain `sendVerificationOTP` callback that calls `sendEmailWithSES` with `emailTemplates.emailOTP` directly — no combo wrapper, no magic-link URL. `useComboAuthEmail` is hardcoded to `false`. The `@quickback-dev/better-auth-combo-auth` package and the `magicLink` plugin are still available for users who explicitly opt in via a custom `sendVerificationOTP` in their config; the change here is just the auto-wired default.
|
|
76
|
+
|
|
77
|
+
Test coverage: `auth-email-wiring.test.ts` was updated to assert the new shape — generated auth files for `emailOtp + aws-ses` now contain `emailTemplates.emailOTP` and `useComboAuthEmail: false`, and explicitly do not contain `createComboAuthSendVerificationOTP` or `better-auth-combo-auth`.
|
|
78
|
+
|
|
79
|
+
### Coming next — `id` field auto-injection (v0.14.8)
|
|
80
|
+
|
|
81
|
+
The compiler treats `id` as load-bearing across CRUD/action route generators, FK probing, access checks, OpenAPI emission, and CMS — but doesn't add it for you the way it adds `createdAt`/`modifiedAt`/`createdBy`/`modifiedBy` (or `organizationId` in org-scoped features, or `deletedAt`/`deletedBy` for soft-delete tables). Tables that omit `id` (or use a non-`id` single PK like `userId.primaryKey()`, or a compound `primaryKey({ columns: [...] })` constraint) are accepted at parse time but produce broken output downstream. AttendVIP's `user_profiles`, `user_presence`, `user_notification_prefs`, `chat_reads`, and `chat_channel_members` all hit this.
|
|
82
|
+
|
|
83
|
+
**Agreed direction:** mirror `injectAuditFields` with a new `injectIdField` that runs unconditionally — including on junction tables. Tables with no PK or a non-`id` PK get an `id` column auto-injected; existing column-level `.primaryKey()` on a non-`id` column gets demoted to `.notNull()`; `primaryKey({ columns: [...] })` constraints get rewritten to `uniqueIndex().on(...)`. The cost (one extra column per junction row) is minimal and closes the asymmetry — every table participating in routes gets a single string-typed `id`, just like every table gets `createdAt`. Migration tail (existing D1 databases need an ADD COLUMN + index rewrite per affected table) is generated alongside.
|
|
84
|
+
|
|
85
|
+
No user code changes required for the four fixes shipping in v0.14.7. Recompile and the affected features typecheck.
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
## v0.14.6 — May 7, 2026
|
|
90
|
+
|
|
91
|
+
### Four more v0.14 compiler bugs caught by AttendVIP's MCP rollout
|
|
92
|
+
|
|
93
|
+
Filed in `research/attendvip-v014-mcp-and-firewall-gaps.md` after AttendVIP patched these locally and asked us to upstream them. All four ride a single MCP `tools/call` against a team-scoped resource over a Bearer api-key — fix any one and the next bug surfaces. We're shipping them as one patch release with end-to-end coverage of the chain.
|
|
94
|
+
|
|
95
|
+
**1. MCP `tools/call` URL is double-prefixed for action tools.** The OpenAPI spec emits action paths as `/api/v1/<action>` already-absolute, but the MCP request builder did `'/api/v1' + tool._path` unconditionally — so action tool calls hit `/api/v1/api/v1/<action>` and 404'd. CRUD tools (bare `_path: '/customers'`) were unaffected. Fix: prefix only when `_path` doesn't already start with `/api/v1/`.
|
|
96
|
+
|
|
97
|
+
**2. Auth middleware ignored `Authorization: Bearer <api-key>`.** MCP clients (claude.ai, etc.) only set `Authorization: Bearer ...`. The api-key block read from `x-api-key` header / `?api_key=` / `?key=` query but not from `Authorization`; the JWT fast-path narrowly gated on `bearerToken.startsWith('eyJ')`. Non-JWT bearers fell through to BA session auth, which doesn't recognise api-keys, so the request authenticated as anonymous and `tools/list` returned only PUBLIC tools. Fix: api-key extraction now also accepts a non-JWT `Authorization: Bearer <token>` as the key candidate. Three transports for one credential — header / query / Bearer.
|
|
98
|
+
|
|
99
|
+
**3. `auth.roleHierarchy` was silently inert for runtime role checks.** A user configured `auth.roleHierarchy: ['owner', 'admin', 'member']` and expected an `owner` to satisfy any check requiring `admin` or `member`. But the api-key + JWT fast-paths populated `ctx.roles` with the single org-member role, and the access checker did strict intersection — owner ∩ {admin, member} = ∅ → 403. Fix: at the api-key, JWT fast-path, AND BA session paths, expand the user's role via `auth.roleHierarchy` so a higher role inherits all lower-role privileges. The hierarchy is auto-normalized — users who write the array reversed (`['owner', 'admin', 'member']` instead of the documented `['member', 'admin', 'owner']`) now get the same correct expansion.
|
|
100
|
+
|
|
101
|
+
**4. Team-firewall predicate hardcoded `eq(table.teamId, ctx.activeTeamId!)` even when no team was active.** The `!` non-null assertion lied at runtime — api-keys, JWTs, and sessions without an active team carry `undefined`. The resulting SQL was `team_id = NULL` which matches nothing, so api-key callers saw zero rows on team-scoped resources. Fix: emit the team predicate as `(ctx.activeTeamId ? eq(...) : undefined)` — drizzle's `and(...)` drops `undefined`, so the WHERE collapses to the org scope only. Org and owner predicates are deliberately NOT softened the same way (those are security boundaries, not optional scopes).
|
|
102
|
+
|
|
103
|
+
After upstreaming, the AttendVIP one-shot verification passes:
|
|
104
|
+
|
|
105
|
+
```bash
|
|
106
|
+
curl -fs -X POST https://attend.vip/mcp \
|
|
107
|
+
-H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
|
|
108
|
+
-d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"listEvents","arguments":{}}}' \
|
|
109
|
+
| jq '.result.content[0].text | fromjson | .data | length' # > 0
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
No user code changes required for any of the four. Recompile and the MCP path works end-to-end against team-scoped, role-gated resources via Bearer api-key.
|
|
113
|
+
|
|
114
|
+
---
|
|
115
|
+
|
|
116
|
+
## v0.14.5 — May 7, 2026
|
|
117
|
+
|
|
118
|
+
### MCP `tools/call` no longer crashes with `undefined (reading 'AUTH_DB')`
|
|
119
|
+
|
|
120
|
+
The generated MCP server's `tools/call` dispatch re-enters the same Hono app via `app.request(internalReq)` so every tool invocation runs through the full middleware chain (auth, firewall, access, guards, masking). But the call passed only the request — not `env` or `executionCtx` — so the sub-request handler ran with `c.env === undefined`. Any tool whose route touched a Cloudflare binding (e.g. the `AUTH_DB` D1, KV, R2, Queues) crashed with `Cannot read properties of undefined (reading 'AUTH_DB')`. Found by AttendVIP — every action that hit auth-side data (acceptInvite, etc.) failed.
|
|
121
|
+
|
|
122
|
+
**Fix:** `mountMcp` now threads `c.env` and `c.executionCtx` through to `handle → handleRpc → callTool → app.request(internalReq, undefined, env, executionCtx)`. Hono's `request()` 3rd/4th args set the bindings + execution context for the sub-request, so the action handler sees the same env the outer worker received. Tools/list was unaffected — it reads ctx in-process and never re-enters the app.
|
|
123
|
+
|
|
124
|
+
No user code changes required. Recompile against v0.14.5 and the MCP endpoint dispatches actions correctly against all bindings.
|
|
125
|
+
|
|
126
|
+
---
|
|
127
|
+
|
|
128
|
+
## v0.14.4 — May 7, 2026
|
|
129
|
+
|
|
130
|
+
### `via:` firewall predicates no longer crash with `ReferenceError: db is not defined`
|
|
131
|
+
|
|
132
|
+
The relationship-role generator (v0.14.0) emits a `buildFirewallConditions` body that references `db`, `inArray`, and `sql` at function scope when any predicate has `via:` — but the resource-file imports it generated only pulled in `eq, and, isNull, type SQL`. So every endpoint guarded by `firewall: [{ field, via }]` threw `ReferenceError: db is not defined` at the very first request, and the catch-all returned 500 before the firewall query ever ran. Found by AttendVIP on `/api/v1/event-pages` against v0.14.3 — none of the v0.14.0 → v0.14.3 unit tests exercised emitted-import resolution, so the bug rode through three patch releases.
|
|
133
|
+
|
|
134
|
+
Two fixes:
|
|
135
|
+
|
|
136
|
+
1. **Imports in the generated resource file now include `inArray, sql`** when the firewall has any `via:` predicate. Hidden behind a flag so a no-via resource still gets the minimal import surface.
|
|
137
|
+
2. **`buildFirewallConditions` now takes `(ctx, db)`** and the wrapper template (`WITH_FIREWALL_HELPER`) pulls `const db = c.get('db' as never) as any;` from the Hono context before invoking it. Every CRUD/action call site (single-record + batch + record-based-action) was updated to pass `db` through.
|
|
138
|
+
|
|
139
|
+
Regression test added (`firewall-via-imports.test.ts`) that parses the generated resource file's top-level imports and asserts every free identifier referenced in `buildFirewallConditions` resolves to either an import or a function parameter — so a future generator change that introduces a new free identifier (`exists`, `not`, etc.) without importing it fails the unit suite instead of leaking to a real project.
|
|
140
|
+
|
|
141
|
+
No user code changes required — recompile and `via:` predicates work end-to-end.
|
|
142
|
+
|
|
143
|
+
---
|
|
144
|
+
|
|
145
|
+
## v0.14.3 — May 7, 2026
|
|
146
|
+
|
|
147
|
+
### Relationship-role consumers now resolve the relationship-table binding at runtime
|
|
148
|
+
|
|
149
|
+
Pre-fix, the v0.14.0 relationship-role generator emitted imports like `import { eventGuests, buildFirewallConditions as buildEventGuestsFirewallConditions } from '../event-guests/event-guests.resource'` on every consuming resource — but the relationship-table's own `.resource.ts` file imported `event_guests` from `./schema` for its own use without re-exporting it. So the consuming file got `undefined` at runtime, every relationship subquery failed with `Cannot read properties of undefined`, and the whole authz layer was unreachable on real projects.
|
|
150
|
+
|
|
151
|
+
Found by AttendVIP within minutes of recompiling against v0.14.2: the moment they hit any endpoint guarded by `firewall: [{ field, via }]` or `crud.<op>.access roles: ['guest']`, the request errored before the firewall query ran.
|
|
152
|
+
|
|
153
|
+
The fix is one line in `generateTableResourceHelpers` — re-export the Drizzle table binding from the `.resource` file alongside the existing import. The `.resource` file is the public surface of the table; the schema is an implementation detail. This decision was implicit in the relationship-import resolver's path choice but not enforced on the producer side.
|
|
154
|
+
|
|
155
|
+
```ts
|
|
156
|
+
// generated <table>.resource.ts (after fix)
|
|
157
|
+
import { event_guests } from './schema';
|
|
158
|
+
export { event_guests }; // ← was missing
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
Regression test added (`authz-end-to-end.test.ts`) that asserts every `.resource` file re-exports its Drizzle binding, so this can't drift again. No user code changes required — recompile and the cross-feature relationship subqueries resolve correctly.
|
|
162
|
+
|
|
163
|
+
---
|
|
164
|
+
|
|
7
165
|
## v0.14.2 — May 7, 2026
|
|
8
166
|
|
|
9
167
|
### Wrangler `[[migrations]]` no longer drops historical Durable Object lifecycle entries
|
|
@@ -225,12 +225,30 @@ cms: { domain: "cms.example.com" },
|
|
|
225
225
|
|
|
226
226
|
// With access control (only admins can access CMS)
|
|
227
227
|
cms: { domain: "cms.example.com", access: "admin" },
|
|
228
|
+
|
|
229
|
+
// Cross-tenant DB-admin tier — sysadmins see every tenant's data
|
|
230
|
+
cms: { domain: "cms.example.com", sysadmin: true },
|
|
228
231
|
```
|
|
229
232
|
|
|
230
233
|
| Option | Type | Default | Description |
|
|
231
234
|
|--------|------|---------|-------------|
|
|
232
235
|
| `domain` | `string` | — | Custom domain for CMS. Adds a `custom_domain` route to `wrangler.toml`. |
|
|
233
236
|
| `access` | `"user" \| "admin"` | `"user"` | Controls who can access the CMS. When `"admin"`, only users with `user.role === "admin"` can enter — enforced at the Worker level (SPA shell, `/api/v1/schema`, and `custom_view` CRUD all return 403 to non-admins) and in the SPA. Also hides the CMS link in Account UI. See [CMS Connecting](/stack/cms/connecting) for the full enforcement model. |
|
|
237
|
+
| `sysadmin` | `boolean` | `false` | Cross-tenant DB-admin tier. When `true`, opts into the `SYSADMIN` pseudo-role (`user.role === "sysadmin"`), the firewall escape hatch (sysadmins bypass tenant scopes, soft-delete still enforced), the cross-tenant `/admin/v1/sysadmin/organizations` endpoint, and the SPA's "All organizations" sentinel. The CMS HTML gate admits `userRole === "sysadmin"` alongside `"admin"` — sysadmin is a strict superset. Off by default. See [`SYSADMIN` pseudo-role](/compiler/definitions/access#sysadmin--cross-tenant-db-admin-tier). |
|
|
238
|
+
|
|
239
|
+
### Sysadmin tier (`cms.sysadmin: true`)
|
|
240
|
+
|
|
241
|
+
Quickback's default model assumes every CMS user belongs to at least one organization (`member` row in the auth DB). For platforms that need a Supabase-style cross-tenant DB-admin tool — debugging a tenant's data, running cross-tenant queries, supporting a customer — that's a poor fit: a sysadmin without `member` rows would dead-end, and auto-filling their active org from "first membership" silently scopes them to a tenant they have no relationship with.
|
|
242
|
+
|
|
243
|
+
`cms: { sysadmin: true }` introduces a separate role tier:
|
|
244
|
+
|
|
245
|
+
- **Role**: `user.role === "sysadmin"` (set on the Better Auth user table). Distinct from `"admin"` — admins keep org-scoped CMS access via the membership switcher; sysadmins get cross-tenant.
|
|
246
|
+
- **Firewall**: every `buildFirewallConditions()` emits an `if (ctx.userRole === "sysadmin") return undefined` (or just the soft-delete predicate when present) at the top, so sysadmins see every tenant's rows. See [Firewall escape hatch](/compiler/definitions/firewall#sysadmin-escape-hatch).
|
|
247
|
+
- **Org listing**: a new `GET /admin/v1/sysadmin/organizations` endpoint selects directly from the auth-schema `organization` table — every row, every tenant. The existing `/admin/v1/organizations` (membership-bound, used by org admins) is unchanged.
|
|
248
|
+
- **CMS SPA**: when the user is a sysadmin, the header switcher loads from the cross-tenant endpoint, defaults to "All organizations" (which omits `?organizationId=` and reaches the firewall escape), and pins selected tenants via `?organizationId=` on every API call. Org admins keep the existing membership-based switcher.
|
|
249
|
+
- **CMS HTML gate**: admits `userRole === "sysadmin"` alongside `"admin"`. Org admins are not locked out — both roles can enter the CMS in `cms.access: "admin"` mode.
|
|
250
|
+
|
|
251
|
+
Off by default. Projects that don't enable it get zero behavior change; setting `cms.sysadmin: true` and granting a user `user.role = "sysadmin"` is the only way to unlock the cross-tenant view.
|
|
234
252
|
|
|
235
253
|
## Account UI Configuration
|
|
236
254
|
|
|
@@ -317,6 +317,40 @@ src/apps/ # Root assets directory
|
|
|
317
317
|
|
|
318
318
|
On custom domains, each SPA is served at root (`/`) via hostname-based routing. On the unified domain, CMS is at `/cms/` and Account is at `/account/`.
|
|
319
319
|
|
|
320
|
+
### Static Assets (`quickback/public/`)
|
|
321
|
+
|
|
322
|
+
Anything you drop under `quickback/public/` is copied verbatim into `src/apps/` on every compile. The compiler does not parse, template, or otherwise touch these files — they are bytes that ride past it into the Cloudflare ASSETS binding.
|
|
323
|
+
|
|
324
|
+
```
|
|
325
|
+
quickback/public/ # Source — checked into your repo
|
|
326
|
+
├── favicon.ico
|
|
327
|
+
├── robots.txt
|
|
328
|
+
├── og/
|
|
329
|
+
│ └── og-image.png
|
|
330
|
+
└── pdfs/
|
|
331
|
+
└── whitepaper.pdf
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
After compile:
|
|
335
|
+
|
|
336
|
+
```
|
|
337
|
+
src/apps/ # Destination — written by the CLI
|
|
338
|
+
├── favicon.ico # Served at https://your-domain/favicon.ico
|
|
339
|
+
├── robots.txt # Served at /robots.txt
|
|
340
|
+
├── og/og-image.png # Served at /og/og-image.png
|
|
341
|
+
├── pdfs/whitepaper.pdf
|
|
342
|
+
├── cms/ # Compiler-emitted SPA (don't shadow)
|
|
343
|
+
└── account/ # Compiler-emitted SPA (don't shadow)
|
|
344
|
+
```
|
|
345
|
+
|
|
346
|
+
Notes:
|
|
347
|
+
|
|
348
|
+
- The folder is optional. If it doesn't exist, this step is a no-op.
|
|
349
|
+
- Files removed from `quickback/public/` disappear from `src/apps/` on the next compile — `src/` is wiped and rewritten each run.
|
|
350
|
+
- Hidden entries (`.DS_Store`, `.git/`, dotfiles) are skipped.
|
|
351
|
+
- A file in `quickback/public/` that would overwrite a compiler-emitted path (e.g. `quickback/public/cms/index.html`) fails the compile with a clear error rather than silently shadowing the SPA shell.
|
|
352
|
+
- Binaries (images, fonts, PDFs) are copied byte-for-byte — there is no string round-trip.
|
|
353
|
+
|
|
320
354
|
### Generated Wrangler Assets Config
|
|
321
355
|
|
|
322
356
|
The compiler always generates `run_worker_first = true` when SPAs are enabled — the Worker handles all SPA routing (per hostname and per path prefix):
|
|
@@ -60,7 +60,7 @@ crud: {
|
|
|
60
60
|
The `+` suffix expands at compile time — `"member+"` becomes `["member", "admin", "owner"]` in the generated code. You can mix hierarchical and exact roles: `roles: ["member+", "finance"]` expands to `["member", "admin", "owner", "finance"]`.
|
|
61
61
|
|
|
62
62
|
- Roles without `+` are exact matches (no expansion)
|
|
63
|
-
- Pseudo-roles (`PUBLIC`, `AUTHENTICATED`, `USER`, `ADMIN`) cannot use the `+` suffix — they're terminal markers
|
|
63
|
+
- Pseudo-roles (`PUBLIC`, `AUTHENTICATED`, `USER`, `ADMIN`, `SYSADMIN`) cannot use the `+` suffix — they're terminal markers
|
|
64
64
|
- Using `+` with a role not in the hierarchy throws a compile error
|
|
65
65
|
- Using `+` without configuring `auth.roleHierarchy` throws a compile error
|
|
66
66
|
|
|
@@ -131,7 +131,7 @@ When `roles` and `userRole` both appear in a single `Access` node, they're combi
|
|
|
131
131
|
|
|
132
132
|
### Pseudo-roles
|
|
133
133
|
|
|
134
|
-
Quickback ships
|
|
134
|
+
Quickback ships five UPPERCASE role markers that are **not backed by a Better Auth role column** — they're system-level shortcuts handled directly by the compiler. The casing carries the boundary: UPPERCASE = pseudo-role (no plugin context required), lowercase = real role from a plugin's table (e.g. `members.role` from the org plugin).
|
|
135
135
|
|
|
136
136
|
| Role | Auth gate | Compile-time requirement | Runtime check |
|
|
137
137
|
|------|-----------|-------------------------|---------------|
|
|
@@ -139,6 +139,7 @@ Quickback ships four UPPERCASE role markers that are **not backed by a Better Au
|
|
|
139
139
|
| `AUTHENTICATED` | required | none | `ctx.authenticated === true` |
|
|
140
140
|
| `USER` | required | resource firewall **must** scope by `userId` | `ctx.authenticated` AND (`ctx.userRole` is unset OR `ctx.userRole === "user"`) |
|
|
141
141
|
| `ADMIN` | required | Better Auth admin plugin **must** be enabled | `ctx.authenticated && ctx.userRole === "admin"` |
|
|
142
|
+
| `SYSADMIN` | required | `cms: { sysadmin: true }` **must** be set on the project | `ctx.authenticated && ctx.userRole === "sysadmin"` |
|
|
142
143
|
|
|
143
144
|
You can mix pseudo-roles with real roles in the same list — they're OR'd together.
|
|
144
145
|
|
|
@@ -220,6 +221,19 @@ read: { access: { roles: ["ADMIN"] } }
|
|
|
220
221
|
|
|
221
222
|
Without the admin plugin you get a compile error pointing you to either enable the plugin or use lowercase `roles: ["admin"]` (the org-membership admin role).
|
|
222
223
|
|
|
224
|
+
#### `SYSADMIN` — cross-tenant DB-admin tier
|
|
225
|
+
|
|
226
|
+
Use `roles: ["SYSADMIN"]` for endpoints that should only be reachable by platform sysadmins — the cross-tenant DB-admin tier introduced in v0.15.0. Compiles to `ctx.userRole === "sysadmin"`. **Requires `cms: { sysadmin: true }` on the project config**; without that flag, using `SYSADMIN` fails the compile so the role can't sit as dead code.
|
|
227
|
+
|
|
228
|
+
```typescript
|
|
229
|
+
// Cross-tenant audit dashboard, sysadmin-only
|
|
230
|
+
read: { access: { roles: ["SYSADMIN"] } }
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
`SYSADMIN` is a strict superset of `ADMIN` — at runtime, the universal-bypass shortcuts in `evaluateAccess` admit `userRole === 'sysadmin'` anywhere they admit `userRole === 'admin'`. The distinction matters for one thing only: **the firewall escape hatch**. When `cms.sysadmin: true`, every `buildFirewallConditions` emits an `if (ctx.userRole === 'sysadmin') return undefined;` (or just the soft-delete predicate when present) at the top — so sysadmins see every tenant's rows, not just their own org's. That escape hatch does NOT fire for `userRole === 'admin'`; admins still go through the firewall like everyone else.
|
|
234
|
+
|
|
235
|
+
This separation exists so Better Auth admin-plugin powers (user management, impersonation) and DB-admin powers (cross-tenant data inspection) stay decoupled. A user can have `user.role === 'admin'` without DB-level cross-tenant access; a user can have `user.role === 'sysadmin'` without org-membership context. See [CMS Configuration](/compiler/config#cms-configuration) for the `cms.sysadmin` flag, the cross-tenant `/admin/v1/sysadmin/organizations` endpoint, and the SPA's "All organizations" sentinel.
|
|
236
|
+
|
|
223
237
|
#### Mixing pseudo-roles with real roles
|
|
224
238
|
|
|
225
239
|
Pseudo-roles and lowercase real roles compose with OR:
|
|
@@ -159,6 +159,33 @@ When the `firewall:` block is omitted, the compiler scans the schema for known s
|
|
|
159
159
|
|
|
160
160
|
So `firewall: [{ exception: true }]` on the default configuration returns `isNull(<table>.deletedAt)` from `buildFirewallConditions()` — no tenant filter, soft-delete filter still applied.
|
|
161
161
|
|
|
162
|
+
## Sysadmin Escape Hatch
|
|
163
|
+
|
|
164
|
+
When `cms: { sysadmin: true }` is set on the project (introduced in v0.15.0), every `buildFirewallConditions()` emits a runtime branch that drops tenant scopes for `ctx.userRole === 'sysadmin'` callers while keeping the soft-delete predicate:
|
|
165
|
+
|
|
166
|
+
```typescript
|
|
167
|
+
// Generated for an org-scoped table when cms.sysadmin: true
|
|
168
|
+
export function buildFirewallConditions(ctx: AppContext): SQL | undefined {
|
|
169
|
+
if (ctx.userRole === 'sysadmin') {
|
|
170
|
+
return isNull(invoices.deletedAt); // tenant predicate dropped, soft-delete kept
|
|
171
|
+
}
|
|
172
|
+
return and(
|
|
173
|
+
eq(invoices.organizationId, ctx.activeOrgId!),
|
|
174
|
+
isNull(invoices.deletedAt),
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
The escape branch is **only** emitted when:
|
|
180
|
+
|
|
181
|
+
- `cms.sysadmin: true` is set on the project config
|
|
182
|
+
- The table has at least one tenant-scope predicate (org / owner / team / `via:` relationship). Tables with no tenant scopes already return what a sysadmin would see, so the runtime check would be dead code.
|
|
183
|
+
- The firewall does not declare `{ exception: true }` (no tenant scopes to drop).
|
|
184
|
+
|
|
185
|
+
**Sysadmin is distinct from admin.** `userRole === 'admin'` callers still go through the firewall normally — only `userRole === 'sysadmin'` triggers the bypass. Admins keep their existing universal-bypass at the *access* layer (cross-org reads on per-record routes via `?organizationId=`), but the firewall's row predicate remains in force. Sysadmin is opt-in, configured per-project, and intended for the cross-tenant CMS DB-admin tier — see [CMS Configuration](/compiler/config#cms-configuration).
|
|
186
|
+
|
|
187
|
+
If your project doesn't set `cms.sysadmin: true`, the escape branch is never emitted and the role value is functionally inert.
|
|
188
|
+
|
|
162
189
|
## Common Patterns
|
|
163
190
|
|
|
164
191
|
```typescript
|
|
@@ -309,6 +309,15 @@ These internal tables still participate in the database schema and migrations
|
|
|
309
309
|
|
|
310
310
|
The compiler automatically injects the four **[audit fields](#audit-fields)** (`createdAt`/`createdBy`/`modifiedAt`/`modifiedBy`), the soft-delete pair (`deletedAt`/`deletedBy`, when soft delete is enabled), and **`organizationId`** into child/junction tables when the parent feature is org-scoped. This ensures cascade soft deletes and scoped queries work correctly without manual column definitions.
|
|
311
311
|
|
|
312
|
+
> **`id` is currently NOT auto-injected — declare it yourself**
|
|
313
|
+
>
|
|
314
|
+
> Unlike audit fields, the `id` column is your responsibility today. The CRUD/action route generators, FK probing, access checks, and OpenAPI emission all assume every queryable table has a single string-typed `id` column. Tables that omit it — or use a non-`id` single PK (`userId.primaryKey()`) or a compound `primaryKey({ columns: [...] })` constraint — parse fine but produce broken generated code downstream.
|
|
315
|
+
>
|
|
316
|
+
> Use `q.id()` (preferred) or `id: text("id").primaryKey()` / `id: integer("id").primaryKey({ autoIncrement: true })` on every table that participates in routes. For internal tables marked `// @quickback-internal`, the constraint doesn't apply.
|
|
317
|
+
>
|
|
318
|
+
> This asymmetry is being closed in **v0.14.8** — `injectIdField` will run unconditionally alongside audit injection, including on junction tables. See the [v0.14.7 changelog](/docs/changelog#coming-next--id-field-auto-injection-v0148) for the migration plan.
|
|
319
|
+
|
|
320
|
+
|
|
312
321
|
## Audit Fields
|
|
313
322
|
|
|
314
323
|
Quickback adds four audit columns to **every table** (including child/junction tables without `defineTable`) — never declare them in your schemas:
|