@quickback-dev/cli 0.31.1 → 0.34.2
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 +9 -1
- package/dist/commands/compile.js.map +1 -1
- package/dist/commands/migrations.d.ts +17 -0
- package/dist/commands/migrations.d.ts.map +1 -0
- package/dist/commands/migrations.js +328 -0
- package/dist/commands/migrations.js.map +1 -0
- package/dist/docs/content.d.ts.map +1 -1
- package/dist/docs/content.js +15 -10
- package/dist/docs/content.js.map +1 -1
- package/dist/index.js +7 -1
- package/dist/index.js.map +1 -1
- package/dist/lib/file-loader.d.ts +15 -0
- package/dist/lib/file-loader.d.ts.map +1 -1
- package/dist/lib/file-loader.js +27 -0
- package/dist/lib/file-loader.js.map +1 -1
- package/dist/lib/file-loader.test.js +22 -1
- package/dist/lib/file-loader.test.js.map +1 -1
- package/dist/skill/docs/changelog.md +758 -0
- package/dist/skill/docs/compiler/config/domains.md +26 -0
- package/dist/skill/docs/compiler/config/index.md +74 -3
- package/dist/skill/docs/compiler/config/single-tenant.md +1 -1
- package/dist/skill/docs/compiler/definitions/access.md +161 -9
- package/dist/skill/docs/compiler/definitions/actions.md +45 -1
- package/dist/skill/docs/stack/account-ui/features/admin.md +2 -2
- package/dist/skill/docs/stack/account-ui/hooks.md +4 -0
- package/dist/skill/docs/stack/auth/plugins/aws-ses.md +60 -0
- package/dist/skill/docs/stack/auth/plugins/aws-sns.md +169 -0
- package/dist/skill/docs/stack/auth/plugins/index.md +32 -0
- package/package.json +1 -1
- package/src/skill/docs/changelog.md +758 -0
- package/src/skill/docs/compiler/config/domains.md +26 -0
- package/src/skill/docs/compiler/config/index.md +74 -3
- package/src/skill/docs/compiler/config/single-tenant.md +1 -1
- package/src/skill/docs/compiler/definitions/access.md +161 -9
- package/src/skill/docs/compiler/definitions/actions.md +45 -1
- package/src/skill/docs/stack/account-ui/features/admin.md +2 -2
- package/src/skill/docs/stack/account-ui/hooks.md +4 -0
- package/src/skill/docs/stack/auth/plugins/aws-ses.md +60 -0
- package/src/skill/docs/stack/auth/plugins/aws-sns.md +169 -0
- package/src/skill/docs/stack/auth/plugins/index.md +32 -0
package/dist/docs/content.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
export const DOCS = {
|
|
4
4
|
"changelog": {
|
|
5
5
|
"title": "Changelog",
|
|
6
|
-
"content": "## v0.24.0 — May 19, 2026\n\n### Cross-feature namespaces: one hoisted gate, many features\n\nv0.23 shipped `defineTable({ namespace: { prefix, via } })` — a hoisted relationship-resolver middleware that gates every standalone action in *one feature's* Hono app. That covers the 95% case where a domain concept (events) and the actions under it all live in the same feature directory.\n\nv0.24 lifts the namespace to the project level so it can span multiple features. A new `authz.namespaces` block on `quickback.config.ts` declares a path-prefix gate that any feature's standalone action can participate in by matching the prefix in its `path:`. One synthetic routes file, one resolver mount, one relationship match per request — regardless of how many feature directories contribute actions.\n\n```ts\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n namespaces: {\n eventScope: { prefix: '/event/:eventId', via: 'attendeeOf' },\n },\n}\n\n// features/feeds/actions/feed-moments.ts (cross-feature)\nexport default defineAction({\n path: '/event/:eventId/feed-moments',\n method: 'POST',\n // No gate boilerplate. ctx.event is typed.\n});\n\n// features/rsvp/actions/respond.ts (different feature, same namespace)\nexport default defineAction({\n path: '/event/:eventId/respond',\n method: 'POST',\n});\n```\n\nThe compiler emits one `src/routes/__namespace-event-scope.routes.ts` mounted at `/api/v1/event/:eventId/*`. The file imports each contributing feature's `actions` map under a distinct alias (`feedsActions`, `rsvpActions`), runs the `attendeeOf` resolver once per request at the head of the file, and dispatches to the matching action handler.\n\n#### Discovery is path-prefix-only\n\nNo new `namespace: 'eventScope'` field on `defineAction`. Actions opt in by matching `path:` against a declared namespace prefix — same model the table-level v0.23 form uses, just lifted to the project level. This means actions move in/out of the namespace based on their path strings, which is the simplest discovery story and matches today's convention (filenames and paths are already the discoverable surface).\n\n#### Source-feature stays the action's home for metadata\n\nOpenAPI tags, MCP tool grouping, and CMS form discovery continue to bucket each action under its source feature. Only the *runtime routes file* moves to the synthetic location — the feed-moments action is still tagged \"feeds\" in OpenAPI, the response shape doesn't change, and your generated SDK reads identically. The URL conveys the namespace membership without forcing every layer of the compiler to re-anchor the action.\n\n#### Worker-root mount order\n\nSynthetic namespace routes files register at priority `20` — ahead of per-feature mounts (priority `0`/`10`). `sortRoutesBySpecificity` keeps the order stable, and the namespace prefix's path parameter makes it sort more specific than `/api/v1/<feature>` anyway, so the middleware fires first for every request under its prefix.\n\n#### Compile-time guardrails\n\nThe same v0.23 invariants apply at the project level, with two additions:\n\n- **`via:` must point at a declared `authz.relationships[*]` entry**, and that relationship must declare `loads + exposeAs` — without `loads` there's nothing for the middleware to hydrate, and a namespace that only gates without hydrating is indistinguishable from a per-action access rule.\n- **`prefix:` must contain at least one `:param` segment** — middleware runs before input parsing, so the relationship key comes from `c.req.param()`.\n- **Same-name conflict** between `defineTable({ namespace })` and `authz.namespaces.<sameName>` is rejected. Pick one declaration site.\n- **Ambiguous prefixes** like `/a/:x` and `/a/:y` (same shape, different `:param` names) error at compile time. Strict super/sub-set relationships (e.g. `/event/:e` and `/event/:e/admin`) are fine — the harvester routes each action to the longest matching prefix.\n- **Unused namespace warning** emits `[quickback:authz]` when no standalone action's path matches a declared prefix. Not a hard error — the namespace may be staged ahead of the actions.\n\n#### Picking the right declaration site\n\nThe table-level v0.23 form is now the **single-feature shorthand**. The project-level v0.24 form is **canonical for cross-feature**.\n\n- **Use `defineTable({ namespace })`** when every action under the prefix lives in the same feature directory. The namespace travels with the table that owns it; nothing to add to `quickback.config.ts`.\n- **Use `authz.namespaces`** when the namespace spans features. The declaration sits next to your `authz.relationships` and `authz.roles` — the canonical home for cross-cutting authz config.\n\nThe two forms can't coexist for the same namespace name. If a v0.23 table-level namespace is starting to attract cross-feature actions, lift it to `authz.namespaces` — same shape, just at the project level, and the matching paths in other features will join automatically.\n\n#### Migration\n\nZero breaking changes. Nothing in v0.23 needs to change for v0.24 to land. The new field is opt-in; existing projects pick it up the moment they declare an `authz.namespaces` entry.\n\nThe harvester runs after Zod schema validation but before route generation, so unused or misconfigured namespaces surface immediately as errors or warnings rather than as silently-broken routes.\n\n---\n\n## v0.23.0 — May 19, 2026\n\n### Authz relationships: compile-time guarantees, less boilerplate, hoisted middleware\n\nThis release closes the gap between what `authz.relationships` *promised* in v0.19 and what it actually enforced. Every documented invariant is now a real compile-time check; every per-action ergonomic friction has a fix. Net effect: relationship-based authorization feels native — declare the relationship once, use the role anywhere, the compiler does the wiring.\n\n#### Compile-time guarantees (the authz `firewall` parity)\n\nThe org/owner/team firewall has always been compile-time-checked: a routed resource without a scope fails the compile, full stop. As of this release, `authz.relationships` carries the same guarantees:\n\n- **Bad `via:` names fail at parse time.** A typo in a firewall predicate (`firewall: [{ field: 'eventId', via: 'guestOff' }]`) used to surface deep inside the firewall generator after most validation had passed. It's now caught alongside the `authz.roles` `via:` validation, same layer, same error format.\n- **Relationship-from tables can't opt out.** The doc at `define/types/authz.ts:73-74` always said a relationship `from:` table with `firewall: { exception: true }` \"refuses to compile\" — that's now enforced. Without this check, every `via:` subquery that pivots through an exception-marked table loses tenant isolation and can return rows from other tenants.\n- **`allowResourceMigration` is now mandatory** when the relationship's `resource.column` is on a writable update endpoint. A guest doing `PATCH /messages/:id { eventId: <other-event-id> }` to migrate a row out of their access scope used to slip past the runtime — it now fails compile with a three-option remediation (set the flag, mark the column immutable, or drop it from the guards.updatable allowlist).\n- **`via: string[]` in firewall predicates.** \"Member of attendees OR speakers\" no longer requires inventing a composite role just to use it once in a firewall — `firewall: [{ field: 'eventId', via: ['attendeeOf', 'speakerOf'] }]` lowers to an OR-combined subquery.\n\n#### Less boilerplate: auto-derivation + realtime resolver\n\n- **`resource.column` auto-derives from FKs.** Omit it and the compiler scans the relationship's `from:` table for foreign-key columns, drops the `subject.column`, and picks the remaining FK. One match → auto; zero or many → error with the candidate list. Pattern mirrors the existing firewall auto-detection.\n- **`realtime.requiredRoles` accepts authz roles.** Previously a relationship-role in `realtime.requiredRoles` fell through with a misleading \"unknown role\" error. The compiler now flattens declared authz roles into their composing Better Auth roles before the realtime ticket-handshake sees them. Relationship-only roles (no static BA fallback) emit a `[quickback:authz]` warning and fail-close at handshake — the row-stream firewall continues to enforce the relationship dimension on the data side.\n\n#### Record-based actions can finally use relationship-roles\n\nThe v0.19 fail-closed hardening had an unintended side effect: a record-based action with `access: { roles: ['attendee'] }` (where `attendee` was a relationship-role) 403'd every caller, including the legitimate ones. The runtime helper couldn't evaluate `relationship:` arms, so it fail-closed correctly — but the inline match expression that *would* evaluate the relationship was never wired up for record-based actions.\n\nThis release routes record-based actions with relationship arms through the same inline access generator the resource CRUD path already uses. `roles: ['attendee']` on `/applications/:id/recap` now actually checks whether the caller is an attendee, with the loaded record in scope. Non-relationship access trees keep the runtime path unchanged.\n\n#### Typed `ctx.<exposeAs>` in action handlers\n\nWhen a relationship declares `loads: 'events', exposeAs: 'event'`, the runtime hydrates `ctx.event` with the loaded row — but the static type was always `any`, so handlers had to write `const event = ctx.event as typeof events.$inferSelect`. As of this release, when an action's access references **exactly one** relationship with `loads + exposeAs`, the compiler emits the cast for you at the execute() call site. Handlers read `ctx.event` with the right shape; no per-handler boilerplate.\n\nMulti-arm OR actions (referencing two relationships with hydration) keep the `any` shape — we can't statically know which arm matched.\n\n#### New: `defineNamespace` — one mount, one resolver, many actions\n\nThe marquee Wave 3 change. Today's pattern for \"five standalone actions under `/event/:eventId/*` all gated by `attendeeOf`\" requires writing the same inline relationship resolver in each action — and pays the resolver cost (one subquery, one row-load) on every request, multiplied by N actions. The new `namespace` field on `defineTable` hoists the resolver into a single Hono middleware mount:\n\n```ts\n// features/events/events.ts\nexport default defineTable(events, {\n firewall: [...],\n crud: { ... },\n namespace: {\n prefix: '/event/:eventId', // absolute URL path the mount covers\n via: 'attendeeOf', // relationship gate\n },\n});\n\n// features/events/actions/post-announcement.ts\nexport default defineAction({\n path: '/event/:eventId/announcements',\n method: 'POST',\n // No relationship-gate boilerplate. ctx.event is typed\n // `typeof events.$inferSelect` inside execute().\n});\n```\n\nThe compiler:\n1. Emits one `app.use('/:eventId/*', async (c, next) => { /* relationship resolver */; await next(); })` at the head of the feature's standalone-routes file (path-prefix stripping handles the feature mount).\n2. Skips the inline relationship resolver in every per-action handler under the prefix — the middleware already ran it.\n3. Hydrates `ctx.event` once per request and threads the typed cast into every namespace action's execute() call.\n\n**Validation guardrails:**\n- `namespace.via` must point at a declared `authz.relationships[*]` entry.\n- The referenced relationship must declare `loads + exposeAs` — without `loads` there's nothing for the middleware to hydrate, and the namespace gate would be indistinguishable from a per-action access rule.\n- `namespace.prefix` must contain at least one `:param` segment — the middleware reads the relationship key from `c.req.param()`, not from request body (body parsing hasn't run at middleware time).\n\n**Scope (v1):**\n- Namespace lives within a single feature's Hono `app`; cross-feature shared namespaces are deferred to v2.\n- One namespace per `defineTable` declaration; multiple namespaces in a feature mount as siblings.\n- For namespace actions whose access references additional relationships beyond the namespace's via, the inline resolver still fires for those — namespace handles only its own.\n\n#### Migration\n\nNothing in v0.20 → v0.23 breaks existing code that compiles cleanly. The new errors fire only against patterns that were already latent bugs:\n\n- A `via:` typo that previously surfaced as a deep codegen error now surfaces at parse time, same message.\n- A `firewall: { exception: true }` on a relationship-from table now errors; this configuration was always documented as unsupported.\n- A relationship's `resource.column` writable on the resource's UPDATE endpoint now errors unless `allowResourceMigration: true` is set; previously this was a runtime escape hatch.\n- Record-based actions with `roles: ['<relationship-role>']` previously 403'd every caller; they now work as the v0.19 docs originally promised.\n\n#### Why this matters\n\nAuthz relationships are how Quickback expresses \"the caller is allowed to touch this resource because of a row in *that* table\" — guest-of-event, member-of-organization, scorer-of-interview. Until now, the feature worked but had sharp edges: typos surfaced late, the documented exception-not-allowed constraint wasn't enforced, and the namespace pattern (which most apps with nested resources end up wanting) required repeating the same gate in every action. This release brings authz to parity with the org/owner/team firewall: declare it once, the compiler enforces it everywhere, the runtime emits exactly one query per request.\n\n---\n\n## v0.22.0 — May 19, 2026\n\n### Quickback Stack is Cloudflare-only: one runtime, two databases, one auth provider\n\nWe've focused the platform on the stack we actually believe in: **Cloudflare Workers + Hono + Better Auth**, with **Cloudflare D1** or **Neon** as the database. Providers and modes that targeted non-Cloudflare backends are gone. The result is a smaller concept set, fewer footguns, and clearer docs.\n\n#### What's been removed\n\n- **Runtimes**: `bun` and `supabase-edge` are no longer supported. The only runtime is `cloudflare`. Local development for compiled projects has always used `wrangler dev` — that's unchanged.\n- **Databases**: `supabase`, `libsql`, `better-sqlite3`, `bun-sqlite` are removed. Use `cloudflare-d1` for SQLite at the edge or `neon` for PostgreSQL via Hyperdrive.\n- **Auth providers**: `supabase-auth` is removed. `better-auth` is the default; `external` (Cloudflare service binding) remains for advanced setups.\n- **Template**: `template: 'nextjs'` is removed from the public config type. It was never fully implemented. The only template is `'hono'`. If you need a Next.js frontend, bring it as a separate deploy and call the Quickback API, or drop a static export into the `apps:` mount.\n- **Quickback for Supabase RLS** product line is retired. The compiler no longer emits Supabase Row Level Security policies. The `/products/quickback-supabase-rls/` and `/for/supabase-users/` pages have been removed from the marketing site, and the `compiler/targets/supabase-rls/` docs section has been deleted.\n\n#### Account UI: one delivery mode\n\nThe standalone `quickback-better-auth-account-ui` npm package has been **deprecated** and the upstream GitHub repo (`Kardoe-com/quickback-better-auth-account-ui`) has been **archived**. Account UI is now exclusively delivered the way 99% of projects already use it: the compiler builds it from source and bundles it into your Worker.\n\n- `account: { domain: 'auth.example.com', ... }` in `quickback.config.ts` — that's the entire integration story.\n- The compiler builds the SPA inside Docker with your branding and feature flags baked in, emits hostname-based routing, and wires cross-subdomain cookies automatically.\n- The three standalone delivery-mode docs (`stack/account-ui/standalone`, `library-usage`, `worker`) are removed; the remaining pages explain the compiler-bundled flow.\n\nIf you previously deployed the standalone Account UI Worker against a Quickback backend, switch to `account: { domain }` in the config — same end result, one less deploy.\n\n#### `VITE_AUTH_ROUTE` hardcoded to Quickback\n\nThe `VITE_AUTH_ROUTE` env var (which used to switch between `quickback` and `better-auth` routing dialects) is gone. The auth-client always uses Quickback's namespaced routes (`/auth/v1`, `/api/v1`, `/storage/v1`). Generic Better Auth backends are no longer a supported target. Removing the var also closes a known footgun where setting the wrong value silently 404'd every auth call.\n\n#### New: every config option is now discoverable\n\nWhen you bootstrap a project, the kitchen-sink marker block in `quickback.config.ts` lists every option Quickback supports — with descriptions and sensible defaults — commented out for you to copy above the marker as needed. Three top-level options were missing from this discovery surface and are now included:\n\n- **`apps`** — mount your own prebuilt SPA on its own hostname (`apps: { www: { domain: 'www.example.com', aliasDomains: ['example.com'] } }`). Drop the build at `quickback/apps/<name>/` and the compiler serves it from your Worker alongside the API. Reserved names: `cms`, `account`, `public`.\n- **`security`** — HTTP security headers (CSP, COOP, COEP, HSTS, Referrer-Policy, Permissions-Policy, X-Frame-Options). Set `security: false` to suppress everything; defaults are sensible for the embedded SPAs.\n- **`authz`** — relationship-based authorization roles. Declare joins between the caller and a resource column, then bind role names to those joins for use in `access: { roles: [...] }`.\n\n#### Migration\n\nProjects that compile cleanly against v0.21 and use any of these providers will hit a clear error at compile time:\n\n```\nUnknown database provider: \"supabase\". Available: cloudflare-d1, neon\n```\n\nTo migrate:\n\n1. **From Supabase**: switch `providers.database` to `cloudflare-d1` or `neon`, and `providers.auth` to `better-auth`. Your `defineTable()` definitions transfer as-is; the security DSL (firewall, access, guards, masking) compiles to Better Auth + Drizzle queries instead of RLS policies.\n2. **From Bun runtime / `bun-sqlite`**: switch `providers.runtime` to `cloudflare` and `providers.database` to `cloudflare-d1`. Local dev becomes `wrangler dev`.\n3. **From libsql / Turso**: switch to `cloudflare-d1` or `neon`. Both run natively from Cloudflare Workers via the right binding.\n4. **From `template: 'nextjs'`**: deploy Next.js separately and call the Quickback API, or drop a static export into `apps:`.\n\n#### Why this matters\n\nThe Quickback Stack is the Supabase alternative for Cloudflare. Every Quickback project ships a Hono API, an Account SPA, a CMS SPA, optional realtime/storage/queues — all built from one config and bundled into one Worker. Keeping that promise focused is more valuable than supporting deployment targets that don't share the runtime.\n\n---\n\n## v0.21.0 — May 19, 2026\n\n### Auto-firewall column swap: `ownerId` is now canonical on feature tables, `userId` warns\n\nThe compiler's default auto-firewall column for feature tables flips from `userId` to `ownerId`. This closes a long-standing footgun where a `userId` column meaning \"a user this row references\" (a member, a contact, an invitee) got silently clobbered with `ctx.userId` on insert, because the wrapper matched purely on column name across every table in the project.\n\n**What changed in the compiler**\n\n- `BETTER_AUTH_DEFAULTS.owner.column`: `'userId'` → `'ownerId'`. Schemas with an `ownerId` column auto-resolve to `firewall: [{ field: 'ownerId', equals: 'ctx.userId' }]` and have `ownerId` auto-stamped on insert.\n- The generated `OWNER_SCOPE_RULES` in `src/lib/scoped-db.ts` is seeded with `ownerId` instead of `userId`. Schemas that don't explicitly name `userId` in a `firewall:` block no longer trigger the global `userId`-stamping rule — the most common collision goes away without renames.\n- A new compile-time warning fires when a feature table carries both an auto-resolved isolation column AND a `userId` column. The warning recommends renaming the column to `linkedUserId` (or similar) if it's informational, or declaring `firewall: [{ field: 'userId', equals: 'ctx.userId' }]` if it really is the access boundary on that table.\n- The targeted compile-time error for \"the only candidate column is `userId`\" now points users at `ownerId` and the explicit-firewall escape hatch. The previous error wording (which assumed `ownerId` was business-logic) is removed.\n\n**What stayed the same**\n\n- Better Auth's own internal tables (`session`, `account`, `member`, `passkey`, `subscriptions`) still use `userId` by convention. They aren't feature tables and don't pass through the auto-firewall.\n- Explicit `firewall: [{ field: 'userId', equals: 'ctx.userId' }]` declarations continue to work and are still recognized as the \"owner\" pattern in the generated comment header.\n- The `USER` pseudo-role validator behaviour is unchanged; only the error-message wording flips to lead with `ownerId` and list `userId` as the explicit fallback.\n- Audit-wrapper (`createdBy` / `modifiedBy`) behavior is untouched.\n\n**Migration**\n\nProjects that auto-firewalled on a `userId` column will see a hard error on next compile telling them which table is affected, with two suggested fixes:\n\n1. **Recommended**: rename the column to `ownerId` in the schema. Cleanest semantics — readers immediately understand the column is access-control.\n2. **Explicit firewall**: keep the `userId` column and add `firewall: [{ field: 'userId', equals: 'ctx.userId' }]` to the resource. The auto-stamping and auto-scoping still happen; you've just opted in by name.\n\nProjects that have a `userId` column meaning \"a user this row references\" no longer need the `linkedUserId` rename workaround — auto-stamping won't touch the column unless you name it in a firewall block. The new warning makes this audit-discoverable.\n\n**Caveat (deferred)**: explicit `firewall: { owner: { column: 'X' } }` declarations still populate the project-global `OWNER_SCOPE_RULES` list, so a hand-named owner column on one resource will still match by name on every other table that happens to have a column called `X`. A future release will make scope-rule resolution per-table rather than project-global. The warning text calls this out so callers know what to expect.\n\n---\n\n## v0.20.0 — May 19, 2026\n\n### CMS + Account SPAs: shadcn base-ui migration, central Tailwind config\n\nBoth first-party SPAs are now on the shadcn **base-ui** variants (`@base-ui/react`) instead of the Radix-based primitives, applied via shadcn preset **`bdvxIkMq`** (style `base-mira`, `baseColor: zinc`, `iconLibrary: remixicon`, Inter Variable font). The migration also collapses the previously duplicated per-SPA theme + `components.json` into a single source at `packages/ui/`.\n\n#### Single source of truth in `packages/ui/`\n\nBoth SPAs were independently declaring the same `@theme` / `:root` / `.dark` token blocks in their own `app.css`, and each had its own `components.json` pointing at non-existent local component directories. That's gone:\n\n- `packages/ui/styles/theme.css` — the only place tokens live. Includes the base-mira palette, sidebar + chart tokens, and the Inter font import.\n- `packages/ui/components.json` — the only shadcn config in the repo. Future `pnpm dlx shadcn@latest add <name>` runs from `packages/ui/`.\n- `packages/cms/app/app.css` and `packages/account/app/app.css` reduce to two imports plus SPA-specific layers (CMS keeps its AG Grid + richtext-display overrides). `packages/{cms,account}/components.json` deleted.\n\n#### Components, icons, deps\n\n- All 22 shadcn primitives regenerated against `@base-ui/react` (`@radix-ui/*` removed everywhere). `Drawer` stays on `vaul` — base-ui has no Drawer primitive.\n- Icons migrated from `lucide-react` to `@remixicon/react` line variants across ~100 source files (`Plus → RiAddLine`, `ChevronDown → RiArrowDownSLine`, `X → RiCloseLine`, etc.). `lucide-react` removed from all `package.json` + `deps-spa-*` files.\n- `pnpm.overrides` pin `@types/react ^19.2.0` workspace-wide to resolve the duplicate-React-types conflict introduced by `@base-ui/react`'s bundled type peer.\n- Per-SPA deps and the Docker build mirrors (`apps/compiler/deps-spa-{cms,account}-package.json`) both gain `@base-ui/react`, `@remixicon/react`, `@fontsource-variable/inter`, and bump `shadcn` to `^4.7.0`.\n\n#### Backwards-compat `asChild` shim\n\nBase-ui replaces Radix's `asChild` boolean with a `render={\n</Button>\n```\n\n`ResponsiveModal` survived the migration unchanged — it composes the higher-level Dialog + Drawer wrappers (preserved public API), not the underlying primitives.\n\n#### Caller-side API changes worth noting\n\nBase-ui ships some real behavioural changes the Radix variants didn't:\n\n- `<Select onValueChange>` now receives `(value: string | null, eventDetails) => void` (was `(value: string) => void`). Existing `Dispatch<SetStateAction<string>>` setters reject `null` — wrap callbacks defensively: `onValueChange={(v) => v != null && setX(v)}`.\n- `<DropdownMenuContent forceMount>` removed (base-ui has no `forceMount`). Use base-ui's `keepMounted` on the Popup/Positioner if you need to preserve unmounted state.\n- Component sub-names shifted (`Dialog.Content` → `Dialog.Popup`, `Dialog.Overlay` → `Dialog.Backdrop`). Data attributes are now `data-open` / `data-closed` (no more `data-state=\"open\"`).\n\n#### Adding a new primitive after this release\n\n```bash\ncd packages/ui\npnpm dlx shadcn@latest add <component> --overwrite --yes\n# Sweep generated `@/` imports to relative paths — the SPAs' vite-tsconfig-paths\n# plugin doesn't see packages/ui's @/* mapping at bundle time:\nsed -i.bak \\\n -e 's|\"@/lib/utils\"|\"../lib/utils\"|g' \\\n -e 's|\"@/components/|\"./|g' \\\n -e 's|\"@/hooks/|\"../hooks/|g' \\\n components/<component>.tsx && rm components/<component>.tsx.bak\n```\n\nIf the new primitive pulls in fresh deps, mirror them into `apps/compiler/deps-spa-{cms,account}-package.json` per the SPA build pipeline or Docker SPA builds will fail.\n\n---\n\n## v0.18.1 — May 18, 2026\n\n### Account SPA — teams, active-team picker, permission-aware UI\n\nThe Account SPA's organization surface is now feature-parity with Better Auth's `organization` plugin for the basic team workflow, and replaces the long-standing hardcoded `role === 'owner' || 'admin'` checks with `checkRolePermission` so projects that ship custom roles get a UI that respects them.\n\n#### Teams (opt-in)\n\nWhen the BA config enables teams — `organization({ teams: { enabled: true } })` — the compiler emits `VITE_ENABLE_ORG_TEAMS=true` and the Account SPA exposes a Teams tab on each organization:\n\n- **Teams index** (`/$slug/teams`) — splits into \"Your teams\" (from `listUserTeams`) and \"Other teams\" so non-admins land on what's relevant. Create / rename / delete from the list, gated on `team:create` / `team:update` / `team:delete`.\n- **Team detail** (`/$slug/teams/$teamId`) — member roster with add / remove, joining `listTeamMembers` against the org's full member list for display.\n- **Active-team picker** in the org header — calls `setActiveTeam` and exposes the choice via `OrganizationContext.activeTeamId` so downstream routes (and the BA `session.activeTeamId` server-side) stay in sync.\n- **Team-aware invites** — `InviteMemberDialog` shows an optional team picker when teams are on and forwards `teamId` to `inviteMember`, so accepting the invite drops the new member straight into the right team.\n\nTeams are loaded once by the `$slug` layout (`listTeams` + `listUserTeams`) and exposed via `OrganizationContext.teams` / `userTeamIds` / `refreshTeams`, so individual team routes don't re-fetch the list.\n\n#### Permission-aware UI via `checkRolePermission`\n\n`OrganizationContext.isOwnerOrAdmin` is gone. Routes now read `can(resource, action)` from context, which delegates to `authClient.organization.checkRolePermission` — synchronous, no roundtrip, and aware of any custom roles registered via the BA `ac` option. Multi-role users (BA stores multiple roles comma-separated) are handled by checking each role; the action is allowed if any role grants it.\n\nMigrated sites:\n\n- `$slug.tsx` tab gates → `can('invitation', 'create')`, `can('organization', 'update')`\n- `members.tsx` action menu → `can('member', 'update' | 'delete')`; the owner-hierarchy guard (non-owners can't touch owner-role members) is preserved as a client-side mirror of BA's server enforcement\n- `invitations.tsx` → `can('invitation', 'create' | 'cancel')` gates the Invite button, resend, and cancel separately\n- `settings.tsx` → `can('organization', 'update')` for the form, `can('organization', 'delete')` for the danger zone (was owner-only)\n- `teams.tsx` / `teams.$teamId.tsx` → `can('team', 'create' | 'update' | 'delete')`\n\nProjects on the default three-role hierarchy see no behaviour change; projects that defined `admin`/`member` overrides via BA's access-control API now get a UI that matches what the server will actually authorize.\n\n#### Editable slug + metadata on organization settings\n\nThe `$slug/settings.tsx` form now edits two more `organization.update` fields:\n\n- **URL slug** — full debounced `checkSlug` flow (mirroring the create-org form); on rename, the SPA navigates to `/${newSlug}/settings` and the layout re-fetches with the new slug.\n- **Metadata** — single `Record<string, any> | null` JSON textarea, parsed on submit with inline error messaging. Empty clears the field.\n\nSlug rename is non-breaking for the SPA itself, but every external link / bookmark that references the old slug becomes a 404 — the form warns about this before saving.\n\n#### Auth client wiring\n\nWhen `VITE_ENABLE_ORG_TEAMS=true`, the SPA's `organizationClient(...)` is instantiated with `teams: { enabled: true }` so the team APIs are typed end-to-end. When the flag is off, team methods aren't surfaced — and the Teams tab is hidden — keeping the bundle and UI honest about what the server actually supports.\n\n---\n\n## v0.18.0 — May 17, 2026\n\n### `config.apps` — mount user-authored SPAs on dedicated hostnames\n\nThe compiler now generates per-hostname Worker middleware for arbitrary user SPAs alongside the built-in CMS and Account UIs. Previously the only way to host a product app next to a Quickback API was a second Worker; `config.apps` brings the full stack — API, account, and product UI — onto one deployment with same-origin auth.\n\n```ts\napps: {\n www: {\n domain: \"www.example.com\",\n aliasDomains: [\"example.com\"], // apex serves the same SPA\n },\n}\n```\n\nEach entry binds one or more hostnames to a directory under `src/apps/<name>/` and inherits the Account-domain pass-through behavior — `/api/`, `/auth/`, `/admin/`, `/storage/`, and `/health` route to Hono so the SPA fetches its API without CORS. The compiler:\n\n- emits a `custom_domain = true` route in `wrangler.toml` for the primary hostname and every alias\n- adds each hostname to Better Auth's `TRUSTED_ORIGINS` (when `trustedOrigins` is left unset)\n- widens the CSP `connect-src` to cover the SPA-baked origins\n- folds the new hostnames into shared-parent detection for `crossSubDomainCookies`\n\nDrop the prebuilt SPA bundle at `quickback/apps/<name>/` — the existing source-apps passthrough copies it byte-for-byte into `src/apps/<name>/`. The compiler doesn't build the SPA; it only emits routing for whatever's already there. The names `cms`, `account`, and `public` are reserved; hostname collisions with `cms.domain` / `account.domain` / `account.adminDomain` or between two `apps[*]` entries fail at compile time.\n\nWhen `cms` and `account` are both configured, the multi-domain catchall now explicitly skips app hostnames — an API miss on an app host returns the standard 404 JSON via `app.notFound` instead of stray-serving a sibling SPA's HTML shell.\n\n### Cross-subdomain cookie inference handles apex aliases\n\nThe shared-parent detection that drives `advanced.crossSubDomainCookies` previously reduced any hostname by stripping the leftmost label — `'example.com'` collapsed to `'com'`, which broke equality against sibling subdomains. Apex hostnames (exactly two dot-segments) are now treated as already being the parent, so apex aliases (`example.com` listed alongside `www.example.com`) coexist cleanly with `auth.example.com` / `cms.example.com` and the compiler still emits `crossSubDomainCookies: { enabled: true, domain: '.example.com' }`.\n\n---\n\n## v0.17.2 — May 15, 2026\n\n### `customPlugins` escape hatch on `defineAuth(\"better-auth\", …)`\n\nThe Better Auth provider now accepts `customPlugins` alongside the named-plugin registry — a path to ship third-party plugins (`@better-auth-kit/audit`, …), unregistered built-ins, or one-off project-local plugins without forking the compiler.\n\nEach entry is an explicit import descriptor:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: { passkey: true, organization: true },\n customPlugins: [\n // (1) Project-local plugin file at quickback/plugins/long-session.ts\n { from: \"./plugins/long-session\", export: \"longSessionPlugin\" },\n // (2) Third-party npm package\n {\n from: \"@better-auth-kit/audit\",\n export: \"auditPlugin\",\n args: { events: [\"sign-in\"] },\n dependencies: { \"@better-auth-kit/audit\": \"^1.0.0\" },\n },\n ],\n}),\n```\n\n`from` is either a relative path under `./plugins/` (the CLI auto-uploads matching files from `quickback/plugins/`; the compiler copies them into `src/plugins/<name>.ts` and rewrites the emitted import) or a bare npm specifier (emitted verbatim; declare `dependencies` so the package lands in the generated `package.json`). Omit `args` to emit the symbol uncalled (plugin instance); provide `args` to emit a JSON-serialized factory call.\n\nThe descriptor is validated with Zod — typos in `from`/`export`, paths that escape `./plugins/`, and references to files the CLI didn't ship all fail at compile time with a targeted message.\n\n---\n\n## v0.17.1 — May 14, 2026\n\n### `quickback start` — interactive onboarding\n\n```bash\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n```\n\n`start` walks new users through template selection, scaffolds the project on disk, and only prompts for an account when it's ready to compile. Cancelling at the login prompt leaves the scaffold intact — sign in and run `quickback compile` whenever you're ready.\n\nThe same deferred-auth flow applies to `quickback create`. Scaffolding and (optional) Cloudflare D1 setup run before authentication, so you can preview the project on disk before committing to an account.\n\n### Named views on the free tier\n\nThe `todos` template now ships a `dashboard` named view, exposing a projected response at `GET /api/v1/todos/views/dashboard`. Named views support per-view access rules and per-view field selection while inheriting the table's firewall and masking — the canonical way to ship list-view payloads that are cheaper to fetch and easier to cache than a full collection read.\n\n### `quickback init` removed\n\nFolded into `start` and `create`. The legacy command name prints a deprecation notice pointing at its replacements.\n\n### Minor\n\n- `quickback whoami` reads the stored tier from your credentials.\n- Pro upsell copy in `quickback login` is shown only when the server returns an explicit free-tier subscription.\n- Bare scaffolds (`cloudflare`, `empty`) report accurately when there are no features to generate migrations for.\n\n---\n\n## v0.16.10 — May 14, 2026\n\n### D1-specific safety pass on generated migrations\n\nThe `cloudflare-d1` provider now runs a post-generation pass over every Drizzle migration directory (auth, features, webhooks, audit) before the compile finishes. Better Auth cleanup for retired managed tables is stripped from raw `DROP TABLE` statements. Drop-only cleanup migrations are reordered child-first when foreign-key dependencies require it. Every generated D1 migration directory is replayed against SQLite during compile, so a D1-breaking migration fails at compile time rather than at `wrangler d1 migrations apply`.\n\n---\n\n## v0.16.9 — May 13, 2026\n\n### Resource-scoped realtime tickets\n\n`providers.database.config.realtime` accepts an object form for projects whose WebSocket subscribers aren't org members:\n\n```ts\nrealtime: {\n wsTicket: {\n role: \"attendee\",\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n}\n```\n\nThe generated `/broadcast/v1/ws-ticket` route authenticates the caller, evaluates the declared relationship role against the request, and mints a short-lived WebSocket ticket scoped to the resolved resource. `realtime: true` continues to enable the org-scoped broadcaster.\n\n### Unified broadcast targeting\n\nThe realtime helper and Broadcaster now route by `scopeKey || organizationId || userId`. String targets remain shorthand for `organizationId`; explicit targets can scope a broadcast to a resource or a single user:\n\n```ts\nawait realtime.broadcast(\"event-page-updated\", payload, { scopeKey: \"events:evt_123\" });\nawait realtime.broadcast(\"dm\", payload, { userId: recipientId });\n```\n\nWebSocket tickets are Quickback-minted (signed with `BETTER_AUTH_SECRET`), not Better Auth tokens — Better Auth remains the front-door auth check; Quickback signs the upgrade ticket after authorization succeeds.\n\n---\n\n## v0.16.8 — May 13, 2026\n\n### One auth transport per request\n\nGenerated middleware treats `Cookie`, `Authorization: Bearer`, and `x-api-key` as distinct auth methods and rejects mixed requests with `400 AUTH_METHOD_CONFLICT`. Query-string API keys (`?api_key=` / `?key=`) are no longer accepted. Machine-to-machine auth is explicit; precedence rules between transports are gone.\n\n### Cookie-backed CSRF gate\n\nGenerated apps now block cross-site `POST` / `PUT` / `PATCH` / `DELETE` requests from cookie-relying callers. The middleware skips explicit `Authorization` clients, requires a trusted `Origin` or `Referer`, and blocks `Sec-Fetch-Site: cross-site`. This matters most for cross-subdomain session setups where `SameSite=None` is intentional.\n\n### First-class Wrangler observability\n\n`providers.runtime.config.observability` now supports nested `logs` / `traces` blocks for `headSamplingRate`, `destinations`, `persist`, and `logs.invocationLogs`, emitting matching `[observability]`, `[observability.logs]`, and `[observability.traces]` TOML.\n\n---\n\n## v0.16.7 — May 12, 2026\n\n### Bearer wins over cookie\n\nA request carrying both `Authorization` and a session `Cookie` resolves entirely from the bearer; the cookie is dropped before `getSession()` runs. All three Bearer flavors (API key, JWT, session-token) now behave consistently — no more silent cookie precedence on session-token bearers.\n\n### Bearer plugin defaults to `requireSignature: true`\n\nBetter Auth's `bearer` plugin defaults to unsigned tokens; Quickback now emits `bearer({ requireSignature: true })`. Tokens emitted in the CORS-exposed `set-auth-token` header are server-signed with `BETTER_AUTH_SECRET` and verified on every request. Projects that genuinely need unsigned bearers can override via `providers.auth.config.plugins.bearer`.\n\nSee [Authentication Security → Bearer Tokens and Cookie Precedence](/stack/auth/security#bearer-tokens-and-cookie-precedence).\n\n---\n\n## v0.16.5 — May 12, 2026\n\n### Flat write DSL\n\nResource write operations are now declared at the table level alongside `read`, replacing the nested `crud` block:\n\n```ts\ndefineTable(customers, {\n read: { ... },\n create: { access: { roles: [\"admin\"] } },\n update: { access: { roles: [\"admin\"] } },\n delete: { access: { roles: [\"admin\"] }, mode: \"soft\" },\n upsert: { access: { roles: [\"admin\"] } },\n guards: { ... },\n});\n```\n\n`crud` and top-level `put` still compile as deprecated compatibility aliases. Mixed usage on the same resource is rejected. `schema-registry.json` emits both shapes during the transition.\n\n### CMS placement for multi-table feature actions\n\nStandalone actions on multi-table features have an explicit placement model:\n\n- `cms.placement: \"feature\"` shows the action on every table toolbar in the feature\n- `cms.placement: \"tables\"` with `cms.tables` scopes it to specific tables\n- `cms.hidden: true` keeps it API-only\n\nFeature-root standalone actions are emitted under a new `featureActions` bucket in `schema-registry.json`. Ambiguous multi-table standalone actions without placement compile with a warning.\n\n### `openapi.types` accepts a string array\n\nOne compile can write the generated types file to multiple locations, keeping colocated SPA clients in sync:\n\n```ts\nopenapi: { types: ['api-types.gen.ts', 'apps/web/src/lib/api-types.gen.ts'] }\n```\n\n### Stable artifact ordering\n\nGenerated route files and `schema-registry.json` are emitted in a stable order across runs. Identical logical input produces identical artifacts.\n\n---\n\n## v0.16.4 — May 12, 2026\n\n### Drizzle snapshot integrity\n\nDrizzle metadata files (`<n>_snapshot.json`) are no longer stamped with a Quickback warning key. The warning is now journal-only. Projects whose snapshots were corrupted by an earlier release self-heal on the next compile — the stripped header is removed during staging and the rewritten snapshot is clean.\n\n### `account.auth.*` drives the server, not just the SPA\n\nThe Account UI's auth flags (`signup`, `password`, `passkey`, `emailOTP`, `emailVerification`) now configure the Better Auth server alongside the SPA bundle. A normalizer maps them into the server config:\n\n- `signup → emailAndPassword.disableSignUp` (inverted)\n- `password → emailAndPassword.enabled`\n- `emailVerification → emailAndPassword.requireEmailVerification`\n- `passkey` / `emailOTP` → plugin additions\n\nThe SPA's `VITE_ENABLE_*` flags are derived from the same canonicalized server config, so the bundle and the server cannot drift. Two new flags ride along: `VITE_ENABLE_API_KEYS` and `VITE_ENABLE_MAGIC_LINK`.\n\n**Breaking** for projects that implicitly relied on the SPA-only behaviour: `account.auth.signup: false` now actually disables `POST /auth/v1/sign-up/email` on the server. Set `providers.auth.config.emailAndPassword.disableSignUp: false` explicitly to keep server signup open while hiding the SPA screen.\n\n---\n\n## v0.16.3 — May 9, 2026\n\n### Standalone action mount order\n\nFeature-level standalone action routers now register before sibling CRUD routers when both mount at the exact same prefix. A literal path like `GET /api/v1/records/today-bundle` resolves to the standalone handler instead of falling through to `GET /:id` and treating `\"today-bundle\"` as a record ID.\n\n---\n\n## v0.16.1 — May 9, 2026\n\n### Cloudflare ASSETS canonicalization\n\nWorker SPA fallbacks now request `/<dir>/` instead of `/<dir>/index.html`. Cloudflare's static-assets binding rewrites `/index.html` requests as 307 redirects to the trailing-slash path under the default `html_handling=auto-trailing-slash`, which previously caused redirect loops in SPA fallback handlers. Affects CMS, Account, admin, and the multi-domain catchall.\n\n### `account.customLogin`\n\nSet `account: { customLogin: true }` to drop a project-branded sign-in page in front of the bundled SPA. Place the page at `quickback/public/account/login/index.html` (as a directory) and the existing public passthrough serves it. The route registers before the `/account/*` SPA catch-all so the static handler wins; everything else under `/account/` continues to route through the bundled SPA.\n\n### Project-level realtime defaults\n\n`providers.database.config.realtime: true` now treats every resource as realtime-enabled by default. Per-resource `realtime: { enabled: false }` still wins.\n\n### Compile-time validators\n\nTwo new compile-time errors over silent runtime failures:\n\n- `AUTHENTICATED` + org-scoped firewall is rejected. The combination silently returned empty lists to sign-in-only callers who lacked an active org; the validator names three valid resolutions (drop the org scope, use `USER`, or split the route).\n- `createRealtime` imports without `realtime: true` enabled in the config are rejected at compile.\n\n### Drizzle metadata hardening\n\nDrizzle journal files carry a \"do not edit\" header. The compiler warns when the journal entry count exceeds the snapshot file count (typically the trace of a hand-deleted snapshot).\n\n### Minor\n\n- `SYSADMIN` is now recognised by the standalone-action org gate's pseudo-role matcher.\n- Apex `/` and `/account/login` get fallback redirects to `auth.loginUrl` when neither bundled SPA is enabled.\n- Record-based action URLs are kebab-case to match the OpenAPI spec (e.g. `/api/v1/widgets/:id/send-invite`).\n\n---\n\n## v0.16.0 — May 9, 2026\n\n### Agent Auth Protocol\n\nQuickback ships a server implementation of the [Agent Auth Protocol](https://agentauthprotocol.com) via `@better-auth/agent-auth`. Enable with `auth.plugins.agentAuth: true` and the compiler emits the full 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 added to the auth schema automatically.\n\n**OpenAPI capability projection runs by default.** Every operation with an `operationId` becomes an agent capability. Default `approvalStrength` map: `GET → \"session\"`, `POST/PUT/PATCH/DELETE → \"webauthn\"`. The proxy `onExecute` makes a self-fetch with a Better Auth JWT minted for the agent session, so the inner request hits the existing JWT fast-path and runs the full firewall + access + masking pipeline. Opt out of OpenAPI projection with `agentAuth: { fromOpenAPI: false }` and wire `capabilities` + `onExecute` by hand.\n\n### Bearer-only on `/mcp` and the agent-auth surface\n\n`/mcp` forwards only `Authorization: Bearer …` into the inner request. Cookie and `x-api-key` forwarding are removed. Three Bearer flavors land on the same header — Better Auth session token (via the `bearer` plugin), OAuth access token (via OAuth Provider), and agent JWT (via `@better-auth/agent-auth`).\n\n### Auth DSL gains first-class plugin entries\n\n`bearer`, `oauthProvider`, and `agentAuth` are now typed entries in both the array-form union and the `BetterAuthPlugins` interface, with their own options shapes (`OAuthProviderOptions`, `AgentAuthOptions`). Existing `as any` casts can come out.\n\nAuto-enable rule: turning on `agentAuth` force-adds `bearer` + `oauthProvider`. No useful agent-auth deployment ships without those two.\n\n### `queue-consumer.ts` gating\n\nThe queue consumer is emitted when any of the following are true: embeddings are configured, queue handlers exist under `services/queues/*`, or `additionalQueues` is declared. Previously the third case left projects with a wrangler binding pointing at a missing handler.\n\n---\n\n## v0.15.0 — May 7, 2026\n\n### Sysadmin tier for the CMS\n\nA new opt-in `cms: { sysadmin: true }` flag turns the CMS into a cross-tenant DB-admin tool gated by `user.role === 'sysadmin'`. Distinct from the Better Auth `'admin'` plugin role, so user-management powers and DB-admin powers stay decoupled. Off by default.\n\nWhen enabled, the compiler emits a `SYSADMIN` pseudo-role (a fifth marker alongside `PUBLIC` / `AUTHENTICATED` / `USER` / `ADMIN`), a firewall escape hatch that drops tenant scopes for sysadmins while preserving soft-delete, a true cross-tenant `/admin/v1/sysadmin/organizations` endpoint, and a relaxed cross-tenant guard for list routes.\n\nThe CMS SPA gains a two-mode design: org admins keep the existing membership-based switcher, sysadmins get an \"All organizations\" selector that pins tenants via `?organizationId=` on every API call.\n\n### Durable Object `[[migrations]]` order is preserved\n\nCloudflare's migration list is append-only. The compiler now reads your existing `wrangler.toml` (when present) and emits auto-generated DO `[[migrations]]` blocks in two phases: deployed entries first (preserving order), net-new entries appended last. Reordering DOs in the config array no longer reshuffles deployed migrations.\n\n### `quickback/public/` — static-asset passthrough\n\nAnything dropped under `quickback/public/` is copied verbatim into `src/apps/` on every compile and served by the wrangler `[assets]` binding. Use for favicons, `robots.txt`, OG images, `.well-known/` files, marketing PDFs — anything that needs to ride past the compiler as bytes.\n\n- Optional. Missing folder is a no-op.\n- Stale-cleaned. Files removed from `quickback/public/` disappear on the next compile.\n- Hidden entries (`.DS_Store`, dotfiles) are skipped.\n- Collisions with compiler-emitted manifest paths fail the compile loudly.\n\n### Minor\n\n- Standalone-action wrapper skips the org gate when the access tree references any pseudo-role.\n- Queue handler emit no longer drops the `queue` export when there are no embeddings.\n\n---\n\n## v0.14.7 — May 7, 2026\n\n### Codegen fixes for projects with non-`id` primary keys and DO-only features\n\nFour surgical fixes to the generated output:\n\n- Duplicate table imports in relationship-role routes are deduplicated.\n- `db` references in single-record and bulk action handlers now resolve correctly during pre-fetch.\n- PartyServer auth gates pass the in-scope `db` handle into firewall calls.\n- Durable-object-only features keep their `lib/` files in the output.\n\n### `emailOtp` + AWS SES is OTP-only\n\n`auth.emailOtp` with the AWS SES email provider no longer auto-wires the magic-link companion. Mail-client URL prefetching can burn the one-time code before the human sees it; the Account SPA's `/email-otp` route is the single canonical entry point. Projects that explicitly want the magic-link arm can wire `sendVerificationOTP` directly.\n\n---\n\n## v0.14.6 — May 7, 2026\n\n### MCP transport correctness\n\nFour fixes to the MCP-over-HTTP path:\n\n- `tools/call` URLs are no longer double-prefixed for action tools.\n- Auth middleware accepts API keys via `Authorization: Bearer` in addition to `x-api-key` and query parameters — the channel MCP clients use exclusively.\n- `auth.roleHierarchy` is expanded for runtime role checks across api-key, JWT, and session auth paths. A higher role inherits the privileges of every lower role.\n- Team-scoped firewall predicates degrade gracefully when no team is active (org scoping continues to apply; team scoping is optional).\n\n---\n\n## v0.14.5 — May 7, 2026\n\n### MCP environment threading\n\nThe generated MCP server's `tools/call` dispatch threads `env` and `executionCtx` into the inner request, so action tools that touch Cloudflare bindings (D1, KV, R2, Queues) no longer crash with `undefined` env access.\n\n---\n\n## v0.14.4 — May 7, 2026\n\n### `via:` firewall predicates pull required imports\n\nThe relationship-role generator emits `inArray` and `sql` imports when the firewall has any `via:` predicate, and `buildFirewallConditions` accepts `(ctx, db)` so the relationship subquery has a Drizzle client to evaluate against. Every CRUD and action call site passes `db` through automatically.\n\n---\n\n## v0.14.3 — May 7, 2026\n\n### Relationship-role table re-exports\n\nGenerated `<table>.resource.ts` files now re-export their Drizzle table binding. Cross-feature relationship subqueries that import the binding from the resource file (rather than the schema) resolve correctly.\n\n---\n\n## v0.14.2 — May 7, 2026\n\n### Historical DO `[[migrations]]` are preserved\n\nA new `bindings.durableObjectMigrations` config slot carries forward `deleted_classes`, `renamed_classes`, and `transferred_classes` lifecycle entries across recompiles. Cloudflare's migration list is append-only; entries declared here are emitted first in `wrangler.toml`, then auto-generated current-class entries follow:\n\n```ts\nbindings: {\n durableObjects: [{ name: 'NOTEPAD', className: 'Notepad', from: 'lib/Notepad' }],\n durableObjectMigrations: [\n { tag: 'qb-do-deleted-legacy-notes-2026-05-05', deletedClasses: ['LegacyNotes'] },\n ],\n}\n```\n\nAll four lifecycle shapes are supported. User-declared entries can override auto-emit by reusing the same tag.\n\n---\n\n## v0.14.1 — May 7, 2026\n\n### Bulk action variants in `openapi.json`\n\nRecord-based actions with `bulkVariant: true` are now emitted as sibling operations in the OpenAPI spec, with the documented `{ ids, input, failFast? }` request shape, 200/207/400 responses, and a separate `<Resource><Action>Bulk` `operationId` so typed-client codegen distinguishes single from bulk.\n\n### Cross-tenant \"my events\" patterns\n\nThe access docs now include a worked example for the cross-tenant aggregation pattern (e.g. `GET /my-events` returning resources across all tenants a caller is invited to). See [Access → Cross-tenant dashboards](/compiler/definitions/access#cross-tenant-my-events-dashboards-are-not-this).\n\n---\n\n## v0.14.0 — May 7, 2026\n\n### Relationship-based authorization\n\nRoles can now be bound to a domain-table membership (\"user is a confirmed guest of this event\") rather than an org membership or a pseudo-role. Declare the relationship once and reference it from `firewall:` or `access.roles:`:\n\n```ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n },\n },\n roles: {\n guest: { via: 'guestOf' },\n eventStaff: { or: [{ via: 'guestOf' }, { roles: ['admin', 'owner'] }] },\n },\n}\n\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' },\n],\nread: { access: { roles: ['admin', 'member', 'guest'] } },\ncreate: { access: { roles: ['admin', 'guest'] } },\nupdate: { access: { roles: ['admin'] } },\n```\n\nThe compiler emits an inline Drizzle subquery against the relationship table and AND-composes it as the outermost firewall clause. The relationship table's own firewall (tenant scope, soft-delete) is honored inside the subquery; cross-tenant grants are impossible because the resource's tenant filter sits outermost.\n\nSupported surfaces: row-level scoping via `firewall: [{ field, via }]`, role gates on writes and reads, view access. Masking and action access reject relationship-roles at compile time with pointers to the working pattern (gate the row at the firewall layer, gate the role at the access layer).\n\nCross-tenant aggregation dashboards aren't solved by relationship-roles — the tenant firewall remains the outermost AND. For that pattern, use a user-scoped firewall or function-form access on a dedicated route.\n\nSee [Firewall → Relationship-based scoping](/compiler/definitions/firewall#relationship-based-scoping-via) and [Access → Relationship-based authorization](/compiler/definitions/access#relationship-based-authorization).\n\n### Bulk variants on record-based actions\n\n`defineAction({ bulkVariant: true })` emits `POST /:resource/batch/{action}` alongside the per-record route. The bulk handler loops the same access + transition + execute pipeline over a `{ ids, input, failFast? }` body:\n\n```ts\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n bulkVariant: true,\n transition: { field: \"status\", via: \"nextStatus\", fromTo: { /* ... */ } },\n async execute({ db, record, input, whereTransition }) {\n // exact same body — runs once per id\n },\n});\n```\n\nPer-record outcomes return as 207 Multi-Status. `failFast: true` aborts on the first failure and wraps the loop in `db.transaction()` on tx-supporting providers; D1 fails fast without rollback. Max 100 IDs per request. Rejected on standalone actions and `unsafe` actions.\n\n### Aggregations on read views\n\nRead views can declare pre-computed metrics that surface alongside the row payload:\n\n```ts\nread: {\n views: {\n pipeline: {\n fields: [\"id\", \"jobId\", \"candidateId\", \"status\", \"appliedAt\"],\n aggregations: {\n totalApplications: { fn: \"count\" },\n byStatus: { fn: \"groupBy\", field: \"status\" },\n },\n },\n },\n}\n```\n\nAggregations run over the same firewalled, filtered set as the row query; pagination is intentionally ignored. Supported functions: `sum`, `avg`, `min`, `max`, `count`, `count_distinct`, `groupBy`. See [Views → Aggregations](/compiler/definitions/views#aggregations).\n\n---\n\n## v0.13.5 — May 6, 2026\n\n### Object-form `auth.plugins` config is honored\n\nThe documented `plugins: { oauthProvider: {...} }`, `plugins: { organization: { teams: { enabled: true } } }` shapes now flow through the compiler unchanged. Per-plugin options reach the generated `auth.ts` as written.\n\n### `roles: [\"PUBLIC\"]` allowed on writes and actions\n\n`PUBLIC` is the explicit, uppercase opt-in for unauthenticated access on every access node — reads, writes, views, and actions. The runtime trusts the marker; row-level safety comes from firewall, masking, and the action's own validation. `PUBLIC` actions continue to receive mandatory audit logging.\n\nCommon pattern: pair `roles: [\"PUBLIC\"]` with `firewall: { exception: true }` on the resource so the row predicate doesn't reject every unauthenticated caller.\n\n---\n\n## v0.12.0 — May 5, 2026\n\n### Per-room authorization for PartyServer\n\n`bindings.durableObjects[].access` declares a path-scoped gate that runs the declared resource's firewall and `read.access` pipeline before the WebSocket upgrade:\n\n```ts\ndurableObjects: [\n // Single-resource: roomId IS the chat row id.\n { name: 'Chat', className: 'Chat', from: 'lib/Chat',\n access: { resource: 'chats' } },\n\n // Multi-resource: regex dispatches kind → resource.\n { name: 'Notepad', className: 'Notepad', from: 'lib/Notepad',\n access: {\n roomId: { pattern: '^(day-note|interaction|record):([A-Za-z0-9_-]+)$', kindGroup: 1, idGroup: 2 },\n resources: {\n 'day-note': { resource: 'day-notes' },\n 'interaction': { resource: 'interactions' },\n 'record': { resource: 'records' },\n },\n } },\n\n // Anonymous lobbies / public pads: explicit opt-out.\n { name: 'PublicLobby', className: 'PublicLobby', from: 'lib/PublicLobby',\n access: 'public' },\n]\n```\n\nThe gate 401s unauthenticated callers, 403s when the firewall hides the row, 404s when the row is missing. Resource references are validated against feature names at compile time. See [PartyServer Rooms → Per-room authorization](/stack/realtime/partyserver-rooms#per-room-authorization-via-access-v012).\n\n---\n\n## v0.11.1 — May 5, 2026\n\n### PartyServer auto-mount is secure by default\n\nThe `/realtime/*` auto-mount now wraps `partyserverMiddleware` in an auth check. Unauthenticated upgrades return 401; the four auth mechanisms (session cookie, JWT bearer, `x-api-key` header, query parameter) all unlock connections. Per-room access remains the `Server` class's responsibility in `onConnect`.\n\n---\n\n## v0.11.0 — May 5, 2026\n\n### OAuth Provider (MCP-ready)\n\nQuickback can act as a standards-compliant OAuth 2.1 + OIDC authorization server via [`@better-auth/oauth-provider`](https://better-auth.com/docs/plugins/oauth-provider). Enable with `plugins: [\"oauthProvider\"]`. The compiler auto-includes Better Auth's `jwt` plugin and the Account SPA gains a `/consent` page for the standard authorization-code flow.\n\nThis replaces Better Auth's deprecated `mcp` plugin and gives every MCP client (Cursor, Claude Desktop, claude.ai connectors, custom tooling) RFC 7591 dynamic client registration plus the discovery documents they need to bootstrap. See [Auth Plugins → OAuth Provider](/stack/auth/plugins#oauth-provider-mcp-ready).\n\n### API keys via query parameter\n\nThe auth middleware now accepts API keys as `?api_key=…` or `?key=…` query parameters. The `x-api-key` header takes precedence when both are sent. Prefer the header whenever the client supports it — query parameters land in access logs and `Referer` headers.\n\n### PartyServer rooms + realtime URL split\n\nThe realtime URL space is reorganized so names match what each primitive does:\n\n- **`/realtime/v1/*` → `/broadcast/v1/*`** — the org-wide Broadcaster moves to its semantically accurate prefix.\n- **`/realtime/<binding>/<room-id>`** — new mount for [PartyServer](/stack/realtime/partyserver-rooms) rooms. Per-room Durable Objects with presence and lifecycle hooks. Auto-mounted whenever a project declares any in-worker DO.\n\n**Breaking** — recompile + redeploy required:\n\n- `REALTIME_URL` env var renamed to `BROADCAST_URL`.\n- SPA helpers `getRealtimeWsUrl()` / `getRealtimeTicketUrl()` renamed to `getBroadcastWsUrl()` / `getBroadcastTicketUrl()`.\n- `appConfig.routes.api.realtime` renamed to `appConfig.routes.api.broadcast`.\n\n`partyserver`, `partysocket`, and `hono-party` are pre-installed in the compiler image; collab projects compile without an extra `npm install` step.\n\n---\n\n## v0.10.20 — May 4, 2026\n\n### In-worker Durable Objects\n\n`bindings.durableObjects[].from` flips a DO binding into in-worker mode and emits the export, the `[[migrations]]` block, and the `CloudflareBindings` type all together:\n\n```ts\ndurableObjects: [{\n name: \"ITEM_STREAM\",\n className: \"ItemStream\",\n from: \"features/loops/lib/ItemStream\",\n}]\n```\n\nDO class files live under `quickback/lib/` or `quickback/features/<feature>/lib/` — both copy verbatim into the generated `src/` tree on every compile. `from` and `scriptName` are mutually exclusive; cross-worker DOs (`scriptName` set) skip the re-export and migration block.\n\n`migrationTag` (default `qb-do-${className}`) is stable across regenerations and must never be removed or renamed once deployed. `useSqlite` defaults to `true`. See [Bindings → Durable Objects](/compiler/config/bindings#durableobjects).\n\n---\n\n## v0.10.18 — May 2, 2026\n\n### `experimentalRemote` — share deployed D1 with `wrangler dev`\n\nPer-binding `experimental_remote = true` lets `wrangler dev` read/write deployed D1 for selected bindings:\n\n```ts\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n splitDatabases: true,\n experimentalRemote: { auth: true, features: false },\n }),\n}\n```\n\nUseful for \"share prod auth in dev, keep feature writes sandboxed.\" Off by default.\n\n### Google OAuth + signup ToS\n\nThe Account SPA wires Google OAuth end-to-end when configured under `auth.config.socialProviders.google.enabled`. The signup flow gains a Terms-of-Service checkbox gate (configurable via the Account SPA branding).\n\n### CLI compile auth gate\n\n`quickback compile` now requires authentication for cloud-compiler runs. Device-flow `?redirect=` parameters are standardized across the login + signup pages so a user clicking \"Create one\" no longer loses their return URL.\n\n---\n\n## v0.10.15–v0.10.17 — May 2, 2026\n\n### CSP auto-config\n\nWhen `security.csp` is set, the compiler widens directives additively based on the project's enabled features:\n\n| Trigger | Auto-added | Directive |\n|---|---|---|\n| `cms: true` OR `account: true` | `'unsafe-inline'`, `https://fonts.googleapis.com` | `styleSrc` |\n| `cms: true` OR `account: true` | `https://fonts.gstatic.com` | `fontSrc` |\n| `csp` set (always) | `@trustedOrigins` | `connectSrc` |\n| Bundled SPA enabled | SPA-baked API origin (`config.domain`, `quickback.{baseDomain}`, `cms.domain`, `account.domain`) | `connectSrc` |\n\nAnything you already wrote stays — auto-config never removes or overrides. Each applied addition is logged to stderr. Opt out with `security: { cspAutoConfig: false }`.\n\nMost projects can write the minimal:\n\n```ts\nsecurity: {\n csp: {\n defaultSrc: ['@self'],\n scriptSrc: ['@self'],\n objectSrc: ['@none'],\n upgradeInsecureRequests: true,\n },\n}\n```\n\n…and the compiler fills in font hosts, trusted origins, and SPA-baked URLs.\n\nWhen a target directive is missing, auto-config scaffolds it from `default-src` baseline rather than widening `default-src` itself — CSP3 fall-back semantics would otherwise leak the addition to every directive that falls back to `default-src`.\n\n---\n\n## v0.10.14 — May 1, 2026\n\n### `auth.jwt` config\n\nThe bearer-token JWT used by the auth fast-path is configurable. Tune `expiresIn` to bound the post-revocation replay window without affecting browser SPAs (which auto-refresh on every authed call):\n\n```ts\nauth: {\n jwt: {\n expiresIn: 30,\n issuer: 'my-api',\n audience: 'partner-svc',\n secretEnv: 'CUSTOM_JWT_SECRET',\n },\n}\n```\n\n### Admin MCP endpoints filtered\n\nBetter Auth admin endpoints (`/admin/list-users`, `/admin/ban-user`, etc.) now carry `x-access: { userRole: ['admin'] }` in the generated OpenAPI spec. The MCP `tools/list` access-filter drops them for non-admin callers.\n\n### Declarative `security` config\n\nEvery security response header (`Content-Security-Policy`, COOP, COEP, CORP, HSTS, `X-Frame-Options`, `Referrer-Policy`, `Permissions-Policy`) is configurable from `quickback.config.ts`. `@`-prefixed sentinels (`@self`, `@none`, `@unsafe-inline`, `@trustedOrigins`, etc.) replace awkward `\"'self'\"` quoting.\n\nThe compiler lints the resolved config for known footguns: `@unsafe-inline` in `script-src`, wildcard sources, missing `default-src`, HSTS preload-list misconfiguration.\n\n### HSTS skipped on localhost\n\nGenerated middleware skips `Strict-Transport-Security` when the request hostname is `localhost`, `127.0.0.1`, or `*.localhost`. Without this gate, `wrangler dev` would pin a developer's browser to HTTPS across every project on that machine.\n\n---\n\n## v0.10.13 — May 1, 2026\n\n### Clickjacking defence on every Worker\n\nEvery Worker emits `Content-Security-Policy: frame-ancestors 'self' <TRUSTED_ORIGINS…>` and `X-Frame-Options: SAMEORIGIN` on every response. The CSP allowlist is sourced from the same `TRUSTED_ORIGINS` constant that gates CORS.\n\n---\n\n## v0.10.11 — May 1, 2026\n\n### MCP `tools/list` is access-filtered\n\nEach MCP tool now carries sanitised access metadata. `tools/list` filters against the caller's `ctx`: unauthenticated callers see only `PUBLIC` tools, authenticated callers see only role-gated tools they pass.\n\n- Wildcard CORS removed from the MCP endpoint.\n- Unauthenticated `GET /mcp` no longer enumerates tool names.\n- Internal flavor text is removed; `annotations.destructiveHint` and `_unsafe` remain — those are the spec-correct signals for clients.\n\n`tools/call` continues to re-enter the Hono app and run every middleware (auth, firewall, access, guards, masking), so hiding a tool from list never weakens the underlying gate.\n\n---\n\n## v0.10.10 — April 29, 2026\n\n### Reserved keys in `access.record` are rejected\n\n`access.record` is a flat field map evaluated as implicit AND between entries — keys must be column names. The compiler now rejects reserved keys (`and`, `or`, `roles`, `userRole`) inside `record` with migration guidance pointing at the working pattern (top-level siblings with their own `record:` blocks).\n\n---\n\n## v0.10.8 — April 29, 2026\n\n### Audit logging on Postgres targets\n\n`audit_events` previously only existed on `cloudflare-d1`. The audit table now lives in a dedicated `audit` schema (`drizzle.pgSchema('audit')`) on Postgres targets. The `hasSecurityAudit` gate accepts D1 or any PG dialect; `auditDatabaseId` remains a D1-only requirement.\n\n### `auditDatabaseId` is a compile-time requirement\n\nProjects with unsafe or `PUBLIC` actions that previously produced a placeholder `database_id = \"local-audit\"` in production now fail at compile time with the exact `wrangler d1 create <project>-audit` command and the config key where the returned ID goes.\n\n### Action input → OpenAPI / MCP\n\n`defineAction({ input: z.object({...}) })` schemas flow into the OpenAPI `requestBody` and the MCP tool's `inputSchema.properties`. Simple `z.object` shapes are extracted at compile time; discriminated unions, refinements, recursive schemas, and bare-identifier references run through Zod's native `z.toJSONSchema()` for full-fidelity output.\n\n### OpenAPI fidelity\n\n- Response schemas emit `required[]` for every non-nullable column.\n- `text(_, { enum: [...] })` columns emit as closed `{ type: \"string\", enum: [...] }`.\n- `id` claims `format: \"uuid\"` only when the project's `generateId` actually produces UUIDs. cuid2 / prefixed / nanoid / serial generators emit plain `{ type: \"string\" }`.\n\n### Minor\n\n- Auto-mask predicate verifies the resolved owner column exists before emitting an `or: 'owner'` clause; falls back to roles-only with a warning otherwise.\n- Generated CRUD errors emit canonical `QuickbackErrorCode` enum values (`DB_NOT_NULL_VIOLATION`, `DB_UNIQUE_VIOLATION`, etc.) so generated SDKs can exhaustively switch on `code`. See [API errors](/compiler/targets/hono-api/using-the-api/errors#database).\n\n---\n\n## DSL: one file per action, multi-table per feature\n\n### One file per action\n\nAction authoring is one file per action under `<feature>/actions/<name>.ts`. The filename is the action name and the URL segment:\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: { applied: [\"screening\"], screening: [\"interview\"], interview: [\"offer\"] },\n },\n async execute({ db, record, input, auditFields, whereTransition }) { /* … */ },\n});\n```\n\n`defineAction` is imported from a generated per-feature helper at `<feature>/.quickback/define-action.ts` — `record`, `input`, and audit fields are typed without manual annotations.\n\n**Discovery rules:**\n- `actions/<name>.ts` binds to the feature's primary table.\n- `actions/<table>/<name>.ts` binds to the sibling table file.\n- Setting `path:` makes the action standalone (custom URL, no record fetch).\n- Tableless features require every action to be standalone.\n\n**Retired** (rejected at load time with migration guidance): `actions.ts` (bundled multi-action file), `_feature.ts`, `handlers/` directory + `handler:` string ref, `defineActions(table, {…})`, colocated `defineActions` inside table files, `standalone: true` flag, `*-actions.ts` / `*.actions.ts` filename patterns.\n\nSee [Actions docs](/compiler/definitions/actions).\n\n### Multi-table actions per feature\n\nOne feature directory can own actions on multiple tables. Three discovery modes:\n\n- **Colocated** (canonical) — `<table>.ts` containing both `defineTable` and `defineActions(<table>, …)`. One file per entity.\n- **`actions.ts`** — single primary-table actions file at feature root.\n- **`actions/<table>.ts`** — per-table action files for strict schema/behavior separation.\n\nPlus a universal `_feature.ts` slot for non-table-bound feature-level actions and shared Zod schemas.\n\nAction names are unique per `(bindTable, name)` pair. Sibling-bound `actions/episodes/publish.ts` and `actions/shows/publish.ts` mount at `/episodes/:id/publish` and `/shows/:id/publish` and compile cleanly.\n\n---\n\n## Firewall: named-scope shape\n\nThe named-scope firewall shape is a co-equal user-facing input alongside the predicate array:\n\n```typescript\nfirewall: { organization: { column: 'tenant_id' } } // named-scope (compact)\nfirewall: { owner: { column: 'account_user_id' } }\nfirewall: { exception: true }\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n] // predicate array (explicit)\n```\n\nPick the form that reads better — named-scope for the common one-line case, predicate array when you need custom `in`-lists or non-scope predicates.\n\n**Auto-detection synonyms.** When `firewall:` is omitted, the compiler scans the schema for an isolation column. The org-scope list accepts `organizationId`, `organisationId`, `orgId`, `organization`, `organisation`, `org` (American + British). User-scope accepts `userId`.\n\n**`ownerId` is a targeted error signal.** When a table carries `ownerId` but no isolation column and no explicit `firewall:`, the compiler raises a specific error — `ownerId` is business-logic ownership, not access control. Use `userId` for access control, declare an explicit `firewall:`, or add a separate isolation column.\n\n---\n\n## v0.10.0 — April 26, 2026\n\n### `q.scope()` — single-declaration tenant scoping\n\n`q.scope(kind)` replaces the three-place pattern (column declaration + firewall predicate + ownership-guard) with one column:\n\n```typescript\ncolumns: {\n organizationId: q.scope('organization'), // → ctx.activeOrgId\n ownerId: q.scope('owner'), // → ctx.userId\n teamId: q.scope('team'), // → ctx.activeTeamId\n}\n```\n\n`q.scope()` columns auto-derive the firewall predicate, register with the guards layer as `systemManaged` (client input rejected), and auto-populate from `ctx` on create / upsert. The systemManaged extension generalises beyond `q.scope()`: any firewall predicate whose `equals` references `ctx.*` registers its `field` automatically.\n\nSee [`q.scope()`](/compiler/definitions/schema#qscope--tenant-scope-columns).\n\n### `masking[col].query.roles` — unified filter / sort / search gate\n\nThe three legacy per-capability flags (`filterable`, `searchable`, `sortable`) are replaced by a single `query.roles` allowlist:\n\n```typescript\nmasking: {\n email: {\n type: 'email',\n show: { roles: ['admin'] },\n query: { roles: ['admin'] }, // defaults to show.roles when omitted\n },\n}\n```\n\nA view's own `query.{filterable,searchable,sortable}` allowlist is the opt-in for higher-privileged roles; the existing intersection validator gates it at compile time.\n\n**Breaking:** `masking[col].filterable / .searchable / .sortable` is rejected at compile time with a migration hint. Replace with `query.roles` (or delete the flags — `query` defaults to `show.roles`).\n\n---\n\n## v0.9.0 — April 25, 2026\n\n### Unified `read:` pipeline\n\nThe read side of every resource has its own block — `read:` — that owns the collection-level `GET /` endpoint, single-record `GET /:id`, and named view projections.\n\n**Breaking changes** (compile-time errors with migration hints):\n\n- `crud.list` → `read.access` (plus `read.pageSize` / `read.maxPageSize`)\n- `crud.get` → `read.access` (single-record GET inherits automatically)\n- Top-level `views: {...}` → `read.views: {...}`\n- `crud.list.fields` / `crud.get.fields` → declare a named view under `read.views` and call `/views/{name}`\n\n### Pre-record access ordering\n\nHandlers on `/:id` run a role-only access check before the firewall query. A caller without a matching role gets 403 before the database is touched. This closes the 404-vs-403 ID-probe channel — an unauthorized caller can no longer distinguish \"row exists in another tenant\" from \"row doesn't exist.\" See [Access evaluation order](/compiler/definitions/access#evaluation-order).\n\n### Transactional batch operations\n\nBatch endpoints expose `failFast` and a `meta.transactional` response field. On tx-supporting providers (postgres, supabase, neon, libsql, better-sqlite3, bun-sqlite), `failFast: true` wraps the per-record loop in `db.transaction(...)` so any failure rolls back the entire batch. On Cloudflare D1 (no `db.transaction`), `failFast: true` stops on the first error but prior writes stay committed.\n\nEmbedding queue messages and realtime broadcasts emit after the transaction commits — rolled-back batches produce no orphan jobs.\n\nSee [Batch Operations → Transactional semantics](/compiler/targets/hono-api/using-the-api/batch-operations#transactional-semantics).\n\n---\n\n## v0.8.7 — April 17, 2026\n\n### Hono CVE bump\n\nHono is bumped to `^4.12.14` across the monorepo, the compiler Docker image's pre-installed deps, and every generator path that emits Hono into compiled projects. Older ranges covered the vulnerable window. Recompile to pick up the fix in your generated project's `package.json`.\n\n### Cloudflare Email Sending in public beta\n\nQuickback defaults to the Workers `send_email` binding for Cloudflare deploys. Cloudflare Email Sending has graduated to public beta — production-ready with zero-config. AWS SES remains a fully supported opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes. See [Email Configuration](/compiler/config#email-configuration).\n\n### Dependency sweep\n\n`wrangler@^4.83.0`, `drizzle-orm@^0.45.2`, `drizzle-kit@^0.31.10`, `zod@^4.3.6`, `@cloudflare/workers-types@^4.20260417.1`.\n\n---\n\n## v0.8.5 — April 15, 2026\n\n### `userRole` access primitive\n\nA new `userRole?: string[]` field in the declarative `Access` config evaluates against `ctx.userRole` (the Better Auth admin-plugin `user.role` column). Distinct from `roles`, which matches `ctx.roles` (org membership).\n\n```typescript\n// Org owner OR platform admin\naccess: { or: [{ roles: ['owner'] }, { userRole: ['admin'] }] }\n\n// Platform admins see SSNs across every org\nmasking: { ssn: { type: 'ssn', show: { userRole: ['admin'] } } }\n```\n\n`userRole` works everywhere `Access` is accepted — CRUD, actions, views, masking, and inside `or` / `and` combinators. See [Access → userRole vs roles](/compiler/definitions/access#userrole-vs-roles).\n\n### CMS admin gate enforced server-side\n\n`cms: { access: \"admin\" }` previously only hid the CMS link in Account UI and rendered an \"Access Denied\" screen inside the SPA. Server-side enforcement now applies at every CMS-facing surface: the SPA shell, `/api/v1/schema`, and `custom_view` CRUD.\n\n### Better Auth 1.5 + `@cloudflare/workers-types` compatibility\n\nGenerated API code typechecks against the new versions. The org-member role-change broadcast hook is emitted via `organizationHooks.afterUpdateMemberRole` (the supported shape after the 1.5 deprecation of `databaseHooks.member.update.after`). `REALTIME_URL` and `ACCESS_TOKEN` are always emitted as optional bindings when the organization plugin is active.\n\n---\n\n## v0.8.4 — April 14, 2026\n\n### `generateId: \"short\"` strategy\n\nA compact ID option for tables where short, shareable codes matter more than collision resistance at scale:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", { generateId: \"short\" }),\n}\n```\n\nGenerates 6-character alphanumeric IDs (e.g. `a3F9xK`) using nanoid's `customAlphabet` with the full 62-char alphabet (`0-9A-Za-z`). Requires the `nanoid` package.\n\n**When to use:** room codes, invite links, share URLs, ephemeral records.\n\n**When not to use:** high-volume tables. 62^6 ≈ 56.8B combinations means ~238K rows before a 50% collision probability. For large tables stick with `\"uuid\"`, `\"cuid\"`, or `\"prefixed\"`. See [Providers → ID Generation Options](/compiler/config/providers#id-generation-options).\n\n---\n\n## v0.8.2 — April 11, 2026\n\n### Catch-all `VITE_QUICKBACK_URL`\n\nA single Quickback origin can be set in place of four separate URL env vars:\n\n```bash\nVITE_QUICKBACK_URL=https://secure.example.com\n```\n\n| Individual var (explicit) | Fallback when unset |\n|---|---|\n| `VITE_QUICKBACK_API_URL` | `${VITE_QUICKBACK_URL}` |\n| `VITE_QUICKBACK_ACCOUNT_URL` | `${VITE_QUICKBACK_URL}/account` |\n| `VITE_QUICKBACK_CMS_URL` | `${VITE_QUICKBACK_URL}/cms` |\n\n`VITE_QUICKBACK_APP_URL` stays independent — it points at the tenant's own frontend. Non-breaking; individual vars take precedence when set. Library users can set `__QUICKBACK_URL__` on `globalThis`. See [Environment Variables](/stack/account-ui/environment-variables).\n\n---\n\n## v0.8.1 — April 9, 2026\n\n### Role hierarchy with `+` suffix\n\nDefine a hierarchy and use `+` to mean \"this role and above\":\n\n```typescript\nauth: { roleHierarchy: ['member', 'admin', 'owner'] }\n\ncrud: {\n list: { access: { roles: [\"member+\"] } }, // member, admin, owner\n create: { access: { roles: [\"admin+\"] } }, // admin, owner\n delete: { access: { roles: [\"owner\"] } }, // owner only\n}\n```\n\nRoles are expanded at compile time. No `+` = exact match. See [Access → Role Hierarchy](/compiler/definitions/access#role-hierarchy).\n\n---\n\n## v0.8.0 — April 9, 2026\n\n### Breaking: VITE URL environment variables namespaced\n\nAll Quickback-generated URL environment variables are namespaced under `VITE_QUICKBACK_*` to avoid collisions with other Vite projects.\n\n| Old | New |\n|-----|-----|\n| `VITE_API_URL` | `VITE_QUICKBACK_API_URL` |\n| `VITE_ACCOUNT_URL` | `VITE_QUICKBACK_ACCOUNT_URL` |\n| `VITE_APP_URL` | `VITE_QUICKBACK_APP_URL` |\n| `VITE_CMS_URL` | `VITE_QUICKBACK_CMS_URL` |\n\nNon-URL variables are unchanged (`VITE_ENABLE_*`, branding vars, `VITE_STRIPE_PUBLISHABLE_KEY`).\n\n**Action required:**\n- Compiled projects: re-run `quickback compile`.\n- Standalone deploys: update `.env`, `.env.production`, and `wrangler.toml` files manually.\n- Library users: `__QUICKBACK_API_URL__` / `__QUICKBACK_APP_URL__` globals are unchanged.\n\n### CMS access control\n\n`cms.access: \"admin\"` enforces access at the CMS level, not just link visibility. Non-admin users (`user.role !== \"admin\"`) see an \"Access Denied\" screen with a sign-out button.\n\n---\n\n## v0.5.11 — February 24, 2026\n\n### Mandatory unsafe action audit trail\n\nStructured `unsafe` config (`unsafe: { reason, adminOnly, crossTenant, targetScope }`). Cross-tenant unsafe actions require Better Auth authentication plus platform admin role (`ctx.userRole === \"admin\"`). Mandatory audit logging on success, denial, and error paths. Cloudflare output includes `AUDIT_DB` wiring, `drizzle.audit.config.ts`, and `db:migrate:audit:*` scripts when unsafe actions are present.\n\nCompile-time raw SQL guard for actions and handlers (`allowRawSql: true` required per action).\n\n### Security contract report artifacts\n\nGenerated security contract artifacts: `reports/security-contracts.report.json`, `reports/security-contracts.report.sig.json`. Config-driven signing controls (`compiler.securityContracts.report.signature.*`). Missing required signing keys fail loudly with explicit remediation.\n\n### Headless Drizzle rename hints\n\n`compiler.migrations.renames` configuration for CI/CD environments where Drizzle's interactive rename prompts block compilation. See [Configuration](/compiler/config).\n\n### Minor\n\n- Email OTP magic links work correctly.\n- Auth is required for all API routes when running locally.\n- Single-file multi-table exports alongside `defineTable()` produce a clear error.\n\n---\n\n## v0.5.8 — February 14, 2026\n\n### Quickback CMS\n\nA schema-driven admin panel that connects to your generated API. The compiler now outputs a JSON schema registry consumed by the CMS at runtime. Firewall error modes (`reveal` for 403 with details, `hide` for opaque 404) are configurable per resource for security-sensitive deployments.\n\n---\n\n## v0.5.7 — February 12, 2026\n\n### Scoped database for actions\n\nActions receive a security-scoped database instead of a raw Drizzle instance. The compiler generates a proxy wrapper that automatically enforces org isolation, owner filtering, and soft-delete visibility — the same protections that CRUD routes have always had.\n\nDuck-typed column detection at runtime:\n\n| Column Detected | SELECT / UPDATE / DELETE | INSERT |\n|---|---|---|\n| `organizationId` | Adds `WHERE organizationId = ?` | Auto-injects `organizationId` from context |\n| `ownerId` | Adds `WHERE ownerId = ?` | Auto-injects `ownerId` from context |\n| `deletedAt` | Adds `WHERE deletedAt IS NULL` | — |\n\nEvery action is secure by default — no manual `WHERE` clauses needed.\n\nActions that intentionally need to bypass security (admin reports, cross-org queries, migrations) can declare `unsafe: true` to receive a raw, unscoped database handle via `rawDb`:\n\n```typescript\ndefineActions(analytics, {\n globalReport: {\n unsafe: true,\n execute: async ({ db, rawDb, ctx, input }) => {\n // db → still scoped (safety net)\n // rawDb → bypasses all security filters\n const allOrgs = await rawDb.select().from(organizations);\n },\n },\n});\n```\n\nWithout `unsafe: true`, `rawDb` is `undefined`. See [Actions](/compiler/definitions/actions).\n\n### Cascading soft delete\n\nSoft-deleting a parent record automatically cascades to child and junction tables within the same feature. The compiler detects foreign key references at build time and generates cascade `UPDATE` statements.\n\nRules:\n- Applies to soft delete only. Hard delete relies on database-level `ON DELETE CASCADE`.\n- Cascades within the same feature only — cross-feature references are not affected.\n- Child tables must have `deletedAt` / `deletedBy` columns (auto-added by the compiler).\n\nSee [Actions API → Cascading Soft Delete](/compiler/targets/hono-api/using-the-api/actions-api#cascading-soft-delete).\n\n### Advanced query parameters\n\nNew capabilities for all list endpoints:\n\n- **Field selection** — `?fields=id,name,status`\n- **Multi-sort** — `?sort=status:asc,createdAt:desc`\n- **Total count** — `?count=true` returns total matching records in `X-Total-Count`\n- **Full-text search** — `?search=keyword` searches across all text columns\n\nSee [Query Parameters](/compiler/targets/hono-api/using-the-api/query-params).\n\n---\n\n## v0.5.5 — February 5, 2026\n\n### OpenAPI spec generation\n\nGenerated APIs include a full OpenAPI specification at `/openapi.json`. Better Auth endpoints are included in the spec.\n\n### Better Auth plugins\n\nPublished `@quickback-dev/better-auth-upgrade-anonymous` (post-passkey email collection flow), `@quickback-dev/better-auth-combo-auth` (combined email + password + OTP), and `@quickback-dev/better-auth-aws-ses` (AWS SES email provider).\n\n### Security headers\n\nGlobal error handler prevents leaking internal error details. Security headers middleware (CSP, HSTS, X-Frame-Options, X-Content-Type-Options). `BETTER_AUTH_SECRET` properly passed to generated config.\n\n---\n\n## v0.5.4 — January 30, 2026\n\n### Account UI\n\nPre-built authentication UI deployed as Cloudflare Workers. Sessions, organizations, passkeys, passwordless, admin panel, API keys. Dual-mode: standalone (degit template) or embedded with Quickback projects.\n\n### Webhook system\n\nInbound webhook endpoints with signature verification. Outbound webhooks via Cloudflare Queues with automatic retries. Configurable per-feature webhook events.\n\n### Realtime & vector search\n\nDurable Objects + WebSocket realtime subscriptions. Vector embeddings via Cloudflare Vectorize. KV and R2 storage integrations.\n\n---\n\n## v0.5.0 — January 2026\n\n### Initial release\n\n- **Quickback Compiler** — TypeScript-first backend compiler.\n- **Four security pillars** — Firewall, Access, Guards, Masking.\n- **`defineTable()`** — schema + security configuration in a single file.\n- **Templates** — Cloudflare Workers, B2B SaaS.\n- **Cloud compiler** — remote compilation via `compiler.quickback.dev`.\n- **CLI** — `quickback create`, `quickback compile`.\n- **Better Auth integration** — organizations, roles, sessions.\n- **Drizzle ORM** — schema-first with automatic migrations.\n- **Cloudflare D1** — split database support (auth + features)."
|
|
6
|
+
"content": "## v0.34.1 — May 24, 2026\n\nPatch fixing a silent-skip bug in drizzle migration emission, plus a new\nCLI subcommand for inspecting and repairing migration-state drift.\n\n### Compiler now fails loud on drizzle migration state drift\n\nWhen `quickback/drizzle/<dialect>/meta/_journal.json` fell out of sync\nwith the on-disk `.sql` files — typically because someone hand-rolled a\nmigration without a journal bump, or because a prior compile collided\nwith an existing tag — drizzle-kit's diff base became stale and it\nsilently skipped emission. The compile reported success, no new `.sql`\nwas written for newly defined tables, and the next `wrangler deploy`\nshipped a Worker that 500'd on every request touching those tables.\n\nThe compiler now runs a precheck before any drizzle-kit invocation and\nrefuses to compile when it detects any of:\n\n- `.sql` files on disk with no matching entry in `_journal.json`\n- journal entries that reference missing `.sql` files\n- non-sequential `idx` values in `_journal.json`\n- two `.sql` files sharing the same `idx`\n- (for `auth/` and `features/` only) journal entries with no matching\n `<idx>_snapshot.json` — drizzle-kit needs the snapshot as a diff base\n\nSnapshot/journal drift that the previous `console.warn` only logged\nserver-side is now propagated to the CLI and printed under\n\"Compilation warnings\".\n\n### New `quickback migrations doctor` CLI command\n\nTwo modes:\n\n```bash\nquickback migrations doctor # diagnose\nquickback migrations doctor --rebuild-journal # repair\n```\n\nDiagnose walks `quickback/drizzle/{auth,features,files,webhooks,audit}/`,\nprints a per-dir table (`.sql files`, `journal entries`, `snapshots`),\nand flags every drift kind the compiler precheck enforces. Repair\nrewrites `_journal.json` from on-disk `.sql` filenames in sorted order —\nthis is the recovery recipe users were applying by hand. Snapshot drift\non drizzle-kit dirs (`auth/`, `features/`) can only be repaired by\nrunning `drizzle-kit introspect` against the live DB; the doctor prints\nthe exact command.\n\n### Upgrade path for projects in the broken state\n\nProjects with existing drift will get a clear error message and an\nexplicit fix command on the next compile against v0.34.1:\n\n```\n✖ Drizzle migration state is inconsistent — refusing to compile.\n Causes:\n - quickback/drizzle/features: 7 .sql file(s) have no matching journal entry: ...\n Fixes:\n - Run `quickback migrations doctor` to diagnose, then\n `quickback migrations doctor --rebuild-journal` to repair.\n```\n\nNo action needed for projects whose journals are already in sync.\n\n## v0.34.0 — May 23, 2026\n\nCustomizable email-OTP templates and a dedicated admin-create-user hook\n— closes a longstanding gap where projects on `email.provider: 'aws-ses'`\nhad to live with the generic \"Your password reset code is ...\" copy for\nadmin-bootstrapped accounts.\n\n### Per-type email-OTP template overrides\n\nDrop a `.ts` file at `quickback/email-templates/<name>.ts` that\ndefault-exports `(input) => ({ subject, html, text })`, then reference\nit from the new `plugins.emailOtp.templates` map. Missing keys fall\nthrough to the package defaults from `@quickback-dev/better-auth-aws-ses`\n— this is purely additive; existing `emailOtp: true` projects emit the\nsame code they did before.\n\n```ts title=\"quickback/quickback.config.ts\"\ndefineAuth(\"better-auth\", {\n plugins: {\n emailOtp: {\n templates: {\n 'forget-password': './email-templates/forget-password',\n 'welcome': './email-templates/welcome',\n },\n },\n },\n});\n```\n\n```ts title=\"quickback/email-templates/welcome.ts\"\nexport default function welcome({ otp, name, appName, appUrl }) {\n const greeting = name ? `Hi ${name},` : 'Hi,';\n return {\n subject: `Welcome to ${appName} — set your password`,\n html: `<h1>Welcome to ${appName}</h1><p>${greeting} use this code: <b>${otp}</b></p>`,\n text: `${greeting}\\n\\nYour ${appName} code: ${otp}`,\n };\n}\n```\n\nRecognized keys: `'sign-in' | 'email-verification' | 'forget-password' |\n'welcome'`. The first three map 1:1 to Better Auth's emailOTP `type`\nenum.\n\n### Synthetic `welcome` routing — credential-row lookup\n\n`'welcome'` has no native Better Auth OTP type. When configured, the\ngenerated `sendVerificationOTP` callback queries the `account` table\nfor a `credential`-provider row for the recipient *before* rendering;\nif the user has none (typical of an admin-plugin-created account\nwithout a password), the send is rerouted through the welcome\ntemplate. Without a welcome template, those sends fall through to\n`forget-password` — same behavior as before. DB-error path fails open\nto the normal forget-password flow so a transient failure can't\ndeadlock the password-reset surface.\n\nProvider scope: overrides are only honored on `email.provider:\n'aws-ses'`. The Cloudflare Email path uses the helper's own template\npipeline and ignores the new config.\n\n### New recognized hook: `after-admin-user-create.ts`\n\nA virtual event that wires into the same Better Auth\n`databaseHooks.user.create.after` slot as the generic\n`after-user-create.ts`, but the generator gates the call on\n`_baCtx?.context?.path` matching `/admin/create-user` so it only fires\nwhen the row came from the admin plugin's create-user endpoint. Use it\nfor first-time-user provisioning (welcome email, default org\nassignment, audit-log writes) without inspecting the BA context by\nhand. The generic `after-user-create.ts` still runs for every signup,\nincluding admin-created ones; the two coexist in a single merged\n`after:` handler.\n\n```\nquickback/hooks/\n after-user-create.ts # every signup\n after-admin-user-create.ts # admin-plugin /admin/create-user only\n```\n\n### File transport mirrors existing slots\n\nThe new `quickback/email-templates/` directory follows the same\npattern as `quickback/plugins/`, `quickback/hooks/`, and\n`quickback/lib/`: the CLI walks the folder and uploads each `.ts` file\nin a new `projectEmailTemplates` field on the compile request; the\nbetter-auth provider stages referenced files into\n`src/email-templates/<name>.ts` and emits default imports in\n`src/lib/auth.ts`. Files not referenced by any template entry are\nignored — the CLI uploads the whole directory; the compiler picks only\nwhat's needed. A relative path pointing at a file the CLI never\nshipped fails compile fast with a \"place the file at … and rerun\"\nhint.\n\nSee [AWS SES Plugin → Per-Type Template Overrides](/stack/auth/plugins/aws-ses#per-type-template-overrides)\nand [Account UI → Hooks](/stack/account-ui/hooks#recognized-events).\n\n## v0.33.6 — May 22, 2026\n\nTwo compiler-side fixes for the queue-consumer / embedding surface and one\nschema-emission bug that blocked `generateId: 'cuid'` projects.\n\n### Schema-emitted `createId()` now ships with a polyfill (no missing import)\n\nWhen `providers.database.config.generateId` is set to `'cuid'`, the audit-\nfield injector emits an id column like\n`id: text('id').primaryKey().$defaultFn(() => createId())`. Previously the\nschema source referenced `createId` but no import landed, so `tsc` on the\ngenerated project failed with `Cannot find name 'createId'`. Recurring\nbug — every recompile re-emitted the broken file (the \"do not edit\"\nbanner doesn't protect from regeneration).\n\nFix: the injector now prepends a top-of-file polyfill backed by\n`crypto.randomUUID()` — a Workers / Node 19+ / Bun global — instead of\ntrying to import `@paralleldrive/cuid2`. The package isn't bundled by\nQuickback (per the [hooks doc](/stack/account-ui/hooks)'s \"stick to\nbuilt-ins\" guidance) and the schema-gen sandbox can't resolve project\nnode_modules anyway, so the polyfill is the only path that works\nout-of-the-box.\n\n```ts title=\"Generated schema header (cuid strategy)\"\n\n// Polyfill — Quickback compiler does not ship @paralleldrive/cuid2 in\n// generated projects, and the schema-gen sandbox can't see node_modules.\n// crypto.randomUUID() is a Workers / Node 19+ / Bun global.\nconst createId = () => crypto.randomUUID();\n\nexport const widgets = sqliteTable('widgets', {\n id: text('id').primaryKey().$defaultFn(() => createId()),\n // ...\n});\n```\n\nIf you want real cuid2 strings (collision-resistant, shorter than UUIDs)\nyou can still install `@paralleldrive/cuid2` and add the import yourself —\nthe injector honours an existing import and skips the polyfill.\n\n### queue-consumer.ts header reflects what the file actually does\n\nBefore v0.33.6 the generated `src/queue-consumer.ts` always carried the\npreamble:\n\n```\n* Queue Consumer for Embedding Jobs & Custom Queue Handlers\n*\n* Processes embedding jobs asynchronously using Workers AI and Vectorize.\n* Also supports custom queue handlers defined in services/queues/.\n```\n\n— even on projects with zero embedding features. Users on\ncustom-queue-only deployments would search for `EMBEDDINGS_QUEUE` /\nVectorize bindings that wrangler.toml correctly didn't emit, wasting\ndiagnostic time.\n\nThe preamble now reflects the actual surface:\n\n| `hasEmbeddings` | `hasCustomHandlers` | Header |\n|---|---|---|\n| ✓ | ✓ | \"Queue Consumer for Embedding Jobs & Custom Queue Handlers\" |\n| ✓ | — | \"Queue Consumer for Embedding Jobs\" |\n| — | ✓ | \"Queue Consumer for Custom Queue Handlers\" + explicit \"No embedding bindings (EMBEDDINGS_QUEUE / Vectorize / AI) are referenced\" |\n| — | — | \"Queue Consumer Stub\" (additionalQueues with no handler yet) |\n\n### Symmetric embedding detection prevents silent drift\n\nThe wrangler.toml emit path (`EMBEDDINGS_QUEUE` producer/consumer\ndeclaration) and the queue-consumer.ts emit path (embedding handler code)\npreviously used two different functions to detect \"this project has\nembeddings\": `hasEmbeddingsConfig` checked both `feature.resource.\nembeddings` and `feature.tables[].resource.embeddings`;\n`extractEmbeddingFeatures` only iterated the tables array. A feature\nshape with feature-level embeddings sugar but no populated tables would\nland in the wrangler binding while NOT landing in the consumer file\n— silent drift.\n\n`hasEmbeddingsConfig` is now defined as\n`extractEmbeddingFeatures(...).length > 0`. The two stay in lock-step\nby construction. `extractEmbeddingFeatures` now reads from both shapes\n(tables-level when present, feature-level otherwise).\n\n## v0.33.5 — May 22, 2026\n\nTwo structural fixes that resolve recurring classes of bug for projects with\ninteger primary keys and for projects whose audit columns drift between\nschema and database.\n\n### URL `:id` params coerce to Number when the PK column is integer\n\nPer-id CRUD handlers (`GET /:id`, `PATCH /:id`, `DELETE /:id`, `PUT /:id`)\nextracted the URL param as a string and passed it straight into\n`eq(table.id, id)`. For resources with `integer().primaryKey()` columns —\ntriggered either by `generateId: 'serial'` on the database config or by\nimported legacy schemas — every per-id route raised a downstream tsc\ntype error (integer ≠ string). One production project reported 249 such\nerrors across 30+ generated `*.routes.ts` files.\n\nGenerated handlers for integer-PK resources now emit:\n\n```ts\nconst __idRaw = c.req.param('id');\nconst id = Number(__idRaw);\nif (!Number.isInteger(id)) {\n return c.json(ValidationErrors.invalidInput([{\n path: ['id'],\n message: `Expected integer, got \"${__idRaw}\"`,\n code: 'invalid_type',\n }]), 400);\n}\n```\n\nText-PK resources (the default and the recommended path) are unchanged.\n\nA soft-deprecation warning now fires at compile time when\n`providers.database.config.generateId === 'serial'` is set, nudging new\nprojects toward text-PK strategies (`'cuid'`, `'uuid'`, `'prefixed'`, or\nthe default). Existing serial-PK projects keep working.\n\n### Audit-field injection now runs for every dialect\n\nThe compiler auto-injects `created_at`, `modified_at`, `created_by`, and\n`modified_by` columns into every feature table, and the scoped-db\nruntime auto-fills them on insert. Until v0.33.5, the early injection\nstep in `parseCompilerInput` was gated on `targetDialect ===\n'postgresql'`. SQLite/D1 projects fell back to a later injection inside\n`generateFeature`, which only fired when `feature.tables.length > 0` —\nfeatures arriving without a populated tables array (raw-drizzle shapes,\ncertain legacy migration tables) silently skipped audit injection.\n\nSymptom: schemas claimed the columns existed (so the scoped-db proxy\ntried to fill them on insert), but the database table didn't have them.\nInserts failed with \"column doesn't exist.\" Users reported this for the\n`user_preferences` table and, earlier, for `chat_reads` (the\n`0028_chat_reads_id_column.sql` incident).\n\nThe early injection now runs for all dialects. `injectAuditFields` is\nalready idempotent, so the subsequent per-target injections in\n`compilePureSQLTarget` and `feature-generator.ts` are no-ops when the\ncolumns are already present. Net: every feature's schema source has\naudit columns by the time drizzle-kit reads it, regardless of dialect\nor feature shape.\n\nUpgrade path: recompile against v0.33.5, commit the generated migration\nthat adds the missing audit columns, then `wrangler d1 migrations apply`.\n\n## v0.33.4 — May 21, 2026\n\nPatch fixes covering upgrade-path bugs and OpenAPI spec/route divergence. No\nnew features or breaking changes.\n\n### OpenAPI emits CRUD endpoints only when the route emitter registers them\n\nThe OpenAPI emitter previously advertised `GET /`, `POST /`, `GET /:id`,\n`PATCH /:id`, `DELETE /:id`, and the corresponding `/batch` operations on\nevery resource, regardless of which CRUD verbs were actually declared.\nClients generated from `openapi.json` then issued requests that fell\nthrough to `ROUTE_NOT_FOUND` from the firewall layer — a silent contract\nbreak for anyone whose code path was driven by openapi-typescript or\nsimilar codegen.\n\nEach gate now mirrors the route emitter exactly. A resource that only\ndeclares `read + create + delete` (no `update`) gets no PATCH operations\nin the spec. A write-only sink (`create` only, no `read`) gets no GET\noperations. Same for batch variants — `POST /batch` only when\n`crud.create` is set, `DELETE /batch` only when `crud.delete` is set,\netc.\n\nIf your generated client was calling these spurious endpoints, those\ncalls were already failing at runtime; this just removes them from the\nspec.\n\n### Legacy D1 audit-timestamp migrations rewritten in place\n\nCompilers ≤ v0.33.1 emitted\n`DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))` for audit columns\n(`created_at`, `modified_at`, etc.). Cloudflare D1 rejects this in\n`ALTER TABLE ADD COLUMN` with `SQLITE_ERROR [code: 7500] \"Cannot add a\ncolumn with non-constant default\"`. v0.33.2 stopped emitting the\nnon-constant form, but pending unapplied legacy migration files on\nupgrading projects still poisoned `wrangler d1 migrations apply` and\nleft the deploy stuck.\n\nThe D1 migration safety pass now retrofits these files in place,\nreplacing the strftime expression with the same `'1970-01-01T00:00:00.000Z'`\nconstant v0.33.2+ uses. The compile-time warning lists the affected\ncolumns:\n\n```\n⚠ D1 helper adjusted features migrations for Cloudflare D1 safety:\n 0004_early_dracula.sql [rewrote=applied_at,created_at,modified_at]\n```\n\nUpgrade path: recompile against v0.33.4, commit the rewritten SQL, then\n`wrangler d1 migrations apply` proceeds.\n\n### D1 helper warning is now actionable\n\nThe same migration safety pass auto-prepends `PRAGMA defer_foreign_keys\n= on` to every drizzle table-rebuild migration — required on D1\nbecause it doesn't honour `PRAGMA foreign_keys=OFF/ON` mid-migration the\nway SQLite does. The pass used to surface this insertion as a warning\non every recompile, training users to ignore the warning entirely.\n\nThe PRAGMA is still inserted (it has to be), but no longer fires the\nwarning. Stripped Better Auth cleanup, reordered child-first DROPs, and\nthe new `rewrote=…` annotation above still warn — those are cases where\na human should look.\n\n### Reference: `account.appUrl` / `account.tenantPattern`\n\nv0.33's redesigned dashboard org-card uses two new optional fields on\nthe `account` config to deep-link into the tenant's own app:\n\n```ts\n// quickback.config.ts\naccount: {\n // …existing fields\n appUrl: 'https://app.example.com',\n tenantPattern: '/{slug}',\n}\n```\n\nBoth are typed in the config schema and baked into the Account SPA at\nbuild time as `VITE_QUICKBACK_APP_URL` and `VITE_TENANT_URL_PATTERN`.\nWithout them, the dashboard falls back to a single-target card that\nlinks to the account org-settings page (legacy v0.32 behaviour). Adding\nthem enables the two-zone layout with the external deep-link affordance.\n\n(No code change in v0.33.4 — the fields shipped with v0.33.0 but weren't\ncalled out in the changelog.)\n\n## v0.33.0 — May 21, 2026\n\n### Dedicated hostnames for `/auth/v1/*` and `/api/v1/*` (Shape 1)\n\nTwo new optional overrides let you carve specific backend surfaces onto dedicated hostnames, served by the same Worker:\n\n```ts\n// quickback.config.ts\nauth: { domain: 'auth.example.com' }, // /auth/v1/* lives here too\napi: { domain: 'api.example.com' }, // /api/v1/* lives here too\n```\n\nOn the dedicated hostname, the hostname IS the namespace — `/v1/*` is a shortcut that the Worker-entry rewriter prepends with `/auth` or `/api` before route matching. So `https://api.example.com/v1/users` reaches the same handler as `https://quickback.example.com/api/v1/users`. Both forms work; the long form is also accepted on the dedicated host. Non-matching paths return a JSON 404 (\"Not found on api.domain — this hostname serves /api/v1/* and the /v1/* shortcut only\") — each hostname stays dedicated to its surface. `/health` and `/openapi.json` are explicit exceptions because monitoring/discovery agents expect them everywhere.\n\nBoth new domains:\n- Get a `{ pattern, custom_domain: true }` route in `wrangler.toml`\n- Join `trustedOrigins` (CORS allowlist)\n- Join the cross-subdomain cookie inference (auto-enables `crossSubDomainCookies` when ≥2 same-parent subdomains are configured)\n- Join CSP `connect-src` so SPAs can fetch from them\n\n**Dual-reach:** all routes remain reachable at the unified backend host (see below) regardless of which dedicated hostnames are configured. The dedicated hostnames are aliases, never replacements.\n\n### `quickback.{baseDomain}` codified as the always-present unified backend\n\nThe compiler has always auto-inferred a `quickback.{baseDomain}` hostname when any subdomain is configured. v0.33 promotes this from inferred fallback to **load-bearing contract**:\n\n- The unified backend hostname is GUARANTEED to exist when any custom subdomain (`account.domain`, `cms.domain`, `auth.domain`, `api.domain`, `apps.<n>.domain`) is set.\n- Every compiler-emitted backend route (api, auth, storage, health, openapi, realtime, mcp, bundled SPAs, sysadmin endpoints) is reachable at the unified host, always.\n- Per-surface domain overrides are additive (Shape 1) — they create more hostnames, never remove routes from the unified host.\n\nThis is forward-pointing: the future management layer can rely on a single discovery URL pattern (`https://quickback.{baseDomain}/...`) to find any backend regardless of how the operator split their surfaces onto subdomains.\n\nInference also extends to consider `auth.domain` and `api.domain` as domain sources, so a project configuring only one of them still derives `quickback.{baseDomain}` automatically. Explicit `config.domain` still wins over inference.\n\n### `compiler.routes` config block (scaffold — partial)\n\nOptional path-prefix overrides for compiler-emitted system routes:\n\n```ts\ncompiler: {\n routes: {\n storage: '/files', // default '/storage'\n broadcast: '/realtime', // default '/broadcast/v1'\n mcp: '/agent', // default '/mcp'\n health: '/_health', // default '/health'\n openapi: '/openapi.yaml', // default '/openapi.json'\n },\n}\n```\n\n**Status:** the config is validated and reaches the reserved-prefix registry (so SPA pass-through and compile-time collision detection already honor overrides), but the per-section route emitters still hardcode the defaults. Setting a non-default value today will produce a misconfigured Worker — the registry knows the new path but the actual `app.route('/storage/v1', …)` mount uses the old one. **Don't set these in production yet.** Per-section emit wiring lands in a follow-up.\n\n`/api/v1/` and `/auth/v1/` are NOT configurable here — those are deep contracts touched by feature emitters, OpenAPI generation, generated clients, and BA's own basePath. The Shape 1 hostname overrides above are the supported way to relocate them.\n\n## v0.32.0 — May 21, 2026\n\n### Single-origin path-routed architecture\n\nA modern Quickback project now runs on **one Cloudflare Worker behind one custom domain**, with the bundled Account and CMS SPAs path-mounted at `/account/` and `/cms/`, system routes at `/api/`, `/auth/`, `/storage/`, and the user's own SPAs anywhere else they want. No cross-subdomain cookies, zero CORS preflights, no separate `api.`/`account.`/`cms.` subdomains required:\n\n```ts\n// quickback.config.ts\napps: { www: { domain: 'app.example.com' } }, // user's root SPA\naccount: true, // bundled at /account/\ncms: true, // bundled at /cms/\n// /api/, /auth/, /storage/, /openapi.json, /health all live here too\n```\n\nThe bug that previously broke this shape: when a hostname-mounted root SPA was configured (`apps.www.domain`), its middleware swallowed every path that wasn't in a hardcoded list (`/api/`, `/auth/`, `/admin/`, `/storage/`, `/health`). Requests to `/account/profile` got remapped to `/www/account/profile`, 404'd, then SPA-fallback'd to the wrong SPA. v0.32 introduces a **reserved-prefix registry** (`resolveReservedPrefixes` in `apps/compiler/src/generators/core/reserved-prefixes.ts`) as the single source of truth for what every catchall middleware must pass through:\n\n- **System** (always present): `/api/`, `/auth/`, `/storage/`, `/health`, `/openapi.json`\n- **Conditional** (only when feature is on): `/account/` (when `account: true`), `/cms/` (when `cms: true`), `/broadcast/v1/` (realtime), `/mcp` (MCP server)\n- **User-contributed**: every `apps.<name>.path` for path-mounted apps\n\nPath-mounted apps that collide with a system or bundled-SPA reservation throw a compile-time error naming both owners. `apps.api = { path: '/api' }` errors clearly instead of silently hijacking feature routes at runtime.\n\n### Admin URL namespace migration: `/admin/v1/*` → `/auth/v1/admin/*`\n\nQuickback's legacy admin tier emitted three things under `/admin/v1/*`:\n\n1. A role-admit middleware that admitted both `'admin'` and `'sysadmin'` — contradicting the pseudo-role evaluator's strict-independence model (`ADMIN` admits `'admin'` only; `SYSADMIN` admits `'sysadmin'` only).\n2. `GET /admin/v1/organizations` — a thin proxy to Better Auth's own `/auth/v1/organization/list`.\n3. `GET /admin/v1/sysadmin/organizations` — cross-tenant org listing, sysadmin-only.\n\nIn v0.32, the first two are **removed** and the third **renames** to `GET /auth/v1/admin/list-organizations`. The new path sits under Better Auth's admin URL namespace (sibling of `/auth/v1/admin/list-users`, `/auth/v1/admin/ban-user`, etc.), follows BA's verb-noun convention, and keeps its sysadmin-only gate inside the handler — Quickback-emitted, not BA-mounted.\n\nWhat this enables: `/admin/*` is no longer a reserved system prefix. Projects can mount their own admin SPA via `apps.admin = { path: '/admin' }` without colliding with anything.\n\nWhat changes for callers:\n- The bundled CMS SPA's sysadmin org switcher is updated in lockstep (no migration needed for projects using the SPA as-is).\n- External callers of `/admin/v1/organizations` should migrate to BA's `/auth/v1/organization/list` (same behavior — caller's memberships).\n- External callers of `/admin/v1/sysadmin/organizations` should migrate to `/auth/v1/admin/list-organizations`.\n- Features that previously relied on the \"admit both admin AND sysadmin\" middleware should declare `access: { roles: ['ADMIN', 'SYSADMIN'] }` explicitly on each route.\n\nThe `ADMIN_ROUTE_FEATURES` carve-out in the compiler is also removed — feature routes always mount at `/api/v1/<feature>`, and admin-only behavior is enforced by per-operation `access: { roles: ['ADMIN'] }` at the resource level.\n\n### Two compiler bug fixes\n\n- **Soft-delete index callback parameter bug.** The auto-index injector emitted hardcoded `t.<col>` references regardless of the existing extras callback's parameter name. When a user (or upstream transform) wrote `(table3) => ({ … })`, the appended composite-index entries referenced `t.organizationId, t.deletedAt` — `t` undefined inside the arrow scope, `ReferenceError` at module load. Fixed in `apps/compiler/src/utils/auto-indexes.ts` by capturing and reusing the callback's parameter name.\n- **Reserved-word action filename collision.** Action discovery walks `actions/*.ts` and emits `import <name> from './actions/<name>'`. A user filename of `import.ts`, `delete.ts`, `await.ts`, `export.ts`, etc. produced `import import from './actions/import';` — a SyntaxError on module load. Fixed in `apps/compiler/src/codegen/discovered-actions.ts` by aliasing reserved-word and invalid-identifier filenames to `__action_<sanitized>` bindings while preserving the public action key (route emitters use bracket notation, so reserved-word keys are fine in the lookup map).\n\n## v0.29.0 — May 19, 2026\n\n### Opt-in `id` auto-injection (`compiler.injectId: 'auto'`)\n\nQuickback's generated CRUD routes, FK extractor, relationship resolver, and `/:id` mount points all assume every feature table has an `id` primary key column. Authoring a table without one — common when porting an existing schema, or when a domain genuinely uses a compound or non-`id` PK — produced silent failures: routes that 404, batch operations that targeted the wrong rows, FK lookups that returned empty.\n\nv0.29 adds an opt-in flag that auto-injects an `id` column into every feature table that doesn't already declare one. Same mechanism as the existing `createdAt`/`modifiedAt` injection — early-pass, idempotent, dialect-aware.\n\n```ts\n// quickback.config.ts\ncompiler: {\n injectId: 'auto', // off by default; opt in per project\n}\n```\n\nWhen `'auto'`:\n- Tables with no `.primaryKey()` declared get `id: text(\"id\").primaryKey().$defaultFn(() => createId())` (or the matching shape for `dbConfig.generateId` — `serial`, `uuid`, `prefixed`).\n- Tables that already declare an `id` column (in any shape) are no-op — the injector is idempotent.\n- Tables with a `.primaryKey()` on a non-`id` column raise a clear compile error that names the offending column and points at the v0.30 follow-up which will rewrite custom PKs to unique indexes automatically. v0.29 surfaces the conflict; v0.30 fixes it.\n\nDefault stays `false` so existing projects don't get migration churn. Opt in when you want to lean on every-table-has-id semantics across your schema.\n\n### Why this is opt-in (and what v0.30 changes)\n\nThe \"every table has `id`\" assumption is load-bearing across 68+ sites in the compiler — every CRUD emitter, the FK regex (`.references(() => target.id)`), the relationship resolver hydration block, the `/:id` route mounts. v0.29 only injects the column; v0.30 will close the remaining gaps:\n\n- FK extraction migrates from `.id` regex to schema-aware metadata lookup, so tables with non-`id` PKs participate in FK display + relationship resolution.\n- The PK→unique-index rewrite lands — tables with explicit non-`id` PKs auto-keep their uniqueness as a constraint while gaining the auto-injected `id`.\n- The flag flips to default-on; opting out becomes the rare path.\n\nv0.29 ships the foundation so projects can opt in today without waiting for the full structural pass.\n\n## v0.28.0 — May 19, 2026\n\n### INTERNAL pseudo-role: server-only schemas, unforgeable from HTTP\n\nv0.27 had five pseudo-roles — `PUBLIC`, `AUTHENTICATED`, `USER`, `ADMIN`, `SYSADMIN` — and one structural gap: there was no way to mark a schema as \"the server enumerates this; no user-facing route should ever read across tenants.\" Push subscriptions, personal access tokens, OAuth tokens, broadcast job tables — anywhere the server needs full visibility but users should only see their own row. The workaround was `firewall: { exception: true }` plus an out-of-band convention, which left auth on the schema looking incidental.\n\nv0.28 adds **`INTERNAL`** as the sixth pseudo-role. Schemas with `roles: ['INTERNAL']` are reachable only by `AppContext` values where `ctx.internal === true` — a flag the HTTP auth middleware **never** sets. No session, JWT, header, query parameter, or body field populates it. The flag is reserved for compiler-emitted server-internal entry points (queue consumers, cron workers, server-side helpers that bypass HTTP entirely).\n\n```ts\n// features/comms/push-subscriptions.ts\nexport default defineTable(push_subscriptions, {\n firewall: [{ field: 'ownerId', equals: 'ctx.userId' }],\n // User reads their own subscriptions via the standard CRUD route.\n read: { access: { roles: ['USER'] } },\n // Server enumerates ALL subscriptions for a broadcast — INTERNAL only.\n crud: {\n delete: { access: { roles: ['INTERNAL'] } },\n },\n});\n```\n\nThe split-surface pattern is the recommended shape: a user-facing access node uses `USER` / `AUTHENTICATED` / a real role; a server-only access node uses `INTERNAL`. Mixing INTERNAL with a user-facing pseudo-role on the **same** access node is a compile error — it almost always means the developer is confused about which side of the trust boundary they're on. The error names the cohabiting markers explicitly and points at the fix (split into separate access blocks).\n\nThe runtime stamping (queue consumer ctx, cron worker ctx) lands in a follow-up; v0.28 ships the declarative surface so projects can mark schemas accurately today. Until the stamping ships, server-internal code uses `unsafeDb` to enumerate INTERNAL surfaces — the security guarantee is in place because no HTTP-derived context can ever carry `ctx.internal === true`.\n\n### Reserved-name fix: SYSADMIN and INTERNAL added to ALWAYS_RESERVED\n\n`SYSADMIN` was previously omitted from the `ALWAYS_RESERVED` set in `authz-schema.ts`. The runtime validator rejected `roles: ['SYSADMIN']` when `cms.sysadmin: true` wasn't set, but the **shadow-declaration path** — user code writing `authz.roles.SYSADMIN: { roles: [...] }` to silently change the pseudo-role's meaning — wasn't blocked. v0.28 closes that gap by adding both `SYSADMIN` and `INTERNAL` to the unconditionally-reserved set.\n\n### Per-table OWNER_SCOPE_RULES: explicit owner predicates no longer over-scope\n\nWhen a user declared a non-canonical owner predicate on one table — e.g. `firewall: [{ field: 'linkedUserId', equals: 'ctx.userId' }]` — that column got promoted into the **project-global** `OWNER_SCOPE_RULES` list. Any other table in the project that happened to have a `linkedUserId` column (even as a plain FK reference, not for scoping) had the same `WHERE linkedUserId = ctx.userId` injected on every read, update, and delete. Silent over-scoping that surfaced only when a query returned the wrong rows.\n\nv0.28 narrows the global list to the **canonical owner column** — the one matching `authDefaults.owner.column` (default `ownerId`). Explicit predicates on custom-named columns are honored on their declaring table via that table's own `buildFirewallConditions` helper, but stay per-table. Reads on other tables with the same column name are unaffected.\n\n```ts\n// Before v0.28: linkedUserId on `comments` ALSO got the WHERE\n// because `event_organizers` declared an explicit owner predicate.\nexport default defineTable(event_organizers, {\n firewall: [{ field: 'linkedUserId', equals: 'ctx.userId' }],\n});\nexport default defineTable(comments, {\n // comments.linkedUserId is just an FK reference; we don't want it scoped.\n firewall: [{ field: 'eventId', equals: 'ctx.activeOrgId' }],\n});\n```\n\nIn v0.28, `event_organizers` queries get the per-table `linkedUserId = ctx.userId` predicate as before; `comments` queries are no longer mis-scoped.\n\nIf you genuinely want the same column to scope multiple tables (rare), declare the explicit firewall predicate on each table. The implicit \"every table with this column gets scoped\" behavior was the bug — explicit-per-table is the cure.\n\n## v0.27.0 — May 19, 2026\n\n### Narrow `ctx.<exposeAs>` typing for namespace-scoped actions\n\nSince v0.23 the namespace middleware has hydrated `ctx.<exposeAs>` with the loaded resource row before each action runs. The static type of that field stayed `any` — runtime safety was solid, but autocomplete and typo-catching were missed opportunities.\n\nv0.27 ships the second half: one **per-namespace `defineAction` helper** emitted alongside the standard one. Importing from the narrowed helper retypes `ctx.<exposeAs>` inside `execute({ ctx })` to the loaded row's `$inferSelect` shape. Nothing about discovery, routing, or runtime behavior changes — this is purely TypeScript ergonomics.\n\n```ts title=\"features/feeds/actions/feed-moments.ts\"\n// Before — ctx.event is `any`\n\n// After — ctx.event is `typeof events.$inferSelect`\n\nexport default defineAction({\n path: '/event/:eventId/feed-moments',\n method: 'POST',\n input: z.object({ body: z.string() }),\n access: { roles: ['attendee'] },\n async execute({ ctx, input }) {\n ctx.event.id // ✓ string, autocomplete works\n ctx.event.startsAt // ✓ Date\n ctx.event.idd // ✗ TS2339 — typo caught at compile time\n },\n});\n```\n\n#### Where the file lives\n\nThe compiler emits one narrowed helper per `(feature, namespace)` pair where the feature owns at least one action whose `path:` falls under the namespace prefix. Filename is `define-action.<kebab(namespaceName)>.ts` (`eventScope` → `define-action.event-scope.ts`), sibling to the standard `define-action.ts`:\n\n```text\nsrc/features/feeds/.quickback/\n├── define-action.ts # generic — standard fallback\n└── define-action.event-scope.ts # ctx.event narrowed\n```\n\nA feature contributing to multiple namespaces gets one helper per namespace. Each action picks the import that matches its path.\n\n#### Opt-in, no breaking change\n\nActions that keep their existing `import { defineAction } from '../.quickback/define-action'` continue to compile unchanged. The `AppContext` index signature still admits `ctx.event` at type `any`; runtime hydration is unaffected. Flip imports per action at your own pace.\n\n#### Compile-time advisory\n\nWhen `quickback compile` sees a namespace-scoped action still importing the generic helper, it logs a one-line `[quickback:typing]` advisory pointing at the narrowed path:\n\n```text\n[quickback:typing] action \"feedMoments\" in feature \"feeds\" lives under\n namespace \"eventScope\" — switch its import to\n `../.quickback/define-action.event-scope` for narrow ctx.<exposeAs> typing.\n (Runtime behavior is unchanged; the narrowed helper only refines TS types.)\n```\n\nNon-blocking — same family as `[quickback:authz]`.\n\n#### Side fix\n\nRepaired a latent off-by-one in the inlined `AppContext` import path that landed in the v0.26 helper prelude but hadn't been exercised against a recompiled project yet (`\"../../lib/types\"` → `\"../../../lib/types\"`). New compiles produce a helper whose `AppContext` import actually resolves.\n\n#### Out of scope\n\nNon-namespace standalone actions with relationship-based access keep their existing `(ctx.event as typeof events.$inferSelect)` body cast. Same per-relationship helper pattern would apply if the demand surfaces — defer until requested.\n\n## v0.26.0 — May 19, 2026\n\n### Bulk-grant namespace lanes: org admins and team members in one line\n\nv0.25 widened `via:` to accept an array of relationship lanes — attendeeOf OR organizerOf, first match wins. That covers per-row authorization paths. v0.26 adds the missing piece: **bulk-grant lanes** for the \"you work here, so you see everything in your scope\" case. Org admins, team members, and other tenant-scoped staff no longer need a per-event relationship row to be authorized for a namespace.\n\n```ts\nauthz: {\n namespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: [\n 'attendeeOf', // per-event relationship\n 'organizerOf', // per-event relationship\n { roles: ['admin', 'owner'] }, // org-role bulk grant\n { team: true }, // active-team-membership bulk grant\n ],\n },\n },\n}\n```\n\nLanes resolve in declaration order, first match wins. Per-row relationships and bulk-grant guards compose freely.\n\n#### What each bulk-grant lane does\n\n- **`{ roles: [...] }`** — passes when the caller's BA org-role for the namespace's loaded resource includes any listed role. The check is in-memory and short-circuits the relationship loop entirely. The loads-table firewall (scoped by `ctx.activeOrgId`) does the tenant isolation; this lane just adds the role precondition on top.\n- **`{ team: true }`** — passes when `ctx.activeTeamId` is set. The loads-table firewall (which scopes by team for team-scoped tables) does the actual `events.teamId === ctx.activeTeamId` match during hydration. If the firewall returns no row, the request gets a contextual 404 explaining the row isn't visible to the current session — same ambiguous-by-design phrasing the firewall has always used to prevent cross-tenant ID probing.\n\n#### Why this matters\n\nUntil v0.26, the only way to authorize an org admin for a namespace was to write `access.or: [{ via: 'attendeeOf' }, { roles: ['admin', 'owner'] }]` on every individual action under it. That OR-arm shim worked but defeated the purpose of namespaces — the whole point of hoisting the gate was to write the auth rule once. Now you do.\n\n#### Rich deny payloads\n\nThe 403 response when every lane misses lists every path the caller could have taken — relationship names, role names, and `\"team-membership\"` for `{ team: true }` lanes — in the `required` field. A developer hitting an unexpected 403 sees the full set of authorization options they need to satisfy, not a generic \"Insufficient permissions\" wall.\n\nThe 404 from hydration (when the loads-table firewall filters the request out) now includes a hint explaining that the row may exist out of scope, and a `details` field with the resource name and key, so a developer working in their own environment has enough to debug.\n\n#### Compile-time guards\n\n- **Pure bulk-grant namespaces** (no relationship lane at all) are accepted as long as `loads:` + `exposeAs:` are declared directly on the namespace. With at least one relationship lane present, those fields are inherited from the relationship — declare them on the namespace itself only when no relationship lane is available to anchor hydration.\n- **Heterogeneous `loads:` between relationship lanes is rejected** — `ctx.<exposeAs>` must always hydrate the same table regardless of which lane matched.\n- **`namespace.loads` that disagrees with the inherited value is rejected** with a clear \"drop one or align the other\" message.\n\n## v0.25.0 — May 19, 2026\n\n### Multi-lane namespace gates: more than one way to be authorized\n\nv0.24 lets you hoist a namespace gate to the project level via `authz.namespaces.<name>.via: 'attendeeOf'` — one relationship-resolver middleware running once per request for every action under `/event/:eventId/*`. That works when there's exactly one way to be authorized for the resource. It breaks the moment you have **two**: an attendee row and a per-event organizer row, say. The shim today is to OR the second check inside every individual action's `access` block, which puts you back to writing the gate over and over.\n\nv0.25 widens `via:` to accept an array of relationship lanes. The middleware tries each in declaration order, and the first one whose subject row matches authorizes the request and hydrates `ctx.<exposeAs>`.\n\n```ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'linkedUserId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events',\n exposeAs: 'event',\n },\n // Per-event named organizers. The subject can be a user OUTSIDE\n // the event's organization — e.g. a freelance event manager.\n organizerOf: {\n from: 'eventOrganizers',\n subject: { column: 'linkedUserId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n namespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: ['attendeeOf', 'organizerOf'], // first match wins\n },\n },\n}\n```\n\nThe thing this actually unlocks isn't \"two checks instead of one.\" It's **per-event grants for users outside the owning organization** — external co-organizers, freelance event managers, partner staff. They don't need a `member` row in the event's org; they just need a row in `event_organizers` for that specific event. The horizontal axis (org / team membership) stays for \"staff at this company\"; the new vertical axis (per-event relationships) handles \"specifically connected to this event,\" regardless of payroll.\n\n#### Backward compatible\n\nThe string form keeps working — `via: 'attendeeOf'` is sugar for `via: ['attendeeOf']`. No existing namespaces break; opt into multi-lane by switching to the array form when you actually need it.\n\n#### Compile-time guards\n\nThe validator rejects three things at parse time:\n\n- **Undeclared lane names** — every entry in the array must resolve to an `authz.relationships[*]` declaration.\n- **Lanes that disagree on `loads:` or `exposeAs:`** — if attendeeOf loads `events` as `ctx.event` and organizerOf loads `agendaItems` as `ctx.agendaItem`, downstream handlers can't predict what's in `ctx.<exposeAs>`. Lanes in one namespace must hydrate the same shape.\n- **Empty arrays** — at least one lane is required (otherwise the namespace gate is meaningless).\n\n#### Follow-up: v0.26 bulk-grant lanes (shipped same day — see above)\n\nThe full 4-lane shape adds heterogeneous `via:` arrays accepting `{ roles: ['admin', 'owner'] }` and `{ team: true }` entries, so org admins and team members get the gate without writing relationship rows. v0.25 was the foundation; [v0.26](#v0260--may-19-2026) lifted the existing per-action `access.or: [..., { roles: [...] }]` shim into the namespace and landed same-day.\n\n## v0.24.0 — May 19, 2026\n\n### Cross-feature namespaces: one hoisted gate, many features\n\nv0.23 shipped `defineTable({ namespace: { prefix, via } })` — a hoisted relationship-resolver middleware that gates every standalone action in *one feature's* Hono app. That covers the 95% case where a domain concept (events) and the actions under it all live in the same feature directory.\n\nv0.24 lifts the namespace to the project level so it can span multiple features. A new `authz.namespaces` block on `quickback.config.ts` declares a path-prefix gate that any feature's standalone action can participate in by matching the prefix in its `path:`. One synthetic routes file, one resolver mount, one relationship match per request — regardless of how many feature directories contribute actions.\n\n```ts\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n namespaces: {\n eventScope: { prefix: '/event/:eventId', via: 'attendeeOf' },\n },\n}\n\n// features/feeds/actions/feed-moments.ts (cross-feature)\nexport default defineAction({\n path: '/event/:eventId/feed-moments',\n method: 'POST',\n // No gate boilerplate. ctx.event is typed.\n});\n\n// features/rsvp/actions/respond.ts (different feature, same namespace)\nexport default defineAction({\n path: '/event/:eventId/respond',\n method: 'POST',\n});\n```\n\nThe compiler emits one `src/routes/__namespace-event-scope.routes.ts` mounted at `/api/v1/event/:eventId/*`. The file imports each contributing feature's `actions` map under a distinct alias (`feedsActions`, `rsvpActions`), runs the `attendeeOf` resolver once per request at the head of the file, and dispatches to the matching action handler.\n\n#### Discovery is path-prefix-only\n\nNo new `namespace: 'eventScope'` field on `defineAction`. Actions opt in by matching `path:` against a declared namespace prefix — same model the table-level v0.23 form uses, just lifted to the project level. This means actions move in/out of the namespace based on their path strings, which is the simplest discovery story and matches today's convention (filenames and paths are already the discoverable surface).\n\n#### Source-feature stays the action's home for metadata\n\nOpenAPI tags, MCP tool grouping, and CMS form discovery continue to bucket each action under its source feature. Only the *runtime routes file* moves to the synthetic location — the feed-moments action is still tagged \"feeds\" in OpenAPI, the response shape doesn't change, and your generated SDK reads identically. The URL conveys the namespace membership without forcing every layer of the compiler to re-anchor the action.\n\n#### Worker-root mount order\n\nSynthetic namespace routes files register at priority `20` — ahead of per-feature mounts (priority `0`/`10`). `sortRoutesBySpecificity` keeps the order stable, and the namespace prefix's path parameter makes it sort more specific than `/api/v1/<feature>` anyway, so the middleware fires first for every request under its prefix.\n\n#### Compile-time guardrails\n\nThe same v0.23 invariants apply at the project level, with two additions:\n\n- **`via:` must point at a declared `authz.relationships[*]` entry**, and that relationship must declare `loads + exposeAs` — without `loads` there's nothing for the middleware to hydrate, and a namespace that only gates without hydrating is indistinguishable from a per-action access rule.\n- **`prefix:` must contain at least one `:param` segment** — middleware runs before input parsing, so the relationship key comes from `c.req.param()`.\n- **Same-name conflict** between `defineTable({ namespace })` and `authz.namespaces.<sameName>` is rejected. Pick one declaration site.\n- **Ambiguous prefixes** like `/a/:x` and `/a/:y` (same shape, different `:param` names) error at compile time. Strict super/sub-set relationships (e.g. `/event/:e` and `/event/:e/admin`) are fine — the harvester routes each action to the longest matching prefix.\n- **Unused namespace warning** emits `[quickback:authz]` when no standalone action's path matches a declared prefix. Not a hard error — the namespace may be staged ahead of the actions.\n\n#### Picking the right declaration site\n\nThe table-level v0.23 form is now the **single-feature shorthand**. The project-level v0.24 form is **canonical for cross-feature**.\n\n- **Use `defineTable({ namespace })`** when every action under the prefix lives in the same feature directory. The namespace travels with the table that owns it; nothing to add to `quickback.config.ts`.\n- **Use `authz.namespaces`** when the namespace spans features. The declaration sits next to your `authz.relationships` and `authz.roles` — the canonical home for cross-cutting authz config.\n\nThe two forms can't coexist for the same namespace name. If a v0.23 table-level namespace is starting to attract cross-feature actions, lift it to `authz.namespaces` — same shape, just at the project level, and the matching paths in other features will join automatically.\n\n#### Migration\n\nZero breaking changes. Nothing in v0.23 needs to change for v0.24 to land. The new field is opt-in; existing projects pick it up the moment they declare an `authz.namespaces` entry.\n\nThe harvester runs after Zod schema validation but before route generation, so unused or misconfigured namespaces surface immediately as errors or warnings rather than as silently-broken routes.\n\n#### Fixes shipped alongside\n\nThe first two were load-bearing for v0.23 namespaces to actually work — projects upgrading from a pre-fix v0.23 will see crashes/compile errors disappear on the v0.24 recompile.\n\n- **No more dual emission of namespace-claimed standalone routes.** Pre-fix, an action with a cross-feature path like `/event/:eventId/agenda/list-my-agenda` emitted into both `src/index.ts` (without the namespace resolver) and the synthetic file (with it). The plain root copy in `src/index.ts` won every URL match and `ctx.<exposeAs>` was never hydrated — every request 500'd with `Cannot read properties of undefined (reading 'id')`. `extractStandaloneActions` now skips namespace-claimed actions; the synthetic namespace file is the sole emission.\n- **Stripped-path validator no longer rejects namespace-claimed actions.** The synthetic file mounts at `/api/v1${namespace.prefix}` and strips the prefix from each action's local path. The per-action relationship-resolver was validating the *stripped* path for `:eventId`, finding nothing, and rejecting every namespace-mounted action with \"action's surface exposes neither a path parameter ':eventId' nor an input field 'eventId'\". `planRelationshipResolver` now receives the namespace's `via` and skips its surface-key check entirely — the hoisted middleware is the single source of truth.\n- **Broadcaster DO migration tag consistent across `realtime.mode`.** Inline-mode emission was already going through `qb-do-${className}` + `new_sqlite_classes`. Separate-mode was still hardcoded `tag = \"v1\"` + `new_classes`, so flipping `realtime: { mode }` produced different migration tags for the same DO class and tripped CF error 10074 (\"class already depended on\") on cross-mode deploys. Both modes now emit `tag = \"qb-do-Broadcaster\"` + `new_sqlite_classes`.\n- **Batch handler id arrays type-derive from the input parser.** Pre-fix, `validIds`, `recordMap`, and `validEntries` in bulk-delete / bulk-update / bulk-upsert were hardcoded `string[]` / `Map<string, any>` even when the table's PK column was `integer(\"id\")` — 274× TS2769 in projects mixing string and integer PKs. Handlers now declare `type IdT = typeof ids[number]` (or `typeof records[number]['id']`) and use it for the local id types. Strings stay strings, integers stay integers, no emitter knowledge of the PK column type required.\n- **`ctx` in action handlers is now `AppContext`, not `any`.** Both `StandaloneExecuteParams.ctx` and `RecordExecuteParams.ctx` in the generated `<feature>/.quickback/define-action.ts` are typed `AppContext`. AppContext keeps its `[key: string]: any` index signature so hydrated namespace keys (`ctx.event`, `ctx.<exposeAs>`) stay accessible without TS2339; named fields (`userId`, `activeOrgId`, `roles`, `authenticated`, `user`) get autocomplete and type-checking. Cleared ~49× TS2339 in generated projects.\n- **`c.get('ctx') as AppContext` in every emitted route handler.** Pre-fix, `const ctx = c.get('ctx')` returned `any`, so `ctx.roles?.some(r => …)` left the callback parameter implicitly `any` — 16× TS7006. Now `ctx.roles` is `string[] | undefined`, `r` is `string`, no callback annotation needed.\n\n#### Deferred (tracked, not blocking)\n\n- Per-namespace narrow typing of `ctx.<exposeAs>` (so `ctx.event` resolves to `typeof events.$inferSelect` instead of `any`). The compiler emits a typed cast at the `execute()` call site in the routes file today, which type-checks the call but not the handler body. Full narrow typing requires per-namespace helper emission (one `define-action.<namespace>.ts` per namespace, or a generic param threading through the action config). Tracked separately.\n\n---\n\n## v0.23.0 — May 19, 2026\n\n### Authz relationships: compile-time guarantees, less boilerplate, hoisted middleware\n\nThis release closes the gap between what `authz.relationships` *promised* in v0.19 and what it actually enforced. Every documented invariant is now a real compile-time check; every per-action ergonomic friction has a fix. Net effect: relationship-based authorization feels native — declare the relationship once, use the role anywhere, the compiler does the wiring.\n\n#### Compile-time guarantees (the authz `firewall` parity)\n\nThe org/owner/team firewall has always been compile-time-checked: a routed resource without a scope fails the compile, full stop. As of this release, `authz.relationships` carries the same guarantees:\n\n- **Bad `via:` names fail at parse time.** A typo in a firewall predicate (`firewall: [{ field: 'eventId', via: 'guestOff' }]`) used to surface deep inside the firewall generator after most validation had passed. It's now caught alongside the `authz.roles` `via:` validation, same layer, same error format.\n- **Relationship-from tables can't opt out.** The doc at `define/types/authz.ts:73-74` always said a relationship `from:` table with `firewall: { exception: true }` \"refuses to compile\" — that's now enforced. Without this check, every `via:` subquery that pivots through an exception-marked table loses tenant isolation and can return rows from other tenants.\n- **`allowResourceMigration` is now mandatory** when the relationship's `resource.column` is on a writable update endpoint. A guest doing `PATCH /messages/:id { eventId: <other-event-id> }` to migrate a row out of their access scope used to slip past the runtime — it now fails compile with a three-option remediation (set the flag, mark the column immutable, or drop it from the guards.updatable allowlist).\n- **`via: string[]` in firewall predicates.** \"Member of attendees OR speakers\" no longer requires inventing a composite role just to use it once in a firewall — `firewall: [{ field: 'eventId', via: ['attendeeOf', 'speakerOf'] }]` lowers to an OR-combined subquery.\n\n#### Less boilerplate: auto-derivation + realtime resolver\n\n- **`resource.column` auto-derives from FKs.** Omit it and the compiler scans the relationship's `from:` table for foreign-key columns, drops the `subject.column`, and picks the remaining FK. One match → auto; zero or many → error with the candidate list. Pattern mirrors the existing firewall auto-detection.\n- **`realtime.requiredRoles` accepts authz roles.** Previously a relationship-role in `realtime.requiredRoles` fell through with a misleading \"unknown role\" error. The compiler now flattens declared authz roles into their composing Better Auth roles before the realtime ticket-handshake sees them. Relationship-only roles (no static BA fallback) emit a `[quickback:authz]` warning and fail-close at handshake — the row-stream firewall continues to enforce the relationship dimension on the data side.\n\n#### Record-based actions can finally use relationship-roles\n\nThe v0.19 fail-closed hardening had an unintended side effect: a record-based action with `access: { roles: ['attendee'] }` (where `attendee` was a relationship-role) 403'd every caller, including the legitimate ones. The runtime helper couldn't evaluate `relationship:` arms, so it fail-closed correctly — but the inline match expression that *would* evaluate the relationship was never wired up for record-based actions.\n\nThis release routes record-based actions with relationship arms through the same inline access generator the resource CRUD path already uses. `roles: ['attendee']` on `/applications/:id/recap` now actually checks whether the caller is an attendee, with the loaded record in scope. Non-relationship access trees keep the runtime path unchanged.\n\n#### Typed `ctx.<exposeAs>` in action handlers\n\nWhen a relationship declares `loads: 'events', exposeAs: 'event'`, the runtime hydrates `ctx.event` with the loaded row — but the static type was always `any`, so handlers had to write `const event = ctx.event as typeof events.$inferSelect`. As of this release, when an action's access references **exactly one** relationship with `loads + exposeAs`, the compiler emits the cast for you at the execute() call site. Handlers read `ctx.event` with the right shape; no per-handler boilerplate.\n\nMulti-arm OR actions (referencing two relationships with hydration) keep the `any` shape — we can't statically know which arm matched.\n\n#### New: `defineNamespace` — one mount, one resolver, many actions\n\nThe marquee Wave 3 change. Today's pattern for \"five standalone actions under `/event/:eventId/*` all gated by `attendeeOf`\" requires writing the same inline relationship resolver in each action — and pays the resolver cost (one subquery, one row-load) on every request, multiplied by N actions. The new `namespace` field on `defineTable` hoists the resolver into a single Hono middleware mount:\n\n```ts\n// features/events/events.ts\nexport default defineTable(events, {\n firewall: [...],\n crud: { ... },\n namespace: {\n prefix: '/event/:eventId', // absolute URL path the mount covers\n via: 'attendeeOf', // relationship gate\n },\n});\n\n// features/events/actions/post-announcement.ts\nexport default defineAction({\n path: '/event/:eventId/announcements',\n method: 'POST',\n // No relationship-gate boilerplate. ctx.event is typed\n // `typeof events.$inferSelect` inside execute().\n});\n```\n\nThe compiler:\n1. Emits one `app.use('/:eventId/*', async (c, next) => { /* relationship resolver */; await next(); })` at the head of the feature's standalone-routes file (path-prefix stripping handles the feature mount).\n2. Skips the inline relationship resolver in every per-action handler under the prefix — the middleware already ran it.\n3. Hydrates `ctx.event` once per request and threads the typed cast into every namespace action's execute() call.\n\n**Validation guardrails:**\n- `namespace.via` must point at a declared `authz.relationships[*]` entry.\n- The referenced relationship must declare `loads + exposeAs` — without `loads` there's nothing for the middleware to hydrate, and the namespace gate would be indistinguishable from a per-action access rule.\n- `namespace.prefix` must contain at least one `:param` segment — the middleware reads the relationship key from `c.req.param()`, not from request body (body parsing hasn't run at middleware time).\n\n**Scope (v1):**\n- Namespace lives within a single feature's Hono `app`; cross-feature shared namespaces are deferred to v2.\n- One namespace per `defineTable` declaration; multiple namespaces in a feature mount as siblings.\n- For namespace actions whose access references additional relationships beyond the namespace's via, the inline resolver still fires for those — namespace handles only its own.\n\n#### Migration\n\nNothing in v0.20 → v0.23 breaks existing code that compiles cleanly. The new errors fire only against patterns that were already latent bugs:\n\n- A `via:` typo that previously surfaced as a deep codegen error now surfaces at parse time, same message.\n- A `firewall: { exception: true }` on a relationship-from table now errors; this configuration was always documented as unsupported.\n- A relationship's `resource.column` writable on the resource's UPDATE endpoint now errors unless `allowResourceMigration: true` is set; previously this was a runtime escape hatch.\n- Record-based actions with `roles: ['<relationship-role>']` previously 403'd every caller; they now work as the v0.19 docs originally promised.\n\n#### Why this matters\n\nAuthz relationships are how Quickback expresses \"the caller is allowed to touch this resource because of a row in *that* table\" — guest-of-event, member-of-organization, scorer-of-interview. Until now, the feature worked but had sharp edges: typos surfaced late, the documented exception-not-allowed constraint wasn't enforced, and the namespace pattern (which most apps with nested resources end up wanting) required repeating the same gate in every action. This release brings authz to parity with the org/owner/team firewall: declare it once, the compiler enforces it everywhere, the runtime emits exactly one query per request.\n\n---\n\n## v0.22.0 — May 19, 2026\n\n### Quickback Stack is Cloudflare-only: one runtime, two databases, one auth provider\n\nWe've focused the platform on the stack we actually believe in: **Cloudflare Workers + Hono + Better Auth**, with **Cloudflare D1** or **Neon** as the database. Providers and modes that targeted non-Cloudflare backends are gone. The result is a smaller concept set, fewer footguns, and clearer docs.\n\n#### What's been removed\n\n- **Runtimes**: `bun` and `supabase-edge` are no longer supported. The only runtime is `cloudflare`. Local development for compiled projects has always used `wrangler dev` — that's unchanged.\n- **Databases**: `supabase`, `libsql`, `better-sqlite3`, `bun-sqlite` are removed. Use `cloudflare-d1` for SQLite at the edge or `neon` for PostgreSQL via Hyperdrive.\n- **Auth providers**: `supabase-auth` is removed. `better-auth` is the default; `external` (Cloudflare service binding) remains for advanced setups.\n- **Template**: `template: 'nextjs'` is removed from the public config type. It was never fully implemented. The only template is `'hono'`. If you need a Next.js frontend, bring it as a separate deploy and call the Quickback API, or drop a static export into the `apps:` mount.\n- **Quickback for Supabase RLS** product line is retired. The compiler no longer emits Supabase Row Level Security policies. The `/products/quickback-supabase-rls/` and `/for/supabase-users/` pages have been removed from the marketing site, and the `compiler/targets/supabase-rls/` docs section has been deleted.\n\n#### Account UI: one delivery mode\n\nThe standalone `quickback-better-auth-account-ui` npm package has been **deprecated** and the upstream GitHub repo (`Kardoe-com/quickback-better-auth-account-ui`) has been **archived**. Account UI is now exclusively delivered the way 99% of projects already use it: the compiler builds it from source and bundles it into your Worker.\n\n- `account: { domain: 'auth.example.com', ... }` in `quickback.config.ts` — that's the entire integration story.\n- The compiler builds the SPA inside Docker with your branding and feature flags baked in, emits hostname-based routing, and wires cross-subdomain cookies automatically.\n- The three standalone delivery-mode docs (`stack/account-ui/standalone`, `library-usage`, `worker`) are removed; the remaining pages explain the compiler-bundled flow.\n\nIf you previously deployed the standalone Account UI Worker against a Quickback backend, switch to `account: { domain }` in the config — same end result, one less deploy.\n\n#### `VITE_AUTH_ROUTE` hardcoded to Quickback\n\nThe `VITE_AUTH_ROUTE` env var (which used to switch between `quickback` and `better-auth` routing dialects) is gone. The auth-client always uses Quickback's namespaced routes (`/auth/v1`, `/api/v1`, `/storage/v1`). Generic Better Auth backends are no longer a supported target. Removing the var also closes a known footgun where setting the wrong value silently 404'd every auth call.\n\n#### New: every config option is now discoverable\n\nWhen you bootstrap a project, the kitchen-sink marker block in `quickback.config.ts` lists every option Quickback supports — with descriptions and sensible defaults — commented out for you to copy above the marker as needed. Three top-level options were missing from this discovery surface and are now included:\n\n- **`apps`** — mount your own prebuilt SPA on its own hostname (`apps: { www: { domain: 'www.example.com', aliasDomains: ['example.com'] } }`). Drop the build at `quickback/apps/<name>/` and the compiler serves it from your Worker alongside the API. Reserved names: `cms`, `account`, `public`.\n- **`security`** — HTTP security headers (CSP, COOP, COEP, HSTS, Referrer-Policy, Permissions-Policy, X-Frame-Options). Set `security: false` to suppress everything; defaults are sensible for the embedded SPAs.\n- **`authz`** — relationship-based authorization roles. Declare joins between the caller and a resource column, then bind role names to those joins for use in `access: { roles: [...] }`.\n\n#### Migration\n\nProjects that compile cleanly against v0.21 and use any of these providers will hit a clear error at compile time:\n\n```\nUnknown database provider: \"supabase\". Available: cloudflare-d1, neon\n```\n\nTo migrate:\n\n1. **From Supabase**: switch `providers.database` to `cloudflare-d1` or `neon`, and `providers.auth` to `better-auth`. Your `defineTable()` definitions transfer as-is; the security DSL (firewall, access, guards, masking) compiles to Better Auth + Drizzle queries instead of RLS policies.\n2. **From Bun runtime / `bun-sqlite`**: switch `providers.runtime` to `cloudflare` and `providers.database` to `cloudflare-d1`. Local dev becomes `wrangler dev`.\n3. **From libsql / Turso**: switch to `cloudflare-d1` or `neon`. Both run natively from Cloudflare Workers via the right binding.\n4. **From `template: 'nextjs'`**: deploy Next.js separately and call the Quickback API, or drop a static export into `apps:`.\n\n#### Why this matters\n\nThe Quickback Stack is the Supabase alternative for Cloudflare. Every Quickback project ships a Hono API, an Account SPA, a CMS SPA, optional realtime/storage/queues — all built from one config and bundled into one Worker. Keeping that promise focused is more valuable than supporting deployment targets that don't share the runtime.\n\n---\n\n## v0.21.0 — May 19, 2026\n\n### Auto-firewall column swap: `ownerId` is now canonical on feature tables, `userId` warns\n\nThe compiler's default auto-firewall column for feature tables flips from `userId` to `ownerId`. This closes a long-standing footgun where a `userId` column meaning \"a user this row references\" (a member, a contact, an invitee) got silently clobbered with `ctx.userId` on insert, because the wrapper matched purely on column name across every table in the project.\n\n**What changed in the compiler**\n\n- `BETTER_AUTH_DEFAULTS.owner.column`: `'userId'` → `'ownerId'`. Schemas with an `ownerId` column auto-resolve to `firewall: [{ field: 'ownerId', equals: 'ctx.userId' }]` and have `ownerId` auto-stamped on insert.\n- The generated `OWNER_SCOPE_RULES` in `src/lib/scoped-db.ts` is seeded with `ownerId` instead of `userId`. Schemas that don't explicitly name `userId` in a `firewall:` block no longer trigger the global `userId`-stamping rule — the most common collision goes away without renames.\n- A new compile-time warning fires when a feature table carries both an auto-resolved isolation column AND a `userId` column. The warning recommends renaming the column to `linkedUserId` (or similar) if it's informational, or declaring `firewall: [{ field: 'userId', equals: 'ctx.userId' }]` if it really is the access boundary on that table.\n- The targeted compile-time error for \"the only candidate column is `userId`\" now points users at `ownerId` and the explicit-firewall escape hatch. The previous error wording (which assumed `ownerId` was business-logic) is removed.\n\n**What stayed the same**\n\n- Better Auth's own internal tables (`session`, `account`, `member`, `passkey`, `subscriptions`) still use `userId` by convention. They aren't feature tables and don't pass through the auto-firewall.\n- Explicit `firewall: [{ field: 'userId', equals: 'ctx.userId' }]` declarations continue to work and are still recognized as the \"owner\" pattern in the generated comment header.\n- The `USER` pseudo-role validator behaviour is unchanged; only the error-message wording flips to lead with `ownerId` and list `userId` as the explicit fallback.\n- Audit-wrapper (`createdBy` / `modifiedBy`) behavior is untouched.\n\n**Migration**\n\nProjects that auto-firewalled on a `userId` column will see a hard error on next compile telling them which table is affected, with two suggested fixes:\n\n1. **Recommended**: rename the column to `ownerId` in the schema. Cleanest semantics — readers immediately understand the column is access-control.\n2. **Explicit firewall**: keep the `userId` column and add `firewall: [{ field: 'userId', equals: 'ctx.userId' }]` to the resource. The auto-stamping and auto-scoping still happen; you've just opted in by name.\n\nProjects that have a `userId` column meaning \"a user this row references\" no longer need the `linkedUserId` rename workaround — auto-stamping won't touch the column unless you name it in a firewall block. The new warning makes this audit-discoverable.\n\n**Caveat (deferred)**: explicit `firewall: { owner: { column: 'X' } }` declarations still populate the project-global `OWNER_SCOPE_RULES` list, so a hand-named owner column on one resource will still match by name on every other table that happens to have a column called `X`. A future release will make scope-rule resolution per-table rather than project-global. The warning text calls this out so callers know what to expect.\n\n---\n\n## v0.20.0 — May 19, 2026\n\n### CMS + Account SPAs: shadcn base-ui migration, central Tailwind config\n\nBoth first-party SPAs are now on the shadcn **base-ui** variants (`@base-ui/react`) instead of the Radix-based primitives, applied via shadcn preset **`bdvxIkMq`** (style `base-mira`, `baseColor: zinc`, `iconLibrary: remixicon`, Inter Variable font). The migration also collapses the previously duplicated per-SPA theme + `components.json` into a single source at `packages/ui/`.\n\n#### Single source of truth in `packages/ui/`\n\nBoth SPAs were independently declaring the same `@theme` / `:root` / `.dark` token blocks in their own `app.css`, and each had its own `components.json` pointing at non-existent local component directories. That's gone:\n\n- `packages/ui/styles/theme.css` — the only place tokens live. Includes the base-mira palette, sidebar + chart tokens, and the Inter font import.\n- `packages/ui/components.json` — the only shadcn config in the repo. Future `pnpm dlx shadcn@latest add <name>` runs from `packages/ui/`.\n- `packages/cms/app/app.css` and `packages/account/app/app.css` reduce to two imports plus SPA-specific layers (CMS keeps its AG Grid + richtext-display overrides). `packages/{cms,account}/components.json` deleted.\n\n#### Components, icons, deps\n\n- All 22 shadcn primitives regenerated against `@base-ui/react` (`@radix-ui/*` removed everywhere). `Drawer` stays on `vaul` — base-ui has no Drawer primitive.\n- Icons migrated from `lucide-react` to `@remixicon/react` line variants across ~100 source files (`Plus → RiAddLine`, `ChevronDown → RiArrowDownSLine`, `X → RiCloseLine`, etc.). `lucide-react` removed from all `package.json` + `deps-spa-*` files.\n- `pnpm.overrides` pin `@types/react ^19.2.0` workspace-wide to resolve the duplicate-React-types conflict introduced by `@base-ui/react`'s bundled type peer.\n- Per-SPA deps and the Docker build mirrors (`apps/compiler/deps-spa-{cms,account}-package.json`) both gain `@base-ui/react`, `@remixicon/react`, `@fontsource-variable/inter`, and bump `shadcn` to `^4.7.0`.\n\n#### Backwards-compat `asChild` shim\n\nBase-ui replaces Radix's `asChild` boolean with a `render={\n</Button>\n```\n\n`ResponsiveModal` survived the migration unchanged — it composes the higher-level Dialog + Drawer wrappers (preserved public API), not the underlying primitives.\n\n#### Caller-side API changes worth noting\n\nBase-ui ships some real behavioural changes the Radix variants didn't:\n\n- `<Select onValueChange>` now receives `(value: string | null, eventDetails) => void` (was `(value: string) => void`). Existing `Dispatch<SetStateAction<string>>` setters reject `null` — wrap callbacks defensively: `onValueChange={(v) => v != null && setX(v)}`.\n- `<DropdownMenuContent forceMount>` removed (base-ui has no `forceMount`). Use base-ui's `keepMounted` on the Popup/Positioner if you need to preserve unmounted state.\n- Component sub-names shifted (`Dialog.Content` → `Dialog.Popup`, `Dialog.Overlay` → `Dialog.Backdrop`). Data attributes are now `data-open` / `data-closed` (no more `data-state=\"open\"`).\n\n#### Adding a new primitive after this release\n\n```bash\ncd packages/ui\npnpm dlx shadcn@latest add <component> --overwrite --yes\n# Sweep generated `@/` imports to relative paths — the SPAs' vite-tsconfig-paths\n# plugin doesn't see packages/ui's @/* mapping at bundle time:\nsed -i.bak \\\n -e 's|\"@/lib/utils\"|\"../lib/utils\"|g' \\\n -e 's|\"@/components/|\"./|g' \\\n -e 's|\"@/hooks/|\"../hooks/|g' \\\n components/<component>.tsx && rm components/<component>.tsx.bak\n```\n\nIf the new primitive pulls in fresh deps, mirror them into `apps/compiler/deps-spa-{cms,account}-package.json` per the SPA build pipeline or Docker SPA builds will fail.\n\n---\n\n## v0.18.1 — May 18, 2026\n\n### Account SPA — teams, active-team picker, permission-aware UI\n\nThe Account SPA's organization surface is now feature-parity with Better Auth's `organization` plugin for the basic team workflow, and replaces the long-standing hardcoded `role === 'owner' || 'admin'` checks with `checkRolePermission` so projects that ship custom roles get a UI that respects them.\n\n#### Teams (opt-in)\n\nWhen the BA config enables teams — `organization({ teams: { enabled: true } })` — the compiler emits `VITE_ENABLE_ORG_TEAMS=true` and the Account SPA exposes a Teams tab on each organization:\n\n- **Teams index** (`/$slug/teams`) — splits into \"Your teams\" (from `listUserTeams`) and \"Other teams\" so non-admins land on what's relevant. Create / rename / delete from the list, gated on `team:create` / `team:update` / `team:delete`.\n- **Team detail** (`/$slug/teams/$teamId`) — member roster with add / remove, joining `listTeamMembers` against the org's full member list for display.\n- **Active-team picker** in the org header — calls `setActiveTeam` and exposes the choice via `OrganizationContext.activeTeamId` so downstream routes (and the BA `session.activeTeamId` server-side) stay in sync.\n- **Team-aware invites** — `InviteMemberDialog` shows an optional team picker when teams are on and forwards `teamId` to `inviteMember`, so accepting the invite drops the new member straight into the right team.\n\nTeams are loaded once by the `$slug` layout (`listTeams` + `listUserTeams`) and exposed via `OrganizationContext.teams` / `userTeamIds` / `refreshTeams`, so individual team routes don't re-fetch the list.\n\n#### Permission-aware UI via `checkRolePermission`\n\n`OrganizationContext.isOwnerOrAdmin` is gone. Routes now read `can(resource, action)` from context, which delegates to `authClient.organization.checkRolePermission` — synchronous, no roundtrip, and aware of any custom roles registered via the BA `ac` option. Multi-role users (BA stores multiple roles comma-separated) are handled by checking each role; the action is allowed if any role grants it.\n\nMigrated sites:\n\n- `$slug.tsx` tab gates → `can('invitation', 'create')`, `can('organization', 'update')`\n- `members.tsx` action menu → `can('member', 'update' | 'delete')`; the owner-hierarchy guard (non-owners can't touch owner-role members) is preserved as a client-side mirror of BA's server enforcement\n- `invitations.tsx` → `can('invitation', 'create' | 'cancel')` gates the Invite button, resend, and cancel separately\n- `settings.tsx` → `can('organization', 'update')` for the form, `can('organization', 'delete')` for the danger zone (was owner-only)\n- `teams.tsx` / `teams.$teamId.tsx` → `can('team', 'create' | 'update' | 'delete')`\n\nProjects on the default three-role hierarchy see no behaviour change; projects that defined `admin`/`member` overrides via BA's access-control API now get a UI that matches what the server will actually authorize.\n\n#### Editable slug + metadata on organization settings\n\nThe `$slug/settings.tsx` form now edits two more `organization.update` fields:\n\n- **URL slug** — full debounced `checkSlug` flow (mirroring the create-org form); on rename, the SPA navigates to `/${newSlug}/settings` and the layout re-fetches with the new slug.\n- **Metadata** — single `Record<string, any> | null` JSON textarea, parsed on submit with inline error messaging. Empty clears the field.\n\nSlug rename is non-breaking for the SPA itself, but every external link / bookmark that references the old slug becomes a 404 — the form warns about this before saving.\n\n#### Auth client wiring\n\nWhen `VITE_ENABLE_ORG_TEAMS=true`, the SPA's `organizationClient(...)` is instantiated with `teams: { enabled: true }` so the team APIs are typed end-to-end. When the flag is off, team methods aren't surfaced — and the Teams tab is hidden — keeping the bundle and UI honest about what the server actually supports.\n\n---\n\n## v0.18.0 — May 17, 2026\n\n### `config.apps` — mount user-authored SPAs on dedicated hostnames\n\nThe compiler now generates per-hostname Worker middleware for arbitrary user SPAs alongside the built-in CMS and Account UIs. Previously the only way to host a product app next to a Quickback API was a second Worker; `config.apps` brings the full stack — API, account, and product UI — onto one deployment with same-origin auth.\n\n```ts\napps: {\n www: {\n domain: \"www.example.com\",\n aliasDomains: [\"example.com\"], // apex serves the same SPA\n },\n}\n```\n\nEach entry binds one or more hostnames to a directory under `src/apps/<name>/` and inherits the Account-domain pass-through behavior — `/api/`, `/auth/`, `/admin/`, `/storage/`, and `/health` route to Hono so the SPA fetches its API without CORS. The compiler:\n\n- emits a `custom_domain = true` route in `wrangler.toml` for the primary hostname and every alias\n- adds each hostname to Better Auth's `TRUSTED_ORIGINS` (when `trustedOrigins` is left unset)\n- widens the CSP `connect-src` to cover the SPA-baked origins\n- folds the new hostnames into shared-parent detection for `crossSubDomainCookies`\n\nDrop the prebuilt SPA bundle at `quickback/apps/<name>/` — the existing source-apps passthrough copies it byte-for-byte into `src/apps/<name>/`. The compiler doesn't build the SPA; it only emits routing for whatever's already there. The names `cms`, `account`, and `public` are reserved; hostname collisions with `cms.domain` / `account.domain` / `account.adminDomain` or between two `apps[*]` entries fail at compile time.\n\nWhen `cms` and `account` are both configured, the multi-domain catchall now explicitly skips app hostnames — an API miss on an app host returns the standard 404 JSON via `app.notFound` instead of stray-serving a sibling SPA's HTML shell.\n\n### Cross-subdomain cookie inference handles apex aliases\n\nThe shared-parent detection that drives `advanced.crossSubDomainCookies` previously reduced any hostname by stripping the leftmost label — `'example.com'` collapsed to `'com'`, which broke equality against sibling subdomains. Apex hostnames (exactly two dot-segments) are now treated as already being the parent, so apex aliases (`example.com` listed alongside `www.example.com`) coexist cleanly with `auth.example.com` / `cms.example.com` and the compiler still emits `crossSubDomainCookies: { enabled: true, domain: '.example.com' }`.\n\n---\n\n## v0.17.2 — May 15, 2026\n\n### `customPlugins` escape hatch on `defineAuth(\"better-auth\", …)`\n\nThe Better Auth provider now accepts `customPlugins` alongside the named-plugin registry — a path to ship third-party plugins (`@better-auth-kit/audit`, …), unregistered built-ins, or one-off project-local plugins without forking the compiler.\n\nEach entry is an explicit import descriptor:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: { passkey: true, organization: true },\n customPlugins: [\n // (1) Project-local plugin file at quickback/plugins/long-session.ts\n { from: \"./plugins/long-session\", export: \"longSessionPlugin\" },\n // (2) Third-party npm package\n {\n from: \"@better-auth-kit/audit\",\n export: \"auditPlugin\",\n args: { events: [\"sign-in\"] },\n dependencies: { \"@better-auth-kit/audit\": \"^1.0.0\" },\n },\n ],\n}),\n```\n\n`from` is either a relative path under `./plugins/` (the CLI auto-uploads matching files from `quickback/plugins/`; the compiler copies them into `src/plugins/<name>.ts` and rewrites the emitted import) or a bare npm specifier (emitted verbatim; declare `dependencies` so the package lands in the generated `package.json`). Omit `args` to emit the symbol uncalled (plugin instance); provide `args` to emit a JSON-serialized factory call.\n\nThe descriptor is validated with Zod — typos in `from`/`export`, paths that escape `./plugins/`, and references to files the CLI didn't ship all fail at compile time with a targeted message.\n\n---\n\n## v0.17.1 — May 14, 2026\n\n### `quickback start` — interactive onboarding\n\n```bash\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n```\n\n`start` walks new users through template selection, scaffolds the project on disk, and only prompts for an account when it's ready to compile. Cancelling at the login prompt leaves the scaffold intact — sign in and run `quickback compile` whenever you're ready.\n\nThe same deferred-auth flow applies to `quickback create`. Scaffolding and (optional) Cloudflare D1 setup run before authentication, so you can preview the project on disk before committing to an account.\n\n### Named views on the free tier\n\nThe `todos` template now ships a `dashboard` named view, exposing a projected response at `GET /api/v1/todos/views/dashboard`. Named views support per-view access rules and per-view field selection while inheriting the table's firewall and masking — the canonical way to ship list-view payloads that are cheaper to fetch and easier to cache than a full collection read.\n\n### `quickback init` removed\n\nFolded into `start` and `create`. The legacy command name prints a deprecation notice pointing at its replacements.\n\n### Minor\n\n- `quickback whoami` reads the stored tier from your credentials.\n- Pro upsell copy in `quickback login` is shown only when the server returns an explicit free-tier subscription.\n- Bare scaffolds (`cloudflare`, `empty`) report accurately when there are no features to generate migrations for.\n\n---\n\n## v0.16.10 — May 14, 2026\n\n### D1-specific safety pass on generated migrations\n\nThe `cloudflare-d1` provider now runs a post-generation pass over every Drizzle migration directory (auth, features, webhooks, audit) before the compile finishes. Better Auth cleanup for retired managed tables is stripped from raw `DROP TABLE` statements. Drop-only cleanup migrations are reordered child-first when foreign-key dependencies require it. Every generated D1 migration directory is replayed against SQLite during compile, so a D1-breaking migration fails at compile time rather than at `wrangler d1 migrations apply`.\n\n---\n\n## v0.16.9 — May 13, 2026\n\n### Resource-scoped realtime tickets\n\n`providers.database.config.realtime` accepts an object form for projects whose WebSocket subscribers aren't org members:\n\n```ts\nrealtime: {\n wsTicket: {\n role: \"attendee\",\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n}\n```\n\nThe generated `/broadcast/v1/ws-ticket` route authenticates the caller, evaluates the declared relationship role against the request, and mints a short-lived WebSocket ticket scoped to the resolved resource. `realtime: true` continues to enable the org-scoped broadcaster.\n\n### Unified broadcast targeting\n\nThe realtime helper and Broadcaster now route by `scopeKey || organizationId || userId`. String targets remain shorthand for `organizationId`; explicit targets can scope a broadcast to a resource or a single user:\n\n```ts\nawait realtime.broadcast(\"event-page-updated\", payload, { scopeKey: \"events:evt_123\" });\nawait realtime.broadcast(\"dm\", payload, { userId: recipientId });\n```\n\nWebSocket tickets are Quickback-minted (signed with `BETTER_AUTH_SECRET`), not Better Auth tokens — Better Auth remains the front-door auth check; Quickback signs the upgrade ticket after authorization succeeds.\n\n---\n\n## v0.16.8 — May 13, 2026\n\n### One auth transport per request\n\nGenerated middleware treats `Cookie`, `Authorization: Bearer`, and `x-api-key` as distinct auth methods and rejects mixed requests with `400 AUTH_METHOD_CONFLICT`. Query-string API keys (`?api_key=` / `?key=`) are no longer accepted. Machine-to-machine auth is explicit; precedence rules between transports are gone.\n\n### Cookie-backed CSRF gate\n\nGenerated apps now block cross-site `POST` / `PUT` / `PATCH` / `DELETE` requests from cookie-relying callers. The middleware skips explicit `Authorization` clients, requires a trusted `Origin` or `Referer`, and blocks `Sec-Fetch-Site: cross-site`. This matters most for cross-subdomain session setups where `SameSite=None` is intentional.\n\n### First-class Wrangler observability\n\n`providers.runtime.config.observability` now supports nested `logs` / `traces` blocks for `headSamplingRate`, `destinations`, `persist`, and `logs.invocationLogs`, emitting matching `[observability]`, `[observability.logs]`, and `[observability.traces]` TOML.\n\n---\n\n## v0.16.7 — May 12, 2026\n\n### Bearer wins over cookie\n\nA request carrying both `Authorization` and a session `Cookie` resolves entirely from the bearer; the cookie is dropped before `getSession()` runs. All three Bearer flavors (API key, JWT, session-token) now behave consistently — no more silent cookie precedence on session-token bearers.\n\n### Bearer plugin defaults to `requireSignature: true`\n\nBetter Auth's `bearer` plugin defaults to unsigned tokens; Quickback now emits `bearer({ requireSignature: true })`. Tokens emitted in the CORS-exposed `set-auth-token` header are server-signed with `BETTER_AUTH_SECRET` and verified on every request. Projects that genuinely need unsigned bearers can override via `providers.auth.config.plugins.bearer`.\n\nSee [Authentication Security → Bearer Tokens and Cookie Precedence](/stack/auth/security#bearer-tokens-and-cookie-precedence).\n\n---\n\n## v0.16.5 — May 12, 2026\n\n### Flat write DSL\n\nResource write operations are now declared at the table level alongside `read`, replacing the nested `crud` block:\n\n```ts\ndefineTable(customers, {\n read: { ... },\n create: { access: { roles: [\"admin\"] } },\n update: { access: { roles: [\"admin\"] } },\n delete: { access: { roles: [\"admin\"] }, mode: \"soft\" },\n upsert: { access: { roles: [\"admin\"] } },\n guards: { ... },\n});\n```\n\n`crud` and top-level `put` still compile as deprecated compatibility aliases. Mixed usage on the same resource is rejected. `schema-registry.json` emits both shapes during the transition.\n\n### CMS placement for multi-table feature actions\n\nStandalone actions on multi-table features have an explicit placement model:\n\n- `cms.placement: \"feature\"` shows the action on every table toolbar in the feature\n- `cms.placement: \"tables\"` with `cms.tables` scopes it to specific tables\n- `cms.hidden: true` keeps it API-only\n\nFeature-root standalone actions are emitted under a new `featureActions` bucket in `schema-registry.json`. Ambiguous multi-table standalone actions without placement compile with a warning.\n\n### `openapi.types` accepts a string array\n\nOne compile can write the generated types file to multiple locations, keeping colocated SPA clients in sync:\n\n```ts\nopenapi: { types: ['api-types.gen.ts', 'apps/web/src/lib/api-types.gen.ts'] }\n```\n\n### Stable artifact ordering\n\nGenerated route files and `schema-registry.json` are emitted in a stable order across runs. Identical logical input produces identical artifacts.\n\n---\n\n## v0.16.4 — May 12, 2026\n\n### Drizzle snapshot integrity\n\nDrizzle metadata files (`<n>_snapshot.json`) are no longer stamped with a Quickback warning key. The warning is now journal-only. Projects whose snapshots were corrupted by an earlier release self-heal on the next compile — the stripped header is removed during staging and the rewritten snapshot is clean.\n\n### `account.auth.*` drives the server, not just the SPA\n\nThe Account UI's auth flags (`signup`, `password`, `passkey`, `emailOTP`, `emailVerification`) now configure the Better Auth server alongside the SPA bundle. A normalizer maps them into the server config:\n\n- `signup → emailAndPassword.disableSignUp` (inverted)\n- `password → emailAndPassword.enabled`\n- `emailVerification → emailAndPassword.requireEmailVerification`\n- `passkey` / `emailOTP` → plugin additions\n\nThe SPA's `VITE_ENABLE_*` flags are derived from the same canonicalized server config, so the bundle and the server cannot drift. Two new flags ride along: `VITE_ENABLE_API_KEYS` and `VITE_ENABLE_MAGIC_LINK`.\n\n**Breaking** for projects that implicitly relied on the SPA-only behaviour: `account.auth.signup: false` now actually disables `POST /auth/v1/sign-up/email` on the server. Set `providers.auth.config.emailAndPassword.disableSignUp: false` explicitly to keep server signup open while hiding the SPA screen.\n\n---\n\n## v0.16.3 — May 9, 2026\n\n### Standalone action mount order\n\nFeature-level standalone action routers now register before sibling CRUD routers when both mount at the exact same prefix. A literal path like `GET /api/v1/records/today-bundle` resolves to the standalone handler instead of falling through to `GET /:id` and treating `\"today-bundle\"` as a record ID.\n\n---\n\n## v0.16.1 — May 9, 2026\n\n### Cloudflare ASSETS canonicalization\n\nWorker SPA fallbacks now request `/<dir>/` instead of `/<dir>/index.html`. Cloudflare's static-assets binding rewrites `/index.html` requests as 307 redirects to the trailing-slash path under the default `html_handling=auto-trailing-slash`, which previously caused redirect loops in SPA fallback handlers. Affects CMS, Account, admin, and the multi-domain catchall.\n\n### `account.customLogin`\n\nSet `account: { customLogin: true }` to drop a project-branded sign-in page in front of the bundled SPA. Place the page at `quickback/public/account/login/index.html` (as a directory) and the existing public passthrough serves it. The route registers before the `/account/*` SPA catch-all so the static handler wins; everything else under `/account/` continues to route through the bundled SPA.\n\n### Project-level realtime defaults\n\n`providers.database.config.realtime: true` now treats every resource as realtime-enabled by default. Per-resource `realtime: { enabled: false }` still wins.\n\n### Compile-time validators\n\nTwo new compile-time errors over silent runtime failures:\n\n- `AUTHENTICATED` + org-scoped firewall is rejected. The combination silently returned empty lists to sign-in-only callers who lacked an active org; the validator names three valid resolutions (drop the org scope, use `USER`, or split the route).\n- `createRealtime` imports without `realtime: true` enabled in the config are rejected at compile.\n\n### Drizzle metadata hardening\n\nDrizzle journal files carry a \"do not edit\" header. The compiler warns when the journal entry count exceeds the snapshot file count (typically the trace of a hand-deleted snapshot).\n\n### Minor\n\n- `SYSADMIN` is now recognised by the standalone-action org gate's pseudo-role matcher.\n- Apex `/` and `/account/login` get fallback redirects to `auth.loginUrl` when neither bundled SPA is enabled.\n- Record-based action URLs are kebab-case to match the OpenAPI spec (e.g. `/api/v1/widgets/:id/send-invite`).\n\n---\n\n## v0.16.0 — May 9, 2026\n\n### Agent Auth Protocol\n\nQuickback ships a server implementation of the [Agent Auth Protocol](https://agentauthprotocol.com) via `@better-auth/agent-auth`. Enable with `auth.plugins.agentAuth: true` and the compiler emits the full 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 added to the auth schema automatically.\n\n**OpenAPI capability projection runs by default.** Every operation with an `operationId` becomes an agent capability. Default `approvalStrength` map: `GET → \"session\"`, `POST/PUT/PATCH/DELETE → \"webauthn\"`. The proxy `onExecute` makes a self-fetch with a Better Auth JWT minted for the agent session, so the inner request hits the existing JWT fast-path and runs the full firewall + access + masking pipeline. Opt out of OpenAPI projection with `agentAuth: { fromOpenAPI: false }` and wire `capabilities` + `onExecute` by hand.\n\n### Bearer-only on `/mcp` and the agent-auth surface\n\n`/mcp` forwards only `Authorization: Bearer …` into the inner request. Cookie and `x-api-key` forwarding are removed. Three Bearer flavors land on the same header — Better Auth session token (via the `bearer` plugin), OAuth access token (via OAuth Provider), and agent JWT (via `@better-auth/agent-auth`).\n\n### Auth DSL gains first-class plugin entries\n\n`bearer`, `oauthProvider`, and `agentAuth` are now typed entries in both the array-form union and the `BetterAuthPlugins` interface, with their own options shapes (`OAuthProviderOptions`, `AgentAuthOptions`). Existing `as any` casts can come out.\n\nAuto-enable rule: turning on `agentAuth` force-adds `bearer` + `oauthProvider`. No useful agent-auth deployment ships without those two.\n\n### `queue-consumer.ts` gating\n\nThe queue consumer is emitted when any of the following are true: embeddings are configured, queue handlers exist under `services/queues/*`, or `additionalQueues` is declared. Previously the third case left projects with a wrangler binding pointing at a missing handler.\n\n---\n\n## v0.15.0 — May 7, 2026\n\n### Sysadmin tier for the CMS\n\nA new opt-in `cms: { sysadmin: true }` flag turns the CMS into a cross-tenant DB-admin tool gated by `user.role === 'sysadmin'`. Distinct from the Better Auth `'admin'` plugin role, so user-management powers and DB-admin powers stay decoupled. Off by default.\n\nWhen enabled, the compiler emits a `SYSADMIN` pseudo-role (a fifth marker alongside `PUBLIC` / `AUTHENTICATED` / `USER` / `ADMIN`), a firewall escape hatch that drops tenant scopes for sysadmins while preserving soft-delete, a true cross-tenant `/admin/v1/sysadmin/organizations` endpoint, and a relaxed cross-tenant guard for list routes.\n\nThe CMS SPA gains a two-mode design: org admins keep the existing membership-based switcher, sysadmins get an \"All organizations\" selector that pins tenants via `?organizationId=` on every API call.\n\n### Durable Object `[[migrations]]` order is preserved\n\nCloudflare's migration list is append-only. The compiler now reads your existing `wrangler.toml` (when present) and emits auto-generated DO `[[migrations]]` blocks in two phases: deployed entries first (preserving order), net-new entries appended last. Reordering DOs in the config array no longer reshuffles deployed migrations.\n\n### `quickback/public/` — static-asset passthrough\n\nAnything dropped under `quickback/public/` is copied verbatim into `src/apps/` on every compile and served by the wrangler `[assets]` binding. Use for favicons, `robots.txt`, OG images, `.well-known/` files, marketing PDFs — anything that needs to ride past the compiler as bytes.\n\n- Optional. Missing folder is a no-op.\n- Stale-cleaned. Files removed from `quickback/public/` disappear on the next compile.\n- Hidden entries (`.DS_Store`, dotfiles) are skipped.\n- Collisions with compiler-emitted manifest paths fail the compile loudly.\n\n### Minor\n\n- Standalone-action wrapper skips the org gate when the access tree references any pseudo-role.\n- Queue handler emit no longer drops the `queue` export when there are no embeddings.\n\n---\n\n## v0.14.7 — May 7, 2026\n\n### Codegen fixes for projects with non-`id` primary keys and DO-only features\n\nFour surgical fixes to the generated output:\n\n- Duplicate table imports in relationship-role routes are deduplicated.\n- `db` references in single-record and bulk action handlers now resolve correctly during pre-fetch.\n- PartyServer auth gates pass the in-scope `db` handle into firewall calls.\n- Durable-object-only features keep their `lib/` files in the output.\n\n### `emailOtp` + AWS SES is OTP-only\n\n`auth.emailOtp` with the AWS SES email provider no longer auto-wires the magic-link companion. Mail-client URL prefetching can burn the one-time code before the human sees it; the Account SPA's `/email-otp` route is the single canonical entry point. Projects that explicitly want the magic-link arm can wire `sendVerificationOTP` directly.\n\n---\n\n## v0.14.6 — May 7, 2026\n\n### MCP transport correctness\n\nFour fixes to the MCP-over-HTTP path:\n\n- `tools/call` URLs are no longer double-prefixed for action tools.\n- Auth middleware accepts API keys via `Authorization: Bearer` in addition to `x-api-key` and query parameters — the channel MCP clients use exclusively.\n- `auth.roleHierarchy` is expanded for runtime role checks across api-key, JWT, and session auth paths. A higher role inherits the privileges of every lower role.\n- Team-scoped firewall predicates degrade gracefully when no team is active (org scoping continues to apply; team scoping is optional).\n\n---\n\n## v0.14.5 — May 7, 2026\n\n### MCP environment threading\n\nThe generated MCP server's `tools/call` dispatch threads `env` and `executionCtx` into the inner request, so action tools that touch Cloudflare bindings (D1, KV, R2, Queues) no longer crash with `undefined` env access.\n\n---\n\n## v0.14.4 — May 7, 2026\n\n### `via:` firewall predicates pull required imports\n\nThe relationship-role generator emits `inArray` and `sql` imports when the firewall has any `via:` predicate, and `buildFirewallConditions` accepts `(ctx, db)` so the relationship subquery has a Drizzle client to evaluate against. Every CRUD and action call site passes `db` through automatically.\n\n---\n\n## v0.14.3 — May 7, 2026\n\n### Relationship-role table re-exports\n\nGenerated `<table>.resource.ts` files now re-export their Drizzle table binding. Cross-feature relationship subqueries that import the binding from the resource file (rather than the schema) resolve correctly.\n\n---\n\n## v0.14.2 — May 7, 2026\n\n### Historical DO `[[migrations]]` are preserved\n\nA new `bindings.durableObjectMigrations` config slot carries forward `deleted_classes`, `renamed_classes`, and `transferred_classes` lifecycle entries across recompiles. Cloudflare's migration list is append-only; entries declared here are emitted first in `wrangler.toml`, then auto-generated current-class entries follow:\n\n```ts\nbindings: {\n durableObjects: [{ name: 'NOTEPAD', className: 'Notepad', from: 'lib/Notepad' }],\n durableObjectMigrations: [\n { tag: 'qb-do-deleted-legacy-notes-2026-05-05', deletedClasses: ['LegacyNotes'] },\n ],\n}\n```\n\nAll four lifecycle shapes are supported. User-declared entries can override auto-emit by reusing the same tag.\n\n---\n\n## v0.14.1 — May 7, 2026\n\n### Bulk action variants in `openapi.json`\n\nRecord-based actions with `bulkVariant: true` are now emitted as sibling operations in the OpenAPI spec, with the documented `{ ids, input, failFast? }` request shape, 200/207/400 responses, and a separate `<Resource><Action>Bulk` `operationId` so typed-client codegen distinguishes single from bulk.\n\n### Cross-tenant \"my events\" patterns\n\nThe access docs now include a worked example for the cross-tenant aggregation pattern (e.g. `GET /my-events` returning resources across all tenants a caller is invited to). See [Access → Cross-tenant dashboards](/compiler/definitions/access#cross-tenant-my-events-dashboards-are-not-this).\n\n---\n\n## v0.14.0 — May 7, 2026\n\n### Relationship-based authorization\n\nRoles can now be bound to a domain-table membership (\"user is a confirmed guest of this event\") rather than an org membership or a pseudo-role. Declare the relationship once and reference it from `firewall:` or `access.roles:`:\n\n```ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n },\n },\n roles: {\n guest: { via: 'guestOf' },\n eventStaff: { or: [{ via: 'guestOf' }, { roles: ['admin', 'owner'] }] },\n },\n}\n\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' },\n],\nread: { access: { roles: ['admin', 'member', 'guest'] } },\ncreate: { access: { roles: ['admin', 'guest'] } },\nupdate: { access: { roles: ['admin'] } },\n```\n\nThe compiler emits an inline Drizzle subquery against the relationship table and AND-composes it as the outermost firewall clause. The relationship table's own firewall (tenant scope, soft-delete) is honored inside the subquery; cross-tenant grants are impossible because the resource's tenant filter sits outermost.\n\nSupported surfaces: row-level scoping via `firewall: [{ field, via }]`, role gates on writes and reads, view access. Masking and action access reject relationship-roles at compile time with pointers to the working pattern (gate the row at the firewall layer, gate the role at the access layer).\n\nCross-tenant aggregation dashboards aren't solved by relationship-roles — the tenant firewall remains the outermost AND. For that pattern, use a user-scoped firewall or function-form access on a dedicated route.\n\nSee [Firewall → Relationship-based scoping](/compiler/definitions/firewall#relationship-based-scoping-via) and [Access → Relationship-based authorization](/compiler/definitions/access#relationship-based-authorization).\n\n### Bulk variants on record-based actions\n\n`defineAction({ bulkVariant: true })` emits `POST /:resource/batch/{action}` alongside the per-record route. The bulk handler loops the same access + transition + execute pipeline over a `{ ids, input, failFast? }` body:\n\n```ts\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n bulkVariant: true,\n transition: { field: \"status\", via: \"nextStatus\", fromTo: { /* ... */ } },\n async execute({ db, record, input, whereTransition }) {\n // exact same body — runs once per id\n },\n});\n```\n\nPer-record outcomes return as 207 Multi-Status. `failFast: true` aborts on the first failure and wraps the loop in `db.transaction()` on tx-supporting providers; D1 fails fast without rollback. Max 100 IDs per request. Rejected on standalone actions and `unsafe` actions.\n\n### Aggregations on read views\n\nRead views can declare pre-computed metrics that surface alongside the row payload:\n\n```ts\nread: {\n views: {\n pipeline: {\n fields: [\"id\", \"jobId\", \"candidateId\", \"status\", \"appliedAt\"],\n aggregations: {\n totalApplications: { fn: \"count\" },\n byStatus: { fn: \"groupBy\", field: \"status\" },\n },\n },\n },\n}\n```\n\nAggregations run over the same firewalled, filtered set as the row query; pagination is intentionally ignored. Supported functions: `sum`, `avg`, `min`, `max`, `count`, `count_distinct`, `groupBy`. See [Views → Aggregations](/compiler/definitions/views#aggregations).\n\n---\n\n## v0.13.5 — May 6, 2026\n\n### Object-form `auth.plugins` config is honored\n\nThe documented `plugins: { oauthProvider: {...} }`, `plugins: { organization: { teams: { enabled: true } } }` shapes now flow through the compiler unchanged. Per-plugin options reach the generated `auth.ts` as written.\n\n### `roles: [\"PUBLIC\"]` allowed on writes and actions\n\n`PUBLIC` is the explicit, uppercase opt-in for unauthenticated access on every access node — reads, writes, views, and actions. The runtime trusts the marker; row-level safety comes from firewall, masking, and the action's own validation. `PUBLIC` actions continue to receive mandatory audit logging.\n\nCommon pattern: pair `roles: [\"PUBLIC\"]` with `firewall: { exception: true }` on the resource so the row predicate doesn't reject every unauthenticated caller.\n\n---\n\n## v0.12.0 — May 5, 2026\n\n### Per-room authorization for PartyServer\n\n`bindings.durableObjects[].access` declares a path-scoped gate that runs the declared resource's firewall and `read.access` pipeline before the WebSocket upgrade:\n\n```ts\ndurableObjects: [\n // Single-resource: roomId IS the chat row id.\n { name: 'Chat', className: 'Chat', from: 'lib/Chat',\n access: { resource: 'chats' } },\n\n // Multi-resource: regex dispatches kind → resource.\n { name: 'Notepad', className: 'Notepad', from: 'lib/Notepad',\n access: {\n roomId: { pattern: '^(day-note|interaction|record):([A-Za-z0-9_-]+)$', kindGroup: 1, idGroup: 2 },\n resources: {\n 'day-note': { resource: 'day-notes' },\n 'interaction': { resource: 'interactions' },\n 'record': { resource: 'records' },\n },\n } },\n\n // Anonymous lobbies / public pads: explicit opt-out.\n { name: 'PublicLobby', className: 'PublicLobby', from: 'lib/PublicLobby',\n access: 'public' },\n]\n```\n\nThe gate 401s unauthenticated callers, 403s when the firewall hides the row, 404s when the row is missing. Resource references are validated against feature names at compile time. See [PartyServer Rooms → Per-room authorization](/stack/realtime/partyserver-rooms#per-room-authorization-via-access-v012).\n\n---\n\n## v0.11.1 — May 5, 2026\n\n### PartyServer auto-mount is secure by default\n\nThe `/realtime/*` auto-mount now wraps `partyserverMiddleware` in an auth check. Unauthenticated upgrades return 401; the four auth mechanisms (session cookie, JWT bearer, `x-api-key` header, query parameter) all unlock connections. Per-room access remains the `Server` class's responsibility in `onConnect`.\n\n---\n\n## v0.11.0 — May 5, 2026\n\n### OAuth Provider (MCP-ready)\n\nQuickback can act as a standards-compliant OAuth 2.1 + OIDC authorization server via [`@better-auth/oauth-provider`](https://better-auth.com/docs/plugins/oauth-provider). Enable with `plugins: [\"oauthProvider\"]`. The compiler auto-includes Better Auth's `jwt` plugin and the Account SPA gains a `/consent` page for the standard authorization-code flow.\n\nThis replaces Better Auth's deprecated `mcp` plugin and gives every MCP client (Cursor, Claude Desktop, claude.ai connectors, custom tooling) RFC 7591 dynamic client registration plus the discovery documents they need to bootstrap. See [Auth Plugins → OAuth Provider](/stack/auth/plugins#oauth-provider-mcp-ready).\n\n### API keys via query parameter\n\nThe auth middleware now accepts API keys as `?api_key=…` or `?key=…` query parameters. The `x-api-key` header takes precedence when both are sent. Prefer the header whenever the client supports it — query parameters land in access logs and `Referer` headers.\n\n### PartyServer rooms + realtime URL split\n\nThe realtime URL space is reorganized so names match what each primitive does:\n\n- **`/realtime/v1/*` → `/broadcast/v1/*`** — the org-wide Broadcaster moves to its semantically accurate prefix.\n- **`/realtime/<binding>/<room-id>`** — new mount for [PartyServer](/stack/realtime/partyserver-rooms) rooms. Per-room Durable Objects with presence and lifecycle hooks. Auto-mounted whenever a project declares any in-worker DO.\n\n**Breaking** — recompile + redeploy required:\n\n- `REALTIME_URL` env var renamed to `BROADCAST_URL`.\n- SPA helpers `getRealtimeWsUrl()` / `getRealtimeTicketUrl()` renamed to `getBroadcastWsUrl()` / `getBroadcastTicketUrl()`.\n- `appConfig.routes.api.realtime` renamed to `appConfig.routes.api.broadcast`.\n\n`partyserver`, `partysocket`, and `hono-party` are pre-installed in the compiler image; collab projects compile without an extra `npm install` step.\n\n---\n\n## v0.10.20 — May 4, 2026\n\n### In-worker Durable Objects\n\n`bindings.durableObjects[].from` flips a DO binding into in-worker mode and emits the export, the `[[migrations]]` block, and the `CloudflareBindings` type all together:\n\n```ts\ndurableObjects: [{\n name: \"ITEM_STREAM\",\n className: \"ItemStream\",\n from: \"features/loops/lib/ItemStream\",\n}]\n```\n\nDO class files live under `quickback/lib/` or `quickback/features/<feature>/lib/` — both copy verbatim into the generated `src/` tree on every compile. `from` and `scriptName` are mutually exclusive; cross-worker DOs (`scriptName` set) skip the re-export and migration block.\n\n`migrationTag` (default `qb-do-${className}`) is stable across regenerations and must never be removed or renamed once deployed. `useSqlite` defaults to `true`. See [Bindings → Durable Objects](/compiler/config/bindings#durableobjects).\n\n---\n\n## v0.10.18 — May 2, 2026\n\n### `experimentalRemote` — share deployed D1 with `wrangler dev`\n\nPer-binding `experimental_remote = true` lets `wrangler dev` read/write deployed D1 for selected bindings:\n\n```ts\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n splitDatabases: true,\n experimentalRemote: { auth: true, features: false },\n }),\n}\n```\n\nUseful for \"share prod auth in dev, keep feature writes sandboxed.\" Off by default.\n\n### Google OAuth + signup ToS\n\nThe Account SPA wires Google OAuth end-to-end when configured under `auth.config.socialProviders.google.enabled`. The signup flow gains a Terms-of-Service checkbox gate (configurable via the Account SPA branding).\n\n### CLI compile auth gate\n\n`quickback compile` now requires authentication for cloud-compiler runs. Device-flow `?redirect=` parameters are standardized across the login + signup pages so a user clicking \"Create one\" no longer loses their return URL.\n\n---\n\n## v0.10.15–v0.10.17 — May 2, 2026\n\n### CSP auto-config\n\nWhen `security.csp` is set, the compiler widens directives additively based on the project's enabled features:\n\n| Trigger | Auto-added | Directive |\n|---|---|---|\n| `cms: true` OR `account: true` | `'unsafe-inline'`, `https://fonts.googleapis.com` | `styleSrc` |\n| `cms: true` OR `account: true` | `https://fonts.gstatic.com` | `fontSrc` |\n| `csp` set (always) | `@trustedOrigins` | `connectSrc` |\n| Bundled SPA enabled | SPA-baked API origin (`config.domain`, `quickback.{baseDomain}`, `cms.domain`, `account.domain`) | `connectSrc` |\n\nAnything you already wrote stays — auto-config never removes or overrides. Each applied addition is logged to stderr. Opt out with `security: { cspAutoConfig: false }`.\n\nMost projects can write the minimal:\n\n```ts\nsecurity: {\n csp: {\n defaultSrc: ['@self'],\n scriptSrc: ['@self'],\n objectSrc: ['@none'],\n upgradeInsecureRequests: true,\n },\n}\n```\n\n…and the compiler fills in font hosts, trusted origins, and SPA-baked URLs.\n\nWhen a target directive is missing, auto-config scaffolds it from `default-src` baseline rather than widening `default-src` itself — CSP3 fall-back semantics would otherwise leak the addition to every directive that falls back to `default-src`.\n\n---\n\n## v0.10.14 — May 1, 2026\n\n### `auth.jwt` config\n\nThe bearer-token JWT used by the auth fast-path is configurable. Tune `expiresIn` to bound the post-revocation replay window without affecting browser SPAs (which auto-refresh on every authed call):\n\n```ts\nauth: {\n jwt: {\n expiresIn: 30,\n issuer: 'my-api',\n audience: 'partner-svc',\n secretEnv: 'CUSTOM_JWT_SECRET',\n },\n}\n```\n\n### Admin MCP endpoints filtered\n\nBetter Auth admin endpoints (`/admin/list-users`, `/admin/ban-user`, etc.) now carry `x-access: { userRole: ['admin'] }` in the generated OpenAPI spec. The MCP `tools/list` access-filter drops them for non-admin callers.\n\n### Declarative `security` config\n\nEvery security response header (`Content-Security-Policy`, COOP, COEP, CORP, HSTS, `X-Frame-Options`, `Referrer-Policy`, `Permissions-Policy`) is configurable from `quickback.config.ts`. `@`-prefixed sentinels (`@self`, `@none`, `@unsafe-inline`, `@trustedOrigins`, etc.) replace awkward `\"'self'\"` quoting.\n\nThe compiler lints the resolved config for known footguns: `@unsafe-inline` in `script-src`, wildcard sources, missing `default-src`, HSTS preload-list misconfiguration.\n\n### HSTS skipped on localhost\n\nGenerated middleware skips `Strict-Transport-Security` when the request hostname is `localhost`, `127.0.0.1`, or `*.localhost`. Without this gate, `wrangler dev` would pin a developer's browser to HTTPS across every project on that machine.\n\n---\n\n## v0.10.13 — May 1, 2026\n\n### Clickjacking defence on every Worker\n\nEvery Worker emits `Content-Security-Policy: frame-ancestors 'self' <TRUSTED_ORIGINS…>` and `X-Frame-Options: SAMEORIGIN` on every response. The CSP allowlist is sourced from the same `TRUSTED_ORIGINS` constant that gates CORS.\n\n---\n\n## v0.10.11 — May 1, 2026\n\n### MCP `tools/list` is access-filtered\n\nEach MCP tool now carries sanitised access metadata. `tools/list` filters against the caller's `ctx`: unauthenticated callers see only `PUBLIC` tools, authenticated callers see only role-gated tools they pass.\n\n- Wildcard CORS removed from the MCP endpoint.\n- Unauthenticated `GET /mcp` no longer enumerates tool names.\n- Internal flavor text is removed; `annotations.destructiveHint` and `_unsafe` remain — those are the spec-correct signals for clients.\n\n`tools/call` continues to re-enter the Hono app and run every middleware (auth, firewall, access, guards, masking), so hiding a tool from list never weakens the underlying gate.\n\n---\n\n## v0.10.10 — April 29, 2026\n\n### Reserved keys in `access.record` are rejected\n\n`access.record` is a flat field map evaluated as implicit AND between entries — keys must be column names. The compiler now rejects reserved keys (`and`, `or`, `roles`, `userRole`) inside `record` with migration guidance pointing at the working pattern (top-level siblings with their own `record:` blocks).\n\n---\n\n## v0.10.8 — April 29, 2026\n\n### Audit logging on Postgres targets\n\n`audit_events` previously only existed on `cloudflare-d1`. The audit table now lives in a dedicated `audit` schema (`drizzle.pgSchema('audit')`) on Postgres targets. The `hasSecurityAudit` gate accepts D1 or any PG dialect; `auditDatabaseId` remains a D1-only requirement.\n\n### `auditDatabaseId` is a compile-time requirement\n\nProjects with unsafe or `PUBLIC` actions that previously produced a placeholder `database_id = \"local-audit\"` in production now fail at compile time with the exact `wrangler d1 create <project>-audit` command and the config key where the returned ID goes.\n\n### Action input → OpenAPI / MCP\n\n`defineAction({ input: z.object({...}) })` schemas flow into the OpenAPI `requestBody` and the MCP tool's `inputSchema.properties`. Simple `z.object` shapes are extracted at compile time; discriminated unions, refinements, recursive schemas, and bare-identifier references run through Zod's native `z.toJSONSchema()` for full-fidelity output.\n\n### OpenAPI fidelity\n\n- Response schemas emit `required[]` for every non-nullable column.\n- `text(_, { enum: [...] })` columns emit as closed `{ type: \"string\", enum: [...] }`.\n- `id` claims `format: \"uuid\"` only when the project's `generateId` actually produces UUIDs. cuid2 / prefixed / nanoid / serial generators emit plain `{ type: \"string\" }`.\n\n### Minor\n\n- Auto-mask predicate verifies the resolved owner column exists before emitting an `or: 'owner'` clause; falls back to roles-only with a warning otherwise.\n- Generated CRUD errors emit canonical `QuickbackErrorCode` enum values (`DB_NOT_NULL_VIOLATION`, `DB_UNIQUE_VIOLATION`, etc.) so generated SDKs can exhaustively switch on `code`. See [API errors](/compiler/targets/hono-api/using-the-api/errors#database).\n\n---\n\n## DSL: one file per action, multi-table per feature\n\n### One file per action\n\nAction authoring is one file per action under `<feature>/actions/<name>.ts`. The filename is the action name and the URL segment:\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: { applied: [\"screening\"], screening: [\"interview\"], interview: [\"offer\"] },\n },\n async execute({ db, record, input, auditFields, whereTransition }) { /* … */ },\n});\n```\n\n`defineAction` is imported from a generated per-feature helper at `<feature>/.quickback/define-action.ts` — `record`, `input`, and audit fields are typed without manual annotations.\n\n**Discovery rules:**\n- `actions/<name>.ts` binds to the feature's primary table.\n- `actions/<table>/<name>.ts` binds to the sibling table file.\n- Setting `path:` makes the action standalone (custom URL, no record fetch).\n- Tableless features require every action to be standalone.\n\n**Retired** (rejected at load time with migration guidance): `actions.ts` (bundled multi-action file), `_feature.ts`, `handlers/` directory + `handler:` string ref, `defineActions(table, {…})`, colocated `defineActions` inside table files, `standalone: true` flag, `*-actions.ts` / `*.actions.ts` filename patterns.\n\nSee [Actions docs](/compiler/definitions/actions).\n\n### Multi-table actions per feature\n\nOne feature directory can own actions on multiple tables. Three discovery modes:\n\n- **Colocated** (canonical) — `<table>.ts` containing both `defineTable` and `defineActions(<table>, …)`. One file per entity.\n- **`actions.ts`** — single primary-table actions file at feature root.\n- **`actions/<table>.ts`** — per-table action files for strict schema/behavior separation.\n\nPlus a universal `_feature.ts` slot for non-table-bound feature-level actions and shared Zod schemas.\n\nAction names are unique per `(bindTable, name)` pair. Sibling-bound `actions/episodes/publish.ts` and `actions/shows/publish.ts` mount at `/episodes/:id/publish` and `/shows/:id/publish` and compile cleanly.\n\n---\n\n## Firewall: named-scope shape\n\nThe named-scope firewall shape is a co-equal user-facing input alongside the predicate array:\n\n```typescript\nfirewall: { organization: { column: 'tenant_id' } } // named-scope (compact)\nfirewall: { owner: { column: 'account_user_id' } }\nfirewall: { exception: true }\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n] // predicate array (explicit)\n```\n\nPick the form that reads better — named-scope for the common one-line case, predicate array when you need custom `in`-lists or non-scope predicates.\n\n**Auto-detection synonyms.** When `firewall:` is omitted, the compiler scans the schema for an isolation column. The org-scope list accepts `organizationId`, `organisationId`, `orgId`, `organization`, `organisation`, `org` (American + British). User-scope accepts `userId`.\n\n**`ownerId` is a targeted error signal.** When a table carries `ownerId` but no isolation column and no explicit `firewall:`, the compiler raises a specific error — `ownerId` is business-logic ownership, not access control. Use `userId` for access control, declare an explicit `firewall:`, or add a separate isolation column.\n\n---\n\n## v0.10.0 — April 26, 2026\n\n### `q.scope()` — single-declaration tenant scoping\n\n`q.scope(kind)` replaces the three-place pattern (column declaration + firewall predicate + ownership-guard) with one column:\n\n```typescript\ncolumns: {\n organizationId: q.scope('organization'), // → ctx.activeOrgId\n ownerId: q.scope('owner'), // → ctx.userId\n teamId: q.scope('team'), // → ctx.activeTeamId\n}\n```\n\n`q.scope()` columns auto-derive the firewall predicate, register with the guards layer as `systemManaged` (client input rejected), and auto-populate from `ctx` on create / upsert. The systemManaged extension generalises beyond `q.scope()`: any firewall predicate whose `equals` references `ctx.*` registers its `field` automatically.\n\nSee [`q.scope()`](/compiler/definitions/schema#qscope--tenant-scope-columns).\n\n### `masking[col].query.roles` — unified filter / sort / search gate\n\nThe three legacy per-capability flags (`filterable`, `searchable`, `sortable`) are replaced by a single `query.roles` allowlist:\n\n```typescript\nmasking: {\n email: {\n type: 'email',\n show: { roles: ['admin'] },\n query: { roles: ['admin'] }, // defaults to show.roles when omitted\n },\n}\n```\n\nA view's own `query.{filterable,searchable,sortable}` allowlist is the opt-in for higher-privileged roles; the existing intersection validator gates it at compile time.\n\n**Breaking:** `masking[col].filterable / .searchable / .sortable` is rejected at compile time with a migration hint. Replace with `query.roles` (or delete the flags — `query` defaults to `show.roles`).\n\n---\n\n## v0.9.0 — April 25, 2026\n\n### Unified `read:` pipeline\n\nThe read side of every resource has its own block — `read:` — that owns the collection-level `GET /` endpoint, single-record `GET /:id`, and named view projections.\n\n**Breaking changes** (compile-time errors with migration hints):\n\n- `crud.list` → `read.access` (plus `read.pageSize` / `read.maxPageSize`)\n- `crud.get` → `read.access` (single-record GET inherits automatically)\n- Top-level `views: {...}` → `read.views: {...}`\n- `crud.list.fields` / `crud.get.fields` → declare a named view under `read.views` and call `/views/{name}`\n\n### Pre-record access ordering\n\nHandlers on `/:id` run a role-only access check before the firewall query. A caller without a matching role gets 403 before the database is touched. This closes the 404-vs-403 ID-probe channel — an unauthorized caller can no longer distinguish \"row exists in another tenant\" from \"row doesn't exist.\" See [Access evaluation order](/compiler/definitions/access#evaluation-order).\n\n### Transactional batch operations\n\nBatch endpoints expose `failFast` and a `meta.transactional` response field. On tx-supporting providers (postgres, supabase, neon, libsql, better-sqlite3, bun-sqlite), `failFast: true` wraps the per-record loop in `db.transaction(...)` so any failure rolls back the entire batch. On Cloudflare D1 (no `db.transaction`), `failFast: true` stops on the first error but prior writes stay committed.\n\nEmbedding queue messages and realtime broadcasts emit after the transaction commits — rolled-back batches produce no orphan jobs.\n\nSee [Batch Operations → Transactional semantics](/compiler/targets/hono-api/using-the-api/batch-operations#transactional-semantics).\n\n---\n\n## v0.8.7 — April 17, 2026\n\n### Hono CVE bump\n\nHono is bumped to `^4.12.14` across the monorepo, the compiler Docker image's pre-installed deps, and every generator path that emits Hono into compiled projects. Older ranges covered the vulnerable window. Recompile to pick up the fix in your generated project's `package.json`.\n\n### Cloudflare Email Sending in public beta\n\nQuickback defaults to the Workers `send_email` binding for Cloudflare deploys. Cloudflare Email Sending has graduated to public beta — production-ready with zero-config. AWS SES remains a fully supported opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes. See [Email Configuration](/compiler/config#email-configuration).\n\n### Dependency sweep\n\n`wrangler@^4.83.0`, `drizzle-orm@^0.45.2`, `drizzle-kit@^0.31.10`, `zod@^4.3.6`, `@cloudflare/workers-types@^4.20260417.1`.\n\n---\n\n## v0.8.5 — April 15, 2026\n\n### `userRole` access primitive\n\nA new `userRole?: string[]` field in the declarative `Access` config evaluates against `ctx.userRole` (the Better Auth admin-plugin `user.role` column). Distinct from `roles`, which matches `ctx.roles` (org membership).\n\n```typescript\n// Org owner OR platform admin\naccess: { or: [{ roles: ['owner'] }, { userRole: ['admin'] }] }\n\n// Platform admins see SSNs across every org\nmasking: { ssn: { type: 'ssn', show: { userRole: ['admin'] } } }\n```\n\n`userRole` works everywhere `Access` is accepted — CRUD, actions, views, masking, and inside `or` / `and` combinators. See [Access → userRole vs roles](/compiler/definitions/access#userrole-vs-roles).\n\n### CMS admin gate enforced server-side\n\n`cms: { access: \"admin\" }` previously only hid the CMS link in Account UI and rendered an \"Access Denied\" screen inside the SPA. Server-side enforcement now applies at every CMS-facing surface: the SPA shell, `/api/v1/schema`, and `custom_view` CRUD.\n\n### Better Auth 1.5 + `@cloudflare/workers-types` compatibility\n\nGenerated API code typechecks against the new versions. The org-member role-change broadcast hook is emitted via `organizationHooks.afterUpdateMemberRole` (the supported shape after the 1.5 deprecation of `databaseHooks.member.update.after`). `REALTIME_URL` and `ACCESS_TOKEN` are always emitted as optional bindings when the organization plugin is active.\n\n---\n\n## v0.8.4 — April 14, 2026\n\n### `generateId: \"short\"` strategy\n\nA compact ID option for tables where short, shareable codes matter more than collision resistance at scale:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", { generateId: \"short\" }),\n}\n```\n\nGenerates 6-character alphanumeric IDs (e.g. `a3F9xK`) using nanoid's `customAlphabet` with the full 62-char alphabet (`0-9A-Za-z`). Requires the `nanoid` package.\n\n**When to use:** room codes, invite links, share URLs, ephemeral records.\n\n**When not to use:** high-volume tables. 62^6 ≈ 56.8B combinations means ~238K rows before a 50% collision probability. For large tables stick with `\"uuid\"`, `\"cuid\"`, or `\"prefixed\"`. See [Providers → ID Generation Options](/compiler/config/providers#id-generation-options).\n\n---\n\n## v0.8.2 — April 11, 2026\n\n### Catch-all `VITE_QUICKBACK_URL`\n\nA single Quickback origin can be set in place of four separate URL env vars:\n\n```bash\nVITE_QUICKBACK_URL=https://secure.example.com\n```\n\n| Individual var (explicit) | Fallback when unset |\n|---|---|\n| `VITE_QUICKBACK_API_URL` | `${VITE_QUICKBACK_URL}` |\n| `VITE_QUICKBACK_ACCOUNT_URL` | `${VITE_QUICKBACK_URL}/account` |\n| `VITE_QUICKBACK_CMS_URL` | `${VITE_QUICKBACK_URL}/cms` |\n\n`VITE_QUICKBACK_APP_URL` stays independent — it points at the tenant's own frontend. Non-breaking; individual vars take precedence when set. Library users can set `__QUICKBACK_URL__` on `globalThis`. See [Environment Variables](/stack/account-ui/environment-variables).\n\n---\n\n## v0.8.1 — April 9, 2026\n\n### Role hierarchy with `+` suffix\n\nDefine a hierarchy and use `+` to mean \"this role and above\":\n\n```typescript\nauth: { roleHierarchy: ['member', 'admin', 'owner'] }\n\ncrud: {\n list: { access: { roles: [\"member+\"] } }, // member, admin, owner\n create: { access: { roles: [\"admin+\"] } }, // admin, owner\n delete: { access: { roles: [\"owner\"] } }, // owner only\n}\n```\n\nRoles are expanded at compile time. No `+` = exact match. See [Access → Role Hierarchy](/compiler/definitions/access#role-hierarchy).\n\n---\n\n## v0.8.0 — April 9, 2026\n\n### Breaking: VITE URL environment variables namespaced\n\nAll Quickback-generated URL environment variables are namespaced under `VITE_QUICKBACK_*` to avoid collisions with other Vite projects.\n\n| Old | New |\n|-----|-----|\n| `VITE_API_URL` | `VITE_QUICKBACK_API_URL` |\n| `VITE_ACCOUNT_URL` | `VITE_QUICKBACK_ACCOUNT_URL` |\n| `VITE_APP_URL` | `VITE_QUICKBACK_APP_URL` |\n| `VITE_CMS_URL` | `VITE_QUICKBACK_CMS_URL` |\n\nNon-URL variables are unchanged (`VITE_ENABLE_*`, branding vars, `VITE_STRIPE_PUBLISHABLE_KEY`).\n\n**Action required:**\n- Compiled projects: re-run `quickback compile`.\n- Standalone deploys: update `.env`, `.env.production`, and `wrangler.toml` files manually.\n- Library users: `__QUICKBACK_API_URL__` / `__QUICKBACK_APP_URL__` globals are unchanged.\n\n### CMS access control\n\n`cms.access: \"admin\"` enforces access at the CMS level, not just link visibility. Non-admin users (`user.role !== \"admin\"`) see an \"Access Denied\" screen with a sign-out button.\n\n---\n\n## v0.5.11 — February 24, 2026\n\n### Mandatory unsafe action audit trail\n\nStructured `unsafe` config (`unsafe: { reason, adminOnly, crossTenant, targetScope }`). Cross-tenant unsafe actions require Better Auth authentication plus platform admin role (`ctx.userRole === \"admin\"`). Mandatory audit logging on success, denial, and error paths. Cloudflare output includes `AUDIT_DB` wiring, `drizzle.audit.config.ts`, and `db:migrate:audit:*` scripts when unsafe actions are present.\n\nCompile-time raw SQL guard for actions and handlers (`allowRawSql: true` required per action).\n\n### Security contract report artifacts\n\nGenerated security contract artifacts: `reports/security-contracts.report.json`, `reports/security-contracts.report.sig.json`. Config-driven signing controls (`compiler.securityContracts.report.signature.*`). Missing required signing keys fail loudly with explicit remediation.\n\n### Headless Drizzle rename hints\n\n`compiler.migrations.renames` configuration for CI/CD environments where Drizzle's interactive rename prompts block compilation. See [Configuration](/compiler/config).\n\n### Minor\n\n- Email OTP magic links work correctly.\n- Auth is required for all API routes when running locally.\n- Single-file multi-table exports alongside `defineTable()` produce a clear error.\n\n---\n\n## v0.5.8 — February 14, 2026\n\n### Quickback CMS\n\nA schema-driven admin panel that connects to your generated API. The compiler now outputs a JSON schema registry consumed by the CMS at runtime. Firewall error modes (`reveal` for 403 with details, `hide` for opaque 404) are configurable per resource for security-sensitive deployments.\n\n---\n\n## v0.5.7 — February 12, 2026\n\n### Scoped database for actions\n\nActions receive a security-scoped database instead of a raw Drizzle instance. The compiler generates a proxy wrapper that automatically enforces org isolation, owner filtering, and soft-delete visibility — the same protections that CRUD routes have always had.\n\nDuck-typed column detection at runtime:\n\n| Column Detected | SELECT / UPDATE / DELETE | INSERT |\n|---|---|---|\n| `organizationId` | Adds `WHERE organizationId = ?` | Auto-injects `organizationId` from context |\n| `ownerId` | Adds `WHERE ownerId = ?` | Auto-injects `ownerId` from context |\n| `deletedAt` | Adds `WHERE deletedAt IS NULL` | — |\n\nEvery action is secure by default — no manual `WHERE` clauses needed.\n\nActions that intentionally need to bypass security (admin reports, cross-org queries, migrations) can declare `unsafe: true` to receive a raw, unscoped database handle via `rawDb`:\n\n```typescript\ndefineActions(analytics, {\n globalReport: {\n unsafe: true,\n execute: async ({ db, rawDb, ctx, input }) => {\n // db → still scoped (safety net)\n // rawDb → bypasses all security filters\n const allOrgs = await rawDb.select().from(organizations);\n },\n },\n});\n```\n\nWithout `unsafe: true`, `rawDb` is `undefined`. See [Actions](/compiler/definitions/actions).\n\n### Cascading soft delete\n\nSoft-deleting a parent record automatically cascades to child and junction tables within the same feature. The compiler detects foreign key references at build time and generates cascade `UPDATE` statements.\n\nRules:\n- Applies to soft delete only. Hard delete relies on database-level `ON DELETE CASCADE`.\n- Cascades within the same feature only — cross-feature references are not affected.\n- Child tables must have `deletedAt` / `deletedBy` columns (auto-added by the compiler).\n\nSee [Actions API → Cascading Soft Delete](/compiler/targets/hono-api/using-the-api/actions-api#cascading-soft-delete).\n\n### Advanced query parameters\n\nNew capabilities for all list endpoints:\n\n- **Field selection** — `?fields=id,name,status`\n- **Multi-sort** — `?sort=status:asc,createdAt:desc`\n- **Total count** — `?count=true` returns total matching records in `X-Total-Count`\n- **Full-text search** — `?search=keyword` searches across all text columns\n\nSee [Query Parameters](/compiler/targets/hono-api/using-the-api/query-params).\n\n---\n\n## v0.5.5 — February 5, 2026\n\n### OpenAPI spec generation\n\nGenerated APIs include a full OpenAPI specification at `/openapi.json`. Better Auth endpoints are included in the spec.\n\n### Better Auth plugins\n\nPublished `@quickback-dev/better-auth-upgrade-anonymous` (post-passkey email collection flow), `@quickback-dev/better-auth-combo-auth` (combined email + password + OTP), and `@quickback-dev/better-auth-aws-ses` (AWS SES email provider).\n\n### Security headers\n\nGlobal error handler prevents leaking internal error details. Security headers middleware (CSP, HSTS, X-Frame-Options, X-Content-Type-Options). `BETTER_AUTH_SECRET` properly passed to generated config.\n\n---\n\n## v0.5.4 — January 30, 2026\n\n### Account UI\n\nPre-built authentication UI deployed as Cloudflare Workers. Sessions, organizations, passkeys, passwordless, admin panel, API keys. Dual-mode: standalone (degit template) or embedded with Quickback projects.\n\n### Webhook system\n\nInbound webhook endpoints with signature verification. Outbound webhooks via Cloudflare Queues with automatic retries. Configurable per-feature webhook events.\n\n### Realtime & vector search\n\nDurable Objects + WebSocket realtime subscriptions. Vector embeddings via Cloudflare Vectorize. KV and R2 storage integrations.\n\n---\n\n## v0.5.0 — January 2026\n\n### Initial release\n\n- **Quickback Compiler** — TypeScript-first backend compiler.\n- **Four security pillars** — Firewall, Access, Guards, Masking.\n- **`defineTable()`** — schema + security configuration in a single file.\n- **Templates** — Cloudflare Workers, B2B SaaS.\n- **Cloud compiler** — remote compilation via `compiler.quickback.dev`.\n- **CLI** — `quickback create`, `quickback compile`.\n- **Better Auth integration** — organizations, roles, sessions.\n- **Drizzle ORM** — schema-first with automatic migrations.\n- **Cloudflare D1** — split database support (auth + features)."
|
|
7
7
|
},
|
|
8
8
|
"compiler/claude-code-skill": {
|
|
9
9
|
"title": "AI Developer Tools",
|
|
@@ -47,11 +47,11 @@ export const DOCS = {
|
|
|
47
47
|
},
|
|
48
48
|
"compiler/config/domains": {
|
|
49
49
|
"title": "Multi-Domain Architecture",
|
|
50
|
-
"content": "A single Quickback-compiled Cloudflare Worker can serve your API, CMS, Account UI, Admin panel, and your own product SPAs on separate custom domains. The compiler generates hostname-based routing so each domain serves the right content.\n\n## How It Works\n\nWhen you configure custom domains for CMS, Account, Admin, or `apps`, the compiler:\n\n1. Adds `custom_domain` routes to `wrangler.toml`\n2. Generates hostname-based middleware in the Worker\n3. Auto-configures cross-subdomain cookies for shared authentication\n4. Auto-infers a unified `quickback.{baseDomain}` fallback domain\n\nAll configured domains point to the **same Worker** — there's only one deployment.\n\n## Domain Types\n\n| Domain | Config | Serves | API Routes |\n|--------|--------|--------|-----------|\n| `api.example.com` | `providers.runtime.config.routes` | API only | All |\n| `cms.example.com` | `cms: { domain }` | CMS SPA | Blocked (404) |\n| `auth.example.com` | `account: { domain }` | Account SPA | Pass-through |\n| `admin.example.com` | `account: { adminDomain }` | Account SPA | Pass-through |\n| `www.example.com` | `apps: { <name>: { domain } }` | User-authored SPA | Pass-through |\n| `quickback.example.com` | Auto-inferred | Everything | All |\n\n### CMS Domain\n\nServes the CMS SPA at root (`/`). API routes (`/api/`, `/auth/`, `/admin/`, `/storage/`, `/health`) return 404 — preventing direct API access on the CMS domain.\n\n### Account Domain\n\nServes the Account SPA at root (`/`). API and auth routes pass through to the Worker so authentication flows work directly on this domain.\n\n### Admin Domain\n\nIdentical behavior to the Account domain — serves the same Account SPA at root. The Account SPA's client-side router handles the `/admin` route, restricting access to users with the `admin` role.\n\n### App Domains\n\nMount your own product SPAs on dedicated hostnames via the `apps` field. Each entry binds one or more hostnames to a directory under `src/apps/<name>/` and inherits the same API/auth pass-through behavior as the Account domain — so the SPA can hit `/api/v1/...` and `/auth/...` same-origin without CORS.\n\n```typescript\napps: {\n www: {\n domain: \"www.example.com\",\n aliasDomains: [\"example.com\"], // apex serves the same SPA\n },\n marketing: {\n domain: \"marketing.example.com\",\n },\n}\n```\n\n| Option | Required | Description |\n|--------|----------|-------------|\n| `domain` | Yes | Primary custom hostname served at root (`/`) |\n| `aliasDomains` | No | Additional hostnames that serve the same SPA. Each gets its own `custom_domain = true` route. Common case: apex (`example.com`) alongside `www.example.com`. |\n| `assetsDir` | No | Subdirectory under `src/apps/` to serve from. Defaults to the record key. Override only when the on-disk directory needs to differ from the URL-facing name. |\n\nDrop the prebuilt SPA output at `quickback/apps/<name>/` — the source-apps passthrough copies it byte-for-byte into `src/apps/<name>/` on every compile. The compiler doesn't build the SPA; it just emits routing for whatever's already there. See [Output Structure](/compiler/config/output#source-apps-quickbackapps) for the passthrough rules.\n\nThe names `cms`, `account`, and `public` are reserved (they collide with compiler-emitted directories under `src/apps/`). Two app entries can't claim the same hostname, and an app's hostname can't collide with `cms.domain` / `account.domain` / `account.adminDomain`.\n\n### Unified Domain\n\nThe compiler auto-infers a `quickback.{baseDomain}` domain from your configured custom domains. For example, if you have `cms.example.com`, it creates `quickback.example.com`.\n\nOn this domain, **everything is available** on a single origin:\n\n| Path | Content |\n|------|---------|\n| `/` | Redirects to `/cms/` |\n| `/cms/` | CMS SPA |\n| `/account/` | Account SPA |\n| `/api/v1/...` | API routes |\n| `/auth/...` | Auth routes |\n| `/admin/...` | Admin API routes |\n| `/storage/...` | File storage |\n| `/health` | Health check |\n| `/openapi.json` | OpenAPI spec |\n\nThe unified domain is useful for development and debugging. You can override it with an explicit `domain` field in your config.\n\n## Configuration\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default {\n name: \"my-app\",\n template: \"hono\",\n cms: { domain: \"cms.example.com\", access: \"admin\" },\n account: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n auth: { password: true, admin: true },\n },\n apps: {\n www: {\n domain: \"www.example.com\",\n aliasDomains: [\"example.com\"],\n },\n },\n providers: {\n runtime: { name: \"cloudflare\", config: {\n routes: [{ pattern: \"api.example.com\", custom_domain: true }],\n }},\n // ...database, auth\n },\n};\n```\n\n`trustedOrigins` is optional here — every `cms.domain`, `account.domain`, `account.adminDomain`, and `apps[*].domain` (plus aliases) is automatically added. Declare `trustedOrigins` only when you need to allow an origin the compiler can't infer (e.g. a third-party domain).\n\nThis generates the following `wrangler.toml` routes:\n\n```toml\nroutes = [\n { pattern = \"api.example.com\", custom_domain = true },\n { pattern = \"cms.example.com\", custom_domain = true },\n { pattern = \"auth.example.com\", custom_domain = true },\n { pattern = \"admin.example.com\", custom_domain = true },\n { pattern = \"www.example.com\", custom_domain = true },\n { pattern = \"example.com\", custom_domain = true },\n { pattern = \"quickback.example.com\", custom_domain = true }\n]\n```\n\n## Cross-Subdomain Authentication\n\nWhen two or more custom domains share a parent domain (e.g., `cms.example.com` + `auth.example.com` + `www.example.com`), the compiler automatically configures Better Auth for cross-subdomain cookie sharing. App hostnames (primary + aliases) are folded into the shared-parent detection alongside the CMS, Account, Admin, and top-level `domain` slots:\n\n- Sets `crossSubDomainCookies: { enabled: true, domain: '.example.com' }`\n- Sets `sameSite: 'none'` and `secure: true` on auth cookies\n\nThis means a user who logs in on `auth.example.com` is automatically authenticated on `cms.example.com`, `admin.example.com`, and `www.example.com` — no additional setup needed. Apex aliases (e.g. `example.com` listed under `aliasDomains`) are recognized as already being the parent — they don't break shared-parent equality.\n\n## Compile-Time Feature Gating\n\nWhen the compiler builds the Account SPA, it excludes route files for disabled features **before** the Vite build. This means disabled features never appear in the JavaScript bundle.\n\n| Feature Flag | Routes Excluded When `false` |\n|-------------|------------------------------|\n| `auth.organizations` | Dashboard, organization CRUD, org switching (`$slug`) |\n| `auth.passkey` | Passkey management and setup |\n| `auth.admin` | Admin panel routes |\n\nThis keeps bundle sizes minimal and prevents dead code in production. Users can't access disabled features even if they navigate to the URL directly — the routes don't exist in the build.\n\n## Hostname Routing Details\n\nThe compiler generates middleware that checks `new URL(c.req.url).hostname` on every request:\n\n**CMS domain** — Blocks API routes with 404. All other paths are mapped to the `/cms/` asset prefix and served with SPA fallback to `/cms/index.html`.\n\n**Account/Admin domain** — API and auth routes (`/api/`, `/auth/`, `/admin/`, `/storage/`, `/health`) pass through to Hono handlers. All other paths are mapped to the `/account/` asset prefix and served with SPA fallback to `/account/index.html`.\n\n**App domain** — Identical to Account: API/auth/admin/storage/health pass through, other paths map to `/<assetsDir>/` with SPA fallback. The multi-domain catchall (emitted when both CMS and Account are configured) explicitly skips app hostnames, so an API miss on an app host lands in `app.notFound` (404 JSON) instead of stray-serving a sibling SPA's HTML.\n\n**Unified domain** — No hostname filtering. CMS is served at `/cms/`, Account at `/account/`. Root (`/`) redirects to `/cms/`. API routes work at their standard paths.\n\n## Without Custom Domains\n\nIf you enable `cms` and `account` without custom domains, everything is served on a single domain:\n\n- CMS at `/cms/` (root `/` redirects to `/cms/`)\n- Account UI at `/account/`\n- API at `/api/v1/`\n- Auth at `/auth/`\n\nThis is the simplest setup — no DNS configuration needed, no cross-subdomain cookies. Auth cookies work naturally because everything is same-origin.\n\n## See Also\n\n- [Configuration](/compiler/config) — CMS and Account config options\n- [Output Structure](/compiler/config/output) — Generated file and directory layout\n- [CMS](/stack/cms) — Schema-driven admin interface\n- [Account UI](/stack/account-ui) — Authentication and account management"
|
|
50
|
+
"content": "A single Quickback-compiled Cloudflare Worker can serve your API, CMS, Account UI, Admin panel, and your own product SPAs on separate custom domains. The compiler generates hostname-based routing so each domain serves the right content.\n\n## How It Works\n\nWhen you configure custom domains for CMS, Account, Admin, or `apps`, the compiler:\n\n1. Adds `custom_domain` routes to `wrangler.toml`\n2. Generates hostname-based middleware in the Worker\n3. Auto-configures cross-subdomain cookies for shared authentication\n4. Auto-infers a unified `quickback.{baseDomain}` fallback domain\n\nAll configured domains point to the **same Worker** — there's only one deployment.\n\n## Domain Types\n\n| Domain | Config | Serves | API Routes |\n|--------|--------|--------|-----------|\n| `api.example.com` | `providers.runtime.config.routes` | API only | All |\n| `cms.example.com` | `cms: { domain }` | CMS SPA | Blocked (404) |\n| `auth.example.com` | `account: { domain }` | Account SPA | Pass-through |\n| `admin.example.com` | `account: { adminDomain }` | Account SPA | Pass-through |\n| `www.example.com` | `apps: { <name>: { domain } }` | User-authored SPA | Pass-through |\n| `quickback.example.com` | Auto-inferred | Everything | All |\n\n### CMS Domain\n\nServes the CMS SPA at root (`/`). API routes (`/api/`, `/auth/`, `/admin/`, `/storage/`, `/health`) return 404 — preventing direct API access on the CMS domain.\n\n### Account Domain\n\nServes the Account SPA at root (`/`). API and auth routes pass through to the Worker so authentication flows work directly on this domain.\n\n### Admin Domain\n\nIdentical behavior to the Account domain — serves the same Account SPA at root. The Account SPA's client-side router handles the `/admin` route, restricting access to users with the `admin` role.\n\n### App Domains\n\nMount your own product SPAs on dedicated hostnames via the `apps` field. Each entry binds one or more hostnames to a directory under `src/apps/<name>/` and inherits the same API/auth pass-through behavior as the Account domain — so the SPA can hit `/api/v1/...` and `/auth/...` same-origin without CORS.\n\n```typescript\napps: {\n www: {\n domain: \"www.example.com\",\n aliasDomains: [\"example.com\"], // apex serves the same SPA\n },\n marketing: {\n domain: \"marketing.example.com\",\n },\n}\n```\n\n| Option | Required | Description |\n|--------|----------|-------------|\n| `domain` | Yes | Primary custom hostname served at root (`/`) |\n| `aliasDomains` | No | Additional hostnames that serve the same SPA. Each gets its own `custom_domain = true` route. Common case: apex (`example.com`) alongside `www.example.com`. |\n| `assetsDir` | No | Subdirectory under `src/apps/` to serve from. Defaults to the record key. Override only when the on-disk directory needs to differ from the URL-facing name. |\n\nDrop the prebuilt SPA output at `quickback/apps/<name>/` — the source-apps passthrough copies it byte-for-byte into `src/apps/<name>/` on every compile. The compiler doesn't build the SPA; it just emits routing for whatever's already there. See [Output Structure](/compiler/config/output#source-apps-quickbackapps) for the passthrough rules.\n\nThe names `cms`, `account`, and `public` are reserved (they collide with compiler-emitted directories under `src/apps/`). Two app entries can't claim the same hostname, and an app's hostname can't collide with `cms.domain` / `account.domain` / `account.adminDomain`.\n\n### Unified Domain\n\nThe compiler auto-infers a `quickback.{baseDomain}` domain from your configured custom domains. For example, if you have `cms.example.com`, it creates `quickback.example.com`.\n\nOn this domain, **everything is available** on a single origin:\n\n| Path | Content |\n|------|---------|\n| `/` | Redirects to `/cms/` |\n| `/cms/` | CMS SPA |\n| `/account/` | Account SPA |\n| `/api/v1/...` | API routes |\n| `/auth/...` | Auth routes |\n| `/admin/...` | Admin API routes |\n| `/storage/...` | File storage |\n| `/health` | Health check |\n| `/openapi.json` | OpenAPI spec |\n\nThe unified domain is useful for development and debugging. You can override it with an explicit `domain` field in your config.\n\n## Configuration\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default {\n name: \"my-app\",\n template: \"hono\",\n cms: { domain: \"cms.example.com\", access: \"admin\" },\n account: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n auth: { password: true, admin: true },\n },\n apps: {\n www: {\n domain: \"www.example.com\",\n aliasDomains: [\"example.com\"],\n },\n },\n providers: {\n runtime: { name: \"cloudflare\", config: {\n routes: [{ pattern: \"api.example.com\", custom_domain: true }],\n }},\n // ...database, auth\n },\n};\n```\n\n`trustedOrigins` is optional here — every `cms.domain`, `account.domain`, `account.adminDomain`, and `apps[*].domain` (plus aliases) is automatically added. Declare `trustedOrigins` only when you need to allow an origin the compiler can't infer (e.g. a third-party domain).\n\nThis generates the following `wrangler.toml` routes:\n\n```toml\nroutes = [\n { pattern = \"api.example.com\", custom_domain = true },\n { pattern = \"cms.example.com\", custom_domain = true },\n { pattern = \"auth.example.com\", custom_domain = true },\n { pattern = \"admin.example.com\", custom_domain = true },\n { pattern = \"www.example.com\", custom_domain = true },\n { pattern = \"example.com\", custom_domain = true },\n { pattern = \"quickback.example.com\", custom_domain = true }\n]\n```\n\n## Cross-Subdomain Authentication\n\nWhen two or more custom domains share a parent domain (e.g., `cms.example.com` + `auth.example.com` + `www.example.com`), the compiler automatically configures Better Auth for cross-subdomain cookie sharing. App hostnames (primary + aliases) are folded into the shared-parent detection alongside the CMS, Account, Admin, and top-level `domain` slots:\n\n- Sets `crossSubDomainCookies: { enabled: true, domain: '.example.com' }`\n- Sets `sameSite: 'none'` and `secure: true` on auth cookies\n\nThis means a user who logs in on `auth.example.com` is automatically authenticated on `cms.example.com`, `admin.example.com`, and `www.example.com` — no additional setup needed. Apex aliases (e.g. `example.com` listed under `aliasDomains`) are recognized as already being the parent — they don't break shared-parent equality.\n\n## Compile-Time Feature Gating\n\nWhen the compiler builds the Account SPA, it excludes route files for disabled features **before** the Vite build. This means disabled features never appear in the JavaScript bundle.\n\n| Feature Flag | Routes Excluded When `false` |\n|-------------|------------------------------|\n| `auth.organizations` | Dashboard, organization CRUD, org switching (`$slug`) |\n| `auth.passkey` | Passkey management and setup |\n| `auth.admin` | Admin panel routes |\n\nThis keeps bundle sizes minimal and prevents dead code in production. Users can't access disabled features even if they navigate to the URL directly — the routes don't exist in the build.\n\n## Hostname Routing Details\n\nThe compiler generates middleware that checks `new URL(c.req.url).hostname` on every request:\n\n**CMS domain** — Blocks API routes with 404. All other paths are mapped to the `/cms/` asset prefix and served with SPA fallback to `/cms/index.html`.\n\n**Account/Admin domain** — API and auth routes (`/api/`, `/auth/`, `/admin/`, `/storage/`, `/health`) pass through to Hono handlers. All other paths are mapped to the `/account/` asset prefix and served with SPA fallback to `/account/index.html`.\n\n**App domain** — Identical to Account: API/auth/admin/storage/health pass through, other paths map to `/<assetsDir>/` with SPA fallback. The multi-domain catchall (emitted when both CMS and Account are configured) explicitly skips app hostnames, so an API miss on an app host lands in `app.notFound` (404 JSON) instead of stray-serving a sibling SPA's HTML.\n\n**Unified domain** — No hostname filtering. CMS is served at `/cms/`, Account at `/account/`. Root (`/`) redirects to `/cms/`. API routes work at their standard paths.\n\n## Without Custom Domains\n\nIf you enable `cms` and `account` without custom domains, everything is served on a single domain:\n\n- CMS at `/cms/` (root `/` redirects to `/cms/`)\n- Account UI at `/account/`\n- API at `/api/v1/`\n- Auth at `/auth/`\n\nThis is the simplest setup — no DNS configuration needed, no cross-subdomain cookies. Auth cookies work naturally because everything is same-origin.\n\n## Preview Deploys\n\nThe same compiled bundle can be deployed to additional hostnames — preview environments, staging, per-PR URLs — without recompiling. Set the `EXTRA_APP_HOSTS` env var on the deploy target (a comma-separated list of hostnames) and the worker treats each one like an entry in `apps[*].domain`:\n\n- Apps hostname middleware serves the SPA at root.\n- CORS / Better Auth `trustedOrigins` trusts requests whose `Origin` hostname matches.\n\nEmpty or unset means no extension and zero behavior change for production.\n\n```toml title=\"wrangler.preview.toml\"\n[vars]\nEXTRA_APP_HOSTS = \"app-preview.example.com,pr-42.example.com\"\n```\n\n```bash\n# Or set as a secret per deploy target\nwrangler secret put EXTRA_APP_HOSTS --env preview\n```\n\nMirrors the existing `BETTER_AUTH_URL` auto-trust behavior, where the deployed worker auto-trusts its own configured base origin without needing an explicit `trustedOrigins` entry. With `EXTRA_APP_HOSTS`, one env var extends both the apps allowlist and the CORS allowlist.\n\n## See Also\n\n- [Configuration](/compiler/config) — CMS and Account config options\n- [Output Structure](/compiler/config/output) — Generated file and directory layout\n- [CMS](/stack/cms) — Schema-driven admin interface\n- [Account UI](/stack/account-ui) — Authentication and account management"
|
|
51
51
|
},
|
|
52
52
|
"compiler/config": {
|
|
53
53
|
"title": "Configuration",
|
|
54
|
-
"content": "The `quickback.config.ts` file configures your Quickback project. It defines which providers to use, which features to enable, and how the compiler generates code.\n\n```typescript\n\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n features: { organizations: true },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## Discoverable options block\n\nAfter your first `quickback compile`, the file gets a managed block bracketed by sentinel comments:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: cloudflare({}),\n\n // [quickback:options-start]\n // ── Project ──\n //\n // Primary custom domain (auto-inferred from cms/account/api domains if unset).\n // domain: \"example.com\",\n //\n // ── Embedded UIs (CMS / Account) ──\n //\n // Login/signup/profile/orgs SPA. Set `true` for default, or object to customize.\n // account: {\n // fileUploads: false, // show the avatar upload UI on the profile page\n // auth: { passkey: false, emailOTP: false, ... },\n // ...\n // },\n //\n // ... every other option Quickback supports\n // [quickback:options-end]\n});\n```\n\nThis block is **regenerated on every compile** — the compiler is the source of truth, so newly added options surface automatically when you upgrade Quickback (no CLI bump needed).\n\n**To enable an option**, copy the line you care about *above* the `[quickback:options-start]` sentinel and uncomment it:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: cloudflare({}),\n\n account: {\n fileUploads: true, // ← lifted out of the managed block\n },\n\n // [quickback:options-start]\n // ... account is now omitted from this block on next compile\n // [quickback:options-end]\n});\n```\n\nQuickback notices that `account` is set above the marker and drops it from the managed block on the next compile to avoid duplicate definitions. Anything outside the marker block is yours and never touched.\n\nIf you ever want to opt out of the auto-managed block, run:\n\n```bash\nquickback compile --no-sync-config\n```\n\n## Required Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `name` | `string` | Project name |\n| `template` | `\"hono\"` | Application template (`\"nextjs\"` is experimental) |\n| `providers` | `object` | Runtime, database, and auth provider configuration |\n\n## Optional Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `features` | `object` | Feature flags — see [Single-Tenant Mode](/compiler/config/single-tenant) |\n| `build` | `object` | Build options (`outputDir`, `packageManager`, `dependencies`) |\n| `compiler` | `object` | Compiler options — `features.auditFields: false` disables audit field injection project-wide; `migrations.renames` provides rename hints for headless CI; `securityContracts` tunes the route/SQL invariants checker |\n| `openapi` | `object` | OpenAPI spec generation (`generate`, `publish`, `docs: 'scalar' \\| 'swagger'` for an in-browser API reference) — see [OpenAPI](/compiler/targets/hono-api/using-the-api/openapi) |\n| `schemaRegistry` | `object` | Schema registry generation for the CMS (enabled by default, `{ generate: false }` to disable) — see [Schema Registry](/stack/cms/schema-registry) |\n| `etag` | `object` | ETag caching for GET responses (enabled by default, `{ enabled: false }` to disable) — see [Caching & ETags](/compiler/targets/hono-api/using-the-api/caching) |\n| `cms` | `boolean \\| object` | Embed CMS in compiled Worker — see [CMS](/stack/cms) |\n| `account` | `boolean \\| object` | Embed Account UI in compiled Worker — see [Account UI](/stack/account-ui) |\n| `trustedOrigins` | `string[]` | CORS trusted origins for cross-domain auth |\n| `domain` | `string` | Primary API domain (auto-inferred from custom domains if not set) |\n| `dev` | `object` | Local development settings (`port`) |\n| `auth` | `object` | App-level auth settings (`roleHierarchy`) — see [Access](/compiler/definitions/access#role-hierarchy) |\n| `email` | `object` | Email delivery config (`provider`, `from`, `fromName`) |\n\n## Custom Dependencies\n\nAdd third-party npm packages to the generated `package.json` using `build.dependencies`. This is useful when your action handlers import external libraries.\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n build: {\n dependencies: {\n \"fast-xml-parser\": \"^4.5.0\",\n \"lodash-es\": \"^4.17.21\",\n },\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\nThese are merged into the generated `package.json` alongside Quickback's own dependencies. Run `npm install` after compiling to install them.\n\n## Headless Migration Rename Hints\n\nWhen `drizzle-kit generate` detects a potential rename, it normally prompts for confirmation. Cloud/CI compiles are non-interactive, so you must provide explicit rename hints.\n\nAdd hints in `compiler.migrations.renames`:\n\n```typescript\nexport default defineConfig({\n // ...\n compiler: {\n migrations: {\n renames: {\n // Keys are NEW names, values are OLD names\n tables: {\n events_v2: \"events\",\n },\n columns: {\n events: {\n summary_text: \"summary\",\n },\n },\n },\n },\n },\n});\n```\n\nRules:\n- `tables`: `new_table_name -> old_table_name`\n- `columns.<table>`: `new_column_name -> old_column_name`\n- Keys must match the names in your current schema (the new names)\n- Validation fails fast for malformed rename config, unsupported keys, or conflicting legacy/new rename paths.\n\n## Disable Audit Field Injection\n\nBy default, Quickback auto-injects four **audit fields** (`createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`) into every feature table, plus two **soft-delete fields** (`deletedAt`, `deletedBy`) into tables that use soft delete (the default delete mode). The audit fields drive record-provenance queries and the CMS audit panel; the soft-delete pair drives soft-delete filtering.\n\nTo opt out project-wide:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n compiler: {\n features: {\n auditFields: false, // skip audit-field injection globally\n },\n },\n providers: { /* ... */ },\n});\n```\n\nWhen disabled, you're responsible for supplying these columns yourself if you want soft delete, audit trails, or modifiedAt-based optimistic concurrency. See the [Schema → Audit Fields](/compiler/definitions/schema#audit-fields) section for the full list and what each field drives.\n\n## Security Contract Reports and Signing\n\nAfter generation, Quickback verifies machine-checkable security contracts for Hono routes and RLS SQL.\n\nIt also emits a report artifact and signature artifact by default:\n\n- `reports/security-contracts.report.json`\n- `reports/security-contracts.report.sig.json`\n\nYou can configure output paths and signing behavior:\n\n```typescript\nexport default defineConfig({\n // ...\n compiler: {\n securityContracts: {\n failMode: \"error\", // or \"warn\"\n report: {\n path: \"reports/security-contracts.report.json\",\n signature: {\n enabled: true,\n required: true,\n keyEnv: \"QUICKBACK_SECURITY_REPORT_SIGNING_KEY\",\n keyId: \"prod-k1\",\n path: \"reports/security-contracts.report.sig.json\",\n },\n },\n },\n },\n});\n```\n\nIf `signature.required: true` and no key is available, compilation fails with a clear error message (or warning in `failMode: \"warn\"`).\n\n## CMS Configuration\n\nEmbed the [Quickback CMS](/stack/cms) in your compiled Worker. The CMS reads your schema registry and renders a complete admin interface — zero UI code per table.\n\n```typescript\n// Simple — embed CMS at root\ncms: true,\n\n// With custom domain\ncms: { domain: \"cms.example.com\" },\n\n// With access control (only admins can access CMS)\ncms: { domain: \"cms.example.com\", access: \"admin\" },\n\n// Cross-tenant DB-admin tier — sysadmins see every tenant's data\ncms: { domain: \"cms.example.com\", sysadmin: true },\n```\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `domain` | `string` | — | Custom domain for CMS. Adds a `custom_domain` route to `wrangler.toml`. |\n| `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. |\n| `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). |\n\n### Sysadmin tier (`cms.sysadmin: true`)\n\nQuickback'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.\n\n`cms: { sysadmin: true }` introduces a separate role tier:\n\n- **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.\n- **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).\n- **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.\n- **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.\n- **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.\n\nOff 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.\n\n## Account UI Configuration\n\nEmbed the [Account UI](/stack/account-ui) in your compiled Worker. Provides login, signup, profile management, organization management, and admin — all built from your config at compile time.\n\nFor post-signup logic — auto-provisioning a workspace, gating signup, setting an active organization — drop a file in `quickback/hooks/`. See [Auth Hooks](/stack/account-ui/hooks).\n\n```typescript\n// Simple — embed Account UI with defaults\naccount: true,\n\n// Full configuration\naccount: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n companyName: \"My Company\",\n auth: {\n password: true,\n emailOTP: false,\n passkey: true,\n organizations: true,\n admin: true,\n },\n},\n```\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `domain` | `string` | Custom domain for Account UI (e.g., `auth.example.com`) |\n| `adminDomain` | `string` | Custom domain for admin-only access (e.g., `admin.example.com`). Serves the same Account SPA — the client-side router handles admin routing. |\n| `appUrl` | `string` | URL of the tenant's main application — where users are redirected after login. Baked into the Account SPA as `VITE_QUICKBACK_APP_URL`. Independent from `domain`. |\n| `name` | `string` | App display name shown on login, profile, and email templates |\n| `companyName` | `string` | Company name for branding |\n| `tagline` | `string` | App tagline shown on login page |\n| `description` | `string` | App description |\n\n### Auth Feature Flags\n\nControl which authentication features are exposed. Disabled features are excluded from the Account UI bundle at compile time (routes removed before the Vite build, keeping bundle sizes minimal) **and** enforced on the server side via the Better Auth config — so \"signup off\" actually closes `POST /auth/v1/sign-up/email`, not just the SPA's signup screen.\n\n`account.auth.*` is a shorthand for `providers.auth.config` — the compiler maps each flag onto the Better Auth server config before any code is generated. You can write either side directly; setting both incompatibly (e.g. `account.auth.signup: false` and `emailAndPassword.disableSignUp: false`) fails the compile with a precise error rather than picking a silent winner.\n\n| Flag | Type | Default | Maps to (server) | Description |\n|------|------|---------|------------------|-------------|\n| `auth.password` | `boolean` | `true` | `emailAndPassword.enabled` | Email/password authentication — both server endpoint and UI |\n| `auth.emailOTP` | `boolean` | `false` | adds `emailOtp` plugin | Email one-time password login — adds plugin server-side, surfaces UI |\n| `auth.passkey` | `boolean` | `false` | adds `passkey` plugin | WebAuthn/FIDO2 passkey authentication — adds plugin server-side, surfaces UI |\n| `auth.signup` | `boolean` | `true` | `emailAndPassword.disableSignUp` (inverted) | Self-service account registration — false hides the UI **and** rejects the server endpoint with 403 |\n| `auth.organizations` | `boolean` | `false` | UI surface only — server gating lives under `features.organizations` | Multi-tenant organization management UI (dashboard, invitations, roles). The BA `organization` plugin is auto-added by `features.organizations` for server-side reasons (org tables) independent of this UI flag |\n| `auth.admin` | `boolean` | `false` | UI surface only — BA `admin` plugin is auto-added when `features.organizations` is on | Admin panel for user management in the Account SPA |\n| `auth.emailVerification` | `boolean` | `false` | `emailAndPassword.requireEmailVerification` | Require email verification before sessions are issued. False = sessions usable immediately after signup |\n\n## Trusted Origins\n\nList of origins allowed to make cross-origin requests to your API. Required when your CMS, Account UI, or frontend app run on different domains.\n\n```typescript\ntrustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n \"https://cms.example.com\",\n \"https://app.example.com\",\n],\n```\n\n## Local Development\n\nConfigure local development URLs. These are automatically added to the trusted origins list for CORS and Better Auth, so authentication works out of the box during local development.\n\n```typescript\ndev: {\n port: 8787, // wrangler dev port (default: 8787)\n api: \"http://localhost:8787\", // API backend URL\n cms: \"http://localhost:8787/cms\", // CMS URL (path on same worker)\n account: \"http://localhost:8787/account\", // Account URL (path on same worker)\n},\n```\n\nIf you run a SPA standalone on its own Vite dev server, set its URL here so CORS allows it:\n\n```typescript\ndev: {\n port: 8787,\n api: \"http://localhost:8787\",\n account: \"http://localhost:5173\", // standalone Account dev server\n},\n```\n\n| Field | Type | Default | Description |\n|-------|------|---------|-------------|\n| `port` | `number` | `8787` | Local dev server port (sets `[dev].port` in wrangler.toml) |\n| `api` | `string` | `http://localhost:{port}` | API backend URL |\n| `cms` | `string` | — | CMS dev URL (added to trusted origins if set) |\n| `account` | `string` | — | Account dev URL (added to trusted origins if set) |\n\n## Email Configuration\n\nConfigure email delivery for authentication emails (verification, password reset, invitations).\n\n> **Cloudflare Email Sending is now in public beta** and is Quickback's default transport for Cloudflare deploys. The Workers `send_email` binding is zero-config — no API keys, no third-party accounts. AWS SES remains supported as an explicit opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes or existing SES setups.\n\n```typescript\n// Cloudflare Email Service (default) — uses send_email binding, no API keys needed\nemail: {\n from: \"noreply@example.com\",\n fromName: \"My App\",\n},\n\n// AWS SES — requires AWS credentials set as Wrangler secrets\nemail: {\n provider: \"aws-ses\",\n region: \"us-east-2\",\n from: \"noreply@example.com\",\n fromName: \"My App\",\n},\n```\n\n| Field | Type | Default | Description |\n|-------|------|---------|-------------|\n| `provider` | `\"cloudflare\" \\| \"aws-ses\"` | `\"cloudflare\"` | Email transport |\n| `from` | `string` | `\"noreply@example.com\"` | Sender email address |\n| `fromName` | `string` | `\"{name} \\| Account Services\"` | Sender display name |\n| `region` | `string` | `\"us-east-2\"` | AWS SES region (aws-ses only) |\n\n### Auto-wiring\n\nFor the Cloudflare provider (the default), the compiler automatically:\n- Emits `[[send_email]] EMAIL` into `wrangler.toml`\n- Generates `src/lib/cloudflare-email.ts`\n- Wires `sendResetPassword`, `sendVerificationEmail`, `sendInvitationEmail`, etc. into Better Auth\n\n…whenever any auth surface needs to send mail — `emailAndPassword.enabled`, the `emailOtp` / `magicLink` / `organization` plugins — or you set the top-level `email: {…}` config. You don't need to add `bindings.sendEmail` by hand for the standard cases.\n\n> **Cloudflare Email Routing setup is required.** The binding alone does not deliver mail. Enable Email Routing on the sending zone and add at least one verified destination address ([Cloudflare docs](https://developers.cloudflare.com/email-routing/get-started/)). Otherwise sends fail at runtime even with the binding present and the `/auth/v1/ses/status` check passing locally.\n\n## Multi-Domain Example\n\nA complete config with CMS, Account UI, and Admin on separate subdomains:\n\n```typescript\nexport default {\n name: \"my-app\",\n template: \"hono\",\n cms: { domain: \"cms.example.com\", access: \"admin\" },\n account: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n companyName: \"Example Inc.\",\n auth: {\n password: true,\n emailOTP: false,\n passkey: true,\n organizations: false,\n admin: true,\n },\n },\n email: {\n from: \"noreply@example.com\",\n fromName: \"My App\",\n },\n trustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n \"https://cms.example.com\",\n \"https://example.com\",\n ],\n providers: {\n runtime: { name: \"cloudflare\", config: {\n routes: [{ pattern: \"api.example.com\", custom_domain: true }],\n }},\n database: { name: \"cloudflare-d1\", config: { binding: \"DB\" } },\n auth: { name: \"better-auth\", config: { plugins: [\"admin\"] } },\n },\n};\n```\n\nThis produces a single Cloudflare Worker serving five domains. See [Multi-Domain Architecture](/compiler/config/domains) for details on hostname routing, cross-subdomain cookies, and the unified fallback domain.\n\n---\n\nSee the sub-pages for detailed reference on each section:\n- [Providers](/compiler/config/providers) — Runtime, database, and auth options\n- [Variables](/compiler/config/variables) — Environment variables and flags\n- [Output](/compiler/config/output) — Generated file structure\n- [Single-Tenant Mode](/compiler/config/single-tenant) — Admin-only and public-facing apps without organizations\n- [Multi-Domain Architecture](/compiler/config/domains) — Custom domains, hostname routing, and cross-subdomain auth"
|
|
54
|
+
"content": "The `quickback.config.ts` file configures your Quickback project. It defines which providers to use, which features to enable, and how the compiler generates code.\n\n```typescript\n\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n features: { organizations: true },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## Discoverable options block\n\nAfter your first `quickback compile`, the file gets a managed block bracketed by sentinel comments:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: cloudflare({}),\n\n // [quickback:options-start]\n // ── Project ──\n //\n // Primary custom domain (auto-inferred from cms/account/api domains if unset).\n // domain: \"example.com\",\n //\n // ── Embedded UIs (CMS / Account) ──\n //\n // Login/signup/profile/orgs SPA. Set `true` for default, or object to customize.\n // account: {\n // fileUploads: false, // show the avatar upload UI on the profile page\n // auth: { passkey: false, emailOTP: false, ... },\n // ...\n // },\n //\n // ... every other option Quickback supports\n // [quickback:options-end]\n});\n```\n\nThis block is **regenerated on every compile** — the compiler is the source of truth, so newly added options surface automatically when you upgrade Quickback (no CLI bump needed).\n\n**To enable an option**, copy the line you care about *above* the `[quickback:options-start]` sentinel and uncomment it:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: cloudflare({}),\n\n account: {\n fileUploads: true, // ← lifted out of the managed block\n },\n\n // [quickback:options-start]\n // ... account is now omitted from this block on next compile\n // [quickback:options-end]\n});\n```\n\nQuickback notices that `account` is set above the marker and drops it from the managed block on the next compile to avoid duplicate definitions. Anything outside the marker block is yours and never touched.\n\nIf you ever want to opt out of the auto-managed block, run:\n\n```bash\nquickback compile --no-sync-config\n```\n\n## Required Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `name` | `string` | Project name |\n| `template` | `\"hono\"` | Application template (`\"nextjs\"` is experimental) |\n| `providers` | `object` | Runtime, database, and auth provider configuration |\n\n## Optional Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `features` | `object` | Feature flags — see [Single-Tenant Mode](/compiler/config/single-tenant) |\n| `build` | `object` | Build options (`outputDir`, `packageManager`, `dependencies`) |\n| `compiler` | `object` | Compiler options — `features.auditFields: false` disables audit field injection project-wide; `migrations.renames` provides rename hints for headless CI; `securityContracts` tunes the route/SQL invariants checker |\n| `openapi` | `object` | OpenAPI spec generation (`generate`, `publish`, `docs: 'scalar' \\| 'swagger'` for an in-browser API reference) — see [OpenAPI](/compiler/targets/hono-api/using-the-api/openapi) |\n| `schemaRegistry` | `object` | Schema registry generation for the CMS (enabled by default, `{ generate: false }` to disable) — see [Schema Registry](/stack/cms/schema-registry) |\n| `etag` | `object` | ETag caching for GET responses (enabled by default, `{ enabled: false }` to disable) — see [Caching & ETags](/compiler/targets/hono-api/using-the-api/caching) |\n| `cms` | `boolean \\| object` | Embed CMS in compiled Worker — see [CMS](/stack/cms) |\n| `account` | `boolean \\| object` | Embed Account UI in compiled Worker — see [Account UI](/stack/account-ui) |\n| `trustedOrigins` | `string[]` | CORS trusted origins for cross-domain auth |\n| `domain` | `string` | Primary API domain (auto-inferred from custom domains if not set) |\n| `dev` | `object` | Local development settings (`port`) |\n| `auth` | `object` | App-level auth settings (`roleHierarchy`) — see [Access](/compiler/definitions/access#role-hierarchy) |\n| `email` | `object` | Email delivery config (`provider`, `from`, `fromName`) |\n\n## Custom Dependencies\n\nAdd third-party npm packages to the generated `package.json` using `build.dependencies`. This is useful when your action handlers import external libraries.\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n build: {\n dependencies: {\n \"fast-xml-parser\": \"^4.5.0\",\n \"lodash-es\": \"^4.17.21\",\n },\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\nThese are merged into the generated `package.json` alongside Quickback's own dependencies. Run `npm install` after compiling to install them.\n\n## Headless Migration Rename Hints\n\nWhen `drizzle-kit generate` detects a potential rename, it normally prompts for confirmation. Cloud/CI compiles are non-interactive, so you must provide explicit rename hints.\n\nAdd hints in `compiler.migrations.renames`:\n\n```typescript\nexport default defineConfig({\n // ...\n compiler: {\n migrations: {\n renames: {\n // Keys are NEW names, values are OLD names\n tables: {\n events_v2: \"events\",\n },\n columns: {\n events: {\n summary_text: \"summary\",\n },\n },\n },\n },\n },\n});\n```\n\nRules:\n- `tables`: `new_table_name -> old_table_name`\n- `columns.<table>`: `new_column_name -> old_column_name`\n- Keys must match the names in your current schema (the new names)\n- Validation fails fast for malformed rename config, unsupported keys, or conflicting legacy/new rename paths.\n\n## Disable Audit Field Injection\n\nBy default, Quickback auto-injects four **audit fields** (`createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`) into every feature table, plus two **soft-delete fields** (`deletedAt`, `deletedBy`) into tables that use soft delete (the default delete mode). The audit fields drive record-provenance queries and the CMS audit panel; the soft-delete pair drives soft-delete filtering.\n\nTo opt out project-wide:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n compiler: {\n features: {\n auditFields: false, // skip audit-field injection globally\n },\n },\n providers: { /* ... */ },\n});\n```\n\nWhen disabled, you're responsible for supplying these columns yourself if you want soft delete, audit trails, or modifiedAt-based optimistic concurrency. See the [Schema → Audit Fields](/compiler/definitions/schema#audit-fields) section for the full list and what each field drives.\n\n## Security Contract Reports and Signing\n\nAfter generation, Quickback verifies machine-checkable security contracts for Hono routes and RLS SQL.\n\nIt also emits a report artifact and signature artifact by default:\n\n- `reports/security-contracts.report.json`\n- `reports/security-contracts.report.sig.json`\n\nYou can configure output paths and signing behavior:\n\n```typescript\nexport default defineConfig({\n // ...\n compiler: {\n securityContracts: {\n failMode: \"error\", // or \"warn\"\n report: {\n path: \"reports/security-contracts.report.json\",\n signature: {\n enabled: true,\n required: true,\n keyEnv: \"QUICKBACK_SECURITY_REPORT_SIGNING_KEY\",\n keyId: \"prod-k1\",\n path: \"reports/security-contracts.report.sig.json\",\n },\n },\n },\n },\n});\n```\n\nIf `signature.required: true` and no key is available, compilation fails with a clear error message (or warning in `failMode: \"warn\"`).\n\n## Hostname architecture (v0.33+)\n\nA modern Quickback project runs on **one Cloudflare Worker** that serves multiple URL surfaces. By default, everything lives under a single unified backend hostname (auto-inferred as `quickback.{baseDomain}` from your other configured subdomains, or overridable via `config.domain`). For larger deployments, you can opt-in to **dedicated hostnames** for specific surfaces — they're additive aliases, never replacements.\n\n### The unified backend contract\n\nWhen any subdomain is configured (`account.domain`, `cms.domain`, `auth.domain`, `api.domain`, `apps.<n>.domain`), the compiler always emits a unified backend host where **every compiler-emitted backend route** is reachable:\n\n- `/api/v1/*` — feature routes\n- `/auth/v1/*` — Better Auth\n- `/storage/*` — R2 file storage\n- `/health`, `/openapi.json` — monitoring/discovery\n- `/account/*`, `/cms/*` — bundled SPAs (when enabled)\n- `/broadcast/v1/*` (realtime), `/mcp` (MCP), etc.\n\nThe unified hostname is `quickback.{baseDomain}` by default (where baseDomain is extracted from your first configured subdomain). Override with `config.domain` if you prefer a different name.\n\nThis contract is forward-pointing: it gives a stable URL pattern for future management tooling — `https://quickback.{baseDomain}/...` will always reach a Quickback backend regardless of how the operator splits their surfaces.\n\n### Dedicated hostnames (optional, additive)\n\nFor branding or operational separation, you can opt specific surfaces onto their own hostnames:\n\n```ts\n{\n // Bundled SPAs on their own hosts (already-shipped pattern):\n cms: { domain: 'cms.example.com' },\n account: { domain: 'account.example.com' },\n\n // v0.33+ — backend surfaces on their own hosts:\n auth: { domain: 'auth.example.com' },\n api: { domain: 'api.example.com' },\n\n // User SPAs (existing pattern):\n apps: {\n www: { domain: 'app.example.com' },\n },\n}\n```\n\nOn a dedicated hostname, **the hostname IS the namespace** — the path drops the prefix that matches the hostname:\n\n| URL on dedicated host | Internally rewritten to | Notes |\n|---|---|---|\n| `https://api.example.com/v1/users` | `/api/v1/users` | Worker-entry rewriter prepends `/api` |\n| `https://auth.example.com/v1/sign-in/email` | `/auth/v1/sign-in/email` | Same shape with `/auth` |\n| `https://api.example.com/api/v1/users` | (unchanged) | Long form also accepted |\n| `https://api.example.com/auth/v1/sign-in` | **404** | Auth doesn't live on the API hostname |\n| `https://api.example.com/health` | (unchanged) | Explicit exception — monitoring agents expect `/health` everywhere |\n\nDual-reach is preserved on the unified host:\n\n| URL on unified host | Handler | Notes |\n|---|---|---|\n| `https://quickback.example.com/api/v1/users` | feature route | Works whether `api.domain` is set or not |\n| `https://quickback.example.com/auth/v1/sign-in/email` | Better Auth | Works whether `auth.domain` is set or not |\n| `https://quickback.example.com/v1/users` | **404** | Shortcut only applies on dedicated hostnames |\n\nEach dedicated hostname also:\n\n- Gets a `{ pattern, custom_domain: true }` route in `wrangler.toml` automatically\n- Joins `trustedOrigins` for CORS\n- Joins the cross-subdomain cookie inference (auto-enables `crossSubDomainCookies` when ≥2 same-parent subdomains are configured, so `auth.example.com` and `app.example.com` can share session cookies)\n- Joins CSP `connect-src` so SPAs can fetch from it\n\n### Why two URL shapes (Shape 1 vs Shape 2)\n\nIf you only want Better Auth to **advertise** itself on a different URL (e.g. so verification emails link to `auth.example.com` instead of the unified host), set the `BETTER_AUTH_URL` env var on the Worker — no code change required. BA generates outgoing URLs against that value. This is sufficient when the goal is branding email/OAuth callback URLs without changing where requests actually land.\n\n`auth.domain` (Shape 1, above) is the heavier option: it binds an actual hostname to the Worker, configures CORS/cookies/CSP for it, and adds the path-shortcut rewriter. Use it when you want the dedicated hostname as a real ingress, not just a label.\n\n## CMS Configuration\n\nEmbed the [Quickback CMS](/stack/cms) in your compiled Worker. The CMS reads your schema registry and renders a complete admin interface — zero UI code per table.\n\n```typescript\n// Simple — embed CMS at root\ncms: true,\n\n// With custom domain\ncms: { domain: \"cms.example.com\" },\n\n// With access control (only admins can access CMS)\ncms: { domain: \"cms.example.com\", access: \"admin\" },\n\n// Cross-tenant DB-admin tier — sysadmins see every tenant's data\ncms: { domain: \"cms.example.com\", sysadmin: true },\n```\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `domain` | `string` | — | Custom domain for CMS. Adds a `custom_domain` route to `wrangler.toml`. |\n| `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. |\n| `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 `/auth/v1/admin/list-organizations` endpoint (sibling of Better Auth's `/auth/v1/admin/list-users`, gated to sysadmin only), and the SPA's \"All organizations\" sentinel. The CMS HTML gate admits `userRole === \"sysadmin\"` alongside `\"admin\"`. Off by default. See [`SYSADMIN` pseudo-role](/compiler/definitions/access#sysadmin--cross-tenant-db-admin-tier). |\n\n### Sysadmin tier (`cms.sysadmin: true`)\n\nQuickback'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.\n\n`cms: { sysadmin: true }` introduces a separate role tier:\n\n- **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. The two roles are independent at the pseudo-role evaluator level: `ADMIN` admits `'admin'` only, `SYSADMIN` admits `'sysadmin'` only. Routes that need both write `access: { roles: ['ADMIN', 'SYSADMIN'] }` explicitly.\n- **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).\n- **Org listing**: a `GET /auth/v1/admin/list-organizations` endpoint selects directly from the auth-schema `organization` table — every row, every tenant. Sits under Better Auth's admin URL namespace (sibling of `/auth/v1/admin/list-users`) so the URL shape matches BA convention; the handler is Quickback-emitted and gated to `user.role === \"sysadmin\"` only. For the membership-bound caller's-orgs listing, use BA's own `/auth/v1/organization/list`.\n- **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.\n- **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.\n\nOff 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.\n\n## Account UI Configuration\n\nEmbed the [Account UI](/stack/account-ui) in your compiled Worker. Provides login, signup, profile management, organization management, and admin — all built from your config at compile time.\n\nFor post-signup logic — auto-provisioning a workspace, gating signup, setting an active organization — drop a file in `quickback/hooks/`. See [Auth Hooks](/stack/account-ui/hooks).\n\n```typescript\n// Simple — embed Account UI with defaults\naccount: true,\n\n// Full configuration\naccount: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n companyName: \"My Company\",\n auth: {\n password: true,\n emailOTP: false,\n passkey: true,\n organizations: true,\n admin: true,\n },\n},\n```\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `domain` | `string` | Custom domain for Account UI (e.g., `auth.example.com`) |\n| `adminDomain` | `string` | Custom domain for admin-only access (e.g., `admin.example.com`). Serves the same Account SPA — the client-side router handles admin routing. |\n| `appUrl` | `string` | URL of the tenant's main application — where users are redirected after login. Baked into the Account SPA as `VITE_QUICKBACK_APP_URL`. Independent from `domain`. |\n| `name` | `string` | App display name shown on login, profile, and email templates |\n| `companyName` | `string` | Company name for branding |\n| `tagline` | `string` | App tagline shown on login page |\n| `description` | `string` | App description |\n\n### Auth Feature Flags\n\nControl which authentication features are exposed. Disabled features are excluded from the Account UI bundle at compile time (routes removed before the Vite build, keeping bundle sizes minimal) **and** enforced on the server side via the Better Auth config — so \"signup off\" actually closes `POST /auth/v1/sign-up/email`, not just the SPA's signup screen.\n\n`account.auth.*` is a shorthand for `providers.auth.config` — the compiler maps each flag onto the Better Auth server config before any code is generated. You can write either side directly; setting both incompatibly (e.g. `account.auth.signup: false` and `emailAndPassword.disableSignUp: false`) fails the compile with a precise error rather than picking a silent winner.\n\n| Flag | Type | Default | Maps to (server) | Description |\n|------|------|---------|------------------|-------------|\n| `auth.password` | `boolean` | `true` | `emailAndPassword.enabled` | Email/password authentication — both server endpoint and UI |\n| `auth.emailOTP` | `boolean` | `false` | adds `emailOtp` plugin | Email one-time password login — adds plugin server-side, surfaces UI |\n| `auth.passkey` | `boolean` | `false` | adds `passkey` plugin | WebAuthn/FIDO2 passkey authentication — adds plugin server-side, surfaces UI |\n| `auth.signup` | `boolean` | `true` | `emailAndPassword.disableSignUp` (inverted) | Self-service account registration — false hides the UI **and** rejects the server endpoint with 403 |\n| `auth.organizations` | `boolean` | `false` | UI surface only — server gating lives under `features.organizations` | Multi-tenant organization management UI (dashboard, invitations, roles). The BA `organization` plugin is auto-added by `features.organizations` for server-side reasons (org tables) independent of this UI flag |\n| `auth.admin` | `boolean` | `false` | UI surface only — BA `admin` plugin is auto-added when `features.organizations` is on | Admin panel for user management in the Account SPA |\n| `auth.emailVerification` | `boolean` | `false` | `emailAndPassword.requireEmailVerification` | Require email verification before sessions are issued. False = sessions usable immediately after signup |\n\n## Trusted Origins\n\nList of origins allowed to make cross-origin requests to your API. Required when your CMS, Account UI, or frontend app run on different domains.\n\n```typescript\ntrustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n \"https://cms.example.com\",\n \"https://app.example.com\",\n],\n```\n\n## Local Development\n\nConfigure local development URLs. These are automatically added to the trusted origins list for CORS and Better Auth, so authentication works out of the box during local development.\n\n```typescript\ndev: {\n port: 8787, // wrangler dev port (default: 8787)\n api: \"http://localhost:8787\", // API backend URL\n cms: \"http://localhost:8787/cms\", // CMS URL (path on same worker)\n account: \"http://localhost:8787/account\", // Account URL (path on same worker)\n},\n```\n\nIf you run a SPA standalone on its own Vite dev server, set its URL here so CORS allows it:\n\n```typescript\ndev: {\n port: 8787,\n api: \"http://localhost:8787\",\n account: \"http://localhost:5173\", // standalone Account dev server\n},\n```\n\n| Field | Type | Default | Description |\n|-------|------|---------|-------------|\n| `port` | `number` | `8787` | Local dev server port (sets `[dev].port` in wrangler.toml) |\n| `api` | `string` | `http://localhost:{port}` | API backend URL |\n| `cms` | `string` | — | CMS dev URL (added to trusted origins if set) |\n| `account` | `string` | — | Account dev URL (added to trusted origins if set) |\n\n## Email Configuration\n\nConfigure email delivery for authentication emails (verification, password reset, invitations).\n\n> **Cloudflare Email Sending is now in public beta** and is Quickback's default transport for Cloudflare deploys. The Workers `send_email` binding is zero-config — no API keys, no third-party accounts. AWS SES remains supported as an explicit opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes or existing SES setups.\n\n```typescript\n// Cloudflare Email Service (default) — uses send_email binding, no API keys needed\nemail: {\n from: \"noreply@example.com\",\n fromName: \"My App\",\n},\n\n// AWS SES — requires AWS credentials set as Wrangler secrets\nemail: {\n provider: \"aws-ses\",\n region: \"us-east-2\",\n from: \"noreply@example.com\",\n fromName: \"My App\",\n},\n```\n\n| Field | Type | Default | Description |\n|-------|------|---------|-------------|\n| `provider` | `\"cloudflare\" \\| \"aws-ses\"` | `\"cloudflare\"` | Email transport |\n| `from` | `string` | `\"noreply@example.com\"` | Sender email address |\n| `fromName` | `string` | `\"{name} \\| Account Services\"` | Sender display name |\n| `region` | `string` | `\"us-east-2\"` | AWS SES region (aws-ses only) |\n\n### Auto-wiring\n\nFor the Cloudflare provider (the default), the compiler automatically:\n- Emits `[[send_email]] EMAIL` into `wrangler.toml`\n- Generates `src/lib/cloudflare-email.ts`\n- Wires `sendResetPassword`, `sendVerificationEmail`, `sendInvitationEmail`, etc. into Better Auth\n\n…whenever any auth surface needs to send mail — `emailAndPassword.enabled`, the `emailOtp` / `magicLink` / `organization` plugins — or you set the top-level `email: {…}` config. You don't need to add `bindings.sendEmail` by hand for the standard cases.\n\n> **Cloudflare Email Routing setup is required.** The binding alone does not deliver mail. Enable Email Routing on the sending zone and add at least one verified destination address ([Cloudflare docs](https://developers.cloudflare.com/email-routing/get-started/)). Otherwise sends fail at runtime even with the binding present and the `/auth/v1/ses/status` check passing locally.\n\n## Multi-Domain Example\n\nA complete config with CMS, Account UI, and Admin on separate subdomains:\n\n```typescript\nexport default {\n name: \"my-app\",\n template: \"hono\",\n cms: { domain: \"cms.example.com\", access: \"admin\" },\n account: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n companyName: \"Example Inc.\",\n auth: {\n password: true,\n emailOTP: false,\n passkey: true,\n organizations: false,\n admin: true,\n },\n },\n email: {\n from: \"noreply@example.com\",\n fromName: \"My App\",\n },\n trustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n \"https://cms.example.com\",\n \"https://example.com\",\n ],\n providers: {\n runtime: { name: \"cloudflare\", config: {\n routes: [{ pattern: \"api.example.com\", custom_domain: true }],\n }},\n database: { name: \"cloudflare-d1\", config: { binding: \"DB\" } },\n auth: { name: \"better-auth\", config: { plugins: [\"admin\"] } },\n },\n};\n```\n\nThis produces a single Cloudflare Worker serving five domains. See [Multi-Domain Architecture](/compiler/config/domains) for details on hostname routing, cross-subdomain cookies, and the unified fallback domain.\n\n---\n\nSee the sub-pages for detailed reference on each section:\n- [Providers](/compiler/config/providers) — Runtime, database, and auth options\n- [Variables](/compiler/config/variables) — Environment variables and flags\n- [Output](/compiler/config/output) — Generated file structure\n- [Single-Tenant Mode](/compiler/config/single-tenant) — Admin-only and public-facing apps without organizations\n- [Multi-Domain Architecture](/compiler/config/domains) — Custom domains, hostname routing, and cross-subdomain auth"
|
|
55
55
|
},
|
|
56
56
|
"compiler/config/output": {
|
|
57
57
|
"title": "Output Structure",
|
|
@@ -67,7 +67,7 @@ export const DOCS = {
|
|
|
67
67
|
},
|
|
68
68
|
"compiler/config/single-tenant": {
|
|
69
69
|
"title": "Single-Tenant Mode",
|
|
70
|
-
"content": "Single-tenant mode disables the Better Auth organization plugin, removing the `organizationId` requirement from your API. This is ideal for personal sites, blogs, admin panels, or any app with a single tenant.\n\n## Enabling Single-Tenant Mode\n\nSet `features.organizations` to `false` in your config:\n\n```typescript\n\nexport default defineConfig({\n name: \"my-site\",\n template: \"hono\",\n features: {\n organizations: false,\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## What Changes\n\n| Aspect | Multi-Tenant (default) | Single-Tenant |\n|--------|----------------------|---------------|\n| Organization plugin | Enabled | Disabled |\n| `organizationId` columns | Required on resources | Not used |\n| Role source | Org membership table | `user.role` field |\n| Firewall scopes | `owner`, `organization`, `team`, `exception` | `owner`, `exception` only |\n| Admin org endpoints | `/
|
|
70
|
+
"content": "Single-tenant mode disables the Better Auth organization plugin, removing the `organizationId` requirement from your API. This is ideal for personal sites, blogs, admin panels, or any app with a single tenant.\n\n## Enabling Single-Tenant Mode\n\nSet `features.organizations` to `false` in your config:\n\n```typescript\n\nexport default defineConfig({\n name: \"my-site\",\n template: \"hono\",\n features: {\n organizations: false,\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## What Changes\n\n| Aspect | Multi-Tenant (default) | Single-Tenant |\n|--------|----------------------|---------------|\n| Organization plugin | Enabled | Disabled |\n| `organizationId` columns | Required on resources | Not used |\n| Role source | Org membership table | `user.role` field |\n| Firewall scopes | `owner`, `organization`, `team`, `exception` | `owner`, `exception` only |\n| Admin org endpoints | Use Better Auth's `/auth/v1/organization/list` (caller's orgs) and `/auth/v1/admin/list-organizations` when `cms.sysadmin: true` (cross-tenant) | N/A (no org plugin) |\n| `ctx.activeOrgId` | From session/JWT | Always `undefined` |\n| `ctx.roles` | From org member role | From `user.role` |\n\n## Firewall Configuration\n\nIn single-tenant mode, resources use either **owner** scope (user-scoped data) or **exception** (public/system data):\n\n```typescript\n// User-scoped data (requires authentication)\nexport default defineTable(posts, {\n firewall: [{ field: 'ownerId', equals: 'ctx.userId' }],\n read: {\n access: { roles: ['user', 'admin'] },\n },\n create: { access: { roles: ['admin'] } },\n});\n\n// Public data (no ownership filtering)\nexport default defineTable(pages, {\n firewall: [{ exception: true }],\n read: {\n access: { roles: ['PUBLIC'] },\n },\n create: { access: { roles: ['admin'] } },\n update: { access: { roles: ['admin'] } },\n delete: { access: { roles: ['admin'] } },\n});\n```\n\n## Public Routes\n\nUse the `PUBLIC` role to expose routes without authentication. This works the same as in multi-tenant mode:\n\n```typescript\nread: {\n access: { roles: ['PUBLIC'] }, // GET / and GET /:id — no auth required\n},\ncreate: { access: { roles: ['admin'] } }, // Admin only\n```\n\n## Role-Based Access\n\nRoles come from the `user.role` field (managed by Better Auth's [admin plugin](https://www.better-auth.com/docs/plugins/admin)).\n\n| Role | Description |\n|------|-------------|\n| `admin` | Full access, set via Better Auth admin plugin |\n| `user` | Default role for authenticated users |\n| `PUBLIC` | Unauthenticated access (special keyword) |\n\n```typescript\n// Admin-only action\nexport default defineActions({\n publish: {\n access: { roles: ['admin'] },\n execute: async ({ ctx, db }) => {\n // ctx.userRole === 'admin'\n // ctx.roles === ['admin']\n },\n },\n});\n```\n\n## Consuming the API\n\nSince single-tenant mode produces a JSON API, pair it with any frontend framework:\n\n```typescript\n// Astro, Next.js, SvelteKit, etc.\nconst posts = await fetch('https://api.mysite.com/api/v1/posts').then(r => r.json());\n\n// Admin operations require authentication\nconst res = await fetch('https://api.mysite.com/api/v1/posts', {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ title: 'New Post', content: '...' }),\n});\n```"
|
|
71
71
|
},
|
|
72
72
|
"compiler/config/variables": {
|
|
73
73
|
"title": "Environment Variables",
|
|
@@ -75,11 +75,11 @@ export const DOCS = {
|
|
|
75
75
|
},
|
|
76
76
|
"compiler/definitions/access": {
|
|
77
77
|
"title": "Access - Role & Condition-Based Access Control",
|
|
78
|
-
"content": "Define who can perform read and write operations and under what conditions.\n\n## Basic Usage\n\n```typescript\n// features/applications/applications.ts\n\nexport const applications = sqliteTable('applications', {\n id: text('id').primaryKey(),\n candidateId: text('candidate_id').notNull(),\n jobId: text('job_id').notNull(),\n stage: text('stage').notNull(),\n notes: text('notes'),\n organizationId: text('organization_id').notNull(),\n});\n\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: { createable: [\"candidateId\", \"jobId\", \"notes\"], updatable: [\"notes\"] },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n});\n```\n\n## Role Hierarchy\n\nIf your project uses a tiered role system (e.g., `member` < `admin` < `owner`), you can define a hierarchy in your config and use the `+` suffix to mean \"this role and above\":\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n name: \"my-app\",\n auth: {\n roleHierarchy: ['member', 'admin', 'owner'], // lowest → highest\n },\n // ...\n});\n```\n\nThen in your resource definitions:\n\n```typescript\nread: { access: { roles: [\"member+\"] } }, // member, admin, owner\ncreate: { access: { roles: [\"admin+\"] } }, // admin, owner\ndelete: { access: { roles: [\"owner\"] } }, // owner only (no +)\n```\n\nThe `+` 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\"]`.\n\n- Roles without `+` are exact matches (no expansion)\n- Pseudo-roles (`PUBLIC`, `AUTHENTICATED`, `USER`, `ADMIN`, `SYSADMIN`) cannot use the `+` suffix — they're terminal markers\n- Using `+` with a role not in the hierarchy throws a compile error\n- Using `+` without configuring `auth.roleHierarchy` throws a compile error\n\n## Configuration Options\n\n```typescript\ninterface Access {\n // Org-membership roles (OR logic — user needs at least one)\n // Matched against ctx.roles. Use \"role+\" suffix for hierarchy expansion.\n roles?: string[];\n\n // User-table role (OR logic). Matched against ctx.userRole from the\n // user.role column — independent of org membership. See userRole below.\n userRole?: string[];\n\n // Record-level conditions\n record?: {\n [field: string]: FieldCondition;\n };\n\n // Combinators\n or?: Access[];\n and?: Access[];\n}\n```\n\n## `userRole` vs `roles`\n\n`roles` and `userRole` check **two different fields** and are often confused — get this wrong and you'll grant access too broadly.\n\n| Primitive | Checks | Source | Example values |\n|-----------|--------|--------|----------------|\n| `roles` | `ctx.roles` | Org membership (multi-tenant) or single-tenant mirror of `user.role` | `\"owner\"`, `\"admin\"`, `\"member\"` |\n| `userRole` | `ctx.userRole` | The `user.role` column (Better Auth admin plugin) | `\"user\"`, `\"admin\"` |\n\nIn multi-tenant mode, **`roles: [\"admin\"]` means \"org admin\" — not a platform-wide admin.** An org-admin of Acme Corp has no elevated rights across other orgs. If you want to let Better Auth system admins through regardless of org membership (e.g., for support/ops), use `userRole: [\"admin\"]`.\n\nIn single-tenant mode (`features.organizations: false`), `ctx.roles` mirrors `user.role`, so `roles: [\"admin\"]` and `userRole: [\"admin\"]` behave the same. Using `userRole` in single-tenant code is still preferred — it documents intent and keeps the gate correct if you later enable orgs.\n\n### When to use `userRole`\n\n```typescript\n// Platform admin can see SSNs on every customer record, regardless of org\nmasking: {\n ssn: { type: 'ssn', show: { userRole: ['admin'] } },\n}\n\n// Support staff (user.role === 'admin') OR the org owner can refund\naccess: {\n or: [\n { userRole: ['admin'] },\n { roles: ['owner'] },\n ],\n}\n\n// CMS-internal resource: only platform admins\nread: { access: { userRole: ['admin'] } },\ncreate: { access: { userRole: ['admin'] } },\nupdate: { access: { userRole: ['admin'] } },\ndelete: { access: { userRole: ['admin'] } },\n```\n\nWhen `roles` and `userRole` both appear in a single `Access` node, they're combined with AND — the user must satisfy both. Use `or:` to express \"one or the other\".\n\n`userRole` doesn't expand with the `+` hierarchy suffix — user-table roles are flat (typically just `\"user\"` and `\"admin\"`). If you've added custom user-table roles via Better Auth, list them explicitly.\n\n### Pseudo-roles\n\nQuickback 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).\n\n| Role | Auth gate | Compile-time requirement | Runtime check |\n|------|-----------|-------------------------|---------------|\n| `PUBLIC` | bypassed | none — explicit opt-in for unauthenticated access | always passes (auth skipped) |\n| `AUTHENTICATED` | required | none | `ctx.authenticated === true` |\n| `USER` | required | resource firewall **must** scope by `userId` | `ctx.authenticated` AND (`ctx.userRole` is unset OR `ctx.userRole === \"user\"`) |\n| `ADMIN` | required | Better Auth admin plugin **must** be enabled | `ctx.authenticated && ctx.userRole === \"admin\"` |\n| `SYSADMIN` | required | `cms: { sysadmin: true }` **must** be set on the project | `ctx.authenticated && ctx.userRole === \"sysadmin\"` |\n\nYou can mix pseudo-roles with real roles in the same list — they're OR'd together.\n\n#### `PUBLIC` — unauthenticated access\n\nUse `roles: [\"PUBLIC\"]` for public-facing endpoints like contact forms, public listings, or webhooks. Skips both the auth gate and the role check.\n\n```typescript\naccess: { roles: [\"PUBLIC\"] }\n```\n\n**Important:**\n- `PUBLIC` skips authentication and role checks — anyone can call the endpoint\n- **`PUBLIC` is the explicit, uppercase opt-in for unauthenticated access.** It works on every access node — reads, top-level writes (`create`/`update`/`delete`/`upsert`), views, and actions. The compiler trusts the marker; row-level safety comes from the firewall, masking, and (for token-gated endpoints like RSVP confirm, magic-link redemption, List-Unsubscribe-Post, webhook ingest) your handler's own validation. Anonymous write endpoints typically pair `roles: [\"PUBLIC\"]` with `firewall: { exception: true }` on the resource so the row predicate doesn't reject every unauthenticated caller.\n- **Firewall still applies** — data is scoped by the firewall (organization, owner, team)\n- Every `PUBLIC` action invocation is **mandatory audit logged** to the security audit table (IP address, input, result, timing)\n- The wildcard `\"*\"` is **not supported** — using it throws a compile-time error\n- Tables with no isolation columns and any `PUBLIC` route do not require `firewall: [{ exception: true }]`\n\nFor org-scoped tables, `PUBLIC` routes still filter by organization. Since the user isn't authenticated, the organization ID must be passed as a query parameter:\n\n```\nGET /api/v1/listings?organizationId=org_abc123\n```\n\nThe firewall WHERE clause is always enforced. If no `organizationId` is provided, the API returns a `400` with code `ORG_REQUIRED`.\n\n```typescript\n// Public listing page — anyone can browse, but scoped to an org\nexport default defineTable(listings, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: { access: { roles: [\"PUBLIC\"] } }, // Public browsing + detail\n create: { access: { roles: [\"admin\", \"member\"] } }, // Auth required to create\n});\n```\n\n#### `AUTHENTICATED` — any signed-in user\n\nUse `roles: [\"AUTHENTICATED\"]` for endpoints that any logged-in user can hit, regardless of role or org membership. No plugin context required.\n\n```typescript\n// Public events feed — any signed-in user can list/read; anonymous gets 401\nread: { access: { roles: [\"AUTHENTICATED\"] } }\n```\n\n#### `USER` — per-user records\n\nUse `roles: [\"USER\"]` for resources where each user only sees their own records. **Requires the firewall to scope by `userId`** — the role marker is the access half of the pair, the firewall is the row-filter half.\n\n```typescript\n// \"My todos\" — each caller sees only their own rows\nexport default defineTable(todos, {\n firewall: [{ field: 'userId', equals: 'ctx.userId' }],\n read: { access: { roles: [\"USER\"] } },\n create: { access: { roles: [\"USER\"] } },\n update: { access: { roles: [\"USER\"] } },\n delete: { access: { roles: [\"USER\"] } },\n});\n```\n\nIf you forget the `userId` firewall predicate, the compiler throws:\n\n> `roles: [\"USER\"]` requires the resource to be scoped per-user. Add a `userId` column (auto-scoped) or an explicit owner predicate. If you want any signed-in user to read all records, use `roles: [\"AUTHENTICATED\"]` instead.\n\nWhen the Better Auth admin plugin is enabled, `USER` matches `user.role === \"user\"` specifically — admins are excluded and should use `[\"USER\", \"ADMIN\"]` if the same route should serve both.\n\n#### `ADMIN` — Better Auth admin-plugin admins\n\nUse `roles: [\"ADMIN\"]` for system-administrator endpoints. **Requires the Better Auth admin plugin** so `user.role` exists. Compiles to `ctx.userRole === \"admin\"`.\n\n```typescript\n// Platform-admin-only audit log\nread: { access: { roles: [\"ADMIN\"] } }\n```\n\nWithout 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).\n\n#### `SYSADMIN` — cross-tenant DB-admin tier\n\nUse `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.\n\n```typescript\n// Cross-tenant audit dashboard, sysadmin-only\nread: { access: { roles: [\"SYSADMIN\"] } }\n```\n\n`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.\n\nThis 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.\n\n#### Mixing pseudo-roles with real roles\n\nPseudo-roles and lowercase real roles compose with OR:\n\n```typescript\n// Record owner OR a system admin can read\nread: { access: { roles: [\"USER\", \"ADMIN\"] } }\n\n// Org owner OR system admin\ndelete: { access: { roles: [\"owner\", \"ADMIN\"] } }\n```\n\n> Note: today, an `ADMIN` match still goes through the `userId` firewall scope on USER-scoped resources — admins see only records they own on those routes. Use `firewall: { exception: true }` on a separate admin-only route if you need cross-user visibility.\n\n#### Quick reference\n\n```typescript\n// Unauthenticated public\naccess: { roles: [\"PUBLIC\"] }\n\n// Any signed-in user, no scoping\naccess: { roles: [\"AUTHENTICATED\"] }\n\n// Per-user records (requires userId firewall scope)\naccess: { roles: [\"USER\"] }\n\n// System admin (requires admin plugin)\naccess: { roles: [\"ADMIN\"] }\n\n// Org-membership roles with hierarchy expansion\naccess: { roles: [\"member+\"] } // expands to [\"member\", \"admin\", \"owner\"]\naccess: { roles: [\"admin+\"] } // expands to [\"admin\", \"owner\"]\naccess: { roles: [\"admin\"] } // exact match (no expansion)\n```\n\n```typescript\n// Field conditions - value can be string | number | boolean\ntype FieldCondition =\n | { equals: value | '$ctx.userId' | '$ctx.activeOrgId' }\n | { notEquals: value }\n | { in: value[] }\n | { notIn: value[] }\n | { lessThan: number }\n | { greaterThan: number }\n | { lessThanOrEqual: number }\n | { greaterThanOrEqual: number };\n```\n\n## Relationship-based authorization\n\nBeyond 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.\n\n### `authz.relationships`\n\nDeclare relationships once in `quickback.config.ts`:\n\n```typescript\n// quickback.config.ts\n\nexport default defineConfig({\n // ...providers...\n authz: {\n relationships: {\n guestOf: {\n from: 'event_guests', // table name string\n subject: { column: 'userId', equals: 'ctx.userId' }, // caller side\n resource: { column: 'eventId' }, // resource side\n where: { status: 'confirmed' }, // optional filter\n },\n },\n roles: {\n guest: { via: 'guestOf' },\n // Composite: any guest OR an org owner/admin\n eventStaff: {\n or: [\n { via: 'guestOf' },\n { roles: ['admin', 'owner'] },\n ],\n },\n },\n },\n});\n```\n\n### Using relationship-roles in resources\n\nResource definitions reference declared roles by name in `roles: [...]` arrays exactly like BA roles or pseudo-roles. The compiler rewrites the access tree at build time so the runtime route does an inline relationship lookup against the declared table.\n\n**Today (v1) this works on:**\n\n| Surface | Status | Notes |\n|---|---|---|\n| `firewall:` `via:` predicate | ✓ Supported | Subquery composes as outermost AND |\n| `crud.*.access` `roles: ['guest']` | ✓ Supported | Inline async lookup per request |\n| `read.access` / `read.views.*.access` `roles: ['guest']` | ✓ Supported | Same inline path |\n| `masking.<field>.show` `roles: ['guest']` | ⚠ Refused at compile | v1 limitation — async/batched mask functions deferred |\n| **Standalone** `actions.<name>.access` `roles: ['guest']` | ✓ Supported (v0.19+) | Inline gate; surface must expose `resource.column` as path param or input field |\n| **Record-based** `actions.<name>.access` `roles: ['guest']` | ⚠ Fail-closed at runtime | Runtime helper denies; inline emission is a planned follow-up. Use `firewall: { exception: true }` or move the check into `execute()` until then |\n\nFor the surfaces that are not yet supported, the compiler refuses at build time with a clear error pointing to a workaround. The runtime evaluator fails closed on relationship arms regardless, so silent grants are impossible.\n\n### Standalone actions: surface keys and `loads` / `exposeAs` (v0.19+)\n\nWhen a standalone action's `access.roles` references a relationship-role, the compiler emits a runtime gate between input validation and `execute()`. The gate reads the relationship's `resource.column` value from the action surface — either a path parameter (`:eventId`) or an input field (`input.eventId`). If neither is present, the compiler:\n\n- **v0.19** — emits a `[quickback:authz]` warning and skips resolver emission. The action's own hand-rolled gate (if any) keeps the route working at runtime.\n- **v0.20** — hard compile error. Set `firewall: { exception: true }` to opt out (cross-tenant/admin routes only).\n\nPair the relationship with `loads` + `exposeAs` to hydrate the loaded resource onto `ctx`:\n\n```typescript\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events', // ← v0.19+: load matching event row\n exposeAs: 'event', // ← onto ctx.event for the action body\n },\n },\n roles: {\n attendee: { via: 'attendeeOf' },\n },\n}\n```\n\nThe resolver (v0.20):\n\n1. **Cheap in-memory role check** first — `ctx.roles?.includes('admin')` and friends. If the caller has a qualifying role, this short-circuits and no DB queries fire for the access gate.\n2. **Firewall-gated relationship match** if the role check failed — `SELECT { organizationId, teamId } FROM guests WHERE userId=ctx.userId AND eventId=input.eventId AND status='confirmed'` with the `guests` table's full firewall AND-applied. If neither role nor relationship qualifies → 403.\n3. **Tenant stamping from the matched row** — for any tenant column the `from` table carries (`organizationId`, `teamId`), the resolver stamps `ctx.activeOrgId ??= matchedRow.organizationId` (and similar for team). This is **in-memory mutation of the request-scoped ctx only** — no JWT remint, no session-record write, no persistent grant.\n4. **Firewall-gated load of the loaded resource** — `SELECT * FROM events WHERE id = :eventId AND buildEventsFirewallConditions(ctx, db)`. The events firewall is applied as normal; it succeeds for attendees because tenant was just stamped from the relationship row.\n5. Assigns the loaded row to `ctx.event` for the action body.\n\n**No firewall bypass anywhere.** Both queries run with their respective tables' full firewalls. The relationship row's existence is the proof that the caller is authorized; its tenant columns are the source of the stamped claim.\n\n### Conditional tenant preconditions (v0.20+)\n\nStandalone actions in features with org/team-scoped tables previously emitted unconditional preconditions:\n\n```ts\nif (!ctx.activeOrgId) return c.json(AccessErrors.noOrg(), 403);\nif (!ctx.activeTeamId) return c.json(AccessErrors.noTeam(), 403);\n```\n\nThese ran **before** the relationship resolver, which 403'd attendees whose sessions don't carry an active tenant claim (the canonical event-attendee shape).\n\nv0.20 makes these preconditions **conditional on relationship supply**. If the access tree contains a relationship arm whose `from` table carries the matching tenant column, the precondition is skipped — the resolver runs first and stamps the value. Pseudo-role short-circuits (PUBLIC / AUTHENTICATED / USER / ADMIN / SYSADMIN) and `firewall: { exception: true }` still bypass the preconditions as before.\n\nTypical event-attendee setup (`guests` table carries `organizationId`): the org precondition is dropped on every action whose access references `attendee` or `eventStaff`. Org admins still get `ctx.activeOrgId` from their session as today; attendees get it from the relationship row, mid-request. Both paths converge on a valid tenant claim before `execute()` runs.\n\n### Requirement on the relationship's `from` table\n\nFor the v0.20 tenant-stamping to work, the relationship's `from` table must carry tenant columns:\n\n- For org stamping: an `organizationId` column (or whatever spelling the project's auth-provider defaults pick).\n- For team stamping: a `teamId` column.\n\nWhen the `from` table has **neither**, the compiler emits a `[quickback:authz]` warning at compile time:\n\n```\nRelationship \"X\" at authz.relationships.X has no organization or team columns\non its `from` table (\"guests\"). Action \"Y\" will compile, but downstream\nscoped-db queries inside execute() may 403 because ctx.activeOrgId /\nactiveTeamId cannot be stamped from the match row. Either add the tenant\ncolumn to \"guests\", or set firewall: { exception: true } on the action.\n```\n\nThe relationship match still works (existence check), but no tenant gets stamped — so the conventional precondition still fires and the action still 403s for callers without a session-resident tenant claim. Add the tenant column (or denormalize it onto the relationship table during writes) to enable the stamping path.\n\nThe body can then trust `ctx.event` and drop the hand-rolled `SELECT … FROM guests WHERE …` boilerplate:\n\n```ts\n// features/chat/actions/getInbox.ts\nexport default defineAction({\n path: '/chat/get-inbox',\n input: z.object({ eventId: z.number().int().positive() }),\n access: { roles: ['admin', 'member', 'attendee'] }, // attendee is a relationship-role\n execute: async ({ db, ctx, input }) => {\n // No hand-rolled attendance check needed — the resolver already ran.\n // ctx.event is the loaded events row (typed as any in v0.19; cast as\n // needed — narrow per-action types are a follow-up).\n const event = ctx.event as typeof events.$inferSelect;\n // … domain logic only.\n },\n});\n```\n\n`loads` and `exposeAs` are co-required (set both or neither). `exposeAs` must be a valid JS identifier and must not collide with built-in `ctx` fields (`userId`, `activeOrgId`, `activeTeamId`, `db`, etc.).\n\n### Action firewall escape hatch (v0.19+)\n\n`defineAction({ firewall: { exception: true } })` opts the action out of the inherited session-key preconditions (`ctx.activeOrgId` / `ctx.activeTeamId` requirements) AND the relationship resolver. The handler receives `unsafeDb` for raw Drizzle access. Use for cross-tenant or admin routes whose surface intentionally doesn't name a session/relationship key:\n\n```ts\ndefineAction({\n path: '/admin/cross-tenant-report',\n firewall: { exception: true },\n unsafe: { reason: 'cross-tenant audit', adminOnly: true, targetScope: 'all' },\n access: { roles: ['ADMIN'] },\n execute: async ({ unsafeDb, ctx }) => { /* cross-org query */ },\n});\n```\n\n`firewall: { exception: true }` is the declarative twin of `unsafe: true` — they're conceptually distinct: `firewall.exception` opts out of the gate-emission pillars; `unsafe` signals audit/cross-tenant intent (and still applies for logging). Most cross-tenant actions set both.\n\n### Recommended pattern: gate at the firewall layer\n\nMost of the time, relationship-based row visibility is what you want, and putting it at the **firewall** layer is the cleanest expression. The firewall is row-filter; the access layer is route/role-filter; let each do its job:\n\n```typescript\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' }, // ← row visibility\n],\nread: {\n access: { roles: ['admin', 'member'] }, // ← who can hit the route\n views: {\n cms: { access: { roles: ['admin', 'member'] }, fields: [...] },\n guest: { access: { roles: ['member', 'admin'] }, fields: [...] },\n },\n},\n```\n\nA guest who's in your org as `member` can hit the endpoint and the firewall filters them down to events they're guests of. Cross-tenant access is impossible because the org filter is the outermost AND.\n\n### Cross-tenant \"my events\" dashboards are NOT this\n\nA common adjacent pattern — \"logged-in user wants `GET /my-events` returning events they're a guest of *across all tenants*\" — is **not** solved by relationship-roles. The tenant firewall is enforced at the outermost AND, so a guest of an event in another tenant remains correctly blocked.\n\nFor cross-tenant aggregation, use one of:\n\n- **User-scoped firewall**: `firewall: { owner: { column: 'userId' } }` — a flat per-user table.\n- **A standalone action that walks the relationship table itself** — see worked example below.\n\nDon't reach for relationship-roles first and then get confused when the tenant firewall blocks. The two patterns serve different problems.\n\n#### Worked example: `GET /my-events` standalone action\n\nThe cleanest expression of the cross-tenant attendee dashboard is a standalone action with a custom path that does its own join against the relationship table. The action is gated by `roles: ['AUTHENTICATED']` (any signed-in user can hit it; per-row scoping is the query itself), and the SQL filters by `ctx.userId` so each caller sees exactly the events they're a guest of:\n\n```ts\n// features/dashboard/actions/myEvents.ts\n\nexport default defineAction({\n description: \"List events the caller is a confirmed guest of, across all tenants.\",\n path: '/my-events',\n method: 'GET',\n input: z.object({}),\n // Any signed-in user. Row visibility comes from the query, not the role.\n access: { roles: ['AUTHENTICATED'] },\n async execute({ db, ctx }) {\n // 1. Find every event the caller has a confirmed guest row for.\n const guestRows = await db\n .select({ eventId: guests.eventId })\n .from(guests)\n .where(\n and(\n eq(guests.userId, ctx.userId!),\n eq(guests.status, 'confirmed'),\n // guests.organizationId is NOT filtered here — that's the whole\n // point of the cross-tenant lane. The relationship row's org is\n // ambient information that this action explicitly traverses.\n )\n );\n\n if (guestRows.length === 0) return { events: [] };\n\n // 2. Pull the matching events. NOTE: this query also bypasses\n // `events.organizationId` scope — by design — so explicitly filter\n // out soft-deleted rows yourself if your `events` table uses them.\n const eventIds = guestRows.map((r) => r.eventId);\n const rows = await db\n .select()\n .from(events)\n .where(inArray(events.id, eventIds));\n\n return { events: rows };\n },\n});\n```\n\nWhy this is a standalone action and not a CRUD route:\n\n- **Tenant firewall would block it.** The default `firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }]` on `events` is correct for every other read — only the cross-tenant dashboard wants to step outside it, and that's a deliberate, explicit step taken in handler code.\n- **The join is the access control.** A relationship-role at the firewall layer can't express \"filter by this user's relationships, ignoring the org context.\" The handler does that join directly.\n- **Audit-logged automatically.** Standalone actions are mandatorily audit-logged in the runtime — the cross-tenant traversal is recorded with `ctx.userId`, IP, and timing.\n\nTwo important guardrails when you write one of these:\n\n1. **Always filter by `ctx.userId` in the relationship lookup.** If you accept a `userId` from the request body and trust it, you've built an IDOR. The example above uses `ctx.userId!` directly so the only events returned are the caller's.\n2. **You take responsibility for soft-delete and other invariants the firewall would otherwise apply.** Add the `deletedAt` filter, status checks, and any other row-level predicates by hand. The action is OUTSIDE the firewall pipeline by design — the cost is that you can't lean on the auto-applied predicates.\n\nIf you find yourself writing more than one of these per project, that's usually a signal to revisit the schema (could a user-owned `userEvents` materialized view replace the join?) rather than a sign Quickback should ship a higher-level abstraction. Cross-tenant lanes are intentionally explicit.\n\n### Compile-time refusals (consolidated)\n\nThe validator and resolver reject:\n\n- Unknown key in `authz` block (typo guard — `realtionships` would otherwise silently produce a permanently-denied role).\n- Reserved role-name (auth-provider-derived). Names like `guest`, `speaker`, `attendee` are free; `admin`/`owner`/`member` are reserved when the BA org plugin is on.\n- Cycle in role composition (`a → b → a`).\n- Relationship `from` references unknown table.\n- Relationship-role used on a resource missing the `resource.column`.\n- Relationship table with `firewall: { exception: true }` (would let cross-tenant grants slip through).\n- `lowering: 'session'` (reserved for v2 — staleness/invalidation ergonomics not yet shipped).\n- `+` hierarchy suffix on a relationship-role name (terminal, like pseudo-roles).\n- Relationship-roles in `masking.show` / `actions.access` (deferred surfaces — see the table above).\n\n## Namespace mounts (hoisted relationship middleware)\n\nWhen several standalone actions share a path prefix and the same relationship gate — `/event/:eventId/announce`, `/event/:eventId/cancel`, `/event/:eventId/respond` — declaring the gate per-action means writing the same `roles: ['attendee']` over and over AND paying the relationship-resolver cost N times per request (one subquery + one row-load, multiplied by the number of actions).\n\nNamespace mounts hoist the resolver into one Hono middleware that runs once per request. Every action under the prefix skips the inline gate; `ctx.<exposeAs>` is hydrated by the middleware and typed automatically inside the handlers.\n\nTwo declaration sites depending on whether the participating actions live in one feature or many:\n\n### Single feature: `defineTable({ namespace })` (v0.23+)\n\nUse when every action under the prefix lives in the same feature directory. The namespace travels with the table that owns it — no addition to `quickback.config.ts` needed.\n\n```typescript\n// features/events/events.ts\nexport default defineTable(events, {\n firewall: [...],\n crud: { ... },\n namespace: {\n prefix: '/event/:eventId', // absolute URL path\n via: 'attendeeOf', // relationship gate (must exist in authz.relationships)\n },\n});\n\n// features/events/actions/post-announcement.ts\nexport default defineAction({\n path: '/event/:eventId/announcements',\n method: 'POST',\n // No gate boilerplate. ctx.event is typed inside execute().\n});\n```\n\nThe compiler emits one `app.use(...)` on the events feature's Hono app. Every standalone action in `features/events/actions/` whose path starts with `/event/:eventId/` joins the namespace automatically.\n\n### Cross-feature: `authz.namespaces` (v0.24+)\n\nUse when the namespace spans multiple features. The declaration sits next to your other authz config in `quickback.config.ts`.\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n namespaces: {\n eventScope: { prefix: '/event/:eventId', via: 'attendeeOf' },\n },\n}\n\n// features/feeds/actions/feed-moments.ts (in a different feature)\nexport default defineAction({\n path: '/event/:eventId/feed-moments',\n method: 'POST',\n});\n\n// features/rsvp/actions/respond.ts (and another)\nexport default defineAction({\n path: '/event/:eventId/respond',\n method: 'POST',\n});\n```\n\nThe compiler emits one synthetic `src/routes/__namespace-event-scope.routes.ts` that imports each contributing feature's `actions` map under a distinct alias, mounts the resolver middleware once, and dispatches to the matching action. Worker-root mount order ensures the middleware fires before any per-feature route handler under the prefix.\n\n### Discovery is path-prefix-only\n\nActions opt in by matching `path:` against a declared namespace prefix. There's no `namespace: 'foo'` field on `defineAction` — the path string is the discoverable surface, consistent with how `path:` already determines an action's URL.\n\n### Requirements (enforced at compile time)\n\nBoth forms share the same shape checks:\n\n- **`via:` must point at a declared `authz.relationships[*]` entry**, and that relationship must declare `loads + exposeAs`. Without `loads` there's nothing for the middleware to hydrate, and the namespace gate becomes indistinguishable from a per-action access rule.\n- **`prefix:` must contain at least one `:param` segment** (e.g. `/event/:eventId`). The middleware reads the relationship key from `c.req.param()` because no request body has been parsed at middleware time.\n- **One declaration per namespace name.** The same name in both `defineTable({ namespace })` and `authz.namespaces` is rejected. The project-level form is canonical for cross-feature; the table-level form is the single-feature shorthand.\n\nProject-level only:\n\n- **Ambiguous prefixes** like `/a/:x` and `/a/:y` (same shape, different `:param` names) are rejected. Strict super/sub-set relationships (`/event/:e` vs `/event/:e/admin`) are fine — the harvester routes each action to the longest matching prefix.\n- **Unused namespace** emits a `[quickback:authz]` warning when no action's path matches the declared prefix. Not a hard error — the namespace may be staged ahead of the actions.\n\n### What namespace actions get for free\n\nInside a namespace action's `execute()`:\n\n- `ctx.<exposeAs>` is populated by the middleware with the loaded resource row, typed as `typeof <loadsTable>.$inferSelect`.\n- Tenant context (`ctx.activeOrgId` / `ctx.activeTeamId`) is stamped from the matched relationship row when its `from` table carries those columns. Downstream scoped queries work without further setup.\n- The action's own `access:` block (additional roles, userRole, record predicates, OTHER relationship arms) still runs after the namespace gate — namespace handles entry, per-action gates further.\n\n## Read & Write Configuration\n\nReads (`GET /` and `GET /:id`) live under `read:`; mutations live under top-level `create:`, `update:`, `delete:`, and `upsert:`. See [Read](/compiler/definitions/read) for the full read pipeline reference.\n\n```typescript\nread: {\n // LIST + GET - GET /resource and GET /resource/:id\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n pageSize: 25, // Default page size\n maxPageSize: 100, // Client can't exceed this\n views: { // Per-view field projections\n summary: {\n fields: ['id', 'candidateId', 'jobId', 'stage'],\n access: { roles: [\"interviewer\"] },\n },\n },\n}\n\ncreate: {\n // CREATE - POST /resource\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] },\n defaults: { // Default values for new records\n stage: 'applied',\n },\n},\n\nupdate: {\n // UPDATE - PATCH /resource/:id\n access: {\n or: [\n { roles: [\"hiring-manager\", \"recruiter\"] },\n { roles: [\"interviewer\"], record: { stage: { equals: \"interview\" } } }\n ]\n },\n},\n\ndelete: {\n // DELETE - DELETE /resource/:id\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"soft\", // 'soft' (default) or 'hard'\n},\n\nupsert: {\n // PUT - PUT /resource/:id (only when generateId: false + guards: false)\n access: { roles: [\"hiring-manager\", \"sync-service\"] },\n}\n```\n\n## Evaluation Order\n\nGenerated `/:id` and batch handlers evaluate access in this fixed order:\n\n1. **Auth gate** — 401 if unauthenticated\n2. **Pre-record access** — role-only check (skips `access.record` predicates)\n3. **Firewall query** — `WHERE` clause filters by ownership\n4. **Post-record access** — full check including record-level predicates\n5. **Masking** — applied to the response\n\nStep 2 closes the 404-vs-403 ID-probe channel: an unauthorized caller without\na matching role gets 403 before the database is touched, so they can't tell\napart \"row exists out-of-scope\" from \"row doesn't exist.\" A caller with the\nright role but the wrong tenant gets 403 by default (firewall reveals via\nthe access layer); set\n[`firewallErrorMode: 'hide'`](/compiler/definitions/firewall) to return an\nopaque 404 instead.\n\nFunction-form access (`access: async (ctx, record) => ...`) is opaque to\nthe pre-record phase and always passes there; it's fully evaluated post-record.\n\n## List Filtering (Query Parameters)\n\nThe LIST endpoint automatically supports filtering via query params:\n\n```\nGET /jobs?status=open # Exact match\nGET /jobs?salaryMin.gt=50000 # Greater than\nGET /jobs?salaryMin.gte=50000 # Greater than or equal\nGET /jobs?salaryMax.lt=200000 # Less than\nGET /jobs?salaryMax.lte=200000 # Less than or equal\nGET /jobs?status.ne=closed # Not equal\nGET /jobs?title.like=Engineer # Pattern match (LIKE %value%)\nGET /jobs?status.in=open,draft # IN clause\n```\n\n| Operator | Query Param | SQL Equivalent |\n|----------|-------------|----------------|\n| Equals | `?field=value` | `WHERE field = value` |\n| Not equals | `?field.ne=value` | `WHERE field != value` |\n| Greater than | `?field.gt=value` | `WHERE field > value` |\n| Greater or equal | `?field.gte=value` | `WHERE field >= value` |\n| Less than | `?field.lt=value` | `WHERE field < value` |\n| Less or equal | `?field.lte=value` | `WHERE field <= value` |\n| Pattern match | `?field.like=value` | `WHERE field LIKE '%value%'` |\n| In list | `?field.in=a,b,c` | `WHERE field IN ('a','b','c')` |\n\n## Sorting & Pagination\n\n```\nGET /jobs?sort=createdAt&order=desc # Sort by field\nGET /jobs?limit=25&offset=50 # Pagination\n```\n\n- **Default limit**: 50\n- **Max limit**: 100 (or `maxPageSize` if configured)\n- **Default order**: `asc`\n\n## Delete Modes\n\n```typescript\ndelete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"soft\", // Sets deletedAt/deletedBy, record stays in DB\n}\n\ndelete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"hard\", // Permanent deletion from database\n}\n```\n\n## Context Variables\n\nUse `$ctx.` prefix to reference context values in conditions:\n\n```typescript\n// User can only view their own records\naccess: {\n record: { userId: { equals: \"$ctx.userId\" } }\n}\n\n// Nested path support for complex context objects\naccess: {\n record: { ownerId: { equals: \"$ctx.user.id\" } }\n}\n```\n\n### AppContext Reference\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `$ctx.userId` | `string` | Current authenticated user's ID |\n| `$ctx.activeOrgId` | `string` | User's active organization ID |\n| `$ctx.activeTeamId` | `string \\| null` | User's active team ID (if applicable) |\n| `$ctx.roles` | `string[]` | User's roles in current context |\n| `$ctx.isAnonymous` | `boolean` | Whether user is anonymous |\n| `$ctx.user` | `object` | Full user object from auth provider |\n| `$ctx.user.id` | `string` | User ID (nested path example) |\n| `$ctx.user.email` | `string` | User's email address |\n| `$ctx.{property}` | `any` | Any custom context property |\n\n## Function-Based Access\n\nFor complex access logic that can't be expressed declaratively, use a function:\n\n```typescript\nupdate: {\n access: async (ctx, record) => {\n // Custom logic - return true to allow, false to deny\n if (ctx.roles.includes('admin')) return true;\n if (record.ownerId === ctx.userId) return true;\n\n // Check custom business logic\n const membership = await checkTeamMembership(ctx.userId, record.teamId);\n return membership.canEdit;\n }\n}\n```\n\nFunction access receives:\n- `ctx`: The full AppContext object\n- `record`: The record being accessed (for get/update/delete operations)"
|
|
78
|
+
"content": "Define who can perform read and write operations and under what conditions.\n\n## Basic Usage\n\n```typescript\n// features/applications/applications.ts\n\nexport const applications = sqliteTable('applications', {\n id: text('id').primaryKey(),\n candidateId: text('candidate_id').notNull(),\n jobId: text('job_id').notNull(),\n stage: text('stage').notNull(),\n notes: text('notes'),\n organizationId: text('organization_id').notNull(),\n});\n\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: { createable: [\"candidateId\", \"jobId\", \"notes\"], updatable: [\"notes\"] },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n});\n```\n\n## Role Hierarchy\n\nIf your project uses a tiered role system (e.g., `member` < `admin` < `owner`), you can define a hierarchy in your config and use the `+` suffix to mean \"this role and above\":\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n name: \"my-app\",\n auth: {\n roleHierarchy: ['member', 'admin', 'owner'], // lowest → highest\n },\n // ...\n});\n```\n\nThen in your resource definitions:\n\n```typescript\nread: { access: { roles: [\"member+\"] } }, // member, admin, owner\ncreate: { access: { roles: [\"admin+\"] } }, // admin, owner\ndelete: { access: { roles: [\"owner\"] } }, // owner only (no +)\n```\n\nThe `+` 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\"]`.\n\n- Roles without `+` are exact matches (no expansion)\n- Pseudo-roles (`PUBLIC`, `AUTHENTICATED`, `USER`, `ADMIN`, `SYSADMIN`) cannot use the `+` suffix — they're terminal markers\n- Using `+` with a role not in the hierarchy throws a compile error\n- Using `+` without configuring `auth.roleHierarchy` throws a compile error\n\n## Configuration Options\n\n```typescript\ninterface Access {\n // Org-membership roles (OR logic — user needs at least one)\n // Matched against ctx.roles. Use \"role+\" suffix for hierarchy expansion.\n roles?: string[];\n\n // User-table role (OR logic). Matched against ctx.userRole from the\n // user.role column — independent of org membership. See userRole below.\n userRole?: string[];\n\n // Record-level conditions\n record?: {\n [field: string]: FieldCondition;\n };\n\n // Combinators\n or?: Access[];\n and?: Access[];\n}\n```\n\n## `userRole` vs `roles`\n\n`roles` and `userRole` check **two different fields** and are often confused — get this wrong and you'll grant access too broadly.\n\n| Primitive | Checks | Source | Example values |\n|-----------|--------|--------|----------------|\n| `roles` | `ctx.roles` | Org membership (multi-tenant) or single-tenant mirror of `user.role` | `\"owner\"`, `\"admin\"`, `\"member\"` |\n| `userRole` | `ctx.userRole` | The `user.role` column (Better Auth admin plugin) | `\"user\"`, `\"admin\"` |\n\nIn multi-tenant mode, **`roles: [\"admin\"]` means \"org admin\" — not a platform-wide admin.** An org-admin of Acme Corp has no elevated rights across other orgs. If you want to let Better Auth system admins through regardless of org membership (e.g., for support/ops), use `userRole: [\"admin\"]`.\n\nIn single-tenant mode (`features.organizations: false`), `ctx.roles` mirrors `user.role`, so `roles: [\"admin\"]` and `userRole: [\"admin\"]` behave the same. Using `userRole` in single-tenant code is still preferred — it documents intent and keeps the gate correct if you later enable orgs.\n\n### When to use `userRole`\n\n```typescript\n// Platform admin can see SSNs on every customer record, regardless of org\nmasking: {\n ssn: { type: 'ssn', show: { userRole: ['admin'] } },\n}\n\n// Support staff (user.role === 'admin') OR the org owner can refund\naccess: {\n or: [\n { userRole: ['admin'] },\n { roles: ['owner'] },\n ],\n}\n\n// CMS-internal resource: only platform admins\nread: { access: { userRole: ['admin'] } },\ncreate: { access: { userRole: ['admin'] } },\nupdate: { access: { userRole: ['admin'] } },\ndelete: { access: { userRole: ['admin'] } },\n```\n\nWhen `roles` and `userRole` both appear in a single `Access` node, they're combined with AND — the user must satisfy both. Use `or:` to express \"one or the other\".\n\n`userRole` doesn't expand with the `+` hierarchy suffix — user-table roles are flat (typically just `\"user\"` and `\"admin\"`). If you've added custom user-table roles via Better Auth, list them explicitly.\n\n### Pseudo-roles\n\nQuickback 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).\n\n| Role | Auth gate | Compile-time requirement | Runtime check |\n|------|-----------|-------------------------|---------------|\n| `PUBLIC` | bypassed | none — explicit opt-in for unauthenticated access | always passes (auth skipped) |\n| `AUTHENTICATED` | required | none | `ctx.authenticated === true` |\n| `USER` | required | resource firewall **must** scope by `userId` | `ctx.authenticated` AND (`ctx.userRole` is unset OR `ctx.userRole === \"user\"`) |\n| `ADMIN` | required | Better Auth admin plugin **must** be enabled | `ctx.authenticated && ctx.userRole === \"admin\"` |\n| `SYSADMIN` | required | `cms: { sysadmin: true }` **must** be set on the project | `ctx.authenticated && ctx.userRole === \"sysadmin\"` |\n\nYou can mix pseudo-roles with real roles in the same list — they're OR'd together.\n\n#### `PUBLIC` — unauthenticated access\n\nUse `roles: [\"PUBLIC\"]` for public-facing endpoints like contact forms, public listings, or webhooks. Skips both the auth gate and the role check.\n\n```typescript\naccess: { roles: [\"PUBLIC\"] }\n```\n\n**Important:**\n- `PUBLIC` skips authentication and role checks — anyone can call the endpoint\n- **`PUBLIC` is the explicit, uppercase opt-in for unauthenticated access.** It works on every access node — reads, top-level writes (`create`/`update`/`delete`/`upsert`), views, and actions. The compiler trusts the marker; row-level safety comes from the firewall, masking, and (for token-gated endpoints like RSVP confirm, magic-link redemption, List-Unsubscribe-Post, webhook ingest) your handler's own validation. Anonymous write endpoints typically pair `roles: [\"PUBLIC\"]` with `firewall: { exception: true }` on the resource so the row predicate doesn't reject every unauthenticated caller.\n- **Firewall still applies** — data is scoped by the firewall (organization, owner, team)\n- Every `PUBLIC` action invocation is **mandatory audit logged** to the security audit table (IP address, input, result, timing)\n- The wildcard `\"*\"` is **not supported** — using it throws a compile-time error\n- Tables with no isolation columns and any `PUBLIC` route do not require `firewall: [{ exception: true }]`\n\nFor org-scoped tables, `PUBLIC` routes still filter by organization. Since the user isn't authenticated, the organization ID must be passed as a query parameter:\n\n```\nGET /api/v1/listings?organizationId=org_abc123\n```\n\nThe firewall WHERE clause is always enforced. If no `organizationId` is provided, the API returns a `400` with code `ORG_REQUIRED`.\n\n```typescript\n// Public listing page — anyone can browse, but scoped to an org\nexport default defineTable(listings, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: { access: { roles: [\"PUBLIC\"] } }, // Public browsing + detail\n create: { access: { roles: [\"admin\", \"member\"] } }, // Auth required to create\n});\n```\n\n#### `AUTHENTICATED` — any signed-in user\n\nUse `roles: [\"AUTHENTICATED\"]` for endpoints that any logged-in user can hit, regardless of role or org membership. No plugin context required.\n\n```typescript\n// Public events feed — any signed-in user can list/read; anonymous gets 401\nread: { access: { roles: [\"AUTHENTICATED\"] } }\n```\n\n#### `USER` — per-user records\n\nUse `roles: [\"USER\"]` for resources where each user only sees their own records. **Requires the firewall to scope by `userId`** — the role marker is the access half of the pair, the firewall is the row-filter half.\n\n```typescript\n// \"My todos\" — each caller sees only their own rows\nexport default defineTable(todos, {\n firewall: [{ field: 'userId', equals: 'ctx.userId' }],\n read: { access: { roles: [\"USER\"] } },\n create: { access: { roles: [\"USER\"] } },\n update: { access: { roles: [\"USER\"] } },\n delete: { access: { roles: [\"USER\"] } },\n});\n```\n\nIf you forget the `userId` firewall predicate, the compiler throws:\n\n> `roles: [\"USER\"]` requires the resource to be scoped per-user. Add a `userId` column (auto-scoped) or an explicit owner predicate. If you want any signed-in user to read all records, use `roles: [\"AUTHENTICATED\"]` instead.\n\nWhen the Better Auth admin plugin is enabled, `USER` matches `user.role === \"user\"` specifically — admins are excluded and should use `[\"USER\", \"ADMIN\"]` if the same route should serve both.\n\n#### `ADMIN` — Better Auth admin-plugin admins\n\nUse `roles: [\"ADMIN\"]` for system-administrator endpoints. **Requires the Better Auth admin plugin** so `user.role` exists. Compiles to `ctx.userRole === \"admin\"`.\n\n```typescript\n// Platform-admin-only audit log\nread: { access: { roles: [\"ADMIN\"] } }\n```\n\nWithout 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).\n\n#### `SYSADMIN` — cross-tenant DB-admin tier\n\nUse `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.\n\n```typescript\n// Cross-tenant audit dashboard, sysadmin-only\nread: { access: { roles: [\"SYSADMIN\"] } }\n```\n\n`ADMIN` and `SYSADMIN` are **independent** at the evaluator level — `ADMIN` admits `userRole === 'admin'` only, `SYSADMIN` admits `userRole === 'sysadmin'` only. Routes that need both write `access: { roles: ['ADMIN', 'SYSADMIN'] }` explicitly. The one place sysadmin gets implicit extra powers is **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.\n\nThis 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 `/auth/v1/admin/list-organizations` endpoint, and the SPA's \"All organizations\" sentinel.\n\n#### Mixing pseudo-roles with real roles\n\nPseudo-roles and lowercase real roles compose with OR:\n\n```typescript\n// Record owner OR a system admin can read\nread: { access: { roles: [\"USER\", \"ADMIN\"] } }\n\n// Org owner OR system admin\ndelete: { access: { roles: [\"owner\", \"ADMIN\"] } }\n```\n\n> Note: today, an `ADMIN` match still goes through the `userId` firewall scope on USER-scoped resources — admins see only records they own on those routes. Use `firewall: { exception: true }` on a separate admin-only route if you need cross-user visibility.\n\n#### Quick reference\n\n```typescript\n// Unauthenticated public\naccess: { roles: [\"PUBLIC\"] }\n\n// Any signed-in user, no scoping\naccess: { roles: [\"AUTHENTICATED\"] }\n\n// Per-user records (requires userId firewall scope)\naccess: { roles: [\"USER\"] }\n\n// System admin (requires admin plugin)\naccess: { roles: [\"ADMIN\"] }\n\n// Org-membership roles with hierarchy expansion\naccess: { roles: [\"member+\"] } // expands to [\"member\", \"admin\", \"owner\"]\naccess: { roles: [\"admin+\"] } // expands to [\"admin\", \"owner\"]\naccess: { roles: [\"admin\"] } // exact match (no expansion)\n```\n\n```typescript\n// Field conditions - value can be string | number | boolean\ntype FieldCondition =\n | { equals: value | '$ctx.userId' | '$ctx.activeOrgId' }\n | { notEquals: value }\n | { in: value[] }\n | { notIn: value[] }\n | { lessThan: number }\n | { greaterThan: number }\n | { lessThanOrEqual: number }\n | { greaterThanOrEqual: number };\n```\n\n## Relationship-based authorization\n\nBeyond 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.\n\n### `authz.relationships`\n\nDeclare relationships once in `quickback.config.ts`:\n\n```typescript\n// quickback.config.ts\n\nexport default defineConfig({\n // ...providers...\n authz: {\n relationships: {\n guestOf: {\n from: 'event_guests', // table name string\n subject: { column: 'userId', equals: 'ctx.userId' }, // caller side\n resource: { column: 'eventId' }, // resource side\n where: { status: 'confirmed' }, // optional filter\n },\n },\n roles: {\n guest: { via: 'guestOf' },\n // Composite: any guest OR an org owner/admin\n eventStaff: {\n or: [\n { via: 'guestOf' },\n { roles: ['admin', 'owner'] },\n ],\n },\n },\n },\n});\n```\n\n### Using relationship-roles in resources\n\nResource definitions reference declared roles by name in `roles: [...]` arrays exactly like BA roles or pseudo-roles. The compiler rewrites the access tree at build time so the runtime route does an inline relationship lookup against the declared table.\n\n**Today (v1) this works on:**\n\n| Surface | Status | Notes |\n|---|---|---|\n| `firewall:` `via:` predicate | ✓ Supported | Subquery composes as outermost AND |\n| `crud.*.access` `roles: ['guest']` | ✓ Supported | Inline async lookup per request |\n| `read.access` / `read.views.*.access` `roles: ['guest']` | ✓ Supported | Same inline path |\n| `masking.<field>.show` `roles: ['guest']` | ⚠ Refused at compile | v1 limitation — async/batched mask functions deferred |\n| **Standalone** `actions.<name>.access` `roles: ['guest']` | ✓ Supported (v0.19+) | Inline gate; surface must expose `resource.column` as path param or input field |\n| **Record-based** `actions.<name>.access` `roles: ['guest']` | ⚠ Fail-closed at runtime | Runtime helper denies; inline emission is a planned follow-up. Use `firewall: { exception: true }` or move the check into `execute()` until then |\n\nFor the surfaces that are not yet supported, the compiler refuses at build time with a clear error pointing to a workaround. The runtime evaluator fails closed on relationship arms regardless, so silent grants are impossible.\n\n### Standalone actions: surface keys and `loads` / `exposeAs` (v0.19+)\n\nWhen a standalone action's `access.roles` references a relationship-role, the compiler emits a runtime gate between input validation and `execute()`. The gate reads the relationship's `resource.column` value from the action surface — either a path parameter (`:eventId`) or an input field (`input.eventId`). If neither is present, the compiler:\n\n- **v0.19** — emits a `[quickback:authz]` warning and skips resolver emission. The action's own hand-rolled gate (if any) keeps the route working at runtime.\n- **v0.20** — hard compile error. Set `firewall: { exception: true }` to opt out (cross-tenant/admin routes only).\n\nPair the relationship with `loads` + `exposeAs` to hydrate the loaded resource onto `ctx`:\n\n```typescript\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events', // ← v0.19+: load matching event row\n exposeAs: 'event', // ← onto ctx.event for the action body\n },\n },\n roles: {\n attendee: { via: 'attendeeOf' },\n },\n}\n```\n\nThe resolver (v0.20):\n\n1. **Cheap in-memory role check** first — `ctx.roles?.includes('admin')` and friends. If the caller has a qualifying role, this short-circuits and no DB queries fire for the access gate.\n2. **Firewall-gated relationship match** if the role check failed — `SELECT { organizationId, teamId } FROM guests WHERE userId=ctx.userId AND eventId=input.eventId AND status='confirmed'` with the `guests` table's full firewall AND-applied. If neither role nor relationship qualifies → 403.\n3. **Tenant stamping from the matched row** — for any tenant column the `from` table carries (`organizationId`, `teamId`), the resolver stamps `ctx.activeOrgId ??= matchedRow.organizationId` (and similar for team). This is **in-memory mutation of the request-scoped ctx only** — no JWT remint, no session-record write, no persistent grant.\n4. **Firewall-gated load of the loaded resource** — `SELECT * FROM events WHERE id = :eventId AND buildEventsFirewallConditions(ctx, db)`. The events firewall is applied as normal; it succeeds for attendees because tenant was just stamped from the relationship row.\n5. Assigns the loaded row to `ctx.event` for the action body.\n\n**No firewall bypass anywhere.** Both queries run with their respective tables' full firewalls. The relationship row's existence is the proof that the caller is authorized; its tenant columns are the source of the stamped claim.\n\n### Conditional tenant preconditions (v0.20+)\n\nStandalone actions in features with org/team-scoped tables previously emitted unconditional preconditions:\n\n```ts\nif (!ctx.activeOrgId) return c.json(AccessErrors.noOrg(), 403);\nif (!ctx.activeTeamId) return c.json(AccessErrors.noTeam(), 403);\n```\n\nThese ran **before** the relationship resolver, which 403'd attendees whose sessions don't carry an active tenant claim (the canonical event-attendee shape).\n\nv0.20 makes these preconditions **conditional on relationship supply**. If the access tree contains a relationship arm whose `from` table carries the matching tenant column, the precondition is skipped — the resolver runs first and stamps the value. Pseudo-role short-circuits (PUBLIC / AUTHENTICATED / USER / ADMIN / SYSADMIN) and `firewall: { exception: true }` still bypass the preconditions as before.\n\nTypical event-attendee setup (`guests` table carries `organizationId`): the org precondition is dropped on every action whose access references `attendee` or `eventStaff`. Org admins still get `ctx.activeOrgId` from their session as today; attendees get it from the relationship row, mid-request. Both paths converge on a valid tenant claim before `execute()` runs.\n\n### Requirement on the relationship's `from` table\n\nFor the v0.20 tenant-stamping to work, the relationship's `from` table must carry tenant columns:\n\n- For org stamping: an `organizationId` column (or whatever spelling the project's auth-provider defaults pick).\n- For team stamping: a `teamId` column.\n\nWhen the `from` table has **neither**, the compiler emits a `[quickback:authz]` warning at compile time:\n\n```\nRelationship \"X\" at authz.relationships.X has no organization or team columns\non its `from` table (\"guests\"). Action \"Y\" will compile, but downstream\nscoped-db queries inside execute() may 403 because ctx.activeOrgId /\nactiveTeamId cannot be stamped from the match row. Either add the tenant\ncolumn to \"guests\", or set firewall: { exception: true } on the action.\n```\n\nThe relationship match still works (existence check), but no tenant gets stamped — so the conventional precondition still fires and the action still 403s for callers without a session-resident tenant claim. Add the tenant column (or denormalize it onto the relationship table during writes) to enable the stamping path.\n\nThe body can then trust `ctx.event` and drop the hand-rolled `SELECT … FROM guests WHERE …` boilerplate:\n\n```ts\n// features/chat/actions/getInbox.ts\nexport default defineAction({\n path: '/chat/get-inbox',\n input: z.object({ eventId: z.number().int().positive() }),\n access: { roles: ['admin', 'member', 'attendee'] }, // attendee is a relationship-role\n execute: async ({ db, ctx, input }) => {\n // No hand-rolled attendance check needed — the resolver already ran.\n // ctx.event is the loaded events row. Typed as `any` here because the\n // hand-rolled `roles: ['attendee']` action gates per-action, not per-\n // namespace — see \"Narrow ctx.<exposeAs> typing\" below for the typed\n // import flip available when the same hydration runs through a\n // namespace mount.\n const event = ctx.event as typeof events.$inferSelect;\n // … domain logic only.\n },\n});\n```\n\n`loads` and `exposeAs` are co-required (set both or neither). `exposeAs` must be a valid JS identifier and must not collide with built-in `ctx` fields (`userId`, `activeOrgId`, `activeTeamId`, `db`, etc.).\n\n### Action firewall escape hatch (v0.19+)\n\n`defineAction({ firewall: { exception: true } })` opts the action out of the inherited session-key preconditions (`ctx.activeOrgId` / `ctx.activeTeamId` requirements) AND the relationship resolver. The handler receives `unsafeDb` for raw Drizzle access. Use for cross-tenant or admin routes whose surface intentionally doesn't name a session/relationship key:\n\n```ts\ndefineAction({\n path: '/admin/cross-tenant-report',\n firewall: { exception: true },\n unsafe: { reason: 'cross-tenant audit', adminOnly: true, targetScope: 'all' },\n access: { roles: ['ADMIN'] },\n execute: async ({ unsafeDb, ctx }) => { /* cross-org query */ },\n});\n```\n\n`firewall: { exception: true }` is the declarative twin of `unsafe: true` — they're conceptually distinct: `firewall.exception` opts out of the gate-emission pillars; `unsafe` signals audit/cross-tenant intent (and still applies for logging). Most cross-tenant actions set both.\n\n### Recommended pattern: gate at the firewall layer\n\nMost of the time, relationship-based row visibility is what you want, and putting it at the **firewall** layer is the cleanest expression. The firewall is row-filter; the access layer is route/role-filter; let each do its job:\n\n```typescript\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' }, // ← row visibility\n],\nread: {\n access: { roles: ['admin', 'member'] }, // ← who can hit the route\n views: {\n cms: { access: { roles: ['admin', 'member'] }, fields: [...] },\n guest: { access: { roles: ['member', 'admin'] }, fields: [...] },\n },\n},\n```\n\nA guest who's in your org as `member` can hit the endpoint and the firewall filters them down to events they're guests of. Cross-tenant access is impossible because the org filter is the outermost AND.\n\n### Cross-tenant \"my events\" dashboards are NOT this\n\nA common adjacent pattern — \"logged-in user wants `GET /my-events` returning events they're a guest of *across all tenants*\" — is **not** solved by relationship-roles. The tenant firewall is enforced at the outermost AND, so a guest of an event in another tenant remains correctly blocked.\n\nFor cross-tenant aggregation, use one of:\n\n- **User-scoped firewall**: `firewall: { owner: { column: 'userId' } }` — a flat per-user table.\n- **A standalone action that walks the relationship table itself** — see worked example below.\n\nDon't reach for relationship-roles first and then get confused when the tenant firewall blocks. The two patterns serve different problems.\n\n#### Worked example: `GET /my-events` standalone action\n\nThe cleanest expression of the cross-tenant attendee dashboard is a standalone action with a custom path that does its own join against the relationship table. The action is gated by `roles: ['AUTHENTICATED']` (any signed-in user can hit it; per-row scoping is the query itself), and the SQL filters by `ctx.userId` so each caller sees exactly the events they're a guest of:\n\n```ts\n// features/dashboard/actions/myEvents.ts\n\nexport default defineAction({\n description: \"List events the caller is a confirmed guest of, across all tenants.\",\n path: '/my-events',\n method: 'GET',\n input: z.object({}),\n // Any signed-in user. Row visibility comes from the query, not the role.\n access: { roles: ['AUTHENTICATED'] },\n async execute({ db, ctx }) {\n // 1. Find every event the caller has a confirmed guest row for.\n const guestRows = await db\n .select({ eventId: guests.eventId })\n .from(guests)\n .where(\n and(\n eq(guests.userId, ctx.userId!),\n eq(guests.status, 'confirmed'),\n // guests.organizationId is NOT filtered here — that's the whole\n // point of the cross-tenant lane. The relationship row's org is\n // ambient information that this action explicitly traverses.\n )\n );\n\n if (guestRows.length === 0) return { events: [] };\n\n // 2. Pull the matching events. NOTE: this query also bypasses\n // `events.organizationId` scope — by design — so explicitly filter\n // out soft-deleted rows yourself if your `events` table uses them.\n const eventIds = guestRows.map((r) => r.eventId);\n const rows = await db\n .select()\n .from(events)\n .where(inArray(events.id, eventIds));\n\n return { events: rows };\n },\n});\n```\n\nWhy this is a standalone action and not a CRUD route:\n\n- **Tenant firewall would block it.** The default `firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }]` on `events` is correct for every other read — only the cross-tenant dashboard wants to step outside it, and that's a deliberate, explicit step taken in handler code.\n- **The join is the access control.** A relationship-role at the firewall layer can't express \"filter by this user's relationships, ignoring the org context.\" The handler does that join directly.\n- **Audit-logged automatically.** Standalone actions are mandatorily audit-logged in the runtime — the cross-tenant traversal is recorded with `ctx.userId`, IP, and timing.\n\nTwo important guardrails when you write one of these:\n\n1. **Always filter by `ctx.userId` in the relationship lookup.** If you accept a `userId` from the request body and trust it, you've built an IDOR. The example above uses `ctx.userId!` directly so the only events returned are the caller's.\n2. **You take responsibility for soft-delete and other invariants the firewall would otherwise apply.** Add the `deletedAt` filter, status checks, and any other row-level predicates by hand. The action is OUTSIDE the firewall pipeline by design — the cost is that you can't lean on the auto-applied predicates.\n\nIf you find yourself writing more than one of these per project, that's usually a signal to revisit the schema (could a user-owned `userEvents` materialized view replace the join?) rather than a sign Quickback should ship a higher-level abstraction. Cross-tenant lanes are intentionally explicit.\n\n### Compile-time refusals (consolidated)\n\nThe validator and resolver reject:\n\n- Unknown key in `authz` block (typo guard — `realtionships` would otherwise silently produce a permanently-denied role).\n- Reserved role-name (auth-provider-derived). Names like `guest`, `speaker`, `attendee` are free; `admin`/`owner`/`member` are reserved when the BA org plugin is on.\n- Cycle in role composition (`a → b → a`).\n- Relationship `from` references unknown table.\n- Relationship-role used on a resource missing the `resource.column`.\n- Relationship table with `firewall: { exception: true }` (would let cross-tenant grants slip through).\n- `lowering: 'session'` (reserved for v2 — staleness/invalidation ergonomics not yet shipped).\n- `+` hierarchy suffix on a relationship-role name (terminal, like pseudo-roles).\n- Relationship-roles in `masking.show` / `actions.access` (deferred surfaces — see the table above).\n\n## Namespace mounts (hoisted relationship middleware)\n\nWhen several standalone actions share a path prefix and the same relationship gate — `/event/:eventId/announce`, `/event/:eventId/cancel`, `/event/:eventId/respond` — declaring the gate per-action means writing the same `roles: ['attendee']` over and over AND paying the relationship-resolver cost N times per request (one subquery + one row-load, multiplied by the number of actions).\n\nNamespace mounts hoist the resolver into one Hono middleware that runs once per request. Every action under the prefix skips the inline gate; `ctx.<exposeAs>` is hydrated by the middleware before the action's `execute()` runs. With the per-namespace helper (v0.27+, [below](#narrow-ctxexposeas-typing-v027)), that field is also statically typed as the loaded row.\n\n### When to use roles vs. relationships\n\nA user is authorized for a row when **any** of the following is true:\n\n- they have a **per-row relationship** to it (e.g. an attendee row, a named organizer row), or\n- they have a **role on the row's tenant** (org admin/owner of the row's `organizationId`), or\n- they have **team membership** matching the row's `teamId`.\n\nUse **relationships** when membership is specific to *this row* — external collaborators who aren't in your org, attendees, anyone connected to the resource by virtue of data rather than payroll. Use **roles / team** when staff at your org/team should see everything in their scope by default.\n\nThe two compose at the action level (`access.or` accepts both relationship-roles and tenant roles) and — as of v0.25 — at the namespace level too: `namespace.via` accepts an array of lanes, first match wins.\n\n> **Rule of thumb.** If the answer is *\"yes if you work here,\"* reach for org/team roles. If the answer is *\"yes if you have something to do with **this** row,\"* reach for a per-row relationship. Reach for both together — at the namespace or via `access.or` — when an action should let either side in.\n\nTwo declaration sites depending on whether the participating actions live in one feature or many:\n\n### Single feature: `defineTable({ namespace })` (v0.23+)\n\nUse when every action under the prefix lives in the same feature directory. The namespace travels with the table that owns it — no addition to `quickback.config.ts` needed.\n\n```typescript\n// features/events/events.ts\nexport default defineTable(events, {\n firewall: [...],\n crud: { ... },\n namespace: {\n prefix: '/event/:eventId', // absolute URL path\n via: 'attendeeOf', // relationship gate (must exist in authz.relationships)\n },\n});\n\n// features/events/actions/post-announcement.ts\nexport default defineAction({\n path: '/event/:eventId/announcements',\n method: 'POST',\n // No gate boilerplate. ctx.event is typed inside execute().\n});\n```\n\nThe compiler emits one `app.use(...)` on the events feature's Hono app. Every standalone action in `features/events/actions/` whose path starts with `/event/:eventId/` joins the namespace automatically.\n\nMulti-lane via (v0.25+) and bulk-grant lanes (v0.26+) work identically on the table-level declaration — `via:` accepts the same shapes documented below for the project-level form.\n\n### Cross-feature: `authz.namespaces` (v0.24+)\n\nUse when the namespace spans multiple features. The declaration sits next to your other authz config in `quickback.config.ts`.\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n namespaces: {\n eventScope: { prefix: '/event/:eventId', via: 'attendeeOf' },\n },\n}\n```\n\nWith the namespace declared, any standalone action whose `path:` matches the prefix joins the gate — regardless of which feature owns it:\n\n```typescript\n// features/feeds/actions/feed-moments.ts (in one feature)\nexport default defineAction({\n path: '/event/:eventId/feed-moments',\n method: 'POST',\n});\n\n// features/rsvp/actions/respond.ts (in a different feature)\nexport default defineAction({\n path: '/event/:eventId/respond',\n method: 'POST',\n});\n```\n\nThe compiler emits one synthetic `src/routes/__namespace-event-scope.routes.ts` that imports each contributing feature's `actions` map under a distinct alias, mounts the resolver middleware once, and dispatches to the matching action. Worker-root mount order ensures the middleware fires before any per-feature route handler under the prefix.\n\n### Multi-lane via (v0.25+) — first match wins\n\nWhen more than one relationship can authorize a caller for the namespaced resource, pass `via:` as an array. The middleware tries each lane in declaration order and stops at the first match — `ctx.<exposeAs>` is hydrated from whichever lane fired.\n\n```typescript\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'linkedUserId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events',\n exposeAs: 'event',\n },\n // Named per-event organizers (potentially EXTERNAL — these users may\n // not be a member of the event's org. That's the point: lets you grant\n // event-level access to freelancers / partner staff without adding\n // them to the org's member list.)\n organizerOf: {\n from: 'eventOrganizers',\n subject: { column: 'linkedUserId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n namespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: ['attendeeOf', 'organizerOf'],\n },\n },\n}\n```\n\nAll relationship lanes in a namespace **must agree on `loads:` + `exposeAs:`** — that's what guarantees `ctx.event` has the same shape regardless of which lane matched. The compiler rejects heterogeneous lanes at parse time.\n\n### Bulk-grant lanes (v0.26+)\n\nRelationship lanes cover \"specifically connected to this row.\" Bulk-grant lanes cover \"anyone with this role / team membership in the row's tenant\" — the case where an org admin or a team member should see every event in their scope without writing per-event relationship rows.\n\n```typescript\nnamespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: [\n 'attendeeOf',\n 'organizerOf',\n { roles: ['admin', 'owner'] }, // org-role bulk grant\n { team: true }, // active-team-membership bulk grant\n ],\n },\n}\n```\n\nEach bulk-grant lane:\n\n- **`{ roles: [...] }`** — passes when the caller's BA org-role for the loaded resource's tenant includes any listed role. Short-circuits the relationship loop entirely; the role check is in-memory and cheap. Use for the \"company admin sees everything\" case.\n- **`{ team: true }`** — passes when `ctx.activeTeamId` is set. The loads-table firewall does the actual `events.teamId === ctx.activeTeamId` check during hydration. Use when the resource is team-scoped and you want active-team membership to grant access.\n\nBoth bulk-grant lanes piggyback on the namespace's relationship lane(s) for hydration — they don't fetch a separate per-row subject; they just gate access and let the loads-table firewall handle the tenant scoping. **At least one relationship lane is required** alongside bulk-grant lanes in v0.26 (to anchor `loads:` + `exposeAs:`).\n\nWhen a request misses every lane, the 403 deny payload lists every authorization path the caller could have taken — relationship names, role names, and `\"team-membership\"` for `{ team: true }` lanes — so a developer debugging an unexpected 403 sees the full surface they need to satisfy.\n\n### Discovery is path-prefix-only\n\nActions opt in by matching `path:` against a declared namespace prefix. There's no `namespace: 'foo'` field on `defineAction` — the path string is the discoverable surface, consistent with how `path:` already determines an action's URL.\n\n### Requirements (enforced at compile time)\n\nBoth forms share the same shape checks:\n\n- **`via:` accepts one of three shapes.** A single relationship name (v0.23+), an array of relationship names (v0.25+, first match wins), or — as of v0.26 — an array mixing relationship names with bulk-grant guards (`{ roles: [...] }`, `{ team: true }`).\n- **Every relationship lane must declare `loads + exposeAs`.** Without `loads` there's nothing for the middleware to hydrate; the namespace gate would be indistinguishable from a per-action access rule.\n- **All relationship lanes in one namespace must agree on `loads:` + `exposeAs:`.** Otherwise `ctx.<exposeAs>` would change shape depending on which lane matched.\n- **Bulk-grant lanes inherit `loads:` + `exposeAs:` from sibling relationship lanes.** Pure bulk-grant namespaces (no relationship lane at all) are also accepted — set `loads:` + `exposeAs:` directly on the namespace declaration so hydration has somewhere to anchor.\n- **`prefix:` must contain at least one `:param` segment** (e.g. `/event/:eventId`). The middleware reads the relationship key from `c.req.param()` because no request body has been parsed at middleware time.\n- **One declaration per namespace name.** The same name in both `defineTable({ namespace })` and `authz.namespaces` is rejected. The project-level form is canonical for cross-feature; the table-level form is the single-feature shorthand.\n\nProject-level only:\n\n- **Ambiguous prefixes** like `/a/:x` and `/a/:y` (same shape, different `:param` names) are rejected. Strict super/sub-set relationships (`/event/:e` vs `/event/:e/admin`) are fine — the harvester routes each action to the longest matching prefix.\n- **Unused namespace** emits a `[quickback:authz]` warning when no action's path matches the declared prefix. Not a hard error — the namespace may be staged ahead of the actions.\n\n### What namespace actions get for free\n\nInside a namespace action's `execute()`:\n\n- `ctx.<exposeAs>` is populated by the middleware with the loaded resource row. Statically `any` by default — narrowed to `typeof <loadsTable>.$inferSelect` when the action's import points at the per-namespace helper (see [below](#narrow-ctxexposeas-typing-v027)).\n- Tenant context (`ctx.activeOrgId` / `ctx.activeTeamId`) is stamped from the matched relationship row when its `from` table carries those columns. Downstream scoped queries work without further setup.\n- The action's own `access:` block (additional roles, userRole, record predicates, OTHER relationship arms) still runs after the namespace gate — namespace handles entry, per-action gates further.\n\n### Narrow `ctx.<exposeAs>` typing (v0.27+)\n\nThe namespace middleware hydrates `ctx.<exposeAs>` at runtime — that's been true since v0.23. The static type of that field, though, is `any` via the `AppContext` index signature: useful for not blocking access, but a missed opportunity for autocomplete and typo-catching.\n\nv0.27 emits one **per-namespace `defineAction` helper** alongside the standard `<feature>/.quickback/define-action.ts`. Importing from the narrowed helper retypes `ctx.<exposeAs>` inside `execute({ ctx })` to the loaded row's `$inferSelect` shape. Nothing else changes — runtime behavior, action discovery, and the `path:` namespace match are identical.\n\n```ts title=\"features/feeds/actions/feed-moments.ts\"\n// One-line flip per namespace-scoped action:\n\n// └──────┬──────┘\n// kebab(namespaceName)\n\nexport default defineAction({\n path: '/event/:eventId/feed-moments',\n method: 'POST',\n input: z.object({ body: z.string() }),\n access: { roles: ['attendee'] },\n async execute({ ctx, input }) {\n ctx.event.id // ✓ string\n ctx.event.startsAt // ✓ Date — autocomplete works\n ctx.event.organizerId // ✓ narrows on the field's declared type\n\n ctx.event.idd // ✗ TS2339 — typo caught at compile time\n },\n});\n```\n\nThe compiler emits one helper per `(feature, namespace)` pair where the feature owns at least one action whose `path:` falls under the namespace prefix. Filename is `define-action.<kebab(namespaceName)>.ts` — `eventScope` becomes `define-action.event-scope.ts`. Helpers live next to the standard `define-action.ts` in `<feature>/.quickback/`, so the relative import is the same shape as every other action file in your project.\n\n#### Opt-in, not breaking\n\nActions that keep their existing `import { defineAction } from '../.quickback/define-action'` continue to compile unchanged — `ctx.<exposeAs>` is `any` via the `AppContext` index signature, which is exactly the v0.23–v0.26 behavior. You flip imports per action at your own pace.\n\n#### Compile-time advisory\n\nWhen `quickback compile` sees a namespace-scoped action still importing the generic helper, it emits a one-line advisory pointing at the narrowed path:\n\n```text\n[quickback:typing] action \"feedMoments\" in feature \"feeds\" lives under\n namespace \"eventScope\" — switch its import to\n `../.quickback/define-action.event-scope` for narrow ctx.<exposeAs> typing.\n (Runtime behavior is unchanged; the narrowed helper only refines TS types.)\n```\n\nNon-blocking — same `[quickback:typing]` family as `[quickback:authz]`. The advisory only mentions actions the compiler can be confident about (namespace-claimed actions whose source still imports the generic helper).\n\n#### Multi-namespace features\n\nA single feature can contribute actions to several namespaces — say, an `interviews` feature with actions under both `interviewScope` and `eventScope`. The compiler emits one narrowed helper per namespace the feature participates in, and each action picks the import that matches its path.\n\n```text\nsrc/features/interviews/.quickback/\n├── define-action.ts # generic — standard fallback\n├── define-action.interview-scope.ts # ctx.interview typed\n└── define-action.event-scope.ts # ctx.event typed\n```\n\n#### Why per-namespace and not per-action\n\nA `defineAction` helper that's narrow to *one* exposed key (the namespace's `exposeAs`) is enough — every action under a namespace sees the same hydrated key. The alternative (per-action emit) duplicates the same prelude N times for the same shape; per-namespace keeps emission proportional to the number of distinct hydration shapes in the project.\n\n## Read & Write Configuration\n\nReads (`GET /` and `GET /:id`) live under `read:`; mutations live under top-level `create:`, `update:`, `delete:`, and `upsert:`. See [Read](/compiler/definitions/read) for the full read pipeline reference.\n\n```typescript\nread: {\n // LIST + GET - GET /resource and GET /resource/:id\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n pageSize: 25, // Default page size\n maxPageSize: 100, // Client can't exceed this\n views: { // Per-view field projections\n summary: {\n fields: ['id', 'candidateId', 'jobId', 'stage'],\n access: { roles: [\"interviewer\"] },\n },\n },\n}\n\ncreate: {\n // CREATE - POST /resource\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] },\n defaults: { // Default values for new records\n stage: 'applied',\n },\n},\n\nupdate: {\n // UPDATE - PATCH /resource/:id\n access: {\n or: [\n { roles: [\"hiring-manager\", \"recruiter\"] },\n { roles: [\"interviewer\"], record: { stage: { equals: \"interview\" } } }\n ]\n },\n},\n\ndelete: {\n // DELETE - DELETE /resource/:id\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"soft\", // 'soft' (default) or 'hard'\n},\n\nupsert: {\n // PUT - PUT /resource/:id (only when generateId: false + guards: false)\n access: { roles: [\"hiring-manager\", \"sync-service\"] },\n}\n```\n\n## Evaluation Order\n\nGenerated `/:id` and batch handlers evaluate access in this fixed order:\n\n1. **Auth gate** — 401 if unauthenticated\n2. **Pre-record access** — role-only check (skips `access.record` predicates)\n3. **Firewall query** — `WHERE` clause filters by ownership\n4. **Post-record access** — full check including record-level predicates\n5. **Masking** — applied to the response\n\nStep 2 closes the 404-vs-403 ID-probe channel: an unauthorized caller without\na matching role gets 403 before the database is touched, so they can't tell\napart \"row exists out-of-scope\" from \"row doesn't exist.\" A caller with the\nright role but the wrong tenant gets 403 by default (firewall reveals via\nthe access layer); set\n[`firewallErrorMode: 'hide'`](/compiler/definitions/firewall) to return an\nopaque 404 instead.\n\nFunction-form access (`access: async (ctx, record) => ...`) is opaque to\nthe pre-record phase and always passes there; it's fully evaluated post-record.\n\n## List Filtering (Query Parameters)\n\nThe LIST endpoint automatically supports filtering via query params:\n\n```\nGET /jobs?status=open # Exact match\nGET /jobs?salaryMin.gt=50000 # Greater than\nGET /jobs?salaryMin.gte=50000 # Greater than or equal\nGET /jobs?salaryMax.lt=200000 # Less than\nGET /jobs?salaryMax.lte=200000 # Less than or equal\nGET /jobs?status.ne=closed # Not equal\nGET /jobs?title.like=Engineer # Pattern match (LIKE %value%)\nGET /jobs?status.in=open,draft # IN clause\n```\n\n| Operator | Query Param | SQL Equivalent |\n|----------|-------------|----------------|\n| Equals | `?field=value` | `WHERE field = value` |\n| Not equals | `?field.ne=value` | `WHERE field != value` |\n| Greater than | `?field.gt=value` | `WHERE field > value` |\n| Greater or equal | `?field.gte=value` | `WHERE field >= value` |\n| Less than | `?field.lt=value` | `WHERE field < value` |\n| Less or equal | `?field.lte=value` | `WHERE field <= value` |\n| Pattern match | `?field.like=value` | `WHERE field LIKE '%value%'` |\n| In list | `?field.in=a,b,c` | `WHERE field IN ('a','b','c')` |\n\n## Sorting & Pagination\n\n```\nGET /jobs?sort=createdAt&order=desc # Sort by field\nGET /jobs?limit=25&offset=50 # Pagination\n```\n\n- **Default limit**: 50\n- **Max limit**: 100 (or `maxPageSize` if configured)\n- **Default order**: `asc`\n\n## Delete Modes\n\n```typescript\ndelete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"soft\", // Sets deletedAt/deletedBy, record stays in DB\n}\n\ndelete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"hard\", // Permanent deletion from database\n}\n```\n\n## Context Variables\n\nUse `$ctx.` prefix to reference context values in conditions:\n\n```typescript\n// User can only view their own records\naccess: {\n record: { userId: { equals: \"$ctx.userId\" } }\n}\n\n// Nested path support for complex context objects\naccess: {\n record: { ownerId: { equals: \"$ctx.user.id\" } }\n}\n```\n\n### AppContext Reference\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `$ctx.userId` | `string` | Current authenticated user's ID |\n| `$ctx.activeOrgId` | `string` | User's active organization ID |\n| `$ctx.activeTeamId` | `string \\| null` | User's active team ID (if applicable) |\n| `$ctx.roles` | `string[]` | User's roles in current context |\n| `$ctx.isAnonymous` | `boolean` | Whether user is anonymous |\n| `$ctx.user` | `object` | Full user object from auth provider |\n| `$ctx.user.id` | `string` | User ID (nested path example) |\n| `$ctx.user.email` | `string` | User's email address |\n| `$ctx.{property}` | `any` | Any custom context property |\n\n## Function-Based Access\n\nFor complex access logic that can't be expressed declaratively, use a function:\n\n```typescript\nupdate: {\n access: async (ctx, record) => {\n // Custom logic - return true to allow, false to deny\n if (ctx.roles.includes('admin')) return true;\n if (record.ownerId === ctx.userId) return true;\n\n // Check custom business logic\n const membership = await checkTeamMembership(ctx.userId, record.teamId);\n return membership.canEdit;\n }\n}\n```\n\nFunction access receives:\n- `ctx`: The full AppContext object\n- `record`: The record being accessed (for get/update/delete operations)"
|
|
79
79
|
},
|
|
80
80
|
"compiler/definitions/actions": {
|
|
81
81
|
"title": "Actions",
|
|
82
|
-
"content": "Actions are custom API endpoints for business logic beyond CRUD operations. They enable workflows, integrations, and complex operations.\n\n## Overview\n\nQuickback supports two types of actions:\n\n| Aspect | Record-Based | Standalone |\n|--------|--------------|------------|\n| Route | `{METHOD} /:id/{actionName}` | Custom `path` (required) |\n| Record fetching | Automatic | None (`record` is `undefined`) |\n| Firewall applied | Yes | No |\n| Preconditions | Supported via `access.record` | Not applicable |\n| Response types | JSON only | JSON, stream, file |\n| Use case | Advance application, reject candidate | AI chat, bulk import from job board, webhooks |\n\nStandalone actions are signalled by the presence of a `path:` field in the action config. Record-based actions omit `path` and bind to the feature's primary table.\n\n## Where do actions live?\n\n**One file per action.** Each action is its own module under the feature's\n`actions/` directory:\n\n```\nfeatures/applications/\n├── applications.ts ← defineTable (primary table)\n├── candidates.ts ← defineTable (sibling table)\n├── actions/\n│ ├── advance.ts ← defineAction, binds to applications\n│ ├── reject.ts ← defineAction, binds to applications\n│ ├── stats.ts ← defineAction, standalone (has `path:`)\n│ └── candidates/\n│ └── disqualify.ts ← defineAction, binds to candidates\n└── lib/\n └── inputs.ts ← shared schemas (optional, copied verbatim)\n```\n\n| Layout | Binds to |\n|--------|----------|\n| `actions/<name>.ts` | The feature's primary table (table file matching the feature name), or standalone if `path:` is set. |\n| `actions/<table>/<name>.ts` | The sibling table file `<table>.ts` at the feature root. Standalone actions inside a subdir ignore the binding. |\n\nThe action's filename (sans `.ts`) is the action name and the URL segment.\nUniqueness is enforced per `(bound table, name)` pair — sibling-bound\nactions on **different** tables may share a verb (`actions/episodes/publish.ts`\nand `actions/shows/publish.ts` mount at `/episodes/:id/publish` and\n`/shows/:id/publish` and compile cleanly). The compiler errors only when\ntwo action files would mount at the same URL — for example, a flat\n`actions/foo.ts` (binds to primary) plus `actions/<primary>/foo.ts`, or\ntwo standalones with the same `(method, path)`. Standalone actions are\nunique per `(method, path)`.\n\nTableless features have no top-level `*.ts` files; every action under\n`actions/` must be standalone (have `path:`). Use this for utility endpoints\nlike webhooks, reports, or integrations that don't operate on a specific\nrecord.\n\n### Retired layouts\n\nThese are rejected at load time with migration guidance:\n\n- **`actions.ts`** (bundled multi-action file)\n- **`_feature.ts`** (shared schemas + non-table-bound actions)\n- **`handlers/`** (separate handler-file directory)\n- **`defineActions(table, {...})`** (the multi-action factory)\n- **`defineActions(null, {...})`** (tableless variant)\n- **`*-actions.ts` / `*.actions.ts`** filename patterns\n\nFor shared Zod schemas or helpers, put them under `<feature>/lib/` and import\nfrom each action file. Files under `lib/` are copied verbatim into the\ngenerated output.\n\n## Defining Actions\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n notes: z.string().max(2000).optional(),\n }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: {\n applied: [\"screening\"],\n screening: [\"interview\"],\n interview: [\"offer\"],\n },\n },\n async execute({ db, record, input, whereTransition }) {\n const [updated] = await db\n .update(applications)\n .set({\n status: input.nextStatus,\n notes: input.notes ?? record.notes,\n })\n .where(whereTransition!(applications))\n .returning();\n return updated;\n },\n});\n```\n\n> **`defineAction` import.** Import from `\"../.quickback/define-action\"` —\n> the `.quickback/` directory is generated alongside your feature with a\n> typed helper that infers `record` and `input` types from the rest of the\n> action config. Audit fields (`createdAt`, `createdBy`, `modifiedAt`,\n> `modifiedBy`) are hard-stamped by the audit DB wrapper on every\n> `db.insert().values()` and `db.update().set()` — handlers don't pass\n> them and can't override them.\n\n### Configuration Options\n\n| Option | Required | Description |\n|--------|----------|-------------|\n| `description` | Yes | Human-readable description of the action |\n| `input` | Yes | Zod schema for request validation |\n| `access` | Yes | Access control (roles, record conditions, or function) |\n| `execute` | Yes | Inline async arrow function (`async (ctx) => { … }`) |\n| `path` | Standalone only | Custom route path. Presence of `path` makes the action standalone. |\n| `method` | No | HTTP method: GET, POST, PUT, PATCH, DELETE (default: POST) |\n| `responseType` | No | Response format: json, stream, file (default: json) |\n| `sideEffects` | No | Hint for AI tools: `'sync'`, `'async'`, or `'fire-and-forget'` |\n| `allowRawSql` | No | Explicit compile-time opt-in for raw SQL in execute code |\n| `unsafe` | No | Unsafe raw DB mode. Object config (`reason`, `adminOnly`, `crossTenant`, `targetScope`). |\n| `transition` | No | State-machine policy enforcing the from/to pair (record-based actions). See [Transitions](#transition-state-machine-policy) |\n| `bulkVariant` | No | Auto-generate a `POST /:resource/batch/{action}` route alongside the per-record route (record-based actions). See [Bulk Variant](#bulk-variant) |\n| `cms` | No | Pass-through metadata blob for CMS surfaces |\n\n`execute` must be an `async (ctx) => { … }` arrow function. `async function`\ndeclarations and non-async forms are rejected at parse time.\n\n## Record-Based Actions\n\nRecord-based actions operate on an existing record. The record is automatically loaded and validated before your action executes.\n\n**Route pattern:** `{METHOD} /:id/{actionName}`\n\n```\nPOST /applications/:id/advance\nPOST /applications/:id/reject\nPOST /applications/:id/schedule-interview\n```\n\n### Runtime Flow\n\n1. **Authentication** - User token is validated\n2. **Record Loading** - The record is fetched by ID\n3. **Firewall Check** - Ensures user can access this record\n4. **Access Check** - Validates roles and preconditions\n5. **Input Validation** - Request body validated against Zod schema\n6. **Execution** - Your action handler runs\n7. **Response** - Result is returned to client\n\n### Example: Advance Application Stage\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move application to the next pipeline stage\",\n input: z.object({\n stage: z.enum([\"screening\", \"interview\", \"offer\", \"hired\"]),\n notes: z.string().optional(),\n }),\n access: {\n roles: [\"owner\", \"hiring-manager\"],\n record: { stage: { notEquals: \"rejected\" } },\n },\n async execute({ db, record, input }) {\n const [updated] = await db\n .update(applications)\n .set({\n stage: input.stage,\n notes: input.notes ?? record.notes,\n })\n .where(eq(applications.id, record.id))\n .returning();\n return updated;\n },\n});\n```\n\n### Request Example\n\n```\nPOST /applications/app_123/advance\nContent-Type: application/json\n\n{\n \"stage\": \"interview\",\n \"notes\": \"Strong technical background, moving to interview\"\n}\n```\n\n### Response Example\n\n```json\n{\n \"data\": {\n \"id\": \"app_123\",\n \"stage\": \"interview\",\n \"notes\": \"Strong technical background, moving to interview\"\n }\n}\n```\n\n### Bulk variant\n\nSet `bulkVariant: true` to auto-generate a bulk version of the action at\n`POST /:resource/batch/{action}`. The compiler emits a second route alongside\nthe per-record one, looping the same access + transition + execute pipeline\nover an array of ids. This is the answer to \"I need to advance 50\napplications at once\" — you don't have to hand-roll a parallel standalone\naction that duplicates the per-record logic.\n\n```typescript\n// features/applications/actions/advance.ts\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n bulkVariant: true,\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: { applied: [\"screening\"], screening: [\"interview\"], interview: [\"offer\"] },\n },\n async execute({ db, record, input, whereTransition }) {\n const [updated] = await db\n .update(applications)\n .set({ status: input.nextStatus })\n .where(whereTransition!(applications))\n .returning();\n if (!updated) throw new TransitionLostError(\"status\", record.status, input.nextStatus);\n return updated;\n },\n});\n```\n\n**Request shape:**\n\n```http\nPOST /applications/batch/advance\nContent-Type: application/json\n\n{\n \"ids\": [\"app_001\", \"app_002\", \"app_003\"],\n \"input\": { \"nextStatus\": \"interview\" },\n \"failFast\": false\n}\n```\n\nThe `input` is shared across the batch — the action's Zod schema is\nvalidated once, not per id. For per-record input variation, use the\nsingle-record endpoint (`POST /:id/{action}`) or write a standalone action.\n\n**Response (207 Multi-Status when any record fails, 200 when clean):**\n\n```json\n{\n \"success\": [{ \"id\": \"app_001\", \"status\": \"interview\" }],\n \"errors\": [\n {\n \"index\": 1,\n \"id\": \"app_002\",\n \"error\": {\n \"error\": \"Action not allowed for current state\",\n \"code\": \"ACCESS_ACTION_NOT_ALLOWED_FOR_STATE\",\n \"details\": { \"field\": \"status\", \"currentValue\": \"rejected\" }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"failFast\": false,\n \"transactional\": false\n }\n}\n```\n\n**Per-record pipeline** mirrors the single-record route exactly — the same\nfirewall fetch, access reason split (403 vs 409), transition pre-check,\n`whereTransition` factory, and `TransitionLostError` handling. Per-record\nfailures land in `errors[]` with their original index; successful records\nland in `success[]` masked the same way the single-record response is.\n\n**Transactional matrix** (same as `PATCH /batch`):\n\n| Provider | failFast | transactional | Behavior |\n|---|---|---|---|\n| neon (Postgres via Hyperdrive) | `true` | `true` | `db.transaction()` wraps the loop; any throw rolls back all writes |\n| (any) | `false` | `false` | Independent per-record outcomes, partial success |\n| cloudflare-d1 | `true` | `false` | Fail-fast loop without rollback — earlier records stay committed (D1 has no `db.transaction`) |\n\n**Constraints:**\n\n- Record-based actions only. Standalone actions reject `bulkVariant: true`\n at compile time (no record context to loop over).\n- `unsafe` actions reject `bulkVariant: true` in v1 — the cross-tenant\n per-record audit story is not yet wired through.\n- Method is forced to POST regardless of the action's `method` setting. The\n semantic asymmetry (one row → many rows) makes inheriting GET/DELETE\n confusing.\n- Max batch size is 100 ids per request.\n\n## Standalone Actions\n\nStandalone actions are independent endpoints that don't require a record context. Set a `path:` to declare the action standalone.\n\n**Route pattern:** Custom `path`\n\n```\nPOST /chat\nGET /reports/summary\nPOST /webhooks/stripe\n```\n\n### Example: AI Chat with Streaming\n\n```typescript\n// features/sessions/actions/chat.ts\n\nexport default defineAction({\n description: \"Send a message to AI\",\n path: \"/chat\",\n method: \"POST\",\n responseType: \"stream\",\n input: z.object({\n message: z.string().min(1).max(2000),\n }),\n access: { roles: [\"recruiter\", \"hiring-manager\"] },\n async execute({ input, c }) {\n // Stream response back to client...\n return c.newResponse(/* ReadableStream */);\n },\n});\n```\n\n### Streaming Response Example\n\nFor actions with `responseType: 'stream'`:\n\n```\nContent-Type: text/event-stream\n\ndata: {\"type\": \"start\"}\ndata: {\"type\": \"chunk\", \"content\": \"Hello\"}\ndata: {\"type\": \"chunk\", \"content\": \"! I'm\"}\ndata: {\"type\": \"chunk\", \"content\": \" here to help.\"}\ndata: {\"type\": \"done\"}\n```\n\n### Tableless Features\n\nA feature directory with no top-level `*.ts` files is \"tableless\" — every\naction under `actions/` must be standalone. Use this for utility endpoints\nlike reports, integrations, or webhooks that don't map to a specific\nresource.\n\n```\nquickback/features/\n└── reports/\n └── actions/\n ├── trial-balance.ts ← standalone (has path:)\n └── profit-loss.ts ← standalone (has path:)\n```\n\n```typescript\n// features/reports/actions/trial-balance.ts\n\nexport default defineAction({\n description: \"Generate trial balance report\",\n path: \"/reports/trial-balance\",\n method: \"GET\",\n input: z.object({\n startDate: z.string(),\n endDate: z.string(),\n }),\n access: { roles: [\"admin\", \"accountant\"] },\n async execute({ db, input }) {\n // ... build report\n return { rows: [] };\n },\n});\n```\n\n## Access Configuration\n\nAccess controls who can execute an action and under what conditions.\n\n### Role-Based Access\n\n```typescript\naccess: {\n roles: [\"hiring-manager\", \"recruiter\"] // OR logic: user needs any of these roles\n}\n```\n\n### Public Access\n\nUse `roles: [\"PUBLIC\"]` for unauthenticated endpoints (contact forms, webhooks, public APIs). Every invocation is **mandatory audit logged** with IP address, input, result, and timing.\n\n```typescript\n// features/contact/actions/submit.ts\n\nexport default defineAction({\n description: \"Public contact form submission\",\n path: \"/submit\",\n input: z.object({\n name: z.string().min(1),\n email: z.string().email(),\n message: z.string().min(10),\n }),\n access: { roles: [\"PUBLIC\"] },\n async execute({ db, input }) {\n // ... persist submission\n return { ok: true };\n },\n});\n```\n\nThe wildcard `\"*\"` is not supported and will throw a compile-time error. Use `\"PUBLIC\"` explicitly.\n\n### Record Conditions\n\nFor record-based actions, you can require the record to be in a specific state:\n\n```typescript\naccess: {\n roles: [\"hiring-manager\"],\n record: {\n stage: { equals: \"screening\" } // Precondition\n }\n}\n```\n\n**Supported operators:**\n\n| Operator | Description |\n|----------|-------------|\n| `equals` | Field must equal value |\n| `notEquals` | Field must not equal value |\n| `in` | Field must be one of the values |\n| `notIn` | Field must not be one of the values |\n\n### Context Substitution\n\nUse `$ctx` to reference the current user's context:\n\n```typescript\naccess: {\n record: {\n ownerId: { equals: \"$ctx.userId\" },\n orgId: { equals: \"$ctx.orgId\" }\n }\n}\n```\n\n### OR/AND Combinations\n\n```typescript\naccess: {\n or: [\n { roles: [\"hiring-manager\"] },\n {\n roles: [\"recruiter\"],\n record: { ownerId: { equals: \"$ctx.userId\" } }\n }\n ]\n}\n```\n\n### Function Access\n\nFor complex logic, use an access function:\n\n```typescript\naccess: async (ctx, record) => {\n return ctx.roles.includes('admin') || record.ownerId === ctx.userId;\n}\n```\n\n### Relationship-roles in actions\n\n**v0.19+** — standalone actions now support relationship-roles in `access.roles` directly. Declare the relationship under `authz.relationships` with optional `loads` / `exposeAs` for ctx hydration, and reference the role by name on the action:\n\n```ts\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n roles: { attendee: { via: 'attendeeOf' } },\n}\n\n// features/chat/actions/getInbox.ts\nexport default defineAction({\n path: '/chat/get-inbox',\n input: z.object({ eventId: z.number().int().positive() }),\n access: { roles: ['admin', 'member', 'attendee'] },\n execute: async ({ db, ctx, input }) => {\n // The resolver already verified attendance and loaded ctx.event.\n // No hand-rolled `SELECT … FROM guests WHERE …` needed.\n },\n});\n```\n\nThe action's surface (path params + input fields) must expose the relationship's `resource.column`. At v0.19 a missing key emits a `[quickback:authz]` warning and skips resolver emission; at v0.20 it becomes a compile error. See [Access — standalone actions](/compiler/definitions/access#standalone-actions-surface-keys-and-loads--exposeas-v019) for the full mechanism.\n\n**Record-based actions** are NOT yet supported — the runtime evaluator fail-closes (403) on relationship arms reached without an inline gate. Until inline emission for record-based actions lands, either:\n\n- Set `firewall: { exception: true }` on the action and gate manually in `execute()`, OR\n- Apply the relationship at the resource's firewall layer (worked example below).\n\n**Resource-layer workaround for record-based actions**: gate the action on BA roles only and apply the relationship at the resource layer via a firewall `via:` predicate:\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n },\n },\n}\n\n// features/sessions/sessions.ts — firewall scopes rows; action gates on BA role\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' }, // ← row-level relationship check\n],\nactions: {\n comment: defineAction({\n access: { roles: ['member', 'admin'] }, // ← BA role only on the action\n input: z.object({ text: z.string() }),\n execute: async (input, ctx, db, record) => {\n // record is already filtered by the firewall — guest membership\n // is enforced before this handler runs.\n return db.insert(comments).values({ ... });\n },\n }),\n}\n```\n\nThis pattern composes cleanly: the firewall guarantees the caller has the relationship to the record being acted on; the action's access list keeps the role surface obvious.\n\nSee [Access — relationship authorization](/compiler/definitions/access#relationship-based-authorization) for the full picture, including `loads` / `exposeAs` and the `firewall: { exception: true }` escape hatch.\n\n## Scoped Database\n\nAll actions receive a **scoped `db`** instance that automatically enforces security:\n\n| Operation | Org Scoping | Owner Scoping | Soft Delete Filter | Auto-inject on INSERT |\n|-----------|-------------|---------------|--------------------|-----------------------|\n| `SELECT` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n| `INSERT` | n/a | n/a | n/a | `organizationId`, `ownerId` from ctx |\n| `UPDATE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n| `DELETE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n\nScoping is duck-typed at runtime — tables with an `organizationId` column get org scoping, tables with `ownerId` get owner scoping, tables with `deletedAt` get soft delete filtering.\n\n```typescript\nasync execute({ db, ctx, input }) {\n // This query automatically includes WHERE organizationId = ? AND deletedAt IS NULL\n const items = await db.select().from(applications).where(eq(applications.stage, 'interview'));\n\n // Inserts automatically include organizationId\n await db.insert(applications).values({ candidateId: input.candidateId, jobId: input.jobId, stage: 'applied' });\n\n return items;\n}\n```\n\n**Not enforced** in scoped DB (by design):\n- **Guards** — actions ARE the authorized way to modify guarded fields\n- **Masking** — actions are backend code that may need raw data\n- **Access** — already checked before action execution\n\n### Unsafe Mode\n\nActions that need to bypass scoped DB filters (for example, platform-level support operations) can enable unsafe mode.\n\nUse object form for explicit policy and mandatory audit metadata:\n\n```typescript\n// features/admin/actions/cross-tenant-report.ts\n\nexport default defineAction({\n description: \"Generate cross-org hiring report\",\n path: \"/admin/cross-tenant-report\",\n input: z.object({ startDate: z.string() }),\n access: { roles: [\"owner\"] },\n unsafe: {\n reason: \"Support investigation for enterprise customer\",\n adminOnly: true, // default true\n crossTenant: true, // default true\n targetScope: \"all\", // \"all\" | \"organization\"\n },\n async execute({ unsafeDb, input }) {\n // unsafeDb bypasses scoped filters\n const allOrgs = await unsafeDb.select().from(applications);\n return allOrgs;\n },\n});\n```\n\nUnsafe cross-tenant actions are generated with:\n\n- Better Auth authentication required (no unauthenticated path)\n- platform admin gate (`ctx.userRole === \"admin\"`)\n- mandatory audit logging on deny/success/error\n\n`PUBLIC` actions also receive mandatory audit logging (same audit table), since unauthenticated endpoints are high-risk by nature.\n\nWithout unsafe mode, `unsafeDb` is `undefined` in the executor params.\n\n### Raw SQL Policy\n\nBy default, the compiler rejects raw SQL in action code. Use Drizzle query-builder syntax whenever possible.\n\nIf a specific action must use raw SQL, opt in explicitly:\n\n```typescript\n// features/ledgers/actions/reconcile.ts\n\nexport default defineAction({\n description: \"Run custom reconciliation query\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n allowRawSql: true,\n async execute({ db }) {\n return db.execute(sql`select 1`);\n },\n});\n```\n\nWithout `allowRawSql: true`, compilation fails with a loud error pointing to the action and snippet.\n\nThe detector checks for SQL keywords in string arguments, so non-SQL method calls like `headers.get(\"X-Forwarded-For\")` or `map.get(\"key\")` will not trigger false positives.\n\n## Sharing Code Between Actions\n\nFor Zod schemas, helpers, or constants used across multiple actions in a\nfeature, put them under `<feature>/lib/` and import from each action file.\nFiles under `lib/` are copied verbatim into the generated output.\n\n```\nfeatures/applications/\n├── applications.ts\n├── actions/\n│ ├── advance.ts\n│ └── reject.ts\n└── lib/\n ├── inputs.ts ← shared Zod schemas\n └── transitions.ts ← state-machine helpers\n```\n\n```typescript\n// features/applications/lib/inputs.ts\n\nexport const advanceInput = z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n notes: z.string().max(2000).optional(),\n});\n```\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move forward\",\n input: advanceInput,\n access: { roles: [\"owner\"] },\n async execute({ db, record, input }) { /* … */ },\n});\n```\n\n### Importing Tables\n\nAction files import tables from their own feature or other features. The compiler generates alias files for each table, so you import by the table's file name:\n\n```typescript\n// features/applications/actions/advance.ts\n\n// Same feature — import from parent directory using the table's file name\n\n// Cross-feature — go up to the features directory, then into the other feature\n\n```\n\n**Path pattern from `features/{name}/actions/`:**\n- Same feature table: `../{table-file-name}` (e.g., `../applications`)\n- Other feature table: `../../{other-feature}/{table-file-name}` (e.g., `../../candidates/candidates`)\n- Generated lib files: `../../../lib/{module}` (e.g., `../../../lib/realtime`, `../../../lib/webhooks`)\n\n### Executor Parameters\n\n```typescript\n\ninterface ActionExecutorParams {\n db: DrizzleDB; // Scoped database (auto-applies org/owner/soft-delete filters)\n unsafeDb?: DrizzleDB; // Unscoped database (only available when unsafe mode is enabled)\n ctx: AppContext; // User context (userId, roles, orgId)\n record?: TRecord; // The record (record-based only, undefined for standalone)\n input: TInput; // Validated input from Zod schema\n services: TServices; // Configured integrations (billing, notifications, etc.)\n c: HonoContext; // Raw Hono context for advanced use\n env: Env; // Runtime bindings (Cloudflare env / process env). Alias for c.env.\n auth: Auth; // Better Auth instance — call auth.api.getSession(...) etc. Lazy on Cloudflare.\n whereRecord?: (table) => SQL; // Pre-built WHERE: firewall + soft-delete + eq(table.id, record.id). Record-based actions only.\n whereTransition?: (table) => SQL; // whereRecord plus the transition's \"from\" precondition. Transition actions only.\n}\n```\n\n#### `auth` — Better Auth instance\n\n`auth` is the Better Auth instance, ready to call from inside an action\nhandler. Use it for things like minting an OAuth access token, fetching the\ncurrent session in a custom way, or invoking a Better Auth plugin method\nthat isn't already exposed by the generated middleware.\n\n```typescript\n// features/integrations/actions/connect-google-drive.ts\n\nexport default defineAction({\n description: \"Get a fresh Google Drive access token for the signed-in user\",\n input: z.object({}),\n access: { roles: [\"AUTHENTICATED\"] },\n async execute({ auth, ctx, c }) {\n // genericOAuth plugin method — needs a cast since the default-generic\n // `Auth` type doesn't carry plugin-specific API surface.\n const token = await (auth.api as any).getAccessToken({\n headers: c.req.raw.headers,\n body: { providerId: \"google\", userId: ctx.userId },\n });\n return { accessToken: token.accessToken };\n },\n});\n```\n\n**Lazy on Cloudflare**: the generated handler emits a `Proxy` so\n`createAuth(c.env, c.req.raw.cf)` only runs the first time you read a\nproperty on `auth`. Actions that never touch `auth` pay zero construction\ncost. On Bun/Node `auth` is the imported singleton (an IIFE that lazy-loads\nthe database adapter) wrapped in the same proxy shape — call sites are\nidentical across runtimes.\n\n**Typing**: `auth` is typed as `Auth` from `better-auth`. The base API\n(`getSession`, `signOut`, `signInEmail`, etc.) is fully typed. Plugin-only\nmethods (`getAccessToken` from `genericOAuth`, admin-plugin methods, etc.)\nneed a cast at the call site — the default-generic `Auth` doesn't infer\nthe project's specific plugin set.\n\n#### `whereRecord` — explicit, scope-safe WHERE\n\nFor protected-field writes inside record-based actions, prefer\n`whereRecord(table)` over `eq(table.id, record.id)`. It returns a Drizzle\nexpression that AND-merges the resource's firewall and soft-delete predicates\nwith the record id, so the WHERE is explicit even if a future refactor swaps\n`db` back to an unscoped client:\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Advance\",\n input: /* … */,\n access: { roles: [\"owner\"] },\n async execute({ db, record, input, whereRecord }) {\n const [updated] = await db\n .update(applications)\n .set({\n status: input.nextStatus,\n notes: input.notes ?? record.notes,\n })\n .where(whereRecord!(applications)) // firewall + soft-delete + id, all in one\n .returning();\n return updated;\n },\n});\n```\n\nThe audit DB wrapper hard-stamps `modifiedAt`/`modifiedBy` on every\n`.set()` call, so handlers don't write them. The same wrapper hard-stamps\n`createdAt`/`createdBy`/`modifiedAt`/`modifiedBy` on every `.values()`.\nCaller-supplied audit fields are dropped on the floor — the audit log\nalways reflects the real actor and the real moment.\n\n`whereRecord` is undefined for standalone actions (they have no record), so\nthe parameter is typed as optional. `whereTransition` extends `whereRecord`\nwith the transition's \"from\" precondition for transition actions.\n\n## HTTP API Reference\n\n### Request Format\n\n| Method | Input Source | Use Case |\n|--------|--------------|----------|\n| `GET` | Query parameters | Read-only operations, fetching data |\n| `POST` | JSON body | Default, state-changing operations |\n| `PUT` | JSON body | Full replacement operations |\n| `PATCH` | JSON body | Partial updates |\n| `DELETE` | JSON body | Deletion with optional payload |\n\n### Response Formats\n\n| Type | Content-Type | Use Case |\n|------|--------------|----------|\n| `json` | `application/json` | Standard API responses (default) |\n| `stream` | `text/event-stream` | Real-time streaming (AI chat, live updates) |\n| `file` | Varies | File downloads (reports, exports) |\n\n### Error Codes\n\n| Status | Description |\n|--------|-------------|\n| `400` | Invalid input / validation error (also `GUARD_FIELD_PROTECTED` for direct protected-field writes) |\n| `401` | Not authenticated |\n| `403` | Access role check failed (`ACCESS_ROLE_REQUIRED`) |\n| `404` | Record not found (record-based actions) |\n| `409` | Record is in the wrong state for this action — `access.record` predicate or `transition` policy failed (`ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`) |\n| `500` | Handler execution error |\n\n### Validation Error Response\n\n```json\n{\n \"error\": \"Invalid request data\",\n \"layer\": \"validation\",\n \"code\": \"VALIDATION_FAILED\",\n \"details\": {\n \"fields\": {\n \"amount\": \"Expected positive number\"\n }\n },\n \"hint\": \"Check the input schema for this action\"\n}\n```\n\n### Error Handling\n\n**Option 1: Return a JSON error response** (recommended for most cases)\n\nSince action handlers receive the Hono context (`c`), you can return error responses directly:\n\n```typescript\nasync execute({ ctx, record, input, c }) {\n if (record.stage === 'hired') {\n return c.json({\n error: 'Cannot modify a hired application',\n code: 'ALREADY_HIRED',\n details: { currentStage: record.stage },\n }, 400);\n }\n // ... continue\n}\n```\n\n**Option 2: Throw an ActionError**\n\n```typescript\n\nasync execute({ ctx, record, input }) {\n if (record.stage === 'hired') {\n throw new ActionError('Cannot modify a hired application', 'ALREADY_HIRED', 400, {\n currentStage: record.stage,\n });\n }\n // ... continue\n}\n```\n\nThe `ActionError` constructor signature is `(message, code, statusCode, details?)`.\n\n## Protected Fields\n\nActions can modify fields that are protected from regular CRUD operations:\n\n```typescript\n// In the table file (defineTable config)\nguards: {\n protected: {\n status: [\"advance\", \"reject\", \"hire\", \"withdraw\"], // Only these actions can modify status\n }\n}\n```\n\nThis allows the `advance` action to set `status = \"interview\"` even though the field is protected from regular PATCH requests. Direct `PATCH /:id` attempts to set `status` are rejected by the guards layer with **400 GUARD_FIELD_PROTECTED**, and the field is omitted from the generated POST/PATCH body Zod schemas — clients cannot even send it past validation.\n\n## Transition (state-machine policy)\n\nFor protected fields that follow a state machine — application status, invoice\nlifecycle, order fulfilment — use `transition` on the action so the compiler\ngenerates a runtime guard that enforces the *from/to pair*, not just the\ncurrent state. Without it, an `advance` action whose input enum allows\n`[\"screening\", \"interview\", \"offer\"]` and whose `access.record` allows\n`status in [\"applied\", \"screening\", \"interview\"]` will happily run\n`applied → offer` (a skip) or `interview → screening` (a regression).\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\", // read target from input.nextStatus\n fromTo: {\n applied: [\"screening\"],\n screening: [\"interview\"],\n interview: [\"offer\"],\n },\n },\n async execute({ db, record, input, whereTransition }) { /* … */ },\n});\n```\n\n```typescript\n// features/applications/actions/hire.ts\n\nexport default defineAction({\n description: \"Finalize an offer.\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n transition: {\n field: \"status\",\n to: \"hired\", // fixed target — same value every call\n fromTo: { offer: [\"hired\"] },\n },\n async execute({ db, record, whereTransition }) { /* … */ },\n});\n```\n\n| Field | Required | Description |\n|---|---|---|\n| `field` | Yes | Record column to validate (e.g. `\"status\"`) |\n| `fromTo` | Yes | Map of current value → permitted next values. Keys also enumerate the legal source states. |\n| `via` | Yes (or `to`) | Input key that carries the target value. Use for variable-target actions like `advance`. |\n| `to` | Yes (or `via`) | Literal target value the action always writes. Use for fixed-target actions like `hire`/`reject`. |\n\nExactly one of `via` or `to` must be provided. The compiler rejects both at\nvalidate time. When `to` is set, it must appear in some `fromTo[*]` array —\notherwise the action would be unreachable, which is almost certainly a bug.\n\n### Wire-level errors\n\nThe compiled guard returns **409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`** with\nthe field, the current value, the requested target, and the allowed set:\n\n```json\n{\n \"error\": \"Action not allowed for current record state\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ACTION_NOT_ALLOWED_FOR_STATE\",\n \"details\": {\n \"field\": \"status\",\n \"current\": \"interview\",\n \"target\": \"screening\",\n \"allowedTargets\": [\"offer\"]\n },\n \"hint\": \"From \\\"interview\\\", status can transition to: offer\"\n}\n```\n\nThis is distinct from a role failure: if the caller has the wrong role they\nget **403 `ACCESS_ROLE_REQUIRED`** as before. Splitting the two lets clients\ntell *\"you can't do this\"* from *\"you can't do this *yet*\"* — the latter is\nrecoverable by the user, the former isn't.\n\nThe same 409 code is used when an `access.record` predicate (without\n`transition`) fails — for example `record: { status: { equals: \"pending\" } }`\ncalled against a paid invoice now returns 409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`,\nnot a misleading 403.\n\n## Examples\n\n### Bulk Import (Standalone, No Record)\n\n```typescript\n// features/candidates/actions/bulk-import.ts\n\nexport default defineAction({\n description: \"Import candidates from job board CSV\",\n path: \"/candidates/import\",\n input: z.object({\n data: z.array(z.object({\n email: z.string().email(),\n name: z.string(),\n })),\n }),\n access: { roles: [\"hiring-manager\", \"recruiter\"] },\n async execute({ db, input }) {\n const inserted = await db\n .insert(candidates)\n .values(input.data)\n .returning();\n return { imported: inserted.length };\n },\n});\n```"
|
|
82
|
+
"content": "Actions are custom API endpoints for business logic beyond CRUD operations. They enable workflows, integrations, and complex operations.\n\n## Overview\n\nQuickback supports two types of actions:\n\n| Aspect | Record-Based | Standalone |\n|--------|--------------|------------|\n| Route | `{METHOD} /:id/{actionName}` | Custom `path` (required) |\n| Record fetching | Automatic | None (`record` is `undefined`) |\n| Firewall applied | Yes | No |\n| Preconditions | Supported via `access.record` | Not applicable |\n| Response types | JSON only | JSON, stream, file |\n| Use case | Advance application, reject candidate | AI chat, bulk import from job board, webhooks |\n\nStandalone actions are signalled by the presence of a `path:` field in the action config. Record-based actions omit `path` and bind to the feature's primary table.\n\n## Where do actions live?\n\n**One file per action.** Each action is its own module under the feature's\n`actions/` directory:\n\n```\nfeatures/applications/\n├── applications.ts ← defineTable (primary table)\n├── candidates.ts ← defineTable (sibling table)\n├── actions/\n│ ├── advance.ts ← defineAction, binds to applications\n│ ├── reject.ts ← defineAction, binds to applications\n│ ├── stats.ts ← defineAction, standalone (has `path:`)\n│ └── candidates/\n│ └── disqualify.ts ← defineAction, binds to candidates\n└── lib/\n └── inputs.ts ← shared schemas (optional, copied verbatim)\n```\n\n| Layout | Binds to |\n|--------|----------|\n| `actions/<name>.ts` | The feature's primary table (table file matching the feature name), or standalone if `path:` is set. |\n| `actions/<table>/<name>.ts` | The sibling table file `<table>.ts` at the feature root. Standalone actions inside a subdir ignore the binding. |\n\nThe action's filename (sans `.ts`) is the action name and the URL segment.\nUniqueness is enforced per `(bound table, name)` pair — sibling-bound\nactions on **different** tables may share a verb (`actions/episodes/publish.ts`\nand `actions/shows/publish.ts` mount at `/episodes/:id/publish` and\n`/shows/:id/publish` and compile cleanly). The compiler errors only when\ntwo action files would mount at the same URL — for example, a flat\n`actions/foo.ts` (binds to primary) plus `actions/<primary>/foo.ts`, or\ntwo standalones with the same `(method, path)`. Standalone actions are\nunique per `(method, path)`.\n\nTableless features have no top-level `*.ts` files; every action under\n`actions/` must be standalone (have `path:`). Use this for utility endpoints\nlike webhooks, reports, or integrations that don't operate on a specific\nrecord.\n\n### Retired layouts\n\nThese are rejected at load time with migration guidance:\n\n- **`actions.ts`** (bundled multi-action file)\n- **`_feature.ts`** (shared schemas + non-table-bound actions)\n- **`handlers/`** (separate handler-file directory)\n- **`defineActions(table, {...})`** (the multi-action factory)\n- **`defineActions(null, {...})`** (tableless variant)\n- **`*-actions.ts` / `*.actions.ts`** filename patterns\n\nFor shared Zod schemas or helpers, put them under `<feature>/lib/` and import\nfrom each action file. Files under `lib/` are copied verbatim into the\ngenerated output.\n\n## Defining Actions\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n notes: z.string().max(2000).optional(),\n }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: {\n applied: [\"screening\"],\n screening: [\"interview\"],\n interview: [\"offer\"],\n },\n },\n async execute({ db, record, input, whereTransition }) {\n const [updated] = await db\n .update(applications)\n .set({\n status: input.nextStatus,\n notes: input.notes ?? record.notes,\n })\n .where(whereTransition!(applications))\n .returning();\n return updated;\n },\n});\n```\n\n> **`defineAction` import.** Import from `\"../.quickback/define-action\"` —\n> the `.quickback/` directory is generated alongside your feature with a\n> typed helper that infers `record` and `input` types from the rest of the\n> action config. Audit fields (`createdAt`, `createdBy`, `modifiedAt`,\n> `modifiedBy`) are hard-stamped by the audit DB wrapper on every\n> `db.insert().values()` and `db.update().set()` — handlers don't pass\n> them and can't override them.\n\n### Configuration Options\n\n| Option | Required | Description |\n|--------|----------|-------------|\n| `description` | Yes | Human-readable description of the action |\n| `input` | Yes | Zod schema for request validation |\n| `access` | Yes | Access control (roles, record conditions, or function) |\n| `execute` | Yes | Inline async arrow function (`async (ctx) => { … }`) |\n| `path` | Standalone only | Custom route path. Presence of `path` makes the action standalone. |\n| `method` | No | HTTP method: GET, POST, PUT, PATCH, DELETE (default: POST). GET actions parse `input` from query params; all other methods parse from the JSON body. See [GET vs POST for input](#get-vs-post-for-input). |\n| `responseType` | No | Response format: json, stream, file (default: json) |\n| `sideEffects` | No | Hint for AI tools: `'sync'`, `'async'`, or `'fire-and-forget'` |\n| `allowRawSql` | No | Explicit compile-time opt-in for raw SQL in execute code |\n| `unsafe` | No | Unsafe raw DB mode. Object config (`reason`, `adminOnly`, `crossTenant`, `targetScope`). |\n| `transition` | No | State-machine policy enforcing the from/to pair (record-based actions). See [Transitions](#transition-state-machine-policy) |\n| `bulkVariant` | No | Auto-generate a `POST /:resource/batch/{action}` route alongside the per-record route (record-based actions). See [Bulk Variant](#bulk-variant) |\n| `cms` | No | Pass-through metadata blob for CMS surfaces |\n\n`execute` must be an `async (ctx) => { … }` arrow function. `async function`\ndeclarations and non-async forms are rejected at parse time.\n\n## Record-Based Actions\n\nRecord-based actions operate on an existing record. The record is automatically loaded and validated before your action executes.\n\n**Route pattern:** `{METHOD} /:id/{actionName}`\n\n```\nPOST /applications/:id/advance\nPOST /applications/:id/reject\nPOST /applications/:id/schedule-interview\n```\n\n### Runtime Flow\n\n1. **Authentication** - User token is validated\n2. **Record Loading** - The record is fetched by ID\n3. **Firewall Check** - Ensures user can access this record\n4. **Access Check** - Validates roles and preconditions\n5. **Input Validation** - Request body validated against Zod schema\n6. **Execution** - Your action handler runs\n7. **Response** - Result is returned to client\n\n### Example: Advance Application Stage\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move application to the next pipeline stage\",\n input: z.object({\n stage: z.enum([\"screening\", \"interview\", \"offer\", \"hired\"]),\n notes: z.string().optional(),\n }),\n access: {\n roles: [\"owner\", \"hiring-manager\"],\n record: { stage: { notEquals: \"rejected\" } },\n },\n async execute({ db, record, input }) {\n const [updated] = await db\n .update(applications)\n .set({\n stage: input.stage,\n notes: input.notes ?? record.notes,\n })\n .where(eq(applications.id, record.id))\n .returning();\n return updated;\n },\n});\n```\n\n### Request Example\n\n```\nPOST /applications/app_123/advance\nContent-Type: application/json\n\n{\n \"stage\": \"interview\",\n \"notes\": \"Strong technical background, moving to interview\"\n}\n```\n\n### Response Example\n\n```json\n{\n \"data\": {\n \"id\": \"app_123\",\n \"stage\": \"interview\",\n \"notes\": \"Strong technical background, moving to interview\"\n }\n}\n```\n\n### Bulk variant\n\nSet `bulkVariant: true` to auto-generate a bulk version of the action at\n`POST /:resource/batch/{action}`. The compiler emits a second route alongside\nthe per-record one, looping the same access + transition + execute pipeline\nover an array of ids. This is the answer to \"I need to advance 50\napplications at once\" — you don't have to hand-roll a parallel standalone\naction that duplicates the per-record logic.\n\n```typescript\n// features/applications/actions/advance.ts\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n bulkVariant: true,\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: { applied: [\"screening\"], screening: [\"interview\"], interview: [\"offer\"] },\n },\n async execute({ db, record, input, whereTransition }) {\n const [updated] = await db\n .update(applications)\n .set({ status: input.nextStatus })\n .where(whereTransition!(applications))\n .returning();\n if (!updated) throw new TransitionLostError(\"status\", record.status, input.nextStatus);\n return updated;\n },\n});\n```\n\n**Request shape:**\n\n```http\nPOST /applications/batch/advance\nContent-Type: application/json\n\n{\n \"ids\": [\"app_001\", \"app_002\", \"app_003\"],\n \"input\": { \"nextStatus\": \"interview\" },\n \"failFast\": false\n}\n```\n\nThe `input` is shared across the batch — the action's Zod schema is\nvalidated once, not per id. For per-record input variation, use the\nsingle-record endpoint (`POST /:id/{action}`) or write a standalone action.\n\n**Response (207 Multi-Status when any record fails, 200 when clean):**\n\n```json\n{\n \"success\": [{ \"id\": \"app_001\", \"status\": \"interview\" }],\n \"errors\": [\n {\n \"index\": 1,\n \"id\": \"app_002\",\n \"error\": {\n \"error\": \"Action not allowed for current state\",\n \"code\": \"ACCESS_ACTION_NOT_ALLOWED_FOR_STATE\",\n \"details\": { \"field\": \"status\", \"currentValue\": \"rejected\" }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"failFast\": false,\n \"transactional\": false\n }\n}\n```\n\n**Per-record pipeline** mirrors the single-record route exactly — the same\nfirewall fetch, access reason split (403 vs 409), transition pre-check,\n`whereTransition` factory, and `TransitionLostError` handling. Per-record\nfailures land in `errors[]` with their original index; successful records\nland in `success[]` masked the same way the single-record response is.\n\n**Transactional matrix** (same as `PATCH /batch`):\n\n| Provider | failFast | transactional | Behavior |\n|---|---|---|---|\n| neon (Postgres via Hyperdrive) | `true` | `true` | `db.transaction()` wraps the loop; any throw rolls back all writes |\n| (any) | `false` | `false` | Independent per-record outcomes, partial success |\n| cloudflare-d1 | `true` | `false` | Fail-fast loop without rollback — earlier records stay committed (D1 has no `db.transaction`) |\n\n**Constraints:**\n\n- Record-based actions only. Standalone actions reject `bulkVariant: true`\n at compile time (no record context to loop over).\n- `unsafe` actions reject `bulkVariant: true` in v1 — the cross-tenant\n per-record audit story is not yet wired through.\n- Method is forced to POST regardless of the action's `method` setting. The\n semantic asymmetry (one row → many rows) makes inheriting GET/DELETE\n confusing.\n- Max batch size is 100 ids per request.\n\n## Standalone Actions\n\nStandalone actions are independent endpoints that don't require a record context. Set a `path:` to declare the action standalone.\n\n**Route pattern:** Custom `path`\n\n```\nPOST /chat\nGET /reports/summary\nPOST /webhooks/stripe\n```\n\n### Example: AI Chat with Streaming\n\n```typescript\n// features/sessions/actions/chat.ts\n\nexport default defineAction({\n description: \"Send a message to AI\",\n path: \"/chat\",\n method: \"POST\",\n responseType: \"stream\",\n input: z.object({\n message: z.string().min(1).max(2000),\n }),\n access: { roles: [\"recruiter\", \"hiring-manager\"] },\n async execute({ input, c }) {\n // Stream response back to client...\n return c.newResponse(/* ReadableStream */);\n },\n});\n```\n\n### Streaming Response Example\n\nFor actions with `responseType: 'stream'`:\n\n```\nContent-Type: text/event-stream\n\ndata: {\"type\": \"start\"}\ndata: {\"type\": \"chunk\", \"content\": \"Hello\"}\ndata: {\"type\": \"chunk\", \"content\": \"! I'm\"}\ndata: {\"type\": \"chunk\", \"content\": \" here to help.\"}\ndata: {\"type\": \"done\"}\n```\n\n### Tableless Features\n\nA feature directory with no top-level `*.ts` files is \"tableless\" — every\naction under `actions/` must be standalone. Use this for utility endpoints\nlike reports, integrations, or webhooks that don't map to a specific\nresource.\n\n```\nquickback/features/\n└── reports/\n └── actions/\n ├── trial-balance.ts ← standalone (has path:)\n └── profit-loss.ts ← standalone (has path:)\n```\n\n```typescript\n// features/reports/actions/trial-balance.ts\n\nexport default defineAction({\n description: \"Generate trial balance report\",\n path: \"/reports/trial-balance\",\n method: \"GET\",\n input: z.object({\n startDate: z.string(),\n endDate: z.string(),\n }),\n access: { roles: [\"admin\", \"accountant\"] },\n async execute({ db, input }) {\n // ... build report\n return { rows: [] };\n },\n});\n```\n\n### GET vs POST for input\n\nGET actions read `input` from URL query parameters; every other method (POST,\nPUT, PATCH, DELETE) reads from the JSON body. The Zod schema is the same in\nboth cases — the compiler picks the right parser based on `method`.\n\n```typescript\n// GET — input populated from ?q=…&limit=…\ndefineAction({\n method: \"GET\",\n path: \"/search\",\n input: z.object({\n q: z.string(),\n limit: z.coerce.number().int().positive().max(100).default(20),\n }),\n access: { roles: [\"AUTHENTICATED\"] },\n async execute({ input }) {\n // input is { q: string, limit: number } — fully typed.\n },\n});\n```\n\nRepeated query keys (`?tag=a&tag=b`) come through as arrays automatically;\nsingle values stay as strings. Use Zod's `.coerce.number()` /\n`.coerce.boolean()` when you want typed primitives from the parsed strings.\n\n**Use POST when input is structured.** GET requests cannot carry a JSON body\nin any of the surfaces Quickback APIs are commonly called from:\n\n- Browsers throw on `fetch(url, { method: 'GET', body })`.\n- CDNs and caches key on URL+method; a GET with a body either gets the body\n stripped at the edge or cache-collides with semantically different requests.\n- OpenAPI client generators (axios, openapi-fetch, openapi-typescript-codegen)\n refuse to emit GET-with-body, so the generated SDKs break.\n- The MCP agent surface treats GET as parameter-only — agents calling a GET\n action will only see what the URL exposes.\n\nIf your action takes nested objects, arrays of objects, or large inputs that\ndon't serialize cleanly to a query string, set `method: \"POST\"`. POST doesn't\nimply \"this writes data\" — it's the right method whenever the request body is\nload-bearing. Use the response shape (`responseType: \"json\"`, or just the data\nyour handler returns) to convey read semantics; HTTP method choice is about\ninput transport, not action intent.\n\n## Access Configuration\n\nAccess controls who can execute an action and under what conditions.\n\n### Role-Based Access\n\n```typescript\naccess: {\n roles: [\"hiring-manager\", \"recruiter\"] // OR logic: user needs any of these roles\n}\n```\n\n### Public Access\n\nUse `roles: [\"PUBLIC\"]` for unauthenticated endpoints (contact forms, webhooks, public APIs). Every invocation is **mandatory audit logged** with IP address, input, result, and timing.\n\n```typescript\n// features/contact/actions/submit.ts\n\nexport default defineAction({\n description: \"Public contact form submission\",\n path: \"/submit\",\n input: z.object({\n name: z.string().min(1),\n email: z.string().email(),\n message: z.string().min(10),\n }),\n access: { roles: [\"PUBLIC\"] },\n async execute({ db, input }) {\n // ... persist submission\n return { ok: true };\n },\n});\n```\n\nThe wildcard `\"*\"` is not supported and will throw a compile-time error. Use `\"PUBLIC\"` explicitly.\n\n### Record Conditions\n\nFor record-based actions, you can require the record to be in a specific state:\n\n```typescript\naccess: {\n roles: [\"hiring-manager\"],\n record: {\n stage: { equals: \"screening\" } // Precondition\n }\n}\n```\n\n**Supported operators:**\n\n| Operator | Description |\n|----------|-------------|\n| `equals` | Field must equal value |\n| `notEquals` | Field must not equal value |\n| `in` | Field must be one of the values |\n| `notIn` | Field must not be one of the values |\n\n### Context Substitution\n\nUse `$ctx` to reference the current user's context:\n\n```typescript\naccess: {\n record: {\n ownerId: { equals: \"$ctx.userId\" },\n orgId: { equals: \"$ctx.orgId\" }\n }\n}\n```\n\n### OR/AND Combinations\n\n```typescript\naccess: {\n or: [\n { roles: [\"hiring-manager\"] },\n {\n roles: [\"recruiter\"],\n record: { ownerId: { equals: \"$ctx.userId\" } }\n }\n ]\n}\n```\n\n### Function Access\n\nFor complex logic, use an access function:\n\n```typescript\naccess: async (ctx, record) => {\n return ctx.roles.includes('admin') || record.ownerId === ctx.userId;\n}\n```\n\n### Relationship-roles in actions\n\n**v0.19+** — standalone actions now support relationship-roles in `access.roles` directly. Declare the relationship under `authz.relationships` with optional `loads` / `exposeAs` for ctx hydration, and reference the role by name on the action:\n\n```ts\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n roles: { attendee: { via: 'attendeeOf' } },\n}\n\n// features/chat/actions/getInbox.ts\nexport default defineAction({\n path: '/chat/get-inbox',\n input: z.object({ eventId: z.number().int().positive() }),\n access: { roles: ['admin', 'member', 'attendee'] },\n execute: async ({ db, ctx, input }) => {\n // The resolver already verified attendance and loaded ctx.event.\n // No hand-rolled `SELECT … FROM guests WHERE …` needed.\n },\n});\n```\n\nThe action's surface (path params + input fields) must expose the relationship's `resource.column`. At v0.19 a missing key emits a `[quickback:authz]` warning and skips resolver emission; at v0.20 it becomes a compile error. See [Access — standalone actions](/compiler/definitions/access#standalone-actions-surface-keys-and-loads--exposeas-v019) for the full mechanism.\n\n**Record-based actions** are NOT yet supported — the runtime evaluator fail-closes (403) on relationship arms reached without an inline gate. Until inline emission for record-based actions lands, either:\n\n- Set `firewall: { exception: true }` on the action and gate manually in `execute()`, OR\n- Apply the relationship at the resource's firewall layer (worked example below).\n\n**Resource-layer workaround for record-based actions**: gate the action on BA roles only and apply the relationship at the resource layer via a firewall `via:` predicate:\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n },\n },\n}\n\n// features/sessions/sessions.ts — firewall scopes rows; action gates on BA role\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' }, // ← row-level relationship check\n],\nactions: {\n comment: defineAction({\n access: { roles: ['member', 'admin'] }, // ← BA role only on the action\n input: z.object({ text: z.string() }),\n execute: async (input, ctx, db, record) => {\n // record is already filtered by the firewall — guest membership\n // is enforced before this handler runs.\n return db.insert(comments).values({ ... });\n },\n }),\n}\n```\n\nThis pattern composes cleanly: the firewall guarantees the caller has the relationship to the record being acted on; the action's access list keeps the role surface obvious.\n\nSee [Access — relationship authorization](/compiler/definitions/access#relationship-based-authorization) for the full picture, including `loads` / `exposeAs` and the `firewall: { exception: true }` escape hatch.\n\n## Scoped Database\n\nAll actions receive a **scoped `db`** instance that automatically enforces security:\n\n| Operation | Org Scoping | Owner Scoping | Soft Delete Filter | Auto-inject on INSERT |\n|-----------|-------------|---------------|--------------------|-----------------------|\n| `SELECT` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n| `INSERT` | n/a | n/a | n/a | `organizationId`, `ownerId` from ctx |\n| `UPDATE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n| `DELETE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n\nScoping is duck-typed at runtime — tables with an `organizationId` column get org scoping, tables with `ownerId` get owner scoping, tables with `deletedAt` get soft delete filtering.\n\n```typescript\nasync execute({ db, ctx, input }) {\n // This query automatically includes WHERE organizationId = ? AND deletedAt IS NULL\n const items = await db.select().from(applications).where(eq(applications.stage, 'interview'));\n\n // Inserts automatically include organizationId\n await db.insert(applications).values({ candidateId: input.candidateId, jobId: input.jobId, stage: 'applied' });\n\n return items;\n}\n```\n\n**Not enforced** in scoped DB (by design):\n- **Guards** — actions ARE the authorized way to modify guarded fields\n- **Masking** — actions are backend code that may need raw data\n- **Access** — already checked before action execution\n\n### Unsafe Mode\n\nActions that need to bypass scoped DB filters (for example, platform-level support operations) can enable unsafe mode.\n\nUse object form for explicit policy and mandatory audit metadata:\n\n```typescript\n// features/admin/actions/cross-tenant-report.ts\n\nexport default defineAction({\n description: \"Generate cross-org hiring report\",\n path: \"/admin/cross-tenant-report\",\n input: z.object({ startDate: z.string() }),\n access: { roles: [\"owner\"] },\n unsafe: {\n reason: \"Support investigation for enterprise customer\",\n adminOnly: true, // default true\n crossTenant: true, // default true\n targetScope: \"all\", // \"all\" | \"organization\"\n },\n async execute({ unsafeDb, input }) {\n // unsafeDb bypasses scoped filters\n const allOrgs = await unsafeDb.select().from(applications);\n return allOrgs;\n },\n});\n```\n\nUnsafe cross-tenant actions are generated with:\n\n- Better Auth authentication required (no unauthenticated path)\n- platform admin gate (`ctx.userRole === \"admin\"`)\n- mandatory audit logging on deny/success/error\n\n`PUBLIC` actions also receive mandatory audit logging (same audit table), since unauthenticated endpoints are high-risk by nature.\n\nWithout unsafe mode, `unsafeDb` is `undefined` in the executor params.\n\n### Raw SQL Policy\n\nBy default, the compiler rejects raw SQL in action code. Use Drizzle query-builder syntax whenever possible.\n\nIf a specific action must use raw SQL, opt in explicitly:\n\n```typescript\n// features/ledgers/actions/reconcile.ts\n\nexport default defineAction({\n description: \"Run custom reconciliation query\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n allowRawSql: true,\n async execute({ db }) {\n return db.execute(sql`select 1`);\n },\n});\n```\n\nWithout `allowRawSql: true`, compilation fails with a loud error pointing to the action and snippet.\n\nThe detector checks for SQL keywords in string arguments, so non-SQL method calls like `headers.get(\"X-Forwarded-For\")` or `map.get(\"key\")` will not trigger false positives.\n\n## Sharing Code Between Actions\n\nFor Zod schemas, helpers, or constants used across multiple actions in a\nfeature, put them under `<feature>/lib/` and import from each action file.\nFiles under `lib/` are copied verbatim into the generated output.\n\n```\nfeatures/applications/\n├── applications.ts\n├── actions/\n│ ├── advance.ts\n│ └── reject.ts\n└── lib/\n ├── inputs.ts ← shared Zod schemas\n └── transitions.ts ← state-machine helpers\n```\n\n```typescript\n// features/applications/lib/inputs.ts\n\nexport const advanceInput = z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n notes: z.string().max(2000).optional(),\n});\n```\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move forward\",\n input: advanceInput,\n access: { roles: [\"owner\"] },\n async execute({ db, record, input }) { /* … */ },\n});\n```\n\n### Importing Tables\n\nAction files import tables from their own feature or other features. The compiler generates alias files for each table, so you import by the table's file name:\n\n```typescript\n// features/applications/actions/advance.ts\n\n// Same feature — import from parent directory using the table's file name\n\n// Cross-feature — go up to the features directory, then into the other feature\n\n```\n\n**Path pattern from `features/{name}/actions/`:**\n- Same feature table: `../{table-file-name}` (e.g., `../applications`)\n- Other feature table: `../../{other-feature}/{table-file-name}` (e.g., `../../candidates/candidates`)\n- Generated lib files: `../../../lib/{module}` (e.g., `../../../lib/realtime`, `../../../lib/webhooks`)\n\n### Executor Parameters\n\n```typescript\n\ninterface ActionExecutorParams {\n db: DrizzleDB; // Scoped database (auto-applies org/owner/soft-delete filters)\n unsafeDb?: DrizzleDB; // Unscoped database (only available when unsafe mode is enabled)\n ctx: AppContext; // User context (userId, roles, orgId)\n record?: TRecord; // The record (record-based only, undefined for standalone)\n input: TInput; // Validated input from Zod schema\n services: TServices; // Configured integrations (billing, notifications, etc.)\n c: HonoContext; // Raw Hono context for advanced use\n env: Env; // Runtime bindings (Cloudflare env / process env). Alias for c.env.\n auth: Auth; // Better Auth instance — call auth.api.getSession(...) etc. Lazy on Cloudflare.\n whereRecord?: (table) => SQL; // Pre-built WHERE: firewall + soft-delete + eq(table.id, record.id). Record-based actions only.\n whereTransition?: (table) => SQL; // whereRecord plus the transition's \"from\" precondition. Transition actions only.\n}\n```\n\n#### `auth` — Better Auth instance\n\n`auth` is the Better Auth instance, ready to call from inside an action\nhandler. Use it for things like minting an OAuth access token, fetching the\ncurrent session in a custom way, or invoking a Better Auth plugin method\nthat isn't already exposed by the generated middleware.\n\n```typescript\n// features/integrations/actions/connect-google-drive.ts\n\nexport default defineAction({\n description: \"Get a fresh Google Drive access token for the signed-in user\",\n input: z.object({}),\n access: { roles: [\"AUTHENTICATED\"] },\n async execute({ auth, ctx, c }) {\n // genericOAuth plugin method — needs a cast since the default-generic\n // `Auth` type doesn't carry plugin-specific API surface.\n const token = await (auth.api as any).getAccessToken({\n headers: c.req.raw.headers,\n body: { providerId: \"google\", userId: ctx.userId },\n });\n return { accessToken: token.accessToken };\n },\n});\n```\n\n**Lazy on Cloudflare**: the generated handler emits a `Proxy` so\n`createAuth(c.env, c.req.raw.cf)` only runs the first time you read a\nproperty on `auth`. Actions that never touch `auth` pay zero construction\ncost. On Bun/Node `auth` is the imported singleton (an IIFE that lazy-loads\nthe database adapter) wrapped in the same proxy shape — call sites are\nidentical across runtimes.\n\n**Typing**: `auth` is typed as `Auth` from `better-auth`. The base API\n(`getSession`, `signOut`, `signInEmail`, etc.) is fully typed. Plugin-only\nmethods (`getAccessToken` from `genericOAuth`, admin-plugin methods, etc.)\nneed a cast at the call site — the default-generic `Auth` doesn't infer\nthe project's specific plugin set.\n\n#### `whereRecord` — explicit, scope-safe WHERE\n\nFor protected-field writes inside record-based actions, prefer\n`whereRecord(table)` over `eq(table.id, record.id)`. It returns a Drizzle\nexpression that AND-merges the resource's firewall and soft-delete predicates\nwith the record id, so the WHERE is explicit even if a future refactor swaps\n`db` back to an unscoped client:\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Advance\",\n input: /* … */,\n access: { roles: [\"owner\"] },\n async execute({ db, record, input, whereRecord }) {\n const [updated] = await db\n .update(applications)\n .set({\n status: input.nextStatus,\n notes: input.notes ?? record.notes,\n })\n .where(whereRecord!(applications)) // firewall + soft-delete + id, all in one\n .returning();\n return updated;\n },\n});\n```\n\nThe audit DB wrapper hard-stamps `modifiedAt`/`modifiedBy` on every\n`.set()` call, so handlers don't write them. The same wrapper hard-stamps\n`createdAt`/`createdBy`/`modifiedAt`/`modifiedBy` on every `.values()`.\nCaller-supplied audit fields are dropped on the floor — the audit log\nalways reflects the real actor and the real moment.\n\n`whereRecord` is undefined for standalone actions (they have no record), so\nthe parameter is typed as optional. `whereTransition` extends `whereRecord`\nwith the transition's \"from\" precondition for transition actions.\n\n## HTTP API Reference\n\n### Request Format\n\n| Method | Input Source | Use Case |\n|--------|--------------|----------|\n| `GET` | Query parameters | Read-only operations, fetching data |\n| `POST` | JSON body | Default, state-changing operations |\n| `PUT` | JSON body | Full replacement operations |\n| `PATCH` | JSON body | Partial updates |\n| `DELETE` | JSON body | Deletion with optional payload |\n\n### Response Formats\n\n| Type | Content-Type | Use Case |\n|------|--------------|----------|\n| `json` | `application/json` | Standard API responses (default) |\n| `stream` | `text/event-stream` | Real-time streaming (AI chat, live updates) |\n| `file` | Varies | File downloads (reports, exports) |\n\n### Error Codes\n\n| Status | Description |\n|--------|-------------|\n| `400` | Invalid input / validation error (also `GUARD_FIELD_PROTECTED` for direct protected-field writes) |\n| `401` | Not authenticated |\n| `403` | Access role check failed (`ACCESS_ROLE_REQUIRED`) |\n| `404` | Record not found (record-based actions) |\n| `409` | Record is in the wrong state for this action — `access.record` predicate or `transition` policy failed (`ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`) |\n| `500` | Handler execution error |\n\n### Validation Error Response\n\n```json\n{\n \"error\": \"Invalid request data\",\n \"layer\": \"validation\",\n \"code\": \"VALIDATION_FAILED\",\n \"details\": {\n \"fields\": {\n \"amount\": \"Expected positive number\"\n }\n },\n \"hint\": \"Check the input schema for this action\"\n}\n```\n\n### Error Handling\n\n**Option 1: Return a JSON error response** (recommended for most cases)\n\nSince action handlers receive the Hono context (`c`), you can return error responses directly:\n\n```typescript\nasync execute({ ctx, record, input, c }) {\n if (record.stage === 'hired') {\n return c.json({\n error: 'Cannot modify a hired application',\n code: 'ALREADY_HIRED',\n details: { currentStage: record.stage },\n }, 400);\n }\n // ... continue\n}\n```\n\n**Option 2: Throw an ActionError**\n\n```typescript\n\nasync execute({ ctx, record, input }) {\n if (record.stage === 'hired') {\n throw new ActionError('Cannot modify a hired application', 'ALREADY_HIRED', 400, {\n currentStage: record.stage,\n });\n }\n // ... continue\n}\n```\n\nThe `ActionError` constructor signature is `(message, code, statusCode, details?)`.\n\n## Protected Fields\n\nActions can modify fields that are protected from regular CRUD operations:\n\n```typescript\n// In the table file (defineTable config)\nguards: {\n protected: {\n status: [\"advance\", \"reject\", \"hire\", \"withdraw\"], // Only these actions can modify status\n }\n}\n```\n\nThis allows the `advance` action to set `status = \"interview\"` even though the field is protected from regular PATCH requests. Direct `PATCH /:id` attempts to set `status` are rejected by the guards layer with **400 GUARD_FIELD_PROTECTED**, and the field is omitted from the generated POST/PATCH body Zod schemas — clients cannot even send it past validation.\n\n## Transition (state-machine policy)\n\nFor protected fields that follow a state machine — application status, invoice\nlifecycle, order fulfilment — use `transition` on the action so the compiler\ngenerates a runtime guard that enforces the *from/to pair*, not just the\ncurrent state. Without it, an `advance` action whose input enum allows\n`[\"screening\", \"interview\", \"offer\"]` and whose `access.record` allows\n`status in [\"applied\", \"screening\", \"interview\"]` will happily run\n`applied → offer` (a skip) or `interview → screening` (a regression).\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\", // read target from input.nextStatus\n fromTo: {\n applied: [\"screening\"],\n screening: [\"interview\"],\n interview: [\"offer\"],\n },\n },\n async execute({ db, record, input, whereTransition }) { /* … */ },\n});\n```\n\n```typescript\n// features/applications/actions/hire.ts\n\nexport default defineAction({\n description: \"Finalize an offer.\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n transition: {\n field: \"status\",\n to: \"hired\", // fixed target — same value every call\n fromTo: { offer: [\"hired\"] },\n },\n async execute({ db, record, whereTransition }) { /* … */ },\n});\n```\n\n| Field | Required | Description |\n|---|---|---|\n| `field` | Yes | Record column to validate (e.g. `\"status\"`) |\n| `fromTo` | Yes | Map of current value → permitted next values. Keys also enumerate the legal source states. |\n| `via` | Yes (or `to`) | Input key that carries the target value. Use for variable-target actions like `advance`. |\n| `to` | Yes (or `via`) | Literal target value the action always writes. Use for fixed-target actions like `hire`/`reject`. |\n\nExactly one of `via` or `to` must be provided. The compiler rejects both at\nvalidate time. When `to` is set, it must appear in some `fromTo[*]` array —\notherwise the action would be unreachable, which is almost certainly a bug.\n\n### Wire-level errors\n\nThe compiled guard returns **409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`** with\nthe field, the current value, the requested target, and the allowed set:\n\n```json\n{\n \"error\": \"Action not allowed for current record state\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ACTION_NOT_ALLOWED_FOR_STATE\",\n \"details\": {\n \"field\": \"status\",\n \"current\": \"interview\",\n \"target\": \"screening\",\n \"allowedTargets\": [\"offer\"]\n },\n \"hint\": \"From \\\"interview\\\", status can transition to: offer\"\n}\n```\n\nThis is distinct from a role failure: if the caller has the wrong role they\nget **403 `ACCESS_ROLE_REQUIRED`** as before. Splitting the two lets clients\ntell *\"you can't do this\"* from *\"you can't do this *yet*\"* — the latter is\nrecoverable by the user, the former isn't.\n\nThe same 409 code is used when an `access.record` predicate (without\n`transition`) fails — for example `record: { status: { equals: \"pending\" } }`\ncalled against a paid invoice now returns 409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`,\nnot a misleading 403.\n\n## Examples\n\n### Bulk Import (Standalone, No Record)\n\n```typescript\n// features/candidates/actions/bulk-import.ts\n\nexport default defineAction({\n description: \"Import candidates from job board CSV\",\n path: \"/candidates/import\",\n input: z.object({\n data: z.array(z.object({\n email: z.string().email(),\n name: z.string(),\n })),\n }),\n access: { roles: [\"hiring-manager\", \"recruiter\"] },\n async execute({ db, input }) {\n const inserted = await db\n .insert(candidates)\n .values(input.data)\n .returning();\n return { imported: inserted.length };\n },\n});\n```"
|
|
83
83
|
},
|
|
84
84
|
"compiler/definitions/concepts": {
|
|
85
85
|
"title": "Glossary",
|
|
@@ -243,7 +243,7 @@ export const DOCS = {
|
|
|
243
243
|
},
|
|
244
244
|
"stack/account-ui/features/admin": {
|
|
245
245
|
"title": "Admin Panel",
|
|
246
|
-
"content": "The admin panel provides a user management dashboard for administrators. It's part of the Account UI SPA — when enabled, the `/admin` route is included in the build.\n\n## Enabling Admin\n\nSet `auth.admin` to `true` in your account config:\n\n```typescript title=\"quickback/quickback.config.ts\"\naccount: {\n auth: {\n admin: true,\n },\n},\n```\n\nThis does two things:\n1. Includes admin route files in the Account SPA build (compile-time gating)\n2. Ensures the Better Auth `admin` plugin is enabled on the backend\n\nWhen `auth.admin` is `false` (the default), admin routes are excluded from the SPA bundle entirely — they don't exist in production.\n\n## What It Can Do\n\n- **View all users** — Paginated list with search\n- **Create users** — Manually create accounts with email/password\n- **Ban/unban users** — Suspend or reactivate user accounts\n- **Reset passwords** — Generate password reset for any user\n- **View sessions** — See active sessions for any user\n\n## Access Control\n\nThe admin panel is restricted to users with `role: \"admin\"` on their Better Auth user record. Non-admin users are redirected away from `/admin`.\n\nTo grant admin access to a user, use the Better Auth admin
|
|
246
|
+
"content": "The admin panel provides a user management dashboard for administrators. It's part of the Account UI SPA — when enabled, the `/admin` route is included in the build.\n\n## Enabling Admin\n\nSet `auth.admin` to `true` in your account config:\n\n```typescript title=\"quickback/quickback.config.ts\"\naccount: {\n auth: {\n admin: true,\n },\n},\n```\n\nThis does two things:\n1. Includes admin route files in the Account SPA build (compile-time gating)\n2. Ensures the Better Auth `admin` plugin is enabled on the backend\n\nWhen `auth.admin` is `false` (the default), admin routes are excluded from the SPA bundle entirely — they don't exist in production.\n\n## What It Can Do\n\n- **View all users** — Paginated list with search\n- **Create users** — Manually create accounts with email/password\n- **Ban/unban users** — Suspend or reactivate user accounts\n- **Reset passwords** — Generate password reset for any user\n- **View sessions** — See active sessions for any user\n\n## Access Control\n\nThe admin panel is restricted to users with `role: \"admin\"` on their Better Auth user record. Non-admin users are redirected away from `/admin`.\n\nTo grant admin access to a user, use the Better Auth admin plugin:\n\n```bash\ncurl -X POST https://api.example.com/auth/v1/admin/set-role \\\n -H \"Authorization: Bearer $TOKEN\" \\\n -H \"Content-Type: application/json\" \\\n -d '{ \"userId\": \"user_123\", \"role\": \"admin\" }'\n```\n\n## Custom Admin Domain\n\nGive the admin panel its own subdomain with `adminDomain`:\n\n```typescript title=\"quickback/quickback.config.ts\"\naccount: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n auth: { password: true, admin: true },\n},\ntrustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n],\n```\n\nThe admin domain serves the same Account SPA at root (`/`). The SPA's client-side router handles showing the admin page at `admin.example.com/admin`. Authentication cookies are shared across subdomains automatically via [cross-subdomain cookie configuration](/compiler/config/domains#cross-subdomain-authentication).\n\n## CMS Access Control\n\nWhen both CMS and Account UI are enabled, the admin panel's profile page shows a \"Go to CMS\" button. You can restrict this to admin users only:\n\n```typescript\ncms: { domain: \"cms.example.com\", access: \"admin\" },\n```\n\nWith `access: \"admin\"`, non-admin users can't access the CMS at any layer: the link is hidden in Account UI, the SPA shell returns `403` before serving `index.html`, `/api/v1/schema` returns `403`, and the `custom_view` CRUD is locked to admins. See [CMS Connecting](/stack/cms/connecting#restrict-cms-access-to-admin-users-only) for the full enforcement model.\n\n## Related\n\n- [Configuration](/compiler/config) — `auth.admin` and `adminDomain` options\n- [Multi-Domain Architecture](/compiler/config/domains) — Custom domains and hostname routing\n- [Access Control](/compiler/definitions/access) — Role-based permissions in your API"
|
|
247
247
|
},
|
|
248
248
|
"stack/account-ui/features/api-keys": {
|
|
249
249
|
"title": "API Key Management",
|
|
@@ -279,7 +279,7 @@ export const DOCS = {
|
|
|
279
279
|
},
|
|
280
280
|
"stack/account-ui/hooks": {
|
|
281
281
|
"title": "Auth Hooks",
|
|
282
|
-
"content": "# Auth Hooks\n\nQuickback discovers project-level auth hooks at `quickback/hooks/` and wires them into [Better Auth's `databaseHooks`](https://www.better-auth.com/docs/concepts/database#database-hooks). Use them for post-signup bootstrap, signup gating, and other lifecycle work.\n\nThe classic case is multi-tenant: when `account.auth.organizations: true` is set, a freshly signed-up user has no `activeOrganizationId`, so every authenticated `/api/v1/*` returns `400 ORG_REQUIRED`. An `after-user-create` hook can auto-provision a personal workspace + member row so the next request just works.\n\n## Folder layout\n\n```\nquickback/\n hooks/\n after-user-create.ts\n before-user-create.ts\n after-session-create.ts\n```\n\nEach file has a single default export — an `async (entity, ctx) => ...` function. The filename determines which Better Auth event the hook fires on.\n\n## Recognized events\n\n| Filename | Better Auth path | Entity | Return |\n|--------------------------------|-----------------------------------|----------|---------------------------------|\n| `before-user-create.ts` | `databaseHooks.user.create.before` | `User` | `void \\| { data?: Partial<User> }` |\n| `after-user-create.ts` | `databaseHooks.user.create.after` | `User` | `void` |\n| `after-session-create.ts` | `databaseHooks.session.create.after` | `Session` | `void` |\n\nFilenames outside this set are a hard compile-time error so a typo never silently disables a hook. Add events by extending [`apps/compiler/src/parser/hooks.ts`](https://github.com/paulstenhouse/quickback-compiler) (and the matching CLI mirror).\n\n## ctx shape\n\nEvery hook receives `(entity, ctx)`:\n\n```ts\ntype HookCtx = {\n /** Drizzle client bound to the auth DB binding (split-DB aware). */\n authDb: DrizzleClient;\n /**\n * Auth schema namespace — destructure to access the BA-managed tables\n * (`user`, `session`, `organization`, `member`, …) without writing an\n * import path. The hook source lives in `quickback/hooks/` pre-compile\n * and `src/lib/auth-hooks/` post-stage; relying on `authSchema`\n * removes the dual-path import problem.\n */\n authSchema: typeof import('../../auth/schema');\n /** Cloudflare bindings (Cloudflare runtime) or process.env (Bun/Node). */\n env: Bindings;\n /** Better Auth's own context object — request, hook metadata, etc. */\n baContext: any;\n};\n```\n\n`authDb` is the load-bearing piece: hooks must write to the auth DB via Drizzle directly. See the [CSRF caveat](#csrf-caveat-server-side-org-create) below. `authSchema` is the namespace export of the generated auth schema module; destructure the tables you need.\n\n## Writing hooks: use built-ins where possible\n\nHook source files are evaluated by the Better Auth schema-generation step at compile time, which runs in a stripped-down sandbox that **does not see your project's `node_modules`**. A hook that imports `@paralleldrive/cuid2`, `nanoid`, or any other third-party package will fail compile with a \"module not found\" error during the auth-schema-generation step — even if the package is installed and runs fine in the deployed Worker.\n\nStick to runtime built-ins for ID generation, hashing, and similar primitives:\n\n| Need | Built-in |\n|--------------------|---------------------------------------------------------|\n| Random ID | `crypto.randomUUID()` |\n| SHA-256 / digest | `crypto.subtle.digest(...)` (Workers / Node 19+) |\n| Random bytes | `crypto.getRandomValues(new Uint8Array(n))` |\n| Time | `Date.now()`, `new Date().toISOString()` |\n\n`drizzle-orm` is already available in the schema-gen sandbox (the auth schema imports from it), so `eq`, `and`, `inArray`, etc. are safe to import.\n\n## Throw semantics\n\nWhat happens when a hook throws is the #1 thing that bites people:\n\n| Hook | Throw effect |\n|-----------------------|------------------------------------------------------------------------------|\n| `before-user-create` | Signup aborts. The user is **not** created. Throw a typed error to gate. |\n| `after-user-create` | The user **is** created (the BA insert already committed). Any derived rows your hook started writing become orphans. |\n| `after-session-create`| Same as above — the session row exists; partial writes leak. |\n\nFor `after-*` hooks, design for **idempotency**: use the entity's `id` as a stable seed for any derived rows so re-running the hook (manually or via a background reconciler) is safe. Don't generate fresh `cuid()`s for derived rows you'd want to recover.\n\n## Examples\n\n### Auto-provision a personal workspace on signup\n\nThe QB-9 case. Without this, `organizations: true` projects break immediately for new users.\n\n```ts title=\"quickback/hooks/after-user-create.ts\"\n\nexport default async (user, { authDb, authSchema }) => {\n const { organization, member } = authSchema;\n\n // Idempotency: derive a stable org id from the user id so re-running this\n // hook (after a partial failure) doesn't create a second workspace.\n const orgId = `org_${user.id}`;\n const slug = `${(user.name ?? 'workspace').toLowerCase().replace(/\\s+/g, '-')}-${user.id.slice(0, 6)}`;\n\n // Skip if the workspace already exists (idempotent).\n const existing = await authDb\n .select({ id: organization.id })\n .from(organization)\n .where(eq(organization.id, orgId));\n if (existing.length > 0) return;\n\n await authDb.insert(organization).values({\n id: orgId,\n name: `${user.name ?? 'Personal'} Workspace`,\n slug,\n createdAt: new Date(),\n });\n\n await authDb.insert(member).values({\n id: crypto.randomUUID(),\n userId: user.id,\n organizationId: orgId,\n role: 'owner',\n createdAt: new Date(),\n });\n};\n```\n\n### Set the active organization on next session\n\nSetting `activeOrganizationId` from a hook means writing to `session.active_organization_id` via Drizzle directly — calling Better Auth's `setActiveOrganization` API server-side is awkward (see the CSRF caveat). The reliable pattern:\n\n```ts title=\"quickback/hooks/after-session-create.ts\"\n\nexport default async (newSession, { authDb, authSchema }) => {\n const { session, member } = authSchema;\n\n // Pick the user's first membership as their active org. Projects that\n // want a sticky last-active-org should track that separately.\n const memberships = await authDb\n .select({ organizationId: member.organizationId })\n .from(member)\n .where(eq(member.userId, newSession.userId))\n .limit(1);\n\n if (memberships.length === 0) return;\n\n await authDb\n .update(session)\n .set({ activeOrganizationId: memberships[0].organizationId })\n .where(eq(session.id, newSession.id));\n};\n```\n\n### Normalize and gate signup\n\n`before-*` hooks can return `{ data: Partial<User> }` to mutate the row before insert. Throw to abort.\n\n```ts title=\"quickback/hooks/before-user-create.ts\"\nexport default async (user: { email: string; name?: string }) => {\n // Block disposable inboxes.\n if (/@(?:mailinator|10minutemail)\\.com$/i.test(user.email)) {\n throw new Error('Disposable email addresses are not allowed.');\n }\n // Trim whitespace from display name.\n return { data: { name: user.name?.trim() } };\n};\n```\n\nThe compiler-generated wrapper merges your `data` onto the original entity, so you only return the fields you actually want to change.\n\n## CSRF caveat — server-side org create\n\n`POST /auth/v1/organization/create` (and Better Auth's `auth.api.createOrganization(...)` server helper) require an `Origin` header. A hook running inside `databaseHooks.user.create.after` is server-side — there is no incoming request, so no `Origin`. Calling those APIs from a hook may also validate `Origin` internally and reject.\n\n**The only safe path is direct Drizzle writes via `authDb`.** Treat the org/member tables as your source of truth and let the SPA call the BA API for user-initiated org creation.\n\n## Generated output\n\nCompile picks up `quickback/hooks/*.ts` and produces:\n\n```\nsrc/lib/auth.ts # imports the hook + adds a databaseHooks block\nsrc/lib/auth-hooks/<file> # your hook source, copied verbatim\n```\n\nInside the generated `auth.ts`:\n\n```ts\n\n// ...inside createAuth(env)...\nreturn betterAuth({\n // ...\n database: drizzleAdapter(db, { /* ... */ }),\n databaseHooks: {\n user: {\n create: {\n after: async (entity, _baCtx) => {\n const _qbCtx = { authDb: db, authSchema: schema, env, baContext: _baCtx };\n await __qbHook_afterUserCreate(entity, _qbCtx);\n },\n },\n },\n },\n});\n```\n\nNo hooks → no `databaseHooks` block emitted. The whole feature is opt-in by file presence.\n\n## See also\n\n- [With Quickback Compiler](/stack/account-ui/with-quickback) — how `account.auth.organizations` flows through the build\n- [Configuration → account block](/compiler/config) — `account.appUrl` and other account-level options\n- [Better Auth: Database Hooks](https://www.better-auth.com/docs/concepts/database#database-hooks)"
|
|
282
|
+
"content": "# Auth Hooks\n\nQuickback discovers project-level auth hooks at `quickback/hooks/` and wires them into [Better Auth's `databaseHooks`](https://www.better-auth.com/docs/concepts/database#database-hooks). Use them for post-signup bootstrap, signup gating, and other lifecycle work.\n\nThe classic case is multi-tenant: when `account.auth.organizations: true` is set, a freshly signed-up user has no `activeOrganizationId`, so every authenticated `/api/v1/*` returns `400 ORG_REQUIRED`. An `after-user-create` hook can auto-provision a personal workspace + member row so the next request just works.\n\n## Folder layout\n\n```\nquickback/\n hooks/\n after-user-create.ts\n before-user-create.ts\n after-session-create.ts\n after-admin-user-create.ts\n```\n\nEach file has a single default export — an `async (entity, ctx) => ...` function. The filename determines which Better Auth event the hook fires on.\n\n## Recognized events\n\n| Filename | Better Auth path | Entity | Return |\n|--------------------------------|-----------------------------------|----------|---------------------------------|\n| `before-user-create.ts` | `databaseHooks.user.create.before` | `User` | `void \\| { data?: Partial<User> }` |\n| `after-user-create.ts` | `databaseHooks.user.create.after` | `User` | `void` |\n| `after-session-create.ts` | `databaseHooks.session.create.after` | `Session` | `void` |\n| `after-admin-user-create.ts` | `databaseHooks.user.create.after` (filtered) | `User` | `void` |\n\n`after-admin-user-create.ts` is a **virtual event** — it wires into the same Better Auth `user.create.after` slot as the generic `after-user-create.ts`, but the compiler wraps the call in a runtime filter on the BA context path so it only fires when the row was created via the admin plugin's `POST /admin/create-user` endpoint. Use it for first-time-user provisioning (welcome email, default org assignment) without inspecting `_baCtx?.context?.path` by hand. The generic `after-user-create.ts` still runs for every signup, including admin-created ones.\n\nFilenames outside this set are a hard compile-time error so a typo never silently disables a hook. Add events by extending [`apps/compiler/src/parser/hooks.ts`](https://github.com/paulstenhouse/quickback-compiler) (and the matching CLI mirror).\n\n## ctx shape\n\nEvery hook receives `(entity, ctx)`:\n\n```ts\ntype HookCtx = {\n /** Drizzle client bound to the auth DB binding (split-DB aware). */\n authDb: DrizzleClient;\n /**\n * Auth schema namespace — destructure to access the BA-managed tables\n * (`user`, `session`, `organization`, `member`, …) without writing an\n * import path. The hook source lives in `quickback/hooks/` pre-compile\n * and `src/lib/auth-hooks/` post-stage; relying on `authSchema`\n * removes the dual-path import problem.\n */\n authSchema: typeof import('../../auth/schema');\n /** Cloudflare bindings (Cloudflare runtime) or process.env (Bun/Node). */\n env: Bindings;\n /** Better Auth's own context object — request, hook metadata, etc. */\n baContext: any;\n};\n```\n\n`authDb` is the load-bearing piece: hooks must write to the auth DB via Drizzle directly. See the [CSRF caveat](#csrf-caveat-server-side-org-create) below. `authSchema` is the namespace export of the generated auth schema module; destructure the tables you need.\n\n## Writing hooks: use built-ins where possible\n\nHook source files are evaluated by the Better Auth schema-generation step at compile time, which runs in a stripped-down sandbox that **does not see your project's `node_modules`**. A hook that imports `@paralleldrive/cuid2`, `nanoid`, or any other third-party package will fail compile with a \"module not found\" error during the auth-schema-generation step — even if the package is installed and runs fine in the deployed Worker.\n\nStick to runtime built-ins for ID generation, hashing, and similar primitives:\n\n| Need | Built-in |\n|--------------------|---------------------------------------------------------|\n| Random ID | `crypto.randomUUID()` |\n| SHA-256 / digest | `crypto.subtle.digest(...)` (Workers / Node 19+) |\n| Random bytes | `crypto.getRandomValues(new Uint8Array(n))` |\n| Time | `Date.now()`, `new Date().toISOString()` |\n\n`drizzle-orm` is already available in the schema-gen sandbox (the auth schema imports from it), so `eq`, `and`, `inArray`, etc. are safe to import.\n\n## Throw semantics\n\nWhat happens when a hook throws is the #1 thing that bites people:\n\n| Hook | Throw effect |\n|-----------------------|------------------------------------------------------------------------------|\n| `before-user-create` | Signup aborts. The user is **not** created. Throw a typed error to gate. |\n| `after-user-create` | The user **is** created (the BA insert already committed). Any derived rows your hook started writing become orphans. |\n| `after-session-create`| Same as above — the session row exists; partial writes leak. |\n\nFor `after-*` hooks, design for **idempotency**: use the entity's `id` as a stable seed for any derived rows so re-running the hook (manually or via a background reconciler) is safe. Don't generate fresh `cuid()`s for derived rows you'd want to recover.\n\n## Examples\n\n### Auto-provision a personal workspace on signup\n\nThe QB-9 case. Without this, `organizations: true` projects break immediately for new users.\n\n```ts title=\"quickback/hooks/after-user-create.ts\"\n\nexport default async (user, { authDb, authSchema }) => {\n const { organization, member } = authSchema;\n\n // Idempotency: derive a stable org id from the user id so re-running this\n // hook (after a partial failure) doesn't create a second workspace.\n const orgId = `org_${user.id}`;\n const slug = `${(user.name ?? 'workspace').toLowerCase().replace(/\\s+/g, '-')}-${user.id.slice(0, 6)}`;\n\n // Skip if the workspace already exists (idempotent).\n const existing = await authDb\n .select({ id: organization.id })\n .from(organization)\n .where(eq(organization.id, orgId));\n if (existing.length > 0) return;\n\n await authDb.insert(organization).values({\n id: orgId,\n name: `${user.name ?? 'Personal'} Workspace`,\n slug,\n createdAt: new Date(),\n });\n\n await authDb.insert(member).values({\n id: crypto.randomUUID(),\n userId: user.id,\n organizationId: orgId,\n role: 'owner',\n createdAt: new Date(),\n });\n};\n```\n\n### Set the active organization on next session\n\nSetting `activeOrganizationId` from a hook means writing to `session.active_organization_id` via Drizzle directly — calling Better Auth's `setActiveOrganization` API server-side is awkward (see the CSRF caveat). The reliable pattern:\n\n```ts title=\"quickback/hooks/after-session-create.ts\"\n\nexport default async (newSession, { authDb, authSchema }) => {\n const { session, member } = authSchema;\n\n // Pick the user's first membership as their active org. Projects that\n // want a sticky last-active-org should track that separately.\n const memberships = await authDb\n .select({ organizationId: member.organizationId })\n .from(member)\n .where(eq(member.userId, newSession.userId))\n .limit(1);\n\n if (memberships.length === 0) return;\n\n await authDb\n .update(session)\n .set({ activeOrganizationId: memberships[0].organizationId })\n .where(eq(session.id, newSession.id));\n};\n```\n\n### Normalize and gate signup\n\n`before-*` hooks can return `{ data: Partial<User> }` to mutate the row before insert. Throw to abort.\n\n```ts title=\"quickback/hooks/before-user-create.ts\"\nexport default async (user: { email: string; name?: string }) => {\n // Block disposable inboxes.\n if (/@(?:mailinator|10minutemail)\\.com$/i.test(user.email)) {\n throw new Error('Disposable email addresses are not allowed.');\n }\n // Trim whitespace from display name.\n return { data: { name: user.name?.trim() } };\n};\n```\n\nThe compiler-generated wrapper merges your `data` onto the original entity, so you only return the fields you actually want to change.\n\n## CSRF caveat — server-side org create\n\n`POST /auth/v1/organization/create` (and Better Auth's `auth.api.createOrganization(...)` server helper) require an `Origin` header. A hook running inside `databaseHooks.user.create.after` is server-side — there is no incoming request, so no `Origin`. Calling those APIs from a hook may also validate `Origin` internally and reject.\n\n**The only safe path is direct Drizzle writes via `authDb`.** Treat the org/member tables as your source of truth and let the SPA call the BA API for user-initiated org creation.\n\n## Generated output\n\nCompile picks up `quickback/hooks/*.ts` and produces:\n\n```\nsrc/lib/auth.ts # imports the hook + adds a databaseHooks block\nsrc/lib/auth-hooks/<file> # your hook source, copied verbatim\n```\n\nInside the generated `auth.ts`:\n\n```ts\n\n// ...inside createAuth(env)...\nreturn betterAuth({\n // ...\n database: drizzleAdapter(db, { /* ... */ }),\n databaseHooks: {\n user: {\n create: {\n after: async (entity, _baCtx) => {\n const _qbCtx = { authDb: db, authSchema: schema, env, baContext: _baCtx };\n await __qbHook_afterUserCreate(entity, _qbCtx);\n },\n },\n },\n },\n});\n```\n\nNo hooks → no `databaseHooks` block emitted. The whole feature is opt-in by file presence.\n\n## See also\n\n- [With Quickback Compiler](/stack/account-ui/with-quickback) — how `account.auth.organizations` flows through the build\n- [Configuration → account block](/compiler/config) — `account.appUrl` and other account-level options\n- [Better Auth: Database Hooks](https://www.better-auth.com/docs/concepts/database#database-hooks)"
|
|
283
283
|
},
|
|
284
284
|
"stack/account-ui": {
|
|
285
285
|
"title": "Account UI",
|
|
@@ -311,7 +311,11 @@ export const DOCS = {
|
|
|
311
311
|
},
|
|
312
312
|
"stack/auth/plugins/aws-ses": {
|
|
313
313
|
"title": "AWS SES Plugin",
|
|
314
|
-
"content": "`@quickback-dev/better-auth-aws-ses` is a Better Auth plugin that sends transactional emails via AWS SES. It handles AWS Signature V4 signing, HTML/text email templates, and rate limiting — designed to work in Cloudflare Workers (no Node.js `aws-sdk` dependency).\n\n> **Cloudflare Email is the default.** As of the Cloudflare Email Sending public beta, the zero-config `send_email` binding is Quickback's default transport for Cloudflare deploys — no API keys, no SES setup. See [Email Configuration](/compiler/config#email-configuration). Use AWS SES when you need it (non-Cloudflare runtimes, existing SES infra, or specific deliverability/compliance requirements).\n\n## Installation\n\n```bash\nnpm install @quickback-dev/better-auth-aws-ses\n```\n\nThis plugin is wired up only when you explicitly opt in via `email.provider: 'aws-ses'` in your Quickback config. Without that, `email.provider` defaults to `'cloudflare'` and the Cloudflare Email helper is used instead.\n\n## Email Types\n\nThe plugin handles 8 email types:\n\n| Endpoint | When Sent |\n|----------|-----------|\n| `/ses/send-verification` | Signup email verification |\n| `/ses/send-password-reset` | Password reset request |\n| `/ses/send-magic-link` | Passwordless sign-in link |\n| `/ses/send-otp` | One-time password code |\n| `/ses/send-welcome` | Post-signup welcome email |\n| `/ses/send-organization-invitation` | Team/org invite with role |\n| Combo auth | Magic link + OTP in a single email |\n| Delete account | Account deletion confirmation |\n\n### Combo Auth Mode\n\nWhen `useComboAuthEmail: true` is set, the plugin sends a single email that includes both a magic link button and an OTP code. Users can choose either method to authenticate.\n\n## AWS Signature V4\n\nThe plugin signs requests to SES using AWS Signature V4 with the Web Crypto API (`crypto.subtle`), making it compatible with Cloudflare Workers without any AWS SDK dependency.\n\n## Templates\n\nEach email type has both HTML and plain text templates. Templates include:\n\n- Responsive HTML layout with MSO (Microsoft Outlook) support\n- Security warning banners for sensitive operations\n- Fallback plain text versions for all email clients\n- XSS prevention via HTML escaping and URL sanitization\n\n## Configuration\n\n### Server Plugin\n\n```typescript\n\nconst auth = betterAuth({\n plugins: [\n awsSESPlugin({\n region: env.AWS_SES_REGION,\n accessKeyId: env.AWS_ACCESS_KEY_ID,\n secretAccessKey: env.AWS_SECRET_ACCESS_KEY,\n fromEmail: env.EMAIL_FROM,\n fromName: env.EMAIL_FROM_NAME || \"My App\",\n replyTo: env.EMAIL_REPLY_TO,\n appName: env.APP_NAME || \"My App\",\n appUrl: env.APP_URL,\n useComboAuthEmail: true, // Optional: combine magic link + OTP\n }),\n ],\n});\n```\n\n### Client Plugin\n\n```typescript\n\nconst authClient = createAuthClient({\n plugins: [awsSESClientPlugin()],\n});\n```\n\n## Required Environment Variables\n\n| Variable | Description |\n|----------|-------------|\n| `AWS_ACCESS_KEY_ID` | AWS access key (use Wrangler secrets) |\n| `AWS_SECRET_ACCESS_KEY` | AWS secret key (use Wrangler secrets) |\n| `AWS_SES_REGION` | SES region (e.g., `us-east-2`) |\n| `EMAIL_FROM` | Sender email address (must be SES-verified) |\n\n## Optional Variables\n\n| Variable | Description |\n|----------|-------------|\n| `EMAIL_FROM_NAME` | Sender display name |\n| `EMAIL_REPLY_TO` | Reply-to address (defaults to `EMAIL_FROM`) |\n| `APP_NAME` | Application name shown in email templates |\n| `APP_URL` | Application URL for links in emails |\n| `BETTER_AUTH_URL` | Auth API URL (for verification/reset links) |\n\n## Rate Limiting\n\nThe plugin includes basic in-memory rate limiting per recipient:\n\n- Configurable hourly and daily limits\n- Per-recipient tracking\n- For production, consider using an external store (Redis, KV)\n\n```typescript\nawsSESPlugin({\n // ...\n rateLimit: {\n maxEmailsPerHour: 10,\n maxEmailsPerDay: 50,\n },\n})\n```\n\n## Error Handling\n\n- Email failures return `false` (don't throw) — signup/login flows continue even if email delivery fails\n- Invalid or placeholder AWS credentials are detected at startup\n- Detailed console logging for debugging delivery issues\n\n## See Also\n\n- [Combo Auth Plugin](/stack/auth/plugins/combo-auth) — Combined magic link + OTP authentication\n- [Auth Configuration](/compiler/config/providers) — Configuring auth plugins"
|
|
314
|
+
"content": "`@quickback-dev/better-auth-aws-ses` is a Better Auth plugin that sends transactional emails via AWS SES. It handles AWS Signature V4 signing, HTML/text email templates, and rate limiting — designed to work in Cloudflare Workers (no Node.js `aws-sdk` dependency).\n\n> **Cloudflare Email is the default.** As of the Cloudflare Email Sending public beta, the zero-config `send_email` binding is Quickback's default transport for Cloudflare deploys — no API keys, no SES setup. See [Email Configuration](/compiler/config#email-configuration). Use AWS SES when you need it (non-Cloudflare runtimes, existing SES infra, or specific deliverability/compliance requirements).\n\n## Installation\n\n```bash\nnpm install @quickback-dev/better-auth-aws-ses\n```\n\nThis plugin is wired up only when you explicitly opt in via `email.provider: 'aws-ses'` in your Quickback config. Without that, `email.provider` defaults to `'cloudflare'` and the Cloudflare Email helper is used instead.\n\n## Email Types\n\nThe plugin handles 8 email types:\n\n| Endpoint | When Sent |\n|----------|-----------|\n| `/ses/send-verification` | Signup email verification |\n| `/ses/send-password-reset` | Password reset request |\n| `/ses/send-magic-link` | Passwordless sign-in link |\n| `/ses/send-otp` | One-time password code |\n| `/ses/send-welcome` | Post-signup welcome email |\n| `/ses/send-organization-invitation` | Team/org invite with role |\n| Combo auth | Magic link + OTP in a single email |\n| Delete account | Account deletion confirmation |\n\n### Combo Auth Mode\n\nWhen `useComboAuthEmail: true` is set, the plugin sends a single email that includes both a magic link button and an OTP code. Users can choose either method to authenticate.\n\n## AWS Signature V4\n\nThe plugin signs requests to SES using AWS Signature V4 with the Web Crypto API (`crypto.subtle`), making it compatible with Cloudflare Workers without any AWS SDK dependency.\n\n## Templates\n\nEach email type has both HTML and plain text templates. Templates include:\n\n- Responsive HTML layout with MSO (Microsoft Outlook) support\n- Security warning banners for sensitive operations\n- Fallback plain text versions for all email clients\n- XSS prevention via HTML escaping and URL sanitization\n\n### Per-Type Template Overrides\n\nOverride the default subject + HTML + text for any OTP type without forking the package. Drop a `.ts` file into `quickback/email-templates/` and reference it from `plugins.emailOtp.templates`:\n\n```typescript\n// quickback/quickback.config.ts\ndefineAuth(\"better-auth\", {\n plugins: {\n emailOtp: {\n templates: {\n 'forget-password': './email-templates/forget-password',\n 'welcome': './email-templates/welcome',\n },\n },\n },\n});\n```\n\nEach template module default-exports a function that returns `{ subject, html, text }`:\n\n```typescript\n// quickback/email-templates/welcome.ts\ninterface Input {\n email: string;\n otp: string;\n type: 'sign-in' | 'email-verification' | 'forget-password' | 'welcome';\n name?: string;\n appName: string;\n appUrl: string;\n supportEmail?: string;\n}\n\nexport default function welcomeTemplate({ otp, name, appName, appUrl }: Input) {\n const greeting = name ? `Hi ${name},` : 'Hi,';\n return {\n subject: `Welcome to ${appName} — set your password`,\n html: `\n <h1>Welcome to ${appName}</h1>\n <p>${greeting} your account is ready. Use this code to set your password and sign in:</p>\n <p style=\"font-size:32px;letter-spacing:8px\"><b>${otp}</b></p>\n <p>Visit <a href=\"${appUrl}/set-password\">${appUrl}/set-password</a> to finish setup.</p>\n `,\n text: `${greeting}\\n\\nYour ${appName} code: ${otp}\\n\\nFinish setup at ${appUrl}/set-password`,\n };\n}\n```\n\nRecognized keys:\n\n| Key | When it fires |\n|-----|---------------|\n| `'sign-in'` | OTP sign-in flow |\n| `'email-verification'` | Signup email verification |\n| `'forget-password'` | Password reset request — and admin-bootstrap if `welcome` isn't set |\n| `'welcome'` | **Synthetic** — routed when `forget-password` fires for a user with no credential row yet (the admin-plugin → bootstrap flow). Without it, those sends fall through to `forget-password`. |\n\nMissing keys fall through to the built-in defaults from `@quickback-dev/better-auth-aws-ses`. The compiler stages each referenced file into `src/email-templates/<name>.ts` and wires the default import in `src/lib/auth.ts` — the template function is called inline from `sendVerificationOTP`, so it has access to whatever modules the file imports.\n\n> **Provider scope.** Overrides are only honored when `email.provider: 'aws-ses'`. The Cloudflare Email path uses the helper's own template pipeline and ignores `plugins.emailOtp.templates`.\n\n## Configuration\n\n### Server Plugin\n\n```typescript\n\nconst auth = betterAuth({\n plugins: [\n awsSESPlugin({\n region: env.AWS_SES_REGION,\n accessKeyId: env.AWS_ACCESS_KEY_ID,\n secretAccessKey: env.AWS_SECRET_ACCESS_KEY,\n fromEmail: env.EMAIL_FROM,\n fromName: env.EMAIL_FROM_NAME || \"My App\",\n replyTo: env.EMAIL_REPLY_TO,\n appName: env.APP_NAME || \"My App\",\n appUrl: env.APP_URL,\n useComboAuthEmail: true, // Optional: combine magic link + OTP\n }),\n ],\n});\n```\n\n### Client Plugin\n\n```typescript\n\nconst authClient = createAuthClient({\n plugins: [awsSESClientPlugin()],\n});\n```\n\n## Required Environment Variables\n\n| Variable | Description |\n|----------|-------------|\n| `AWS_ACCESS_KEY_ID` | AWS access key (use Wrangler secrets) |\n| `AWS_SECRET_ACCESS_KEY` | AWS secret key (use Wrangler secrets) |\n| `AWS_SES_REGION` | SES region (e.g., `us-east-2`) |\n| `EMAIL_FROM` | Sender email address (must be SES-verified) |\n\n## Optional Variables\n\n| Variable | Description |\n|----------|-------------|\n| `EMAIL_FROM_NAME` | Sender display name |\n| `EMAIL_REPLY_TO` | Reply-to address (defaults to `EMAIL_FROM`) |\n| `APP_NAME` | Application name shown in email templates |\n| `APP_URL` | Application URL for links in emails |\n| `BETTER_AUTH_URL` | Auth API URL (for verification/reset links) |\n\n## Rate Limiting\n\nThe plugin includes basic in-memory rate limiting per recipient:\n\n- Configurable hourly and daily limits\n- Per-recipient tracking\n- For production, consider using an external store (Redis, KV)\n\n```typescript\nawsSESPlugin({\n // ...\n rateLimit: {\n maxEmailsPerHour: 10,\n maxEmailsPerDay: 50,\n },\n})\n```\n\n## Error Handling\n\n- Email failures return `false` (don't throw) — signup/login flows continue even if email delivery fails\n- Invalid or placeholder AWS credentials are detected at startup\n- Detailed console logging for debugging delivery issues\n\n## See Also\n\n- [Combo Auth Plugin](/stack/auth/plugins/combo-auth) — Combined magic link + OTP authentication\n- [Auth Configuration](/compiler/config/providers) — Configuring auth plugins"
|
|
315
|
+
},
|
|
316
|
+
"stack/auth/plugins/aws-sns": {
|
|
317
|
+
"title": "AWS SNS Plugin (SMS OTP)",
|
|
318
|
+
"content": "`@quickback-dev/better-auth-aws-sns` is the SMS transport package Quickback wires into Better Auth's built-in `phoneNumber` plugin when you opt in to SMS OTP. It signs SNS `Publish` requests with AWS Signature V4 using the Web Crypto API — zero AWS SDK dependency, runs on Cloudflare Workers.\n\n> **Why SMS?** Corporate email gateways aggressively filter or rewrite transactional auth emails (link previews, click-tracking, MITM scanners). For some user bases SMS is the most reliable channel for a six-digit code that has to land in under a minute.\n\n## What it provides\n\nThe package itself does **not** register a Better Auth plugin. Better Auth's builtin [`phoneNumber`](https://www.better-auth.com/docs/plugins/phone-number) plugin owns the endpoints (`/auth/v1/phone-number/send-otp`, `/verify`, `/sign-in/phone-number`, password reset). This package fills the `sendOTP` / `sendPasswordResetOTP` callbacks and the `phoneNumberValidator` hook.\n\n| Export | Purpose |\n|--------|---------|\n| `sendSMSWithSNS(config, { to, message })` | Publish to SNS with SigV4 + in-memory rate limit + E.164 validation. |\n| `smsTemplates.otp` / `smsTemplates.passwordReset` | Short transactional SMS bodies (single GSM-7 segment). |\n| `isValidE164(phone)` / `normalizeE164(phone)` | Phone number validators. Wired into Better Auth's `phoneNumberValidator`. |\n\n## Enable in config\n\n```ts\n\nexport default defineConfig({\n name: \"my-app\",\n sms: {\n provider: \"aws-sns\",\n region: \"us-east-1\",\n senderId: \"MyApp\", // optional — non-US countries only\n smsType: \"Transactional\", // default\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: { phoneNumber: true },\n }),\n },\n});\n```\n\nThe compiler:\n\n1. Adds `@quickback-dev/better-auth-aws-sns` to the generated `package.json`.\n2. Emits a `getSNSConfig(env)` helper in `src/lib/auth.ts`.\n3. Wires the `phoneNumber` plugin with `sendOTP`, `sendPasswordResetOTP`, and `phoneNumberValidator: isValidE164`.\n4. Drops `AWS_SNS_REGION` / `APP_NAME` (and `SMS_SENDER_ID` / `SMS_TYPE` when set) into `[vars]` in `wrangler.toml`.\n5. Forwards `c.executionCtx` from the Hono handler so OTP sends use `waitUntil(...)` — Better Auth advises **not** awaiting `sendOTP` to keep SMS latency out of the response.\n\n## What you get from Better Auth's `phoneNumber` plugin\n\nSchema (added to your user table):\n\n| Column | Type | Notes |\n|--------|------|-------|\n| `phoneNumber` | `string \\| null` | E.164 format |\n| `phoneNumberVerified` | `boolean` | Set on successful verify |\n\nEndpoints:\n\n| Method | Path | Purpose |\n|--------|------|---------|\n| `POST` | `/auth/v1/phone-number/send-otp` | Trigger an OTP SMS |\n| `POST` | `/auth/v1/phone-number/verify` | Verify the OTP code |\n| `POST` | `/auth/v1/sign-in/phone-number` | Phone + password sign-in |\n| `POST` | `/auth/v1/phone-number/request-password-reset` | Send a reset OTP |\n| `POST` | `/auth/v1/phone-number/reset-password` | Complete password reset |\n\nDefaults: 6-digit codes, 300s expiry, 3 verify attempts (exceeding deletes the OTP and returns 403). See the [Better Auth plugin docs](https://www.better-auth.com/docs/plugins/phone-number) for the full option surface.\n\n## Required environment variables\n\nWrangler `[vars]` (non-secret, emitted by the compiler):\n\n| Name | Default | Notes |\n|------|---------|-------|\n| `AWS_SNS_REGION` | `us-east-1` | Any SNS-enabled region. |\n| `APP_NAME` | `<your config.name>` | Appears in the SMS body. |\n| `SMS_SENDER_ID` | — | Optional. Set only for non-US/CA traffic. |\n| `SMS_TYPE` | `Transactional` | Override only to send promotional traffic. |\n\nSecrets (set with `wrangler secret put`):\n\n| Name | Required | Notes |\n|------|----------|-------|\n| `AWS_ACCESS_KEY_ID` | yes | IAM key with `sns:Publish`. Shared with SES if used. |\n| `AWS_SECRET_ACCESS_KEY` | yes | Companion secret. |\n\n## AWS prerequisites\n\nBefore SMS will actually deliver in production, do this in the AWS console:\n\n1. **Pull out of the SNS sandbox.** New accounts can only send to verified numbers and have a low monthly cap. Submit a \"Request production access\" case from the SNS SMS Preferences page.\n2. **Set a monthly spend cap.** SMS gets expensive fast — set a limit before you go live.\n3. **US A2P (10DLC).** Long codes sending app-to-person SMS to US numbers must be registered with TCR (The Campaign Registry) via Pinpoint SMS Voice v2. Carrier filtering rejects unregistered A2P traffic. Allow several weeks for approval.\n4. **Sender ID support.** Alphanumeric sender IDs work in many countries (UK, France, Germany, India, etc.) but **not** the US or Canada. Pick origination identities per country.\n5. **IAM policy.** The access key needs `sns:Publish` on `*` plus `sns:SetSMSAttributes` if you want to manage the spend cap programmatically.\n\n## Validation and rate limiting\n\n- **E.164 only.** `isValidE164` rejects anything that's not `+[country code][7–14 digits]`. There is no automatic country-code inference — capture the country in your UI (e.g. `react-phone-number-input`).\n- **Send-side rate limit.** The package's in-memory map caps sends per phone (hourly + daily) when `rateLimit` is set on the config. It's an isolate-local guard; for stricter limits put a KV-backed limiter in front of `/auth/v1/phone-number/send-otp`.\n- **Verify-side rate limit.** Better Auth's `phoneNumber` plugin enforces 3 attempts before deleting the OTP. You can additionally tighten Quickback's per-route limit on `/auth/v1/phone-number/send-otp` via `auth.rateLimit.customRules`.\n\n## Carrier filtering\n\nKeep the SMS body short, transactional, and link-free. The default template is:\n\n```\nYour <AppName> code is 123456. Expires in 5 min. Don't share it.\n```\n\n— under 80 characters, no URL, no marketing copy. Carriers filter long messages, links, and brand-imitation prefixes aggressively. If you customize the body, keep it under one GSM-7 segment (160 chars) to avoid multi-segment billing.\n\n## Verifying the wiring\n\nAfter compile, check the generated `src/lib/auth.ts`:\n\n```ts\n\nfunction getSNSConfig(env: CloudflareBindings | undefined): SNSConfig { /* ... */ }\n\nfunction createAuth(env, cf, executionCtx) {\n const fireAndForget = (p) => { /* waitUntil(p) */ };\n\n return betterAuth({\n plugins: [\n phoneNumber({\n phoneNumberValidator: isValidE164,\n sendOTP: async ({ phoneNumber, code }) => {\n fireAndForget(sendSMSWithSNS(getSNSConfig(env), {\n to: phoneNumber,\n message: smsTemplates.otp.message({ code, appName: ... }),\n }));\n },\n // ...\n }),\n ],\n });\n}\n```\n\nThat's the contract: callbacks are fire-and-forget via `executionCtx.waitUntil`, never `await`ed.\n\n## Sign-in flow\n\n```ts\n// 1. Request OTP\nawait fetch('/auth/v1/phone-number/send-otp', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ phoneNumber: '+14155550100' }),\n});\n\n// 2. Verify the code the user types in\nconst res = await fetch('/auth/v1/phone-number/verify', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ phoneNumber: '+14155550100', code: '123456' }),\n});\n```\n\nFor Better Auth's signed-in client SDK, use `authClient.phoneNumber.sendOtp(...)` / `authClient.phoneNumber.verify(...)`.\n\n## Compliance reminders\n\n- **TCPA (US).** Capture explicit opt-in for transactional SMS at signup; keep an audit trail. STOP / HELP keyword handling is mandatory for A2P traffic — SNS handles standard keywords automatically on registered origination numbers, but verify it's enabled.\n- **GDPR (EU).** Phone numbers are personal data. Use Quickback's masking pillar to redact them in CMS views where appropriate.\n- **Don't use SMS as your only second factor.** SIM-swap attacks are real; pair phone OTP with passkeys / TOTP for high-value accounts."
|
|
315
319
|
},
|
|
316
320
|
"stack/auth/plugins/combo-auth": {
|
|
317
321
|
"title": "Combo Auth Plugin",
|
|
@@ -319,7 +323,7 @@ export const DOCS = {
|
|
|
319
323
|
},
|
|
320
324
|
"stack/auth/plugins": {
|
|
321
325
|
"title": "Auth Plugins",
|
|
322
|
-
"content": "Quickback ships with a curated set of Better Auth plugins and helper wiring so your auth stack is production-ready by default. Enable these in `quickback.config.ts` under `providers.auth`.\n\n## Available Plugins\n\n### Email OTP (with AWS SES)\n\nQuickback wires the Better Auth Email OTP flow to AWS SES. When `emailOtp` is enabled, the compiler emits the SES plugin and combo-auth email flow (magic link + OTP).\n\n**Enable in config:**\n\n```ts\n\nexport default defineConfig({\n name: \"quickback-api\",\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\", {\n vars: {\n AWS_SES_REGION: \"us-east-2\",\n EMAIL_FROM: \"noreply@yourdomain.com\",\n EMAIL_FROM_NAME: \"Your App | Account Services\",\n APP_NAME: \"Your App\",\n APP_URL: \"https://account.yourdomain.com\",\n BETTER_AUTH_URL: \"https://api.yourdomain.com\",\n },\n }),\n auth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: [\"emailOtp\"],\n }),\n },\n});\n```\n\n**Endpoints:**\n- `POST /auth/v1/email-otp/send-verification-otp`\n- `POST /auth/v1/email-otp/verify-otp`\n\n**Email readiness check:**\n\nUse this to show UI warnings when SES isn't configured.\n\n- `GET /api/v1/system/email-status`\n- Response: `{ \"emailConfigured\": true|false }`\n\n### Upgrade Anonymous\n\nAdds a first-class endpoint to convert an anonymous user into a full user. This flips `isAnonymous` to `false` and refreshes the session cache immediately.\n\n**Enable in config:**\n\n```ts\nauth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: [\"anonymous\", \"upgradeAnonymous\"],\n}),\n```\n\n**Endpoint:**\n- `POST /auth/v1/upgrade-anonymous`\n\n**Note:** If you send `Content-Type: application/json`, include a body (an empty `{}` is fine). This avoids request parsing errors in some clients.\n\n### AWS SES Plugin\n\nThis is a Quickback-provided Better Auth plugin for Email OTP and other transactional emails. It handles SES signing and delivery over the Web Crypto API so it runs in Cloudflare Workers without the AWS SDK. It is wired up only when you opt in via `email.provider: 'aws-ses'` — the default transport is Cloudflare Email Sending (`send_email` binding).\n\nRequired vars (only when `email.provider: 'aws-ses'` is set; use Wrangler secrets for credentials):\n- `AWS_ACCESS_KEY_ID` (secret)\n- `AWS_SECRET_ACCESS_KEY` (secret)\n- `AWS_SES_REGION`\n- `EMAIL_FROM`\n\nOptional vars:\n- `EMAIL_FROM_NAME`\n- `EMAIL_REPLY_TO` - Reply-to address for emails (defaults to `EMAIL_FROM`)\n- `APP_NAME`\n- `APP_URL`\n- `BETTER_AUTH_URL`\n\n### Magic Links\n\nMagic links provide passwordless authentication by sending a unique login link to the user's email. When clicked, the link authenticates the user without requiring a password.\n\n**Enable in config:**\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: [\"magicLink\"],\n}),\n```\n\n**Endpoints:**\n- `POST /auth/v1/magic-link/send` - Send magic link email\n- `GET /auth/v1/magic-link/verify` - Verify magic link token\n\n**Email customization:**\n\nMagic link emails use the same AWS SES configuration as Email OTP. Customize the email template via environment variables:\n\n- `APP_NAME` - Application name in email subject\n- `APP_URL` - Base URL for magic link redirect\n- `EMAIL_FROM` - Sender email address\n- `EMAIL_FROM_NAME` - Sender display name\n\n**Frontend integration:**\n\n```ts\n// Request magic link\nawait fetch('/auth/v1/magic-link/send', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email: 'user@yourdomain.com' })\n});\n\n// User clicks link in email, which redirects to your app\n// The token is verified automatically via the callback URL\n```\n\n### Passkeys\n\nPasskeys provide passwordless authentication using WebAuthn/FIDO2. Users authenticate with biometrics (fingerprint, face) or device PIN instead of passwords.\n\n**Enable in config:**\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: [\"passkey\"],\n}),\n```\n\n**Required environment variable:**\n- `ACCOUNT_URL` - Your account/frontend URL (used as the relying party origin for WebAuthn)\n\n**Endpoints:**\n- `POST /auth/v1/passkey/register/options` - Get registration challenge\n- `POST /auth/v1/passkey/register/verify` - Complete registration\n- `POST /auth/v1/passkey/authenticate/options` - Get authentication challenge\n- `POST /auth/v1/passkey/authenticate/verify` - Complete authentication\n- `GET /auth/v1/passkey/list-user-passkeys` - List user's registered passkeys\n- `POST /auth/v1/passkey/delete-passkey` - Delete a registered passkey\n\n**Browser support:**\n\nPasskeys are supported in all modern browsers:\n- Chrome 67+\n- Safari 14+\n- Firefox 60+\n- Edge 79+\n\n**Registration flow:**\n\n```ts\n// 1. Get registration options\nconst optionsRes = await fetch('/auth/v1/passkey/register/options', {\n method: 'POST',\n credentials: 'include'\n});\nconst options = await optionsRes.json();\n\n// 2. Create credential using WebAuthn API\nconst credential = await navigator.credentials.create({\n publicKey: options\n});\n\n// 3. Send credential to server\nawait fetch('/auth/v1/passkey/register/verify', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n credentials: 'include',\n body: JSON.stringify(credential)\n});\n```\n\n**Authentication flow:**\n\n```ts\n// 1. Get authentication options\nconst optionsRes = await fetch('/auth/v1/passkey/authenticate/options', {\n method: 'POST'\n});\nconst options = await optionsRes.json();\n\n// 2. Get credential using WebAuthn API\nconst credential = await navigator.credentials.get({\n publicKey: options\n});\n\n// 3. Verify credential\nawait fetch('/auth/v1/passkey/authenticate/verify', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n credentials: 'include',\n body: JSON.stringify(credential)\n});\n```\n\n### JWT Plugin\n\nBetter Auth's JWT plugin adds asymmetric-signed tokens and a JWKS endpoint for external services that need to verify user identity without sharing a shared secret.\n\n**Enable in config:**\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: [\"jwt\"],\n}),\n```\n\n**Endpoints:**\n- `GET /auth/v1/jwks` — public keys for verifying BA-issued tokens\n- `POST /auth/v1/token` — mint an asymmetric-signed JWT from the current session\n\n**When to enable:** you have external services (non-Quickback workers, third-party integrations) that need to verify a user's identity via JWKS without holding `BETTER_AUTH_SECRET`. The BA-issued tokens won't carry Quickback's `orgId`/`role` claims, so they're for identity, not API access.\n\n### API Keys\n\nStatic, long-lived credentials for cron jobs, scripts, and machine-to-machine integrations. Better Auth's `apiKey` plugin is auto-included when you enable the organizations feature, so no explicit config is required for the standard B2B SaaS shape.\n\n**Authenticating requests:**\n\nPass the key as the `x-api-key` header (preferred) or as an `?api_key=` / `?key=` query parameter:\n\n```bash\n# Header form (preferred — keys don't leak into access logs or Referer)\ncurl -H \"x-api-key: ${KEY}\" https://api.example.com/v1/jobs\n\n# Query-param form (for clients that can't inject custom headers,\n# e.g., claude.ai's MCP connector)\ncurl \"https://api.example.com/v1/jobs?api_key=${KEY}\"\n```\n\nThe header takes precedence when both are present. The query-param form lands in nginx / Cloudflare access logs and `Referer` headers when the page navigates away — prefer headers whenever the client supports them.\n\n**Endpoints (managed by Better Auth):**\n- `POST /auth/v1/api-key/create` — issue a new key (returns the secret once; store it)\n- `GET /auth/v1/api-key/list` — list keys for the current user\n- `POST /auth/v1/api-key/delete` — revoke a key\n\nKeys can carry organization context via `metadata.organizationId` — when set, the auth middleware looks up the user's role in that org and populates `ctx.roles` accordingly, so a single key inherits the same firewall + access scope as the user who created it.\n\n### OAuth Provider (MCP-ready)\n\nTurns your Quickback worker into a standards-compliant OAuth 2.1 + OIDC authorization server. The plugin ships RFC 7591 dynamic client registration plus the well-known discovery documents an MCP client needs to bootstrap itself, so every future MCP client (Cursor, Claude Desktop, Cowork, custom integrations) Just Works without bespoke per-client header injection.\n\n**Enable in config:**\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: [\"oauthProvider\"],\n}),\n```\n\nThe compiler auto-includes Better Auth's `jwt` plugin alongside `oauthProvider` — `@better-auth/oauth-provider` delegates access-token signing to it, and schema generation fails without it.\n\n**Custom configuration** (object form):\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: {\n oauthProvider: {\n consentPage: \"/consent\", // path on ACCOUNT_URL — default\n loginPage: \"/login\", // path on ACCOUNT_URL — default\n allowDynamicClientRegistration: true, // default\n allowUnauthenticatedClientRegistration: true, // default — MCP needs this\n validAudiences: [\"https://api.example.com\"], // optional — defaults to BETTER_AUTH_URL\n scopes: [\"openid\", \"profile\", \"email\", \"offline_access\"],\n },\n },\n}),\n```\n\n**Endpoints:**\n\nDiscovery (public, no auth):\n- `GET /.well-known/oauth-authorization-server` — RFC 8414 metadata\n- `GET /.well-known/oauth-protected-resource` — MCP resource metadata\n- `GET /.well-known/openid-configuration` — OIDC discovery\n\nAuthorization flow:\n- `POST /oauth2/register` — RFC 7591 dynamic client registration\n- `POST /oauth2/authorize` — start auth code flow\n- `POST /oauth2/token` — exchange code or refresh for access token\n- `POST /oauth2/consent` — accept/deny (called by the consent page)\n- `POST /oauth2/introspect` — RFC 7662 token validity check\n- `POST /oauth2/revoke` — RFC 7009 token revocation\n- `GET /oauth2/userinfo` — OIDC user info (requires `openid` scope)\n\nClient management (authenticated):\n- `GET /oauth2/get-clients`, `GET /oauth2/get-client?client_id=`, `GET /oauth2/public-client?client_id=`\n- `POST /oauth2/create-client`, `POST /oauth2/update-client`, `POST /oauth2/delete-client`\n- `POST /oauth2/client/rotate-secret`\n\nConsent management:\n- `GET /oauth2/get-consents`, `GET /oauth2/get-consent?id=`\n- `POST /oauth2/update-consent`, `POST /oauth2/delete-consent`\n\n**Account SPA wiring:**\n\nThe compiled Account SPA already serves `/consent`. When `oauthProvider` is enabled, Better Auth redirects unauthenticated users to `${ACCOUNT_URL}/login?redirect=...` and authenticated users straight to `${ACCOUNT_URL}/consent?client_id=...&scope=...&oauth_query=...`. The bundled consent screen reads those params, fetches client metadata via `/oauth2/public-client`, and POSTs back to `/oauth2/consent`.\n\n**Verifying tokens in your own Workers / route handlers:**\n\nIssued tokens are JWTs by default — verify them locally without a DB hit:\n\n```ts\n\nconst serverClient = createAuthClient({\n plugins: [oauthProviderResourceClient(auth)],\n});\n\nconst token = req.headers.get(\"authorization\")?.replace(\"Bearer \", \"\");\nconst payload = await serverClient.verifyAccessToken(token, {\n verifyOptions: { issuer: env.BETTER_AUTH_URL, audience: env.BETTER_AUTH_URL },\n});\n// payload.sub → userId, payload.scope → granted scopes\n```\n\n**Why this and not the deprecated `mcp` plugin?**\n\nBetter Auth's older `better-auth/plugins/mcp` is being deprecated in favour of `@better-auth/oauth-provider`. The new package is a full OAuth 2.1 server (the MCP plugin only exposed a subset), supports dynamic registration that MCP clients now require, and lets you scope/revoke per-client.\n\nKeep `apiKey` enabled alongside it — server-to-server flows (cron, scripts) want a static key; OAuth is for interactive clients.\n\n### Custom plugins (escape hatch)\n\nThe named plugins above cover the curated set Quickback ships first-class wiring for. For anything else — third-party packages (`@better-auth-kit/audit`, …), Better Auth built-ins outside the registry, or project-local plugins — use `customPlugins`.\n\n```ts\nauth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: { passkey: true, organization: true },\n customPlugins: [\n // (1) Project-local plugin file at quickback/plugins/long-session.ts\n { from: \"./plugins/long-session\", export: \"longSessionPlugin\" },\n // (2) Third-party npm package\n {\n from: \"@better-auth-kit/audit\",\n export: \"auditPlugin\",\n args: { events: [\"sign-in\"] },\n dependencies: { \"@better-auth-kit/audit\": \"^1.0.0\" },\n },\n ],\n}),\n```\n\nEach entry in `customPlugins` is an explicit import descriptor. The compiler runs each through Zod, then emits an `import { <export> } from \"<from>\"` line in the generated `src/lib/auth.ts` and appends the call (or bare symbol) to the `plugins: [...]` array — after the named plugins, in declared order.\n\n#### `from`\n\n- **Relative path** (must start with `./` or `../`, must resolve under `./plugins/`): refers to a file you author in `quickback/plugins/`. The CLI auto-discovers `quickback/plugins/**/*.ts` and ships matching files; the compiler copies the source into the generated output at `src/plugins/<name>.ts` and rewrites the emitted import path. Files in `quickback/plugins/` that aren't referenced by any descriptor are uploaded but ignored — the compiler picks only what's needed.\n- **Bare specifier** (any value not starting with `./` or `../`): treated as an npm import, emitted verbatim. Combine with `dependencies` so the package lands in the generated `package.json`.\n\n#### `export`\n\nThe named export to import. Must be a valid JS identifier (e.g. `longSessionPlugin`, `auditPlugin`). Use the symbol's source name from the file or package — Quickback emits the import as-is.\n\n#### `args` (optional)\n\n- **Omitted** → emits the symbol uncalled (`plugins: [..., longSessionPlugin]`). Use this when your export is already a `BetterAuthPlugin` instance.\n- **Provided** → emits a factory call with JSON-serialized args (`plugins: [..., auditPlugin({\"events\":[\"sign-in\"]})]`). The value must be JSON-serializable; functions and other non-serializable values fail at compile time. (The user config crosses an HTTP boundary as JSON, so this constraint exists by construction.)\n\n#### `dependencies` (optional)\n\n`Record<string, string>` of npm packages and version specs. Merged into the generated `package.json` alongside the named-plugin deps. Only meaningful for bare-specifier `from` — relative-path entries don't need to declare anything.\n\n#### Project-local plugin shape\n\nA plugin file in `quickback/plugins/` is plain Better Auth — the compiler doesn't transform it. Author it like any other BA plugin and let TypeScript check it against the `BetterAuthPlugin` type:\n\n```ts\n// quickback/plugins/long-session.ts\n\nexport const longSessionPlugin = {\n id: \"long-session\",\n databaseHooks: {\n session: {\n create: {\n before: async (session) => ({\n data: {\n ...session,\n // 5-year session for an event-app use case\n expiresAt: new Date(Date.now() + 5 * 365 * 24 * 60 * 60 * 1000),\n },\n }),\n },\n },\n },\n} satisfies BetterAuthPlugin;\n```\n\n#### Out of scope\n\n- **No schema generation.** If your plugin needs database tables, declare them as a Quickback feature — the compiler does not run schema introspection on custom plugins.\n- **No conditional inclusion.** Every entry in `customPlugins` is always emitted. Gate environment-specific plugins inside the plugin file itself.\n- **No name collision check against the named registry.** Duplicate registration is a Better Auth runtime concern, not a compile-time one — don't reach for `customPlugins` to override a named plugin's options; use the object form on `plugins` instead.\n\n## Where This Runs\n\nAll Better Auth plugin routes are served under your auth base path:\n\n```\n/auth/v1/*\n```"
|
|
326
|
+
"content": "Quickback ships with a curated set of Better Auth plugins and helper wiring so your auth stack is production-ready by default. Enable these in `quickback.config.ts` under `providers.auth`.\n\n## Available Plugins\n\n### Email OTP (with AWS SES)\n\nQuickback wires the Better Auth Email OTP flow to AWS SES. When `emailOtp` is enabled, the compiler emits the SES plugin and combo-auth email flow (magic link + OTP).\n\n**Enable in config:**\n\n```ts\n\nexport default defineConfig({\n name: \"quickback-api\",\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\", {\n vars: {\n AWS_SES_REGION: \"us-east-2\",\n EMAIL_FROM: \"noreply@yourdomain.com\",\n EMAIL_FROM_NAME: \"Your App | Account Services\",\n APP_NAME: \"Your App\",\n APP_URL: \"https://account.yourdomain.com\",\n BETTER_AUTH_URL: \"https://api.yourdomain.com\",\n },\n }),\n auth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: [\"emailOtp\"],\n }),\n },\n});\n```\n\n**Endpoints:**\n- `POST /auth/v1/email-otp/send-verification-otp`\n- `POST /auth/v1/email-otp/verify-otp`\n\n**Email readiness check:**\n\nUse this to show UI warnings when SES isn't configured.\n\n- `GET /api/v1/system/email-status`\n- Response: `{ \"emailConfigured\": true|false }`\n\n### Upgrade Anonymous\n\nAdds a first-class endpoint to convert an anonymous user into a full user. This flips `isAnonymous` to `false` and refreshes the session cache immediately.\n\n**Enable in config:**\n\n```ts\nauth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: [\"anonymous\", \"upgradeAnonymous\"],\n}),\n```\n\n**Endpoint:**\n- `POST /auth/v1/upgrade-anonymous`\n\n**Note:** If you send `Content-Type: application/json`, include a body (an empty `{}` is fine). This avoids request parsing errors in some clients.\n\n### SMS OTP (with AWS SNS)\n\nWhen `phoneNumber` is enabled, the compiler wires Better Auth's built-in `phoneNumber` plugin to AWS SNS for SMS delivery via [`@quickback-dev/better-auth-aws-sns`](/stack/auth/plugins/aws-sns). The plugin adds `phoneNumber` / `phoneNumberVerified` columns to the user table, handles OTP generation + storage + verify-attempt limits, and exposes endpoints for phone-only sign-in, phone+password sign-in, and password reset via SMS.\n\n**Enable in config:**\n\n```ts\nexport default defineConfig({\n name: \"my-app\",\n sms: {\n provider: \"aws-sns\",\n region: \"us-east-1\",\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\", {\n plugins: { phoneNumber: true },\n }),\n },\n});\n```\n\n**Endpoints (managed by Better Auth):**\n- `POST /auth/v1/phone-number/send-otp`\n- `POST /auth/v1/phone-number/verify`\n- `POST /auth/v1/sign-in/phone-number`\n- `POST /auth/v1/phone-number/request-password-reset`\n- `POST /auth/v1/phone-number/reset-password`\n\n**Why use SMS:** corporate email gateways frequently break transactional auth emails (link rewriting, click-tracking, MITM scanners). SMS is the most reliable channel for a six-digit code that has to land in under a minute. See the [AWS SNS plugin page](/stack/auth/plugins/aws-sns) for IAM, 10DLC registration, and sender-ID details.\n\n### AWS SES Plugin\n\nThis is a Quickback-provided Better Auth plugin for Email OTP and other transactional emails. It handles SES signing and delivery over the Web Crypto API so it runs in Cloudflare Workers without the AWS SDK. It is wired up only when you opt in via `email.provider: 'aws-ses'` — the default transport is Cloudflare Email Sending (`send_email` binding).\n\nRequired vars (only when `email.provider: 'aws-ses'` is set; use Wrangler secrets for credentials):\n- `AWS_ACCESS_KEY_ID` (secret)\n- `AWS_SECRET_ACCESS_KEY` (secret)\n- `AWS_SES_REGION`\n- `EMAIL_FROM`\n\nOptional vars:\n- `EMAIL_FROM_NAME`\n- `EMAIL_REPLY_TO` - Reply-to address for emails (defaults to `EMAIL_FROM`)\n- `APP_NAME`\n- `APP_URL`\n- `BETTER_AUTH_URL`\n\n### Magic Links\n\nMagic links provide passwordless authentication by sending a unique login link to the user's email. When clicked, the link authenticates the user without requiring a password.\n\n**Enable in config:**\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: [\"magicLink\"],\n}),\n```\n\n**Endpoints:**\n- `POST /auth/v1/magic-link/send` - Send magic link email\n- `GET /auth/v1/magic-link/verify` - Verify magic link token\n\n**Email customization:**\n\nMagic link emails use the same AWS SES configuration as Email OTP. Customize the email template via environment variables:\n\n- `APP_NAME` - Application name in email subject\n- `APP_URL` - Base URL for magic link redirect\n- `EMAIL_FROM` - Sender email address\n- `EMAIL_FROM_NAME` - Sender display name\n\n**Frontend integration:**\n\n```ts\n// Request magic link\nawait fetch('/auth/v1/magic-link/send', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email: 'user@yourdomain.com' })\n});\n\n// User clicks link in email, which redirects to your app\n// The token is verified automatically via the callback URL\n```\n\n### Passkeys\n\nPasskeys provide passwordless authentication using WebAuthn/FIDO2. Users authenticate with biometrics (fingerprint, face) or device PIN instead of passwords.\n\n**Enable in config:**\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: [\"passkey\"],\n}),\n```\n\n**Required environment variable:**\n- `ACCOUNT_URL` - Your account/frontend URL (used as the relying party origin for WebAuthn)\n\n**Endpoints:**\n- `POST /auth/v1/passkey/register/options` - Get registration challenge\n- `POST /auth/v1/passkey/register/verify` - Complete registration\n- `POST /auth/v1/passkey/authenticate/options` - Get authentication challenge\n- `POST /auth/v1/passkey/authenticate/verify` - Complete authentication\n- `GET /auth/v1/passkey/list-user-passkeys` - List user's registered passkeys\n- `POST /auth/v1/passkey/delete-passkey` - Delete a registered passkey\n\n**Browser support:**\n\nPasskeys are supported in all modern browsers:\n- Chrome 67+\n- Safari 14+\n- Firefox 60+\n- Edge 79+\n\n**Registration flow:**\n\n```ts\n// 1. Get registration options\nconst optionsRes = await fetch('/auth/v1/passkey/register/options', {\n method: 'POST',\n credentials: 'include'\n});\nconst options = await optionsRes.json();\n\n// 2. Create credential using WebAuthn API\nconst credential = await navigator.credentials.create({\n publicKey: options\n});\n\n// 3. Send credential to server\nawait fetch('/auth/v1/passkey/register/verify', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n credentials: 'include',\n body: JSON.stringify(credential)\n});\n```\n\n**Authentication flow:**\n\n```ts\n// 1. Get authentication options\nconst optionsRes = await fetch('/auth/v1/passkey/authenticate/options', {\n method: 'POST'\n});\nconst options = await optionsRes.json();\n\n// 2. Get credential using WebAuthn API\nconst credential = await navigator.credentials.get({\n publicKey: options\n});\n\n// 3. Verify credential\nawait fetch('/auth/v1/passkey/authenticate/verify', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n credentials: 'include',\n body: JSON.stringify(credential)\n});\n```\n\n### JWT Plugin\n\nBetter Auth's JWT plugin adds asymmetric-signed tokens and a JWKS endpoint for external services that need to verify user identity without sharing a shared secret.\n\n**Enable in config:**\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: [\"jwt\"],\n}),\n```\n\n**Endpoints:**\n- `GET /auth/v1/jwks` — public keys for verifying BA-issued tokens\n- `POST /auth/v1/token` — mint an asymmetric-signed JWT from the current session\n\n**When to enable:** you have external services (non-Quickback workers, third-party integrations) that need to verify a user's identity via JWKS without holding `BETTER_AUTH_SECRET`. The BA-issued tokens won't carry Quickback's `orgId`/`role` claims, so they're for identity, not API access.\n\n### API Keys\n\nStatic, long-lived credentials for cron jobs, scripts, and machine-to-machine integrations. Better Auth's `apiKey` plugin is auto-included when you enable the organizations feature, so no explicit config is required for the standard B2B SaaS shape.\n\n**Authenticating requests:**\n\nPass the key as the `x-api-key` header (preferred) or as an `?api_key=` / `?key=` query parameter:\n\n```bash\n# Header form (preferred — keys don't leak into access logs or Referer)\ncurl -H \"x-api-key: ${KEY}\" https://api.example.com/v1/jobs\n\n# Query-param form (for clients that can't inject custom headers,\n# e.g., claude.ai's MCP connector)\ncurl \"https://api.example.com/v1/jobs?api_key=${KEY}\"\n```\n\nThe header takes precedence when both are present. The query-param form lands in nginx / Cloudflare access logs and `Referer` headers when the page navigates away — prefer headers whenever the client supports them.\n\n**Endpoints (managed by Better Auth):**\n- `POST /auth/v1/api-key/create` — issue a new key (returns the secret once; store it)\n- `GET /auth/v1/api-key/list` — list keys for the current user\n- `POST /auth/v1/api-key/delete` — revoke a key\n\nKeys can carry organization context via `metadata.organizationId` — when set, the auth middleware looks up the user's role in that org and populates `ctx.roles` accordingly, so a single key inherits the same firewall + access scope as the user who created it.\n\n### OAuth Provider (MCP-ready)\n\nTurns your Quickback worker into a standards-compliant OAuth 2.1 + OIDC authorization server. The plugin ships RFC 7591 dynamic client registration plus the well-known discovery documents an MCP client needs to bootstrap itself, so every future MCP client (Cursor, Claude Desktop, Cowork, custom integrations) Just Works without bespoke per-client header injection.\n\n**Enable in config:**\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: [\"oauthProvider\"],\n}),\n```\n\nThe compiler auto-includes Better Auth's `jwt` plugin alongside `oauthProvider` — `@better-auth/oauth-provider` delegates access-token signing to it, and schema generation fails without it.\n\n**Custom configuration** (object form):\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: {\n oauthProvider: {\n consentPage: \"/consent\", // path on ACCOUNT_URL — default\n loginPage: \"/login\", // path on ACCOUNT_URL — default\n allowDynamicClientRegistration: true, // default\n allowUnauthenticatedClientRegistration: true, // default — MCP needs this\n validAudiences: [\"https://api.example.com\"], // optional — defaults to BETTER_AUTH_URL\n scopes: [\"openid\", \"profile\", \"email\", \"offline_access\"],\n },\n },\n}),\n```\n\n**Endpoints:**\n\nDiscovery (public, no auth):\n- `GET /.well-known/oauth-authorization-server` — RFC 8414 metadata\n- `GET /.well-known/oauth-protected-resource` — MCP resource metadata\n- `GET /.well-known/openid-configuration` — OIDC discovery\n\nAuthorization flow:\n- `POST /oauth2/register` — RFC 7591 dynamic client registration\n- `POST /oauth2/authorize` — start auth code flow\n- `POST /oauth2/token` — exchange code or refresh for access token\n- `POST /oauth2/consent` — accept/deny (called by the consent page)\n- `POST /oauth2/introspect` — RFC 7662 token validity check\n- `POST /oauth2/revoke` — RFC 7009 token revocation\n- `GET /oauth2/userinfo` — OIDC user info (requires `openid` scope)\n\nClient management (authenticated):\n- `GET /oauth2/get-clients`, `GET /oauth2/get-client?client_id=`, `GET /oauth2/public-client?client_id=`\n- `POST /oauth2/create-client`, `POST /oauth2/update-client`, `POST /oauth2/delete-client`\n- `POST /oauth2/client/rotate-secret`\n\nConsent management:\n- `GET /oauth2/get-consents`, `GET /oauth2/get-consent?id=`\n- `POST /oauth2/update-consent`, `POST /oauth2/delete-consent`\n\n**Account SPA wiring:**\n\nThe compiled Account SPA already serves `/consent`. When `oauthProvider` is enabled, Better Auth redirects unauthenticated users to `${ACCOUNT_URL}/login?redirect=...` and authenticated users straight to `${ACCOUNT_URL}/consent?client_id=...&scope=...&oauth_query=...`. The bundled consent screen reads those params, fetches client metadata via `/oauth2/public-client`, and POSTs back to `/oauth2/consent`.\n\n**Verifying tokens in your own Workers / route handlers:**\n\nIssued tokens are JWTs by default — verify them locally without a DB hit:\n\n```ts\n\nconst serverClient = createAuthClient({\n plugins: [oauthProviderResourceClient(auth)],\n});\n\nconst token = req.headers.get(\"authorization\")?.replace(\"Bearer \", \"\");\nconst payload = await serverClient.verifyAccessToken(token, {\n verifyOptions: { issuer: env.BETTER_AUTH_URL, audience: env.BETTER_AUTH_URL },\n});\n// payload.sub → userId, payload.scope → granted scopes\n```\n\n**Why this and not the deprecated `mcp` plugin?**\n\nBetter Auth's older `better-auth/plugins/mcp` is being deprecated in favour of `@better-auth/oauth-provider`. The new package is a full OAuth 2.1 server (the MCP plugin only exposed a subset), supports dynamic registration that MCP clients now require, and lets you scope/revoke per-client.\n\nKeep `apiKey` enabled alongside it — server-to-server flows (cron, scripts) want a static key; OAuth is for interactive clients.\n\n### Custom plugins (escape hatch)\n\nThe named plugins above cover the curated set Quickback ships first-class wiring for. For anything else — third-party packages (`@better-auth-kit/audit`, …), Better Auth built-ins outside the registry, or project-local plugins — use `customPlugins`.\n\n```ts\nauth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: { passkey: true, organization: true },\n customPlugins: [\n // (1) Project-local plugin file at quickback/plugins/long-session.ts\n { from: \"./plugins/long-session\", export: \"longSessionPlugin\" },\n // (2) Third-party npm package\n {\n from: \"@better-auth-kit/audit\",\n export: \"auditPlugin\",\n args: { events: [\"sign-in\"] },\n dependencies: { \"@better-auth-kit/audit\": \"^1.0.0\" },\n },\n ],\n}),\n```\n\nEach entry in `customPlugins` is an explicit import descriptor. The compiler runs each through Zod, then emits an `import { <export> } from \"<from>\"` line in the generated `src/lib/auth.ts` and appends the call (or bare symbol) to the `plugins: [...]` array — after the named plugins, in declared order.\n\n#### `from`\n\n- **Relative path** (must start with `./` or `../`, must resolve under `./plugins/`): refers to a file you author in `quickback/plugins/`. The CLI auto-discovers `quickback/plugins/**/*.ts` and ships matching files; the compiler copies the source into the generated output at `src/plugins/<name>.ts` and rewrites the emitted import path. Files in `quickback/plugins/` that aren't referenced by any descriptor are uploaded but ignored — the compiler picks only what's needed.\n- **Bare specifier** (any value not starting with `./` or `../`): treated as an npm import, emitted verbatim. Combine with `dependencies` so the package lands in the generated `package.json`.\n\n#### `export`\n\nThe named export to import. Must be a valid JS identifier (e.g. `longSessionPlugin`, `auditPlugin`). Use the symbol's source name from the file or package — Quickback emits the import as-is.\n\n#### `args` (optional)\n\n- **Omitted** → emits the symbol uncalled (`plugins: [..., longSessionPlugin]`). Use this when your export is already a `BetterAuthPlugin` instance.\n- **Provided** → emits a factory call with JSON-serialized args (`plugins: [..., auditPlugin({\"events\":[\"sign-in\"]})]`). The value must be JSON-serializable; functions and other non-serializable values fail at compile time. (The user config crosses an HTTP boundary as JSON, so this constraint exists by construction.)\n\n#### `dependencies` (optional)\n\n`Record<string, string>` of npm packages and version specs. Merged into the generated `package.json` alongside the named-plugin deps. Only meaningful for bare-specifier `from` — relative-path entries don't need to declare anything.\n\n#### Project-local plugin shape\n\nA plugin file in `quickback/plugins/` is plain Better Auth — the compiler doesn't transform it. Author it like any other BA plugin and let TypeScript check it against the `BetterAuthPlugin` type:\n\n```ts\n// quickback/plugins/long-session.ts\n\nexport const longSessionPlugin = {\n id: \"long-session\",\n databaseHooks: {\n session: {\n create: {\n before: async (session) => ({\n data: {\n ...session,\n // 5-year session for an event-app use case\n expiresAt: new Date(Date.now() + 5 * 365 * 24 * 60 * 60 * 1000),\n },\n }),\n },\n },\n },\n} satisfies BetterAuthPlugin;\n```\n\n#### Out of scope\n\n- **No schema generation.** If your plugin needs database tables, declare them as a Quickback feature — the compiler does not run schema introspection on custom plugins.\n- **No conditional inclusion.** Every entry in `customPlugins` is always emitted. Gate environment-specific plugins inside the plugin file itself.\n- **No name collision check against the named registry.** Duplicate registration is a Better Auth runtime concern, not a compile-time one — don't reach for `customPlugins` to override a named plugin's options; use the object form on `plugins` instead.\n\n## Where This Runs\n\nAll Better Auth plugin routes are served under your auth base path:\n\n```\n/auth/v1/*\n```"
|
|
323
327
|
},
|
|
324
328
|
"stack/auth/plugins/upgrade-anonymous": {
|
|
325
329
|
"title": "Upgrade Anonymous Plugin",
|
|
@@ -537,6 +541,7 @@ export const TOPIC_LIST = [
|
|
|
537
541
|
"stack/auth/jwt-optimization",
|
|
538
542
|
"stack/auth/plugins/agent-auth",
|
|
539
543
|
"stack/auth/plugins/aws-ses",
|
|
544
|
+
"stack/auth/plugins/aws-sns",
|
|
540
545
|
"stack/auth/plugins/combo-auth",
|
|
541
546
|
"stack/auth/plugins",
|
|
542
547
|
"stack/auth/plugins/upgrade-anonymous",
|