@quickback-dev/cli 0.14.2 → 0.16.1

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 (34) hide show
  1. package/dist/commands/compile.d.ts.map +1 -1
  2. package/dist/commands/compile.js +40 -2
  3. package/dist/commands/compile.js.map +1 -1
  4. package/dist/docs/content.d.ts.map +1 -1
  5. package/dist/docs/content.js +12 -7
  6. package/dist/docs/content.js.map +1 -1
  7. package/dist/index.js +1 -1
  8. package/dist/lib/copy-public-assets.d.ts +34 -0
  9. package/dist/lib/copy-public-assets.d.ts.map +1 -0
  10. package/dist/lib/copy-public-assets.js +118 -0
  11. package/dist/lib/copy-public-assets.js.map +1 -0
  12. package/dist/lib/copy-public-assets.test.d.ts +2 -0
  13. package/dist/lib/copy-public-assets.test.d.ts.map +1 -0
  14. package/dist/lib/copy-public-assets.test.js +151 -0
  15. package/dist/lib/copy-public-assets.test.js.map +1 -0
  16. package/dist/skill/docs/changelog.md +256 -0
  17. package/dist/skill/docs/compiler/config/index.md +18 -0
  18. package/dist/skill/docs/compiler/config/output.md +34 -0
  19. package/dist/skill/docs/compiler/definitions/access.md +17 -3
  20. package/dist/skill/docs/compiler/definitions/firewall.md +27 -0
  21. package/dist/skill/docs/compiler/definitions/schema.md +9 -0
  22. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/errors.md +84 -2
  23. package/dist/skill/docs/stack/auth/plugins/agent-auth.md +131 -0
  24. package/dist/skill/docs/stack/realtime/partyserver-rooms.md +10 -2
  25. package/package.json +1 -1
  26. package/src/skill/docs/changelog.md +256 -0
  27. package/src/skill/docs/compiler/config/index.md +18 -0
  28. package/src/skill/docs/compiler/config/output.md +34 -0
  29. package/src/skill/docs/compiler/definitions/access.md +17 -3
  30. package/src/skill/docs/compiler/definitions/firewall.md +27 -0
  31. package/src/skill/docs/compiler/definitions/schema.md +9 -0
  32. package/src/skill/docs/compiler/targets/hono-api/using-the-api/errors.md +84 -2
  33. package/src/skill/docs/stack/auth/plugins/agent-auth.md +131 -0
  34. package/src/skill/docs/stack/realtime/partyserver-rooms.md +10 -2
@@ -4,6 +4,262 @@ Release notes for the Quickback compiler, CLI, and platform.
4
4
 
5
5
  ---
6
6
 
7
+ ## v0.16.1 — May 9, 2026
8
+
9
+ ### Cloudflare ASSETS canonicalization — worker SPA emits no longer 307-loop
10
+
11
+ Cloudflare's static-assets binding canonicalizes any request for `/<dir>/index.html` into a 307 redirect to `/<dir>/` (the default `html_handling=auto-trailing-slash`). When a worker subrequest issues `c.env.ASSETS.fetch(new Request(new URL('/<dir>/index.html', …)))`, the binding returns the 307; the worker forwards it; the browser re-requests `/<dir>/`; the same SPA-fallback handler (or hostname middleware) catches the directory request and re-fetches `/<dir>/index.html`. Infinite loop. Caught by AttendVIP writing custom `/admin/` and `/m/` host-routing patches on the deployed worker — the fix in their patches was switching to `/admin/` (trailing slash, no `index.html`), which Cloudflare resolves to the directory's `index.html` content with a 200.
12
+
13
+ The compiler had the same bug baked into every emit point. `cloudflare.ts` now fetches `/<dir>/` everywhere it previously asked for `/<dir>/index.html`: CMS hostname middleware, `/cms/*` SPA catchall, apex `/` handler, account/admin hostname middleware, `/account/*` SPA catchall, and the multi-domain catchall. Eight regression tests in `cf-assets-canonicalization-spa-fallback.test.ts` pin every emit so a future copy/paste can't sneak the literal back in.
14
+
15
+ ### `account.customLogin` — drop a project-branded sign-in page in front of the SPA
16
+
17
+ A new `account: { customLogin: true }` flag emits an explicit `app.get('/account/login', …)` route that serves a project-supplied static page instead of letting the bundled Account SPA's client router handle the path. Drop the page at `quickback/public/account/login/index.html` (a *directory*, not a bare `login.html` — see the canonicalization note above) and the existing `quickback/public/` passthrough copies it into the asset binding. The route is registered before the `/account/*` SPA catch-all so the static handler wins; everything else under `/account/...` (profile, organizations, devices, …) keeps going through the React SPA. Same surface AttendVIP was hand-patching post-compile — promoting the flag means the next compile no longer wipes their override. Default `false`.
18
+
19
+ ### Project-level realtime auto-broadcasts every resource by default
20
+
21
+ `dbConfig.realtime: true` now treats every resource as realtime-enabled unless its `realtime` block explicitly opts out. The previous behavior set `effectiveResourceRealtime` to `undefined` when a resource didn't declare its own block — so a project that flipped the project-level flag still had to add per-table `realtime: { enabled: true }` everywhere to actually get auto-broadcasts. Caught against AttendVIP after the v0.15.x auto-broadcast wiring landed but didn't fire. New default: project-level on with no per-resource override = `{ enabled: true }`. Per-resource `realtime: { enabled: false }` still wins.
22
+
23
+ ### Drizzle metadata gets a DO NOT EDIT header + journal drift warning
24
+
25
+ Two changes that protect the drizzle plumbing from quiet corruption.
26
+
27
+ `compile-runner.ts:addJsonHeader` now stamps drizzle's generated JSON (`_journal.json`, `<n>_snapshot.json`) with a `$__quickback_warning__$` key explaining the file is regenerated by the compiler and should not be edited by hand. The disclaimer matches the one already on `.ts` outputs — the journal had been the one drizzle file users felt entitled to "tidy up" because nothing in it said otherwise.
28
+
29
+ A new check in the same module compares the journal entry count against the snapshot file count. drizzle-kit only produces one snapshot per `generate` run, so `journal.entries.length > snapshots + 1` means the journal claims migrations the snapshot side has lost (typical cause: a manual delete of an `<n>_snapshot.json` that left the journal entry behind). The compiler logs a warning and lists the orphan entries. Detected directly out of AttendVIP's `Travel 500` triage — drizzle-kit was diffing against a stale `0002_snapshot.json` and emitting bogus full `CREATE TABLE` migrations for tables that had been added in subsequent (now-orphaned) journal entries.
30
+
31
+ ### Two new compile-time validators (LOUD failures over silent traps)
32
+
33
+ **`AUTHENTICATED` + tenant-scoped firewall now refuses to compile.** `pseudo-role-validator.ts` rejects any access tree that admits `AUTHENTICATED` on a resource whose firewall scopes by `organizationId`. The combination is the silent-empty trap: a sign-in-only caller with no active org passes the role gate, the firewall WHERE clause filters every row out, and the API returns `[]` with a 200. The error message names three valid resolutions — drop the org scope (`firewall: { exception: true }`), tighten the role to `USER` or a role with implied org membership, or split the route into a token-auth branch and an org-membership branch.
34
+
35
+ **`createRealtime` imports without `dbConfig.realtime: true` now throw.** Project lib + action + feature-lib files are scanned at compile time for `import { createRealtime }` (and the equivalent named binding). When the project hasn't enabled realtime, the compile fails with the offending file paths and remediation: either enable `dbConfig.realtime: true` so the runtime helper exists, or remove the import. Caught against AttendVIP — three handler files (`broadcastAnnouncement.ts`, `declineActivityForGuest.ts`, `applyRsvp.ts`) imported `createRealtime` after the v0.15 auto-broadcast wiring landed, but their config never set `realtime: true`. The Worker compiled, deployed, and 500'd at first call. The user's framing was "config should be the source of truth" — this validator enforces that. Five regression tests in `realtime-import-without-config-rejected.test.ts`.
36
+
37
+ ### Fixes
38
+
39
+ **1. `SYSADMIN` was missing from the per-feature standalone gate's `allowsWithoutOrg` set.** The standalone-action wrapper skips its `if (!ctx.activeOrgId)` gate for any access tree referencing a pseudo-role (`PUBLIC`, `AUTHENTICATED`, `USER`, `ADMIN`) — but `SYSADMIN`, the v0.15.0 fifth marker, was missing from the matcher. Sysadmin actions on `cms.sysadmin: true` projects were 403'ing on cross-tenant calls (sysadmins have no member rows, so `ctx.activeOrgId` is unset by design). The matcher now includes `SYSADMIN`.
40
+
41
+ **2. Apex `/` and `/account/login` get fallback redirects when neither CMS nor Account SPA is bundled.** Projects that opt out of both bundled SPAs still receive traffic at `/` (no apex handler, 404) and `/account/login` (no Account fallback, 404). Setting `auth.loginUrl` to an external sign-in host now activates two compiler-emitted redirects so those natural inbound URLs land somewhere useful: `/account/login → loginUrl?redirect=…` (preserves the bounce param) and `/ → loginUrl` (or `/account` when the Account SPA is bundled). Both opt in via `auth.loginUrl !== '/account/login'` so projects using the built-in `/account/login` keep the existing SPA-fallback behavior unchanged.
42
+
43
+ **3. Record-based action URLs are now kebab-case to match OpenAPI.** `record-based.ts` was emitting URL paths from the camelCase action name (e.g. `/api/v1/widgets/:id/sendInvite`) while OpenAPI emit produced `/widgets/:id/send-invite`. Admin tooling and SDK consumers reading the OpenAPI spec hit 404s on every multi-word action. URL paths and OpenAPI emit now share a `urlPath = toKebabCase(urlSegment)` helper. Identifiers in audit `actionName`, error messages, and console logs stay camel — those are programmatic surfaces and breaking them would churn audit logs. Same fix shape as the v0.15.0 standalone-action URL casing.
44
+
45
+ ### Notes
46
+
47
+ Test coverage: 1175 → 1183 (+8 across the canonicalization, customLogin, and createRealtime regression files). Verified end-to-end against AttendVIP — `quickback compile` produces a worker whose `/account/login`, hostname-routed account/admin SPAs, and apex / handler all return 200 with the right SPA shell on the deployed Cloudflare worker, no 307 loops.
48
+
49
+ The bundled docs (`packages/claude-skill/docs/changelog.md`, `packages/cli/src/skill/docs/changelog.md`) and the CLI's `packages/cli/src/docs/content.ts` are regenerated by `scripts/bundle-docs.ts` — run that before publishing the CLI bump.
50
+
51
+ ---
52
+
53
+ ## v0.16.0 — May 9, 2026
54
+
55
+ ### Agent Auth Protocol — first-class agent identity for AI callers
56
+
57
+ Quickback now ships a server implementation of the [Agent Auth Protocol](https://agentauthprotocol.com) by way of `@better-auth/agent-auth`. Opt in with `auth.plugins.agentAuth: true` (or the array form `plugins: ["agentAuth"]`). When enabled, the compiler emits a complete agent-auth surface: discovery at `/.well-known/agent-configuration`, capability projection from the project's OpenAPI spec, a device-authorization approval page in the Account SPA at `/agents/approve`, and the four agent-auth tables (`agent`, `agentHost`, `agentCapabilityGrant`, `approvalRequest`) added to the auth schema automatically by `auth generate`.
58
+
59
+ **OpenAPI capability projection runs by default.** The compiler emits `src/lib/openapi-spec.ts` (the project's full OpenAPI spec inlined as a const) and wires `createFromOpenAPI(openapiSpec, { ... })` into the `agentAuth(...)` call. Every operation with an `operationId` becomes an agent capability. Default `approvalStrength` map: `GET → "session"`, `POST/PUT/PATCH/DELETE → "webauthn"`. Default `defaultHostCapabilities`: `["GET", "HEAD"]`.
60
+
61
+ The proxy `onExecute` makes a self-fetch to the worker's own URL with a Better Auth JWT minted for `agentSession.user.id`, so the inner request hits the existing JWT fast-path, populates `ctx`, and the full firewall + access + masking pipeline runs on the proxied call. No new middleware code, no parallel security path — agent capability calls go through the same gates as regular REST traffic. The cost is one Cloudflare subrequest per capability call (~50ms); fine for typical agent traffic. Opt out of OpenAPI projection with `agentAuth: { fromOpenAPI: false }` and wire `capabilities` + `onExecute` by hand.
62
+
63
+ The Account SPA gains `/agents/approve` (`packages/account/app/routes/agents.approve.tsx`) — modeled on the existing `/cli/authorize` device-code page. Pastes the user code, fetches the pending request, lists the requested capabilities with a "Step-up" badge on any capability whose `approvalStrength` is `"webauthn"`, then approves or denies. WebAuthn step-up itself is a placeholder for v0.16.0 — the upstream agent-auth API for the escalation call is still settling, so capabilities tagged `"webauthn"` will fail server-side until that lands. The badge tells the user what's coming.
64
+
65
+ ### Bearer-only on `/mcp` and the agent-auth surface
66
+
67
+ `/mcp` now forwards **only** `Authorization: Bearer …` into the inner `app.request()` re-entry. Cookie + `x-api-key` forwarding has been removed. The MCP surface is server-to-server by nature — there are no browser callers, no CSRF surface to defend, and no benefit to fragmenting the auth model across three header conventions. Three Bearer flavors all land on the same header, resolved by the inner Hono middleware chain:
68
+
69
+ - Better Auth session token via the official `bearer` plugin
70
+ - OAuth access token via the OAuth Provider plugin
71
+ - Agent JWT via `@better-auth/agent-auth`
72
+
73
+ If a project still wants API-key auth here, configure the `apiKey` plugin to accept its key via `Authorization: Bearer` so everything stays one channel. The existing `mcp-server.test.ts` regression seal flips from "forwards Cookie + x-api-key" to "forwards only Authorization (bearer-only surface)".
74
+
75
+ ### Auth DSL: `bearer`, `oauthProvider`, `agentAuth` are now first-class plugin entries
76
+
77
+ Both the array-form union and the `BetterAuthPlugins` interface in `apps/compiler/src/define/auth.ts` gain `"bearer"`, `"oauthProvider"`, and `"agentAuth"`. `bearer` was previously in the runtime registry but missing from the TS type, so callsites had to use `as any` or `// @ts-expect-error` to set it. Both are gone now. New typed options interfaces — `OAuthProviderOptions` (audience, login/consent paths, dynamic registration) and `AgentAuthOptions` (providerName, providerDescription, modes, fromOpenAPI, approvalStrength, defaultHostCapabilities) — let users override defaults through the object form.
78
+
79
+ Auto-enable rule lives in the canonical `computeAutoAddedPlugins` (`generators/auth.ts`): turning on `agentAuth` force-adds `bearer` + `oauthProvider`. There is no useful agent-auth deployment without those two — surfacing it as auto-add rather than a confusing "missing dependency" runtime error matches the existing pattern (`oauthProvider` already auto-adds `jwt`).
80
+
81
+ ### `queue-consumer.ts` now emitted for `additionalQueues` too
82
+
83
+ Prior to this release, the queue consumer emit gated on `embeddingFeatures.length > 0 || queueHandlers.length > 0`. Projects that declared queue infrastructure via `dbConfig.additionalQueues` but had no embeddings + no `services/queues/*` handlers shipped a `wrangler.toml` with `[[queues.consumers]]` entries pointing at a missing worker `queue` export. The CLI's archive-restore step kept a stale `queue-consumer.ts` around, so the file appeared "stuck" across compiles — same class of bug as the v0.15.0 services/queues/* regression caught against AttendVIP, just one source removed.
84
+
85
+ The gate is now a three-way OR: `hasEmbeddings || hasQueueHandlers || hasAdditionalQueues`. When only `additionalQueues` is set, the compiler emits a stub `queue-consumer.ts` whose `queue` export acks every message with a warning — Cloudflare needs an export for every consumer binding, and a noisy-but-correct stub beats a silent deploy break. `MainAppOptions` and `CloudflareMainAppOptions` gain `hasAdditionalQueues`; `generateQueueImport` and `generateCloudflareExport` mirror the new gate. Regression test: `src/__tests__/queue-additional-queues-gate.test.ts`.
86
+
87
+ ### Fixes
88
+
89
+ **1. `bearer` was missing from the `BetterAuthPlugins` TypeScript interface.** The runtime plugin registry has had `bearer` since the pre-1.0 cuts, but `apps/compiler/src/define/auth.ts` never declared it on the typed shape — so any `quickback.config.ts` using `plugins: { bearer: true }` had to `as any`-cast or sit behind a `@ts-expect-error`. Both `bearer` and `oauthProvider` (same gap, same workaround) are now first-class typed entries; `agentAuth` joins them. The array-form union also gains all three. No behavior change at runtime; existing casts can come out.
90
+
91
+ **2. MCP `buildInternalRequest` no longer forwards Cookie or `x-api-key`.** The MCP surface is server-to-server — there are no browser callers, no CSRF surface to defend, and no benefit to fragmenting the auth model across three header conventions. The inner `app.request()` re-entry now forwards only `Authorization: Bearer …`. Three Bearer flavors all land on the same header (BA session token via the `bearer` plugin, OAuth access token via OAuth Provider, agent JWT via `@better-auth/agent-auth`). Existing `mcp-server.test.ts` regression flipped from "forwards Cookie + x-api-key" to "forwards only Authorization (bearer-only surface)".
92
+
93
+ **3. `agentAuth` now auto-enables `bearer` + `oauthProvider`.** There is no useful agent-auth deployment without those two — the agent surface is bearer-only and MCP clients need OAuth to register. Auto-enable lives in the canonical `computeAutoAddedPlugins` (`generators/auth.ts`), so it propagates to every consumer (better-auth generator, schema generation, package-deps emission). Same pattern as the existing `oauthProvider` → `jwt` rule. Surfaced in `agent-auth.test.ts` with a regression seal that asserts both plugins land in the merged plugin list whether the user wrote the array form or the object form.
94
+
95
+ **4. `OpenAPISpec` literal type rejected by tsc on inlined spec.** Quickback's OpenAPI emit produces `$ref`-style parameter entries (`{ "$ref": "#/components/parameters/X" }`) that the agent-auth plugin's stricter `OpenAPIParameter` type doesn't model — `tsc` fails the generated project with "Type … is not assignable to OpenAPIParameter". The plugin handles refs correctly at runtime; only the structural narrowing on the TS literal needed help. The generated `agentAuth({ ...createFromOpenAPI(openapiSpec as any, { ... }) })` call now carries an `as any` cast on the spec with an inline comment explaining why. Drop when upstream models `$ref` parameters.
96
+
97
+ ### Notes
98
+
99
+ `@better-auth/agent-auth` 0.4.5 ships ESM-only exports without a `require` condition, so the Better Auth CLI's `auth generate` step (jiti / CJS resolver) bails with `ERR_PACKAGE_PATH_NOT_EXPORTED`. The compiler image patches the package's `package.json` at install time to add a matching `require` condition pointing at the same dist file (Node 22+ supports `require(esm)`). Remove the patch in `apps/compiler/Dockerfile` when upstream ships proper exports.
100
+
101
+ Test coverage: 1136 → 1152 (+11 `agent-auth.test.ts`, +5 `queue-additional-queues-gate.test.ts`). Verified end-to-end against `examples/recruitment` with `agentAuth` enabled — `quickback compile` produces a project whose `npm run build` typechecks clean and whose generated schema includes all four agent-auth tables (`agent`, `agentHost`, `agentCapabilityGrant`, `approvalRequest`).
102
+
103
+ ---
104
+
105
+ ## v0.15.0 — May 7, 2026
106
+
107
+ ### Sysadmin tier — cross-tenant DB-admin role for the CMS
108
+
109
+ 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.
110
+
111
+ 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.
112
+
113
+ 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.
114
+
115
+ 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.
116
+
117
+ ### Durable Object `[[migrations]]` order is now preserved across recompiles
118
+
119
+ 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).
120
+
121
+ 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.
122
+
123
+ ### Standalone-action wrapper no longer 403s `AUTHENTICATED`-only routes on org-scoped projects
124
+
125
+ 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.
126
+
127
+ ### Queue handler emit no longer drops the `queue` export when there are no embeddings
128
+
129
+ `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`.
130
+
131
+ ### `quickback/public/` — static-asset passthrough into `src/apps/`
132
+
133
+ 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.
134
+
135
+ 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`.
136
+
137
+ Rules:
138
+
139
+ - **Optional.** If the folder doesn't exist, the step is a no-op.
140
+ - **Stale-cleaned.** `src/` is wiped and rewritten each compile, so files removed from `quickback/public/` disappear from `src/apps/` automatically on the next run.
141
+ - **Hidden entries skipped.** `.DS_Store`, `.git/`, dotfiles — none of these were intentional drops; including them would break worker asset bindings.
142
+ - **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.
143
+
144
+ 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.
145
+
146
+ ---
147
+
148
+ ## v0.14.7 — May 7, 2026
149
+
150
+ ### Four more codegen bugs caught by AttendVIP — generated output now typechecks for projects with non-`id` PKs and DO-only features
151
+
152
+ 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).
153
+
154
+ **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).
155
+
156
+ **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.
157
+
158
+ **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.
159
+
160
+ **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.
161
+
162
+ **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.
163
+
164
+ ### Account auth: emailOtp on AWS SES drops the magic-link companion (OTP-only)
165
+
166
+ 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.
167
+
168
+ Two reasons to drop the magic-link half:
169
+
170
+ 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.
171
+ 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.
172
+
173
+ 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.
174
+
175
+ 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`.
176
+
177
+ ### Coming next — `id` field auto-injection (v0.14.8)
178
+
179
+ 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.
180
+
181
+ **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.
182
+
183
+ No user code changes required for the four fixes shipping in v0.14.7. Recompile and the affected features typecheck.
184
+
185
+ ---
186
+
187
+ ## v0.14.6 — May 7, 2026
188
+
189
+ ### Four more v0.14 compiler bugs caught by AttendVIP's MCP rollout
190
+
191
+ 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.
192
+
193
+ **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/`.
194
+
195
+ **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.
196
+
197
+ **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.
198
+
199
+ **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).
200
+
201
+ After upstreaming, the AttendVIP one-shot verification passes:
202
+
203
+ ```bash
204
+ curl -fs -X POST https://attend.vip/mcp \
205
+ -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
206
+ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"listEvents","arguments":{}}}' \
207
+ | jq '.result.content[0].text | fromjson | .data | length' # > 0
208
+ ```
209
+
210
+ 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.
211
+
212
+ ---
213
+
214
+ ## v0.14.5 — May 7, 2026
215
+
216
+ ### MCP `tools/call` no longer crashes with `undefined (reading 'AUTH_DB')`
217
+
218
+ 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.
219
+
220
+ **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.
221
+
222
+ No user code changes required. Recompile against v0.14.5 and the MCP endpoint dispatches actions correctly against all bindings.
223
+
224
+ ---
225
+
226
+ ## v0.14.4 — May 7, 2026
227
+
228
+ ### `via:` firewall predicates no longer crash with `ReferenceError: db is not defined`
229
+
230
+ 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.
231
+
232
+ Two fixes:
233
+
234
+ 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.
235
+ 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.
236
+
237
+ 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.
238
+
239
+ No user code changes required — recompile and `via:` predicates work end-to-end.
240
+
241
+ ---
242
+
243
+ ## v0.14.3 — May 7, 2026
244
+
245
+ ### Relationship-role consumers now resolve the relationship-table binding at runtime
246
+
247
+ 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.
248
+
249
+ 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.
250
+
251
+ 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.
252
+
253
+ ```ts
254
+ // generated <table>.resource.ts (after fix)
255
+ import { event_guests } from './schema';
256
+ export { event_guests }; // ← was missing
257
+ ```
258
+
259
+ 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.
260
+
261
+ ---
262
+
7
263
  ## v0.14.2 — May 7, 2026
8
264
 
9
265
  ### 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 four 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).
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:
@@ -272,7 +286,7 @@ type FieldCondition =
272
286
 
273
287
  Beyond Better Auth roles (org membership, user-table role) and pseudo-roles, Quickback supports **relationship-based authorization roles** — names that bind to a declared relationship between the caller and a resource. Use these when access should follow a domain-table membership ("user is a confirmed guest of this event") rather than an org/admin gate.
274
288
 
275
- ### `authz.relationships` { #authz-relationships }
289
+ ### `authz.relationships`
276
290
 
277
291
  Declare relationships once in `quickback.config.ts`:
278
292
 
@@ -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:
@@ -17,7 +17,7 @@ The generated API returns structured error responses with consistent fields acro
17
17
 
18
18
  ## Error Response Format
19
19
 
20
- All errors use a flat structure with contextual fields:
20
+ All errors use a flat structure with contextual fields. Every structured error response also carries a `request` block with the HTTP method, URL, request ID, and a redacted+truncated copy of the request body — enough to triage or hand the response to an LLM agent without grepping logs:
21
21
 
22
22
  ```json
23
23
  {
@@ -28,7 +28,13 @@ All errors use a flat structure with contextual fields:
28
28
  "required": ["hiring-manager"],
29
29
  "current": ["interviewer"]
30
30
  },
31
- "hint": "Contact an administrator to grant necessary permissions"
31
+ "hint": "Contact an administrator to grant necessary permissions",
32
+ "request": {
33
+ "method": "POST",
34
+ "url": "/api/v1/candidates/cnd_01H.../advance",
35
+ "body": "{\"stage\":\"offer\"}",
36
+ "requestId": "0c4f2c9e-..."
37
+ }
32
38
  }
33
39
  ```
34
40
 
@@ -39,6 +45,7 @@ All errors use a flat structure with contextual fields:
39
45
  | `code` | string | Machine-readable error code |
40
46
  | `details` | object | Layer-specific context (optional) |
41
47
  | `hint` | string | Actionable guidance for resolution (optional) |
48
+ | `request` | object | Method, URL, redacted body, and request ID. Auto-attached by the runtime so the error body is self-contained — bodies are capped at 4 KB and well-known sensitive keys (`password`, `token`, `secret`, `apiKey`, `otp`, `code`, `authorization`, …) are replaced with `"[REDACTED]"` |
42
49
 
43
50
  ## Errors by Security Layer
44
51
 
@@ -222,3 +229,78 @@ Batch operations can return:
222
229
  | `BATCH_SIZE_EXCEEDED` | Too many records in a single request |
223
230
  | `BATCH_ATOMIC_FAILED` | Atomic batch failed, all changes rolled back |
224
231
  | `BATCH_MISSING_IDS` | Batch update/delete missing required IDs |
232
+
233
+ ## Action Failures (500)
234
+
235
+ When an action's `execute()` body throws something that isn't a known
236
+ transition / state / FK / constraint failure (e.g. a `TypeError`, a
237
+ fetch timeout, a third-party API error), the route returns
238
+ `ACTION_EXECUTION_FAILED`. The body forwards as much of the underlying
239
+ error as is safe to expose: error class name, message, cause-chain
240
+ message, and the top three stack frames with absolute paths sanitized
241
+ to basename + line number.
242
+
243
+ ```json
244
+ {
245
+ "error": "Cannot read properties of undefined (reading 'getXmlFragment')",
246
+ "layer": "action",
247
+ "code": "ACTION_EXECUTION_FAILED",
248
+ "details": {
249
+ "name": "TypeError",
250
+ "frames": [
251
+ "at updateContent (notebooks.ts:142:31)",
252
+ "at execute (actions.ts:88:7)"
253
+ ]
254
+ },
255
+ "hint": "The action handler threw an unhandled error. Check server logs for the underlying cause.",
256
+ "request": {
257
+ "method": "POST",
258
+ "url": "/api/v1/notebooks/nb_123/updateContent",
259
+ "body": "{\"content\":\"...\"}",
260
+ "requestId": "0c4f2c9e-..."
261
+ }
262
+ }
263
+ ```
264
+
265
+ ## Internal Errors (500)
266
+
267
+ Uncaught throws that escape every route handler land in the global
268
+ `onError` and return `INTERNAL_ERROR`. The body carries the same
269
+ underlying-error context as `ACTION_EXECUTION_FAILED`: `name`, `cause`,
270
+ sanitized `frames`, and the request block.
271
+
272
+ ```json
273
+ {
274
+ "error": "Connection terminated unexpectedly",
275
+ "layer": "database",
276
+ "code": "INTERNAL_ERROR",
277
+ "details": {
278
+ "name": "Error",
279
+ "cause": "ECONNRESET",
280
+ "frames": ["at query (db.ts:54:12)"]
281
+ },
282
+ "hint": "Uncaught error during request handling. Look up the requestId in server logs for the full stack trace, or set EXPOSE_ERROR_STACK=1 to include it inline.",
283
+ "requestId": "0c4f2c9e-...",
284
+ "request": {
285
+ "method": "GET",
286
+ "url": "/api/v1/jobs",
287
+ "requestId": "0c4f2c9e-..."
288
+ }
289
+ }
290
+ ```
291
+
292
+ ### Exposing the full stack
293
+
294
+ By default the response body only carries the top three sanitized
295
+ frames — full stack traces stay server-side so the worker bundle's
296
+ on-disk layout doesn't leak to API clients. To include the full stack
297
+ in the response (useful in dev / staging), set `EXPOSE_ERROR_STACK=1`
298
+ on the worker (`wrangler.toml` `[vars]`, or `wrangler secret put`):
299
+
300
+ ```toml
301
+ [vars]
302
+ EXPOSE_ERROR_STACK = "1"
303
+ ```
304
+
305
+ When set, both the global 500 and `ACTION_EXECUTION_FAILED` bodies
306
+ gain a `details.stack` field with the unsanitized stack trace.