@quickback-dev/cli 0.40.0 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/dist/commands/claude.d.ts.map +1 -1
  2. package/dist/commands/claude.js +8 -0
  3. package/dist/commands/claude.js.map +1 -1
  4. package/dist/commands/compile.d.ts.map +1 -1
  5. package/dist/commands/compile.js +13 -2
  6. package/dist/commands/compile.js.map +1 -1
  7. package/dist/commands/compile.test.js +26 -21
  8. package/dist/commands/compile.test.js.map +1 -1
  9. package/dist/commands/create.js +6 -9
  10. package/dist/commands/create.js.map +1 -1
  11. package/dist/commands/login.d.ts.map +1 -1
  12. package/dist/commands/login.js +0 -9
  13. package/dist/commands/login.js.map +1 -1
  14. package/dist/commands/start.d.ts.map +1 -1
  15. package/dist/commands/start.js +6 -7
  16. package/dist/commands/start.js.map +1 -1
  17. package/dist/commands/whoami.d.ts.map +1 -1
  18. package/dist/commands/whoami.js +0 -4
  19. package/dist/commands/whoami.js.map +1 -1
  20. package/dist/docs/content.d.ts.map +1 -1
  21. package/dist/docs/content.js +23 -33
  22. package/dist/docs/content.js.map +1 -1
  23. package/dist/index.js +1 -1
  24. package/dist/lib/api-client.d.ts +0 -12
  25. package/dist/lib/api-client.d.ts.map +1 -1
  26. package/dist/lib/api-client.js +0 -10
  27. package/dist/lib/api-client.js.map +1 -1
  28. package/dist/lib/api-client.test.js +13 -8
  29. package/dist/lib/api-client.test.js.map +1 -1
  30. package/dist/lib/auth.d.ts +0 -1
  31. package/dist/lib/auth.d.ts.map +1 -1
  32. package/dist/lib/auth.js.map +1 -1
  33. package/dist/lib/compiler-stubs.d.ts +12 -0
  34. package/dist/lib/compiler-stubs.d.ts.map +1 -1
  35. package/dist/lib/compiler-stubs.js +18 -0
  36. package/dist/lib/compiler-stubs.js.map +1 -1
  37. package/dist/lib/file-loader.d.ts +14 -0
  38. package/dist/lib/file-loader.d.ts.map +1 -1
  39. package/dist/lib/file-loader.js +63 -9
  40. package/dist/lib/file-loader.js.map +1 -1
  41. package/dist/skill/SKILL.md +76 -6
  42. package/dist/skill/docs/changelog.md +253 -0
  43. package/dist/skill/docs/compiler/cloud-compiler/authentication.md +1 -2
  44. package/dist/skill/docs/compiler/cloud-compiler/cli.md +7 -8
  45. package/dist/skill/docs/compiler/config/agents.md +49 -1
  46. package/dist/skill/docs/compiler/config/auth.md +20 -5
  47. package/dist/skill/docs/compiler/config/security.md +46 -0
  48. package/dist/skill/docs/compiler/definitions/access.md +1 -1
  49. package/dist/skill/docs/compiler/definitions/actions.md +46 -4
  50. package/dist/skill/docs/compiler/definitions/scopes.md +11 -3
  51. package/dist/skill/docs/compiler/getting-started/full-example.md +5 -3
  52. package/dist/skill/docs/compiler/getting-started/index.md +7 -7
  53. package/dist/skill/docs/compiler/getting-started/patterns.md +39 -5
  54. package/dist/skill/docs/compiler/getting-started/template-blog.md +65 -44
  55. package/dist/skill/docs/compiler/getting-started/template-cloudflare.md +4 -5
  56. package/dist/skill/docs/compiler/getting-started/template-empty.md +7 -1
  57. package/dist/skill/docs/compiler/getting-started/templates.md +6 -6
  58. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/openapi.md +23 -0
  59. package/dist/skill/docs/stack/account-ui/features/passwordless.md +4 -10
  60. package/dist/skill/docs/stack/account-ui/hooks.md +24 -1
  61. package/dist/skill/docs/stack/auth/plugins/aws-ses.md +0 -7
  62. package/dist/skill/docs/stack/auth/plugins/index.md +71 -28
  63. package/dist/skill/docs/stack/storage/r2.md +8 -6
  64. package/dist/skill/docs/stack/storage/using-r2.md +58 -33
  65. package/dist/templates/registry.d.ts +0 -12
  66. package/dist/templates/registry.d.ts.map +1 -1
  67. package/dist/templates/registry.js +0 -42
  68. package/dist/templates/registry.js.map +1 -1
  69. package/package.json +1 -1
  70. package/src/skill/SKILL.md +76 -6
  71. package/src/skill/docs/changelog.md +253 -0
  72. package/src/skill/docs/compiler/cloud-compiler/authentication.md +1 -2
  73. package/src/skill/docs/compiler/cloud-compiler/cli.md +7 -8
  74. package/src/skill/docs/compiler/config/agents.md +49 -1
  75. package/src/skill/docs/compiler/config/auth.md +20 -5
  76. package/src/skill/docs/compiler/config/security.md +46 -0
  77. package/src/skill/docs/compiler/definitions/access.md +1 -1
  78. package/src/skill/docs/compiler/definitions/actions.md +46 -4
  79. package/src/skill/docs/compiler/definitions/scopes.md +11 -3
  80. package/src/skill/docs/compiler/getting-started/full-example.md +5 -3
  81. package/src/skill/docs/compiler/getting-started/index.md +7 -7
  82. package/src/skill/docs/compiler/getting-started/patterns.md +39 -5
  83. package/src/skill/docs/compiler/getting-started/template-blog.md +65 -44
  84. package/src/skill/docs/compiler/getting-started/template-cloudflare.md +4 -5
  85. package/src/skill/docs/compiler/getting-started/template-empty.md +7 -1
  86. package/src/skill/docs/compiler/getting-started/templates.md +6 -6
  87. package/src/skill/docs/compiler/targets/hono-api/using-the-api/openapi.md +23 -0
  88. package/src/skill/docs/stack/account-ui/features/passwordless.md +4 -10
  89. package/src/skill/docs/stack/account-ui/hooks.md +24 -1
  90. package/src/skill/docs/stack/auth/plugins/aws-ses.md +0 -7
  91. package/src/skill/docs/stack/auth/plugins/index.md +71 -28
  92. package/src/skill/docs/stack/storage/r2.md +8 -6
  93. package/src/skill/docs/stack/storage/using-r2.md +58 -33
  94. package/dist/skill/docs/stack/auth/plugins/combo-auth.md +0 -74
  95. package/dist/skill/docs/stack/auth/plugins/upgrade-anonymous.md +0 -155
  96. package/src/skill/docs/stack/auth/plugins/combo-auth.md +0 -74
  97. package/src/skill/docs/stack/auth/plugins/upgrade-anonymous.md +0 -155
@@ -3,7 +3,7 @@
3
3
  export const DOCS = {
4
4
  "changelog": {
5
5
  "title": "Changelog",
6
- "content": "## v0.40.0 — June 2, 2026\n\nR2 file storage is now **presign-only by default**. Adding\n`defineFileStorage(\"cloudflare-r2\")` emits just the `ctx.storage` signer — no\nFILES_DB database, no `/storage/v1/*` endpoints, no files worker. You sign\npresigned URLs against a bucket and store references in your own table. The\nturnkey managed subsystem is still available, now behind `managed: true`.\n\nThis decouples the lightweight primitive from the heavyweight subsystem so you\ncan add uploads without standing up a metadata database you don't use.\n\n### Presign-only by default; managed is opt-in\n\n```ts\n// Presign-only (default) — ctx.storage against a bucket, nothing else\ndefineFileStorage(\"cloudflare-r2\", { bucketName: \"my-app-media\" })\n\n// Managed subsystem — FILES_DB + /storage/v1/* + files worker\ndefineFileStorage(\"cloudflare-r2\", { managed: true })\n```\n\n- New projects can omit `bucketName` — it defaults to `<project>-media`, so\n setup is one `wrangler r2 bucket create` plus the R2 API-token secrets.\n- Existing projects set `bucketName` to a bucket they already have. Presign-only\n emits **no** R2 bucket binding and **no** FILES_DB binding — nothing to\n provision, nothing to migrate.\n\n### Per-call bucket + custom secret names\n\n```ts\n// Sign against a different bucket than the configured default\nawait storage.signPutUrl(key, { bucket: \"my-app-public\", contentType });\n```\n\nIf your project already stores R2 credentials under different env-var names,\nmap them so the signer reads yours:\n\n```ts\ndefineFileStorage(\"cloudflare-r2\", {\n bucketName: \"my-app-media\",\n presign: { accountIdEnv: \"CF_ACCOUNT_ID\", accessKeyIdEnv: \"S3_KEY\", secretAccessKeyEnv: \"S3_SECRET\" },\n})\n```\n\n### Fixes\n\n- `maxFileSize` now accepts a human string (`\"100mb\"`, `\"5gb\"`) as well as a\n number of bytes — previously a string emitted invalid TypeScript.\n- Presign-only no longer emits a stray `FILES_DB` `[[d1_databases]]` block (with\n an invalid `database_id = \"local-files\"`) into `wrangler.toml`, which would\n have made `wrangler deploy` reject the worker.\n\n## v0.39.1 — June 2, 2026\n\nDeduplicate colliding OpenAPI `operationId`s. The auto-generated list id\n`list\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.46.0 — June 11, 2026\n\n### Breaking: \"no organization context\" responses unified on HTTP 403\n\nGenerated APIs used to answer the same semantic condition — *the caller has no\nactive organization context* — with two different statuses: `400 ORG_REQUIRED`\nfrom the collection list guard and the create/PUT/batch org validation, but\n`403 ACCESS_NO_ORG` from standalone actions and `403\nACCESS_TENANT_SCOPE_REQUIRED` from unsafe org-scoped actions. Clients and SDKs\nhad to special-case the split.\n\n**Breaking** — recompile + redeploy required; every \"no org context\" denial is\nnow **403**:\n\n- `GET /api/v1/<resource>` (and views) without an active org or\n `?organizationId=` → `403 ORG_REQUIRED` (was 400).\n- `POST /`, `PUT /:id`, `POST /batch`, `PUT /batch` without an active org →\n `403 ORG_REQUIRED` (was 400).\n- Standalone actions (`403 ACCESS_NO_ORG`) and unsafe org-scoped actions\n (`403 ACCESS_TENANT_SCOPE_REQUIRED`) were already 403 and are unchanged.\n\nError **codes are unchanged** — `ORG_REQUIRED`, `ACCESS_NO_ORG`, and\n`ACCESS_TENANT_SCOPE_REQUIRED` keep their identities, so clients that\ndiscriminate on `code` need no changes. Only clients that branch on the raw\n`400` status for these responses must update to `403`.\n\n### Breaking: root-mounted actions lose their nested alias URLs\n\nA standalone action whose declared `path:` lives outside its feature prefix\n(e.g. `path: \"/reports/orders\"` in the `orders` feature) mounts at the root:\n`/api/v1/reports/orders`. That root URL is the one the OpenAPI spec, the MCP\nsurface, and the operations manifest have always advertised — but the\ngenerated per-feature routes file *also* carried an undocumented, fully-gated\ncopy at the nested `/api/v1/<feature><path>` URL (e.g.\n`/api/v1/orders/reports/orders`).\n\n**Breaking** — the nested alias is no longer emitted. One URL per operation:\na root-mounted action exists only at its advertised `/api/v1<path>` mount.\nAnything calling the unadvertised nested URL gets a 404 after recompile +\nredeploy; switch to the documented root URL. Actions declared *under* the\nfeature prefix are untouched, and a feature whose standalone actions are all\nroot-mounted no longer emits an (empty) feature actions routes file.\n\n## v0.45.0 — June 9, 2026\n\n### `auth.jwt.revocationCheck: 'kv'` — sub-TTL JWT revocation\n\nThe JWT fast-path trusts signed claims for their full lifetime — that's what\nmakes it a fast-path. Until now the only revocation bounds were the TTL\n(plain claims) and the carry-forward cap (scope claims, v0.44.0). The\nlong-promised `'kv'` mode is now real on the **Cloudflare runtime**:\n\n```ts\nauth: { jwt: { revocationCheck: 'kv' } }\n```\n\n- **Per-principal revocation timestamps, not per-token denylists.** A\n revocation event writes \"everything for this principal minted before now is\n dead\" to the project's **existing `KV` binding** (keys prefixed `qbrev:`) —\n nothing extra to provision. Entries self-expire after the maximum token\n lifetime, so the store never accumulates.\n- **The bearer fast-path checks before trusting.** A verified token whose\n `iat` (or `sct`, for the relationship-scope claim) predates the stored\n timestamp is rejected and falls through to session auth, which re-checks\n membership and re-mints — an active legitimate session recovers\n transparently. Costs 2+ edge-cached KV reads per bearer verify; the\n explicit trade the opt-in buys.\n- **Written automatically where revocation actually happens:** org-member\n removal and role change (Better Auth `organizationHooks`), and\n UPDATE/DELETE of scope-conferring relationship rows — through the same\n audit-wrapper write chokepoint Live Views uses, plus the single DELETE\n route (which has the row in hand but no `.returning()`). Revoke-on-touch:\n a false positive just forces a cheap re-prove.\n- **User bans flip automatically.** The Better Auth admin plugin's ban lands\n as a user-row update, so a generated `databaseHooks.user.update.after` hook\n stamps the user-level revocation the moment `banned` flips — every\n outstanding JWT dies on its next use, and the cookie/session path already\n rejects banned sessions, completing the lockout. When outbound webhooks are\n configured, the same hook emits a `user.banned` event so subscribed\n endpoints are notified.\n- **App-code helpers** for everything else: `src/lib/jwt-revocation.ts`\n exports `revokeUserTokens` / `revokeMemberTokens` / `revokeScopeTokens`\n (e.g. call `revokeUserTokens` from a custom revoke-all flow).\n- **Fails open.** A KV outage degrades revocation to the TTL /\n carry-forward-cap bound — it never locks every bearer out.\n\nBun/Node + `'kv'` fails at compile time with a clear message (the store rides\nthe Cloudflare KV binding; those runtimes own immediate-revoke via the\ncookie/session path). Default remains `'none'`; without the flag the emitted\nmiddleware is byte-identical to v0.44.0.\n\n## v0.44.0 — June 9, 2026\n\n### Scope carry-forward is now bounded (revocation fix)\n\nThe auth middleware's rolling refresh re-signs a verified `scope` claim on\nevery authed call without re-probing the relationship — that's what lets a\nscoped session ride past the short JWT TTL with zero per-request DB cost. But\nunbounded, it defeated the revocation model the docs promised: a removed\nguest/staff who kept polling got a fresh TTL on every request, so \"removal\ntakes effect within one TTL\" only held for *idle* clients, and the refresh\nalso bypassed the ≤180s scope-token ceiling (it re-signed with the raw\n`auth.jwt.expiresIn`).\n\nScope tokens now carry a proof timestamp (`sct`), stamped exclusively by the\nproven mint sites (`POST /scope/v1/enter` and the namespace resolver, via the\nshared mint helper). The rolling refresh:\n\n- **refuses once the claim's proof is older than the carry-forward cap\n (15 minutes)** — past it, the token expires within one TTL and the client\n re-proves via `enter` or any minting namespace route, which won't re-mint a\n revoked role. Worst-case post-revocation window for an active client:\n **cap + one TTL** from the last real proof, instead of unbounded.\n- **carries `sct` forward verbatim** — the refresh can never restart the\n window without an actual relationship probe. Claims without `sct`\n (pre-0.44 tokens) fail closed and simply stop refreshing.\n- **signs through the same ≤180s ceiling as the mint sites** — an\n `auth.jwt.expiresIn` above the ceiling no longer leaks into scope-bearing\n tokens via the refresh path.\n\nNo client changes needed: tokens renew exactly as before inside the window,\nand re-entering is the existing flow. For tables where even the capped window\nis too wide, gate with a `via` arm (live relationship subquery per request)\ninstead of a bare `ctx.scope.<kind>` arm; immediate revocation\n(`auth.jwt.revocationCheck: 'kv'`) remains on the roadmap.\n\n## v0.43.0 — June 4, 2026\n\n### Better Auth 1.6\n\nGenerated projects are now pinned to Better Auth **1.6**. The `agents.mcp.requireAuth` work in 0.42.0 surfaced a long-standing version drift: the compiler emitted `better-auth: ^1.5.0`, but `@better-auth/oauth-provider` resolves a tree that requires `@better-auth/core ^1.6.14` and imports `@better-auth/core/utils/host` + `/redirect-uri` — subpaths that only exist in 1.6.x. The result was a `wrangler deploy` that failed at bundle time with `Could not resolve …` and never uploaded.\n\nThis release aligns the **entire** Better Auth dependency set to a coherent 1.6.9 floor so npm resolves one consistent tree:\n\n- `better-auth`, `@better-auth/drizzle-adapter`, `@better-auth/api-key`, `@better-auth/passkey`, `@better-auth/oauth-provider` → `^1.6.9` (generated projects, the baked Docker deps, and the bundled CMS/Account SPAs).\n- Added an explicit `kysely ^0.28.16` pin: Better Auth 1.6's migrator imports `DEFAULT_MIGRATION_TABLE` / `DEFAULT_MIGRATION_LOCK_TABLE` from kysely but doesn't *declare* kysely, so the Worker bundle needs it pinned directly.\n\nNo code migration was required — Quickback already uses `@better-auth/oauth-provider` (not the now-deprecated OIDC Provider plugin), and emits no `freshAge`/SAML usage affected by 1.6's behavioral changes. Verified end to end: a `requireAuth` project and a normal project both `npm install` a clean 1.6.14 tree and bundle with `wrangler deploy --dry-run` with zero resolution errors.\n\n### Larger migration histories no longer hit the upload ceiling\n\nLong-lived projects accumulate one full-schema drizzle snapshot per migration, and the whole cumulative meta payload (snapshots + journals + `.sql`, across both the auth and features dirs) is re-sent on **every** compile — even a no-schema-change one. Projects with deep migration histories were hitting the compiler's `existingFiles` size limit and failing to compile, with no schema drift and nothing to fix on their end.\n\nThe server-side ceilings are raised so this is no longer the binding constraint:\n\n- `existingFiles` payload: **4 MiB → 16 MiB**\n- total request body: **8 MiB → 32 MiB** (kept above the per-category limits so it doesn't trip first)\n\nThis is enforced entirely on the compiler, so no CLI upgrade is needed — the new headroom applies as soon as `compiler.quickback.dev` is on this release.\n\n### Custom response headers (`security.headers`)\n\nThe generated Worker emitted a fixed set of security headers (CSP, HSTS,\n`X-Content-Type-Options`, …) with no supported way to add your own — teams that\nwanted, say, an `X-Server-Version` build stamp on every response had to\npost-patch the generated middleware after each compile.\n\nNew `security.headers` sets arbitrary response headers natively. Values are\nstatic strings or templates interpolating per-deploy Worker env vars via the\n`{{env.VAR_NAME}}` token:\n\n```ts\nsecurity: {\n headers: {\n // Both vars must be set, or the header is omitted entirely.\n 'X-Server-Version': '{{env.SERVER_VERSION}}+{{env.SERVER_BUILD}}',\n 'X-Powered-By': 'Quickback',\n },\n}\n```\n\n- **Omit-if-unset** — a header that references env vars is emitted only when\n *every* referenced var is set (non-empty) at runtime. A Worker that forgot to\n inject the var emits no header, never `X-Server-Version: undefined`. Static\n headers are always emitted.\n- The value is read from `c.env` per request, so it picks up whatever Worker\n var is injected at deploy time — nothing is baked at compile time.\n- **Managed headers are rejected** — names owned by a dedicated `security` field\n (CSP, HSTS, `X-Frame-Options`, `Referrer-Policy`, …) error at compile so the\n two emitters can't race. Malformed `{{env…}}` tokens error too, rather than\n leaking literal braces into the wire header.\n\nSurvives a clean `quickback compile` with no post-processing. See\n[Security Headers → Custom response headers](/compiler/config/security#custom-response-headers).\n\n## v0.42.0 — June 4, 2026\n\n### Interactive OAuth for the generated MCP server\n\nMCP connectors (Claude, Cursor, …) could only connect to a generated `/mcp`\nendpoint **anonymously** — they never launched a sign-in flow, so auth-gated\ntools stayed invisible. The OAuth machinery was already present (Better Auth's\n`oauth-provider` ships `/oauth2/authorize`, `/token`, `/register` + PKCE under\n`/auth/v1`); the compiler just never let a connector discover or trigger it.\n\nNew `agents.mcp.requireAuth` makes the MCP surface authenticated-only:\n\n```ts\nagents: { mcp: { requireAuth: true } },\n```\n\nWhen enabled, the compiler:\n\n- **Challenges unauthenticated `/mcp`** with `401` + `WWW-Authenticate: Bearer\n resource_metadata=\"…\"` ([RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) §5.1) — the signal connectors use to start OAuth.\n- **Force-enables `oauthProvider` + `bearer`**, so `/oauth2/authorize`, `/token`,\n and `/register` ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591) dynamic client registration) exist with PKCE.\n- **Delegates `/.well-known/oauth-authorization-server`** to Better Auth's real\n metadata instead of a hand-rolled stub that advertised a non-existent\n authorization endpoint.\n- Adds the `<origin>/mcp` resource to `validAudiences`\n ([RFC 8707](https://datatracker.ietf.org/doc/html/rfc8707)) so the connector's access token isn't rejected.\n\nLogin and consent are served by your Account SPA, so users authenticate with\nwhatever methods you already enabled. Default is unchanged (anonymous public\ntools); set `requireAuth: true` for servers meant for authenticated users.\n\n## v0.40.2 — June 3, 2026\n\n### Passwordless plugins can no longer bypass the signup gate\n\nBetter Auth's `emailOtp` and `magicLink` plugins auto-create an account when a\ncode/link is verified for an unknown email — and that path is independent of\n`emailAndPassword.disableSignUp`. As a result, `account.auth.signup: false`\nclosed `POST /auth/v1/sign-up/email` but left OTP / magic-link verification as an\nopen back-door for account creation.\n\nThe compiler now emits each plugin's own `disableSignUp` flag, and new\nper-plugin options expose it directly:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: {\n emailOtp: { disableSignUp: true }, // OTP sign-in only; unknown emails rejected\n magicLink: { disableSignUp: true }, // same for magic links\n },\n}),\n```\n\nBoth default to following the global gate: setting `account.auth.signup: false`\n(→ `emailAndPassword.disableSignUp: true`) now also gates the OTP and magic-link\npaths automatically. Set `{ disableSignUp: false }` on a plugin explicitly to\nkeep its sign-up open while password sign-up stays closed.\n\n## v0.40.1 — June 2, 2026\n\n- The generated `wrangler.toml` and `Env` type now emit the `ASSETS` binding\n type for projects that mount SPAs (CMS / Account), so handler code that\n references `c.env.ASSETS` typechecks.\n- Compiler Docker builds preserve their layer cache across rebuilds, cutting\n local recompile time.\n\n## v0.40.0 — June 2, 2026\n\nR2 file storage is now **presign-only by default**. Adding\n`defineFileStorage(\"cloudflare-r2\")` emits just the `ctx.storage` signer — no\nFILES_DB database, no `/storage/v1/*` endpoints, no files worker. You sign\npresigned URLs against a bucket and store references in your own table. The\nturnkey managed subsystem is still available, now behind `managed: true`.\n\nThis decouples the lightweight primitive from the heavyweight subsystem so you\ncan add uploads without standing up a metadata database you don't use.\n\n### Presign-only by default; managed is opt-in\n\n```ts\n// Presign-only (default) — ctx.storage against a bucket, nothing else\ndefineFileStorage(\"cloudflare-r2\", { bucketName: \"my-app-media\" })\n\n// Managed subsystem — FILES_DB + /storage/v1/* + files worker\ndefineFileStorage(\"cloudflare-r2\", { managed: true })\n```\n\n- New projects can omit `bucketName` — it defaults to `<project>-media`, so\n setup is one `wrangler r2 bucket create` plus the R2 API-token secrets.\n- Existing projects set `bucketName` to a bucket they already have. Presign-only\n emits **no** R2 bucket binding and **no** FILES_DB binding — nothing to\n provision, nothing to migrate.\n\n### Per-call bucket + custom secret names\n\n```ts\n// Sign against a different bucket than the configured default\nawait storage.signPutUrl(key, { bucket: \"my-app-public\", contentType });\n```\n\nIf your project already stores R2 credentials under different env-var names,\nmap them so the signer reads yours:\n\n```ts\ndefineFileStorage(\"cloudflare-r2\", {\n bucketName: \"my-app-media\",\n presign: { accountIdEnv: \"CF_ACCOUNT_ID\", accessKeyIdEnv: \"S3_KEY\", secretAccessKeyEnv: \"S3_SECRET\" },\n})\n```\n\n### Fixes\n\n- `maxFileSize` now accepts a human string (`\"100mb\"`, `\"5gb\"`) as well as a\n number of bytes — previously a string emitted invalid TypeScript.\n- Presign-only no longer emits a stray `FILES_DB` `[[d1_databases]]` block (with\n an invalid `database_id = \"local-files\"`) into `wrangler.toml`, which would\n have made `wrangler deploy` reject the worker.\n\n## v0.39.1 — June 2, 2026\n\nDeduplicate colliding OpenAPI `operationId`s. The auto-generated list id\n`list\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",
@@ -11,11 +11,11 @@ export const DOCS = {
11
11
  },
12
12
  "compiler/cloud-compiler/authentication": {
13
13
  "title": "Authentication",
14
- "content": "The CLI supports two authentication methods: interactive login for development and API keys for CI/CD.\n\n## Interactive Login (Recommended)\n\nThe CLI uses [OAuth 2.0 Device Authorization](https://datatracker.ietf.org/doc/html/rfc8628) to authenticate:\n\n```bash\nquickback login\n```\n\nA code is displayed in your terminal. Approve it in your browser and you're authenticated. See the [CLI Reference](/compiler/cloud-compiler/cli#login) for the full flow.\n\nCredentials are stored at `~/.quickback/credentials.json` and include your session token, user info, and active organization.\n\n## API Key (CI/CD)\n\nFor non-interactive environments (CI/CD, scripts), use an API key:\n\n```bash\nQUICKBACK_API_KEY=your_api_key quickback compile\n```\n\nCreate API keys from your [Quickback account](https://account.quickback.dev/profile). Each key is scoped to your organization.\n\nThe API key takes precedence over stored credentials from `quickback login`.\n\n## How Tokens Are Validated\n\nThe compiler-cloud worker validates authentication by forwarding your token to the Quickback API's `/internal/validate` endpoint via a [Cloudflare service binding](https://developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/). This resolves both session tokens (from `quickback login`) and API keys (from `QUICKBACK_API_KEY`).\n\n## Credential Storage\n\nCredentials are stored at `~/.quickback/credentials.json`:\n\n```json\n{\n \"token\": \"...\",\n \"user\": {\n \"id\": \"...\",\n \"email\": \"paul@example.com\",\n \"name\": \"Paul Stenhouse\",\n \"tier\": \"free\"\n },\n \"expiresAt\": \"2026-02-16T01:42:21.519Z\",\n \"organization\": {\n \"id\": \"...\",\n \"name\": \"Acme\",\n \"slug\": \"acme\"\n }\n}\n```\n\nSessions expire after 7 days. Run `quickback login` again to re-authenticate.\n\n## Organizations\n\nAfter login, the CLI auto-selects your organization:\n- **One organization** — automatically set as active.\n- **Multiple organizations** — you're prompted to choose one.\n\nThe active organization is stored in your credentials and sent with compile requests, so the compiler knows which org context to use."
14
+ "content": "The CLI supports two authentication methods: interactive login for development and API keys for CI/CD.\n\n## Interactive Login (Recommended)\n\nThe CLI uses [OAuth 2.0 Device Authorization](https://datatracker.ietf.org/doc/html/rfc8628) to authenticate:\n\n```bash\nquickback login\n```\n\nA code is displayed in your terminal. Approve it in your browser and you're authenticated. See the [CLI Reference](/compiler/cloud-compiler/cli#login) for the full flow.\n\nCredentials are stored at `~/.quickback/credentials.json` and include your session token, user info, and active organization.\n\n## API Key (CI/CD)\n\nFor non-interactive environments (CI/CD, scripts), use an API key:\n\n```bash\nQUICKBACK_API_KEY=your_api_key quickback compile\n```\n\nCreate API keys from your [Quickback account](https://account.quickback.dev/profile). Each key is scoped to your organization.\n\nThe API key takes precedence over stored credentials from `quickback login`.\n\n## How Tokens Are Validated\n\nThe compiler-cloud worker validates authentication by forwarding your token to the Quickback API's `/internal/validate` endpoint via a [Cloudflare service binding](https://developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/). This resolves both session tokens (from `quickback login`) and API keys (from `QUICKBACK_API_KEY`).\n\n## Credential Storage\n\nCredentials are stored at `~/.quickback/credentials.json`:\n\n```json\n{\n \"token\": \"...\",\n \"user\": {\n \"id\": \"...\",\n \"email\": \"paul@example.com\",\n \"name\": \"Paul Stenhouse\"\n },\n \"expiresAt\": \"2026-02-16T01:42:21.519Z\",\n \"organization\": {\n \"id\": \"...\",\n \"name\": \"Acme\",\n \"slug\": \"acme\"\n }\n}\n```\n\nSessions expire after 7 days. Run `quickback login` again to re-authenticate.\n\n## Organizations\n\nAfter login, the CLI auto-selects your organization:\n- **One organization** — automatically set as active.\n- **Multiple organizations** — you're prompted to choose one.\n\nThe active organization is stored in your credentials and sent with compile requests, so the compiler knows which org context to use."
15
15
  },
16
16
  "compiler/cloud-compiler/cli": {
17
17
  "title": "CLI Reference",
18
- "content": "The Quickback CLI is the fastest way to create, compile, and manage your backend projects.\n\n## Installation\n\n```bash\n# One-shot via npx — recommended for first run\nnpx @quickback-dev/cli start\n\n# Or install globally for repeat use\nnpm install -g @quickback-dev/cli\n```\n\n## Commands\n\n### Start a Project (interactive)\n\n```bash\nquickback start\n```\n\nInteractive onboarding designed for new users. No flags required.\n\n- Prompts for a template (curated free-tier picker: `cloudflare`, `todos`, `blog`, `empty`)\n- Prompts for a project name (defaults to the current directory's name if empty)\n- Auto-detects whether to scaffold in-place or create a `./<name>/` subdirectory\n- Defers login until just before the compile step — cancel at the auth prompt and the scaffold stays on disk, ready for `quickback compile` later\n\n**Example:**\n```bash\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n```\n\n### Create a Project (scriptable)\n\n```bash\nquickback create <template> <name>\n```\n\n**Templates:**\n- `cloudflare` — Cloudflare Workers + D1 + Better Auth, bare scaffold (free)\n- `todos` — Working todos example with masking + actions + a named view (free)\n- `blog` — Single-tenant blog, PUBLIC reads, admin writes (free)\n- `empty` — Cloudflare scaffold, no example features (free)\n- `saas` — Full B2B SaaS: orgs, R2 file storage, webhooks, split databases, realtime (pro)\n\n**Example:**\n```bash\nquickback create todos my-app\n```\n\nThis scaffolds a complete project with:\n- `quickback.config.ts` — Project configuration\n- `quickback/features/` — Your table definitions\n- Example feature with full security configuration (for `todos` / `blog` / `saas`)\n\nSee the [Templates](/compiler/getting-started/templates) page for a deeper guide on choosing between them.\n\n### Compile Definitions\n\n```bash\nquickback compile\n```\n\nReads your definitions and generates:\n- Database migrations (Drizzle)\n- API route handlers (Hono)\n- TypeScript client SDK\n- OpenAPI specification\n\nRun this after making changes to your definitions.\n\n#### Generated `src/` is hermetic\n\nEvery file under `src/` carries a `Generated by quickback.dev` header and is owned by the compiler. Before each compile writes its output, the CLI:\n\n1. Snapshots the existing `src/` tree to `quickback/.archives/src-<ISO-timestamp>/` (a plain recursive copy — `cp -R` semantics, no compression).\n2. Wipes `src/` entirely.\n3. Writes the fresh manifest from the compiler.\n\nThis prevents stale output: removed features stop leaving orphan folders, deleted SPA assets with old content hashes get cleared, and `.DS_Store` files don't keep retired directories alive.\n\nThe most recent **3** archives are retained (older ones are pruned automatically). If a compile produces unexpected output, your last-known-good tree is sitting in `quickback/.archives/` ready to grep or copy back:\n\n```bash\nls quickback/.archives/\n# src-2026-04-27T16-31-02-014/\n# src-2026-04-27T16-29-44-882/\n# src-2026-04-27T16-12-19-301/\n```\n\nAs a safety net, the wipe is **skipped** when the manifest contains zero files for the target directory — that's almost always an upstream compile bug, and we'd rather keep your last working tree than overwrite it with nothing.\n\n### View Documentation\n\n```bash\nquickback docs # List available topics\nquickback docs <topic> # Show documentation for a topic\n```\n\n**Available topics:**\n- `firewall` - Data isolation layer\n- `access` - Role-based permissions\n- `guards` - Field protection\n- `masking` - PII redaction\n- `actions` - Custom business logic\n- `api` - CRUD endpoints reference\n- `config` - Configuration reference\n- `features` - Schema definitions\n\nDocumentation is bundled with the CLI and works offline.\n\n### Manage Claude Code Skill\n\n```bash\nquickback claude install # Interactive install\nquickback claude install --global # Install to ~/.claude/skills/\nquickback claude install --local # Install to ./quickback/.claude/\nquickback claude update # Update to latest version\nquickback claude remove # Remove installed skill\nquickback claude status # Check installation status\n```\n\nThe Quickback skill for Claude Code provides AI assistance for:\n- Creating resource definitions with proper security layers\n- Configuring Firewall, Access, Guards, and Masking\n- Debugging configuration issues\n- Understanding security patterns\n\n## Authentication\n\n### Login\n\n```bash\nquickback login\n```\n\nUses the [OAuth 2.0 Device Authorization Grant](https://datatracker.ietf.org/doc/html/rfc8628) (RFC 8628) to authenticate securely without exposing tokens in URLs.\n\n**How it works:**\n\n1. The CLI requests a one-time device code from the Quickback API.\n2. A code is displayed in your terminal (e.g., `AUL8-H93S`).\n3. Your browser opens to the Quickback account page where you approve the code.\n4. The CLI detects approval and exchanges it for a session token.\n5. If you belong to one organization, it's auto-selected. If you have multiple, you choose one.\n6. Credentials are stored locally.\n\n```\n$ quickback login\n\n🔐 Quickback Login\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n Your code: AUL8-H93S\n\n Visit: https://account.quickback.dev/cli/authorize\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n✓ Login successful!\nWelcome, Paul Stenhouse!\n\nUsing organization: Acme\n✓ Active organization: Acme\n```\n\nThis flow works in headless environments (SSH, containers, WSL) since it doesn't require a localhost callback.\n\n### Logout\n\n```bash\nquickback logout\n```\n\nClears stored credentials from `~/.quickback/credentials.json`.\n\n### Check Auth Status\n\n```bash\nquickback whoami\n```\n\nShows the currently authenticated user, organization, and token expiration.\n\n### Credential Storage\n\nCredentials are stored at `~/.quickback/credentials.json`:\n\n```json\n{\n \"token\": \"...\",\n \"user\": {\n \"id\": \"...\",\n \"email\": \"paul@example.com\",\n \"name\": \"Paul Stenhouse\",\n \"tier\": \"free\"\n },\n \"expiresAt\": \"2026-02-16T01:42:21.519Z\",\n \"organization\": {\n \"id\": \"...\",\n \"name\": \"Acme\",\n \"slug\": \"acme\"\n }\n}\n```\n\nSessions expire after 7 days. Run `quickback login` again to re-authenticate.\n\n### Organizations\n\nAfter login, the CLI auto-selects your organization:\n- **One organization** - automatically set as active.\n- **Multiple organizations** - you're prompted to choose one.\n\nThe active organization is stored in your credentials and sent with compile requests, so the compiler knows which org context to use.\n\n## Quick Start\n\n```bash\n# 1. Start a new project (interactive — picks template, scaffolds,\n# prompts for login only when needed)\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n\n# 2. Run locally\nnpm run dev\n```\n\nOr the scriptable form:\n\n```bash\n# 1. Create the project (scaffolds + compiles + installs)\nquickback create todos my-app # prompts for login on first compile\ncd my-app\n\n# 2. Run\nnpm run dev\n\n# 3. Recompile after editing definitions\nquickback compile\n```\n\n## Options\n\n| Flag | Description |\n|------|-------------|\n| `-v, --version` | Show version number |\n| `-h, --help` | Show help message |\n\n## Environment Variables\n\n| Variable | Description |\n|----------|-------------|\n| `QUICKBACK_API_KEY` | API key for authentication (alternative to `quickback login`) |\n| `QUICKBACK_API_URL` | Override compiler API URL |\n\n### API Key Authentication\n\nUse an API key instead of interactive login. Useful for CI/CD pipelines and automated workflows:\n\n```bash\n# Pass API key for a single command\nQUICKBACK_API_KEY=your_api_key quickback compile\n\n# Or export for the session\nexport QUICKBACK_API_KEY=your_api_key\nquickback compile\n```\n\nThe API key takes precedence over stored credentials from `quickback login`.\n\nYou can create API keys from your [Quickback account](https://account.quickback.dev/profile). Each key is scoped to your organization.\n\n### Custom Compiler URL\n\nPoint the CLI to a different compiler (local or custom):\n\n```bash\n# Use a local compiler\nQUICKBACK_API_URL=http://localhost:3020 quickback compile\n\n# Or export for the session\nexport QUICKBACK_API_URL=http://localhost:3020\nquickback compile\n```\n\nSee [Local Compiler](/compiler/cloud-compiler/local-compiler) for running the compiler locally with Docker.\n\n## Troubleshooting\n\n### \"Command not found: quickback\"\n\nMake sure the CLI is installed globally:\n```bash\nnpm install -g @quickback-dev/cli\n```\n\nOr use npx (no global install needed):\n```bash\nnpx @quickback-dev/cli start\n```\n\n### Compile errors\n\n1. Check your `quickback.config.ts` exists and is valid\n2. Ensure all tables in `quickback/features/` have valid exports\n3. Run `quickback compile` with `--verbose` for detailed output\n4. For rename-related Drizzle failures in CI/headless runs, configure `compiler.migrations.renames` in `quickback.config.ts`\n\n### Authentication issues\n\nClear credentials and re-authenticate:\n```bash\nquickback logout\nquickback login\n```\n\n### \"Could not load organizations\"\n\nThis can happen if your session token expired or if the API is temporarily unavailable. Re-login:\n```bash\nquickback logout\nquickback login\n```"
18
+ "content": "The Quickback CLI is the fastest way to create, compile, and manage your backend projects.\n\n## Installation\n\n```bash\n# One-shot via npx — recommended for first run\nnpx @quickback-dev/cli start\n\n# Or install globally for repeat use\nnpm install -g @quickback-dev/cli\n```\n\n## Commands\n\n### Start a Project (interactive)\n\n```bash\nquickback start\n```\n\nInteractive onboarding designed for new users. No flags required.\n\n- Prompts for a template (`cloudflare`, `todos`, `blog`, `empty`)\n- Prompts for a project name (defaults to the current directory's name if empty)\n- Auto-detects whether to scaffold in-place or create a `./<name>/` subdirectory\n- Defers login until just before the compile step — cancel at the auth prompt and the scaffold stays on disk, ready for `quickback compile` later\n\n**Example:**\n```bash\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n```\n\n### Create a Project (scriptable)\n\n```bash\nquickback create <template> <name>\n```\n\n**Templates:**\n- `cloudflare` — Cloudflare Workers + D1 + Better Auth, bare scaffold\n- `todos` — Working todos example with masking + actions + a named view\n- `blog` — Single-tenant blog, PUBLIC reads, admin writes\n- `empty` — Cloudflare scaffold, no example features\n- `saas` — Full B2B SaaS: orgs, R2 file storage, webhooks, split databases, realtime\n\n**Example:**\n```bash\nquickback create todos my-app\n```\n\nThis scaffolds a complete project with:\n- `quickback.config.ts` — Project configuration\n- `quickback/features/` — Your table definitions\n- Example feature with full security configuration (for `todos` / `blog` / `saas`)\n\nSee the [Templates](/compiler/getting-started/templates) page for a deeper guide on choosing between them.\n\n### Compile Definitions\n\n```bash\nquickback compile\n```\n\nReads your definitions and generates:\n- Database migrations (Drizzle)\n- API route handlers (Hono)\n- TypeScript client SDK\n- OpenAPI specification\n\nRun this after making changes to your definitions.\n\n#### Generated `src/` is hermetic\n\nEvery file under `src/` carries a `Generated by quickback.dev` header and is owned by the compiler. Before each compile writes its output, the CLI:\n\n1. Snapshots the existing `src/` tree to `quickback/.archives/src-<ISO-timestamp>/` (a plain recursive copy — `cp -R` semantics, no compression).\n2. Wipes `src/` entirely.\n3. Writes the fresh manifest from the compiler.\n\nThis prevents stale output: removed features stop leaving orphan folders, deleted SPA assets with old content hashes get cleared, and `.DS_Store` files don't keep retired directories alive.\n\nThe most recent **3** archives are retained (older ones are pruned automatically). If a compile produces unexpected output, your last-known-good tree is sitting in `quickback/.archives/` ready to grep or copy back:\n\n```bash\nls quickback/.archives/\n# src-2026-04-27T16-31-02-014/\n# src-2026-04-27T16-29-44-882/\n# src-2026-04-27T16-12-19-301/\n```\n\nAs a safety net, the wipe is **skipped** when the manifest contains zero files for the target directory — that's almost always an upstream compile bug, and we'd rather keep your last working tree than overwrite it with nothing.\n\n### View Documentation\n\n```bash\nquickback docs # List available topics\nquickback docs <topic> # Show documentation for a topic\n```\n\n**Available topics:**\n- `firewall` - Data isolation layer\n- `access` - Role-based permissions\n- `guards` - Field protection\n- `masking` - PII redaction\n- `actions` - Custom business logic\n- `api` - CRUD endpoints reference\n- `config` - Configuration reference\n- `features` - Schema definitions\n\nDocumentation is bundled with the CLI and works offline.\n\n### Manage Claude Code Skill\n\n```bash\nquickback claude install # Interactive install\nquickback claude install --global # Install to ~/.claude/skills/\nquickback claude install --local # Install to ./quickback/.claude/\nquickback claude update # Update to latest version\nquickback claude remove # Remove installed skill\nquickback claude status # Check installation status\n```\n\nThe Quickback skill for Claude Code provides AI assistance for:\n- Creating resource definitions with proper security layers\n- Configuring Firewall, Access, Guards, and Masking\n- Debugging configuration issues\n- Understanding security patterns\n\n## Authentication\n\n### Login\n\n```bash\nquickback login\n```\n\nUses the [OAuth 2.0 Device Authorization Grant](https://datatracker.ietf.org/doc/html/rfc8628) (RFC 8628) to authenticate securely without exposing tokens in URLs.\n\n**How it works:**\n\n1. The CLI requests a one-time device code from the Quickback API.\n2. A code is displayed in your terminal (e.g., `AUL8-H93S`).\n3. Your browser opens to the Quickback account page where you approve the code.\n4. The CLI detects approval and exchanges it for a session token.\n5. If you belong to one organization, it's auto-selected. If you have multiple, you choose one.\n6. Credentials are stored locally.\n\n```\n$ quickback login\n\n🔐 Quickback Login\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n Your code: AUL8-H93S\n\n Visit: https://account.quickback.dev/cli/authorize\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n✓ Login successful!\nWelcome, Paul Stenhouse!\n\nUsing organization: Acme\n✓ Active organization: Acme\n```\n\nThis flow works in headless environments (SSH, containers, WSL) since it doesn't require a localhost callback.\n\n### Logout\n\n```bash\nquickback logout\n```\n\nClears stored credentials from `~/.quickback/credentials.json`.\n\n### Check Auth Status\n\n```bash\nquickback whoami\n```\n\nShows the currently authenticated user, organization, and token expiration.\n\n### Credential Storage\n\nCredentials are stored at `~/.quickback/credentials.json`:\n\n```json\n{\n \"token\": \"...\",\n \"user\": {\n \"id\": \"...\",\n \"email\": \"paul@example.com\",\n \"name\": \"Paul Stenhouse\"\n },\n \"expiresAt\": \"2026-02-16T01:42:21.519Z\",\n \"organization\": {\n \"id\": \"...\",\n \"name\": \"Acme\",\n \"slug\": \"acme\"\n }\n}\n```\n\nSessions expire after 7 days. Run `quickback login` again to re-authenticate.\n\n### Organizations\n\nAfter login, the CLI auto-selects your organization:\n- **One organization** - automatically set as active.\n- **Multiple organizations** - you're prompted to choose one.\n\nThe active organization is stored in your credentials and sent with compile requests, so the compiler knows which org context to use.\n\n## Quick Start\n\n```bash\n# 1. Start a new project (interactive — picks template, scaffolds,\n# prompts for login only when needed)\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n\n# 2. Run locally\nnpm run dev\n```\n\nOr the scriptable form:\n\n```bash\n# 1. Create the project (scaffolds + compiles + installs)\nquickback create todos my-app # prompts for login on first compile\ncd my-app\n\n# 2. Run\nnpm run dev\n\n# 3. Recompile after editing definitions\nquickback compile\n```\n\n## Options\n\n| Flag | Description |\n|------|-------------|\n| `-v, --version` | Show version number |\n| `-h, --help` | Show help message |\n\n## Environment Variables\n\n| Variable | Description |\n|----------|-------------|\n| `QUICKBACK_API_KEY` | API key for authentication (alternative to `quickback login`) |\n| `QUICKBACK_API_URL` | Override compiler API URL |\n\n### API Key Authentication\n\nUse an API key instead of interactive login. Useful for CI/CD pipelines and automated workflows:\n\n```bash\n# Pass API key for a single command\nQUICKBACK_API_KEY=your_api_key quickback compile\n\n# Or export for the session\nexport QUICKBACK_API_KEY=your_api_key\nquickback compile\n```\n\nThe API key takes precedence over stored credentials from `quickback login`.\n\nYou can create API keys from your [Quickback account](https://account.quickback.dev/profile). Each key is scoped to your organization.\n\n### Custom Compiler URL\n\nPoint the CLI to a different compiler (local or custom):\n\n```bash\n# Use a local compiler\nQUICKBACK_API_URL=http://localhost:3020 quickback compile\n\n# Or export for the session\nexport QUICKBACK_API_URL=http://localhost:3020\nquickback compile\n```\n\nSee [Local Compiler](/compiler/cloud-compiler/local-compiler) for running the compiler locally with Docker.\n\n## Troubleshooting\n\n### \"Command not found: quickback\"\n\nMake sure the CLI is installed globally:\n```bash\nnpm install -g @quickback-dev/cli\n```\n\nOr use npx (no global install needed):\n```bash\nnpx @quickback-dev/cli start\n```\n\n### Compile errors\n\n1. Check your `quickback.config.ts` exists and is valid\n2. Ensure all tables in `quickback/features/` have valid exports\n3. Run `quickback compile` with `--verbose` for detailed output\n4. For rename-related Drizzle failures in CI/headless runs, configure `compiler.migrations.renames` in `quickback.config.ts`\n\n### Authentication issues\n\nClear credentials and re-authenticate:\n```bash\nquickback logout\nquickback login\n```\n\n### \"Could not load organizations\"\n\nThis can happen if your session token expired or if the API is temporarily unavailable. Re-login:\n```bash\nquickback logout\nquickback login\n```"
19
19
  },
20
20
  "compiler/cloud-compiler/endpoints": {
21
21
  "title": "Endpoints",
@@ -35,11 +35,11 @@ export const DOCS = {
35
35
  },
36
36
  "compiler/config/agents": {
37
37
  "title": "AI Agent Readiness",
38
- "content": "Every compiled Quickback Worker advertises itself to AI agents and MCP clients — no user wiring required. One config flag controls the whole discovery surface.\n\n## What the compiler generates\n\nWhen `agents` is enabled (the default), the Worker serves:\n\n| Route | What it is |\n|-------|-----------|\n| `GET /robots.txt` | AI-bot policy with the [Cloudflare Content Signals](https://developers.cloudflare.com/bots/concepts/content-signals/) preamble and explicit `Allow:` rules for GPTBot, ClaudeBot, PerplexityBot, Google-Extended, CCBot, Applebot-Extended, Bytespider, MistralAI, Cohere, DuckAssist. |\n| `GET /llms.txt` | Agent-facing summary of the API — project name, authentication, resource list, endpoint conventions — derived from your own config. |\n| `GET /.well-known/oauth-protected-resource` | [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) metadata declaring this Worker as a protected resource. |\n| `GET /.well-known/oauth-authorization-server` | [RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414) metadata pointing at the sign-in and token endpoints. |\n| `GET /.well-known/api-catalog` | [RFC 9727](https://datatracker.ietf.org/doc/html/rfc9727) catalog linking at `/openapi.json`. |\n| `GET /.well-known/mcp.json` | MCP Server Card — discoverable metadata for the MCP server below. |\n| `POST /mcp` | Auto-generated MCP-over-HTTP server. One tool per OpenAPI operation, JWT auth forwarded through the same middleware as the REST API. |\n\n## Default behavior\n\n```ts title=\"quickback.config.ts\"\n\nexport default defineConfig({\n name: 'my-api',\n // …\n // agents: true is the default — no need to write it.\n});\n```\n\nRun `quickback compile` and every endpoint above ships in the Worker.\n\n## Opting out\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // …\n agents: false, // disables everything\n});\n```\n\n## Fine-grained control\n\nPass an object to toggle individual surfaces:\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // …\n agents: {\n robotsTxt: true, // default\n llmsTxt: true, // default\n mcp: true, // default\n oauthDiscovery: true, // default\n apiCatalog: true, // default\n allowAiCrawlers: true, // default — flip to false to Disallow in robots.txt\n },\n});\n```\n\n## The MCP server\n\n### Tools\n\nEvery operation in your generated OpenAPI spec becomes one MCP tool. The tool name is the operation's `operationId` (e.g. `listCustomers`, `createInvoice`, `sendInvoice`). Each tool's `inputSchema` is a flat JSON Schema combining path params, query params, and the request body.\n\n`tools/call` re-enters the same Hono app via `app.request(...)` — so **every existing middleware runs exactly as it would for a direct REST call**: authentication, firewall, access control, guards, masking. No bypass.\n\n### Access-filtered `tools/list`\n\n`tools/list` only returns tools the calling identity could actually invoke. Each generated tool entry carries the operation's access metadata (`roles`, `userRole`, `or` / `and` combinators) and `tools/list` filters against `ctx` before responding:\n\n- **Unauthenticated callers** see only tools whose access declares the `PUBLIC` pseudo-role, or operations that have no security requirement at all (e.g. sign-in / sign-up).\n- **Authenticated callers** see tools whose role gate intersects their `ctx.roles` or `ctx.userRole`. Platform-operator endpoints don't appear for callers outside the required user roles.\n- **Function-form access** (escape hatch) is opaque at list time — surfaced to any authenticated caller, then evaluated for real on `tools/call`.\n- **Record predicates** are dropped from the list-time check (no record yet) and applied normally on the actual call.\n\nThis is recon-mitigation, not a security boundary. Hiding a tool from the list never weakens the underlying gate — `tools/call` still runs the full middleware chain and rejects unauthorized invocations the same way a direct REST call would.\n\nThe unauthenticated `GET /mcp` discovery payload returns server info only; it does **not** enumerate tool names. Inventory is exclusively available via the access-filtered `tools/list`.\n\n### Authentication\n\nMCP clients pass their credentials through the standard `Authorization: Bearer <jwt>` header. The generated MCP handler forwards the header verbatim into the internal request, and the same JWT middleware that guards `/api/v1/*` validates it.\n\nMint a JWT from an authenticated session:\n\n```bash\ncurl -X POST https://my-api.example.com/api/v1/token \\\n -H \"Cookie: better-auth.session_token=...\" \\\n -H \"Content-Type: application/json\"\n```\n\n### Connecting clients\n\n**Claude Desktop** — add to `~/Library/Application Support/Claude/claude_desktop_config.json`:\n\n```json\n{\n \"mcpServers\": {\n \"my-api\": {\n \"url\": \"https://my-api.example.com/mcp\",\n \"headers\": {\n \"Authorization\": \"Bearer <jwt>\"\n }\n }\n }\n}\n```\n\n**Cursor** — use the same config shape under `.cursor/mcp.json`.\n\n**Quick sanity check with curl:**\n\n```bash\n# List available tools\ncurl -X POST https://my-api.example.com/mcp \\\n -H \"Authorization: Bearer $JWT\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}'\n\n# Call a tool\ncurl -X POST https://my-api.example.com/mcp \\\n -H \"Authorization: Bearer $JWT\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{\"name\":\"listCustomers\",\"arguments\":{\"limit\":10}}}'\n```\n\n### Transport\n\nThe server speaks the **Streamable HTTP** MCP transport — JSON-RPC 2.0 over `POST`. A plain `GET /mcp` returns the server info document for sanity checks.\n\nThe MCP route does **not** emit its own CORS headers. The Worker's existing `cors()` middleware applies uniformly, so browser-origin access is governed by the same allowlist as the rest of the API (`auth.trustedOrigins` + the deploy origin). Server-to-server clients (Claude Desktop, Cursor, MCP Inspector) connect with a Bearer token and don't need browser CORS at all. If you want a browser-based MCP client (ChatGPT, Claude.ai) to connect cross-origin, add its origin to `auth.trustedOrigins` like any other web client.\n\n## Verification\n\nAfter you deploy, scan both the REST and MCP surfaces:\n\n```bash\n# Agent-readiness scan (external)\nopen https://isitagentready.com/?url=https://my-api.example.com\n\n# MCP Inspector (official tool)\nnpx @modelcontextprotocol/inspector https://my-api.example.com/mcp\n```"
38
+ "content": "Every compiled Quickback Worker advertises itself to AI agents and MCP clients — no user wiring required. One config flag controls the whole discovery surface.\n\n## What the compiler generates\n\nWhen `agents` is enabled (the default), the Worker serves:\n\n| Route | What it is |\n|-------|-----------|\n| `GET /robots.txt` | AI-bot policy with the [Cloudflare Content Signals](https://developers.cloudflare.com/bots/concepts/content-signals/) preamble and explicit `Allow:` rules for GPTBot, ClaudeBot, PerplexityBot, Google-Extended, CCBot, Applebot-Extended, Bytespider, MistralAI, Cohere, DuckAssist. |\n| `GET /llms.txt` | Agent-facing summary of the API — project name, authentication, resource list, endpoint conventions — derived from your own config. |\n| `GET /.well-known/oauth-protected-resource` | [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) metadata declaring this Worker as a protected resource. |\n| `GET /.well-known/oauth-authorization-server` | [RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414) authorization-server metadata. When the `oauthProvider` plugin is enabled it **delegates to Better Auth's real OAuth 2.1 surface** (`/oauth2/authorize`, `/oauth2/token`, `/oauth2/register` dynamic client registration, PKCE); otherwise it advertises only the truthful token-mint subset. |\n| `GET /.well-known/api-catalog` | [RFC 9727](https://datatracker.ietf.org/doc/html/rfc9727) catalog linking at `/openapi.json`. |\n| `GET /.well-known/mcp.json` | MCP Server Card — discoverable metadata for the MCP server below. |\n| `POST /mcp` | Auto-generated MCP-over-HTTP server. One tool per OpenAPI operation, JWT auth forwarded through the same middleware as the REST API. |\n\n## Default behavior\n\n```ts title=\"quickback.config.ts\"\n\nexport default defineConfig({\n name: 'my-api',\n // …\n // agents: true is the default — no need to write it.\n});\n```\n\nRun `quickback compile` and every endpoint above ships in the Worker.\n\n## Opting out\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // …\n agents: false, // disables everything\n});\n```\n\n## Fine-grained control\n\nPass an object to toggle individual surfaces:\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // …\n agents: {\n robotsTxt: true, // default\n llmsTxt: true, // default\n mcp: true, // default\n oauthDiscovery: true, // default\n apiCatalog: true, // default\n allowAiCrawlers: true, // default — flip to false to Disallow in robots.txt\n },\n});\n```\n\n`mcp` also accepts an object for an authenticated-only MCP surface:\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // …\n agents: {\n mcp: { requireAuth: true }, // /mcp challenges anonymous callers → interactive OAuth\n },\n});\n```\n\nSee [Interactive OAuth](#interactive-oauth-requireauth) below.\n\n## The MCP server\n\n### Tools\n\nEvery operation in your generated OpenAPI spec becomes one MCP tool. The tool name is the operation's `operationId` (e.g. `listCustomers`, `createInvoice`, `sendInvoice`). Each tool's `inputSchema` is a flat JSON Schema combining path params, query params, and the request body.\n\n`tools/call` re-enters the same Hono app via `app.request(...)` — so **every existing middleware runs exactly as it would for a direct REST call**: authentication, firewall, access control, guards, masking. No bypass.\n\n### Access-filtered `tools/list`\n\n`tools/list` only returns tools the calling identity could actually invoke. Each generated tool entry carries the operation's access metadata (`roles`, `userRole`, `or` / `and` combinators) and `tools/list` filters against `ctx` before responding:\n\n- **Unauthenticated callers** see only tools whose access declares the `PUBLIC` pseudo-role, or operations that have no security requirement at all (e.g. sign-in / sign-up).\n- **Authenticated callers** see tools whose role gate intersects their `ctx.roles` or `ctx.userRole`. Platform-operator endpoints don't appear for callers outside the required user roles.\n- **Function-form access** (escape hatch) is opaque at list time — surfaced to any authenticated caller, then evaluated for real on `tools/call`.\n- **Record predicates** are dropped from the list-time check (no record yet) and applied normally on the actual call.\n\nThis is recon-mitigation, not a security boundary. Hiding a tool from the list never weakens the underlying gate — `tools/call` still runs the full middleware chain and rejects unauthorized invocations the same way a direct REST call would.\n\nThe unauthenticated `GET /mcp` discovery payload returns server info only; it does **not** enumerate tool names. Inventory is exclusively available via the access-filtered `tools/list`.\n\n### Authentication\n\nMCP clients pass their credentials through the standard `Authorization: Bearer <jwt>` header. The generated MCP handler forwards the header verbatim into the internal request, and the same JWT middleware that guards `/api/v1/*` validates it.\n\nMint a JWT from an authenticated session:\n\n```bash\ncurl -X POST https://my-api.example.com/api/v1/token \\\n -H \"Cookie: better-auth.session_token=...\" \\\n -H \"Content-Type: application/json\"\n```\n\n### Interactive OAuth (`requireAuth`)\n\nStatically pasting a Bearer token works, but it isn't how an MCP connector wants to authenticate — it expects to **launch a sign-in flow**. By default `/mcp` serves an anonymous session (the access-filtered public tool list), and a connector that never sees an auth challenge never offers to sign in. Set `agents.mcp.requireAuth: true` to turn `/mcp` into an authenticated-only endpoint:\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // …\n agents: { mcp: { requireAuth: true } },\n});\n```\n\nThis does three things:\n\n1. **Force-enables the `oauthProvider` + `bearer` Better Auth plugins** — so `/oauth2/authorize`, `/oauth2/token`, and `/oauth2/register` ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591) dynamic client registration) exist for a connector to discover, with PKCE.\n2. **Challenges unauthenticated `/mcp` requests** with `401` and a `WWW-Authenticate: Bearer resource_metadata=\"…/.well-known/oauth-protected-resource\"` header ([RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) §5.1). This is the signal MCP connectors use to start OAuth.\n3. **Makes the root `/.well-known/oauth-authorization-server` doc delegate to Better Auth's real metadata**, so discovery resolves to working `/oauth2/*` endpoints instead of a hand-rolled stub.\n\nThe full handshake a connector runs:\n\n```text\nPOST /mcp (no token)\n → 401 + WWW-Authenticate: resource_metadata=\"…/.well-known/oauth-protected-resource\"\nGET /.well-known/oauth-protected-resource → authorization_servers: [<origin>]\nGET /.well-known/oauth-authorization-server → authorize/token/register + PKCE\nPOST /oauth2/register → dynamic client registration\nGET /oauth2/authorize?code_challenge=… → redirect to your Account login → consent\nPOST /oauth2/token (code + code_verifier) → access token\nPOST /mcp (Bearer access token) → authenticated tool list\n```\n\nThe login and consent screens are served by your [Account SPA](/stack/account-ui) (`ACCOUNT_URL/login`, `ACCOUNT_URL/consent`), so users sign in with whatever methods you already enabled (Google, GitHub, email, passkey). No connector-specific configuration is required — adding the server URL is enough.\n\n### Connecting clients\n\n**Claude Desktop** — add to `~/Library/Application Support/Claude/claude_desktop_config.json`:\n\n```json\n{\n \"mcpServers\": {\n \"my-api\": {\n \"url\": \"https://my-api.example.com/mcp\",\n \"headers\": {\n \"Authorization\": \"Bearer <jwt>\"\n }\n }\n }\n}\n```\n\n**Cursor** — use the same config shape under `.cursor/mcp.json`.\n\n**Quick sanity check with curl:**\n\n```bash\n# List available tools\ncurl -X POST https://my-api.example.com/mcp \\\n -H \"Authorization: Bearer $JWT\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}'\n\n# Call a tool\ncurl -X POST https://my-api.example.com/mcp \\\n -H \"Authorization: Bearer $JWT\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{\"name\":\"listCustomers\",\"arguments\":{\"limit\":10}}}'\n```\n\n### Transport\n\nThe server speaks the **Streamable HTTP** MCP transport — JSON-RPC 2.0 over `POST`. A plain `GET /mcp` returns the server info document for sanity checks.\n\nThe MCP route does **not** emit its own CORS headers. The Worker's existing `cors()` middleware applies uniformly, so browser-origin access is governed by the same allowlist as the rest of the API (`auth.trustedOrigins` + the deploy origin). Server-to-server clients (Claude Desktop, Cursor, MCP Inspector) connect with a Bearer token and don't need browser CORS at all. If you want a browser-based MCP client (ChatGPT, Claude.ai) to connect cross-origin, add its origin to `auth.trustedOrigins` like any other web client.\n\n## Verification\n\nAfter you deploy, scan both the REST and MCP surfaces:\n\n```bash\n# Agent-readiness scan (external)\nopen https://isitagentready.com/?url=https://my-api.example.com\n\n# MCP Inspector (official tool)\nnpx @modelcontextprotocol/inspector https://my-api.example.com/mcp\n```"
39
39
  },
40
40
  "compiler/config/auth": {
41
41
  "title": "Auth & JWT",
42
- "content": "The top-level `auth` config block holds provider-agnostic auth knobs that affect how Quickback emits the auth middleware, JWT helpers, and access-rule expansion.\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // ...\n auth: {\n roleHierarchy: ['member', 'admin', 'owner'],\n jwt: {\n expiresIn: 60,\n issuer: 'my-api',\n // audience, secretEnv, algorithm, revocationCheck...\n },\n },\n});\n```\n\n## `auth.roleHierarchy`\n\nLowest-to-highest privilege list. Lets access rules use `'role+'` shorthand to mean \"this role and above\". Documented in detail under [Access — Role hierarchy](/compiler/definitions/access#role-hierarchy).\n\n## `auth.jwt` — JWT bearer-token fast-path\n\nQuickback ships its own custom HMAC-SHA256 JWT (not Better Auth's JWT plugin) so it can embed `orgId` and `role` claims the fast-path needs to reconstruct `AppContext` without a database round-trip. The signing secret is shared with Better Auth (`BETTER_AUTH_SECRET`) by default — users only manage one secret.\n\n### Behavior recap\n\n1. The browser SPA gets a JWT via the `set-auth-token` response header on every authenticated call.\n2. On subsequent requests the SPA sends `Authorization: Bearer <jwt>`.\n3. The auth middleware's **fast-path** verifies the signature only — no DB query, no session lookup. `AppContext` is reconstructed from JWT claims.\n4. If verification fails (or no JWT is present), the middleware falls back to session auth.\n5. After successful session auth, a fresh JWT is minted and returned via `set-auth-token`. The cycle continues.\n\nThe fast-path is intentionally stateless: it trusts the claims for the full TTL. **Stolen or pre-revocation tokens are valid until they expire.** That's the trade-off the fast-path makes — and the reason `expiresIn` is the most-tuned knob below.\n\n### `expiresIn?: number` — TTL in seconds\n\nDefault `180` (3 minutes).\n\nLowering this shrinks the worst-case window where a stolen / pre-revocation token still works. Browser SPAs auto-refresh via `set-auth-token` on every authed call, so a low TTL is invisible to logged-in users; only stale server-to-server bearer tokens feel it.\n\n```ts\nauth: { jwt: { expiresIn: 30 } } // 30s — tight post-revocation window\nauth: { jwt: { expiresIn: 3600 } } // 1h — longer-lived tokens for CLI / CI\n```\n\n### `issuer?: string` — `iss` claim\n\nDefault omitted.\n\nSet this when other services need to distinguish JWTs minted by this Worker from other issuers. The compiler bakes the issuer into both the mint side (added to claims) and the verify side (rejects tokens with mismatched `iss`).\n\n### `audience?: string` — `aud` claim\n\nDefault omitted.\n\nSet this when this Worker's JWTs are consumed by a sibling service that should reject tokens minted for a different audience. Same mint-and-verify treatment as `issuer`.\n\n### `secretEnv?: string` — signing secret env var\n\nDefault `'BETTER_AUTH_SECRET'`.\n\nOverride this if you want JWT signing isolated from the Better Auth secret (e.g. rotating one without invalidating the other).\n\n```ts\nauth: { jwt: { secretEnv: 'CUSTOM_JWT_SECRET' } }\n```\n\nThe compiler emits `c.env.CUSTOM_JWT_SECRET` (or `process.env.CUSTOM_JWT_SECRET` on Bun/Node) in the auth middleware's verify and mint sites and the `/api/v1/token` endpoint.\n\n> **Note:** the files-worker (separate Worker for R2 access) still reads `BETTER_AUTH_SECRET` directly. If you override `secretEnv`, set both env vars to the same value or the files worker's JWT verification will fall back to DB session lookup. Threading `secretEnv` through the files worker is on the roadmap.\n\n### `algorithm?: 'HS256'`\n\nOnly `HS256` is supported in 0.10.14. `RS256` (asymmetric, public-key verify / private-key sign) is on the roadmap.\n\n### `revocationCheck?: 'none' | 'kv'` — token revocation strategy\n\nDefault `'none'`.\n\n| Value | Behavior | Cost per verify |\n|---|---|---|\n| `'none'` | No revocation check. Stolen tokens valid until TTL expires. Use a low `expiresIn` to bound the replay window. | 0 |\n| `'kv'` | Fast-path consults a denylist KV namespace before accepting the token. Banning a user / revoking sessions writes the user's `sub` to the denylist. | 1 KV read (~5-15ms, edge-cached) |\n\nThe `'kv'` path keeps the fast-path stateless against the auth DB (still 0 D1 queries) — KV reads on Workers are an order of magnitude cheaper than a D1 round trip *and* give sub-second revocation.\n\n> **`'kv'` is deferred to 0.10.15.** Setting `'kv'` in 0.10.14 errors at compile time so the migration path is explicit; the schema accepts it now so users can author their final config today.\n\n## Defaults preserve 0.10.13 behavior\n\nAdding the `auth.jwt` block without setting any field is a no-op vs. the 0.10.13 baseline. Each missing field falls back to its hardcoded value:\n\n| Field | Default |\n|---|---|\n| `expiresIn` | 180 |\n| `issuer` | omitted |\n| `audience` | omitted |\n| `secretEnv` | `'BETTER_AUTH_SECRET'` |\n| `algorithm` | `'HS256'` |\n| `revocationCheck` | `'none'` |\n\n## Tuning recommendations\n\n- **B2C SaaS, mostly browser traffic:** keep defaults. The 180s TTL + auto-refresh model just works.\n- **Pentest engagement / enterprise compliance:** set `expiresIn: 30`. Tokens stay invisible to logged-in users (auto-refreshed every authed call) but stolen-token windows shrink to 30s.\n- **CLI-heavy / long-running CI tokens:** `expiresIn: 3600` for one-hour bearer tokens. Pair with `issuer` / `audience` if multiple services consume the same JWT.\n- **Need immediate revocation:** wait for 0.10.15's `revocationCheck: 'kv'`. Or, today, drop TTL to ~30s — same effect with bounded delay.\n\n## `auth.loginUrl` / `auth.profileUrl` — external sign-in for consumer Workers\n\nWhen a Quickback Worker doesn't host its own Account SPA — e.g. an internal-app mesh where one Worker on the parent domain owns identity (`auth.example.com`) and other Workers share cookies — the compiler-emitted CMS access gates need to redirect unauthenticated visitors to the central sign-in surface, not the local `/account/login` (which doesn't exist there).\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // ...\n auth: {\n loginUrl: 'https://auth.example.com/login',\n profileUrl: 'https://auth.example.com/profile',\n },\n});\n```\n\nBoth fields override compiler-emitted browser redirects in the CMS shell:\n\n- **Unauthenticated visitor hits a CMS route** → `302 → <loginUrl>?redirect=<original-url>`\n- **Authenticated user fails the `cms.access: 'admin'` platform-role check** → `302 → <profileUrl>`\n\nThe `?redirect=…` query param is preserved unchanged so the central sign-in surface can bounce the user back after authentication.\n\n### Resolution precedence\n\nMost-specific wins:\n\n1. Explicit `auth.loginUrl` / `auth.profileUrl` — the cookie-trusting consumer-Worker case (this section).\n2. `https://<account.domain>/login` — inferred when this project hosts its own Account SPA on a custom domain.\n3. `/account/login` — built-in fallback, when neither knob is set.\n\n### Independent from `account.domain`\n\n`account.domain` does *two* things: redirect targets *and* hostname-based asset routing for an Account SPA hosted by this project. Consumer Workers don't host Account at all — they only need the URL. `auth.loginUrl` is a redirect-target string with no routing side effects, which is why it's a separate knob.\n\n### When both are set\n\nSetting `auth.loginUrl` *and* `account.domain` is legal — the explicit override beats the inferred URL at the redirect site, while `account.domain` still drives the local Account SPA's hostname routing as usual. Useful when you want to host Account on one custom domain (`account.foo.com`) but redirect *somewhere else* for sign-in (e.g. an SSO surface at `auth.foo.com`)."
42
+ "content": "The top-level `auth` config block holds provider-agnostic auth knobs that affect how Quickback emits the auth middleware, JWT helpers, and access-rule expansion.\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // ...\n auth: {\n roleHierarchy: ['member', 'admin', 'owner'],\n jwt: {\n expiresIn: 60,\n issuer: 'my-api',\n // audience, secretEnv, algorithm, revocationCheck...\n },\n },\n});\n```\n\n## `auth.roleHierarchy`\n\nLowest-to-highest privilege list. Lets access rules use `'role+'` shorthand to mean \"this role and above\". Documented in detail under [Access — Role hierarchy](/compiler/definitions/access#role-hierarchy).\n\n## `auth.jwt` — JWT bearer-token fast-path\n\nQuickback ships its own custom HMAC-SHA256 JWT (not Better Auth's JWT plugin) so it can embed `orgId` and `role` claims the fast-path needs to reconstruct `AppContext` without a database round-trip. The signing secret is shared with Better Auth (`BETTER_AUTH_SECRET`) by default — users only manage one secret.\n\n### Behavior recap\n\n1. The browser SPA gets a JWT via the `set-auth-token` response header on every authenticated call.\n2. On subsequent requests the SPA sends `Authorization: Bearer <jwt>`.\n3. The auth middleware's **fast-path** verifies the signature only — no DB query, no session lookup. `AppContext` is reconstructed from JWT claims.\n4. If verification fails (or no JWT is present), the middleware falls back to session auth.\n5. After successful session auth, a fresh JWT is minted and returned via `set-auth-token`. The cycle continues.\n\nThe fast-path is intentionally stateless: it trusts the claims for the full TTL. **Stolen or pre-revocation tokens are valid until they expire.** That's the trade-off the fast-path makes — and the reason `expiresIn` is the most-tuned knob below.\n\n### `expiresIn?: number` — TTL in seconds\n\nDefault `180` (3 minutes).\n\nLowering this shrinks the worst-case window where a stolen / pre-revocation token still works. Browser SPAs auto-refresh via `set-auth-token` on every authed call, so a low TTL is invisible to logged-in users; only stale server-to-server bearer tokens feel it.\n\n```ts\nauth: { jwt: { expiresIn: 30 } } // 30s — tight post-revocation window\nauth: { jwt: { expiresIn: 3600 } } // 1h — longer-lived tokens for CLI / CI\n```\n\n### `issuer?: string` — `iss` claim\n\nDefault omitted.\n\nSet this when other services need to distinguish JWTs minted by this Worker from other issuers. The compiler bakes the issuer into both the mint side (added to claims) and the verify side (rejects tokens with mismatched `iss`).\n\n### `audience?: string` — `aud` claim\n\nDefault omitted.\n\nSet this when this Worker's JWTs are consumed by a sibling service that should reject tokens minted for a different audience. Same mint-and-verify treatment as `issuer`.\n\n### `secretEnv?: string` — signing secret env var\n\nDefault `'BETTER_AUTH_SECRET'`.\n\nOverride this if you want JWT signing isolated from the Better Auth secret (e.g. rotating one without invalidating the other).\n\n```ts\nauth: { jwt: { secretEnv: 'CUSTOM_JWT_SECRET' } }\n```\n\nThe compiler emits `c.env.CUSTOM_JWT_SECRET` (or `process.env.CUSTOM_JWT_SECRET` on Bun/Node) in the auth middleware's verify and mint sites and the `/api/v1/token` endpoint.\n\n> **Note:** the files-worker (separate Worker for R2 access) still reads `BETTER_AUTH_SECRET` directly. If you override `secretEnv`, set both env vars to the same value or the files worker's JWT verification will fall back to DB session lookup. Threading `secretEnv` through the files worker is on the roadmap.\n\n### `algorithm?: 'HS256'`\n\nOnly `HS256` is supported in 0.10.14. `RS256` (asymmetric, public-key verify / private-key sign) is on the roadmap.\n\n### `revocationCheck?: 'none' | 'kv'` — token revocation strategy\n\nDefault `'none'`.\n\n| Value | Behavior | Cost per verify |\n|---|---|---|\n| `'none'` | No revocation check. Stolen / pre-revocation tokens valid until TTL expires (scope claims: until the carry-forward cap). Use a low `expiresIn` to bound the replay window. | 0 |\n| `'kv'` | Fast-path checks per-principal revocation timestamps in the project's existing `KV` binding before trusting a verified token. | 2+ KV reads (~5-15ms, edge-cached) |\n\n`'kv'` (v0.45+, **Cloudflare runtime only**) keeps the fast-path stateless against the auth DB (still 0 D1 queries). There is nothing extra to provision — entries ride the `KV` binding every project already has, prefixed `qbrev:` and self-expiring after the maximum token lifetime, so the store never accumulates.\n\nA token is rejected when its mint timestamp (`iat`, or `sct` for the relationship-scope claim) predates the stored timestamp for any principal key it rides on:\n\n| Key | Revokes | Written automatically on |\n|---|---|---|\n| `qbrev:user:<userId>` | every JWT for the user | user ban (`databaseHooks.user.update.after` — flipping `banned` stamps the key and, when outbound webhooks are enabled, emits a `user.banned` event). Call `revokeUserTokens` for custom flows (revoke-all, etc.) |\n| `qbrev:member:<userId>:<orgId>` | the user's org-membership claims | member removal / role change (Better Auth `organizationHooks`) |\n| `qbrev:scope:<userId>:<kind>:<id>` | the user's carried scope claim | UPDATE/DELETE of a scope-conferring relationship row (audit-wrapper chokepoint + the single DELETE route) |\n\n`src/lib/jwt-revocation.ts` exports `revokeUserTokens` / `revokeMemberTokens` / `revokeScopeTokens` for explicit calls from actions. A rejected token falls through to session auth, which re-checks membership and re-mints — an active legitimate session recovers transparently.\n\nSemantics worth knowing:\n\n- **Revoke-on-touch for scopes:** any update or delete of a conferring row stamps the revocation, without evaluating whether the change actually ended the relationship. A false positive just forces a cheap re-prove (`/scope/v1/enter` or a minting namespace route).\n- **Fails open:** a missing binding or KV outage skips the check (logged) — revocation degrades to the TTL / carry-forward-cap bound rather than locking every bearer out.\n- **Eventual consistency:** KV propagates cross-PoP in ~60s. \"Immediate\" means seconds at the writing location, bounded-seconds globally — still far inside the 15-minute carry-forward cap that bounds revocation without this check.\n- **Coverage gap:** batch *hard* deletes don't return rows through the chokepoint; call `revokeScopeTokens` explicitly if you bulk-hard-delete conferring rows.\n\n## Defaults preserve 0.10.13 behavior\n\nAdding the `auth.jwt` block without setting any field is a no-op vs. the 0.10.13 baseline. Each missing field falls back to its hardcoded value:\n\n| Field | Default |\n|---|---|\n| `expiresIn` | 180 |\n| `issuer` | omitted |\n| `audience` | omitted |\n| `secretEnv` | `'BETTER_AUTH_SECRET'` |\n| `algorithm` | `'HS256'` |\n| `revocationCheck` | `'none'` |\n\n## Tuning recommendations\n\n- **B2C SaaS, mostly browser traffic:** keep defaults. The 180s TTL + auto-refresh model just works.\n- **Pentest engagement / enterprise compliance:** set `expiresIn: 30`. Tokens stay invisible to logged-in users (auto-refreshed every authed call) but stolen-token windows shrink to 30s.\n- **CLI-heavy / long-running CI tokens:** `expiresIn: 3600` for one-hour bearer tokens. Pair with `issuer` / `audience` if multiple services consume the same JWT.\n- **Need immediate revocation:** set `revocationCheck: 'kv'` (Cloudflare runtime). Or drop TTL to ~30s — similar effect with bounded delay and zero KV reads.\n\n## `auth.loginUrl` / `auth.profileUrl` — external sign-in for consumer Workers\n\nWhen a Quickback Worker doesn't host its own Account SPA — e.g. an internal-app mesh where one Worker on the parent domain owns identity (`auth.example.com`) and other Workers share cookies — the compiler-emitted CMS access gates need to redirect unauthenticated visitors to the central sign-in surface, not the local `/account/login` (which doesn't exist there).\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // ...\n auth: {\n loginUrl: 'https://auth.example.com/login',\n profileUrl: 'https://auth.example.com/profile',\n },\n});\n```\n\nBoth fields override compiler-emitted browser redirects in the CMS shell:\n\n- **Unauthenticated visitor hits a CMS route** → `302 → <loginUrl>?redirect=<original-url>`\n- **Authenticated user fails the `cms.access: 'admin'` platform-role check** → `302 → <profileUrl>`\n\nThe `?redirect=…` query param is preserved unchanged so the central sign-in surface can bounce the user back after authentication.\n\n### Resolution precedence\n\nMost-specific wins:\n\n1. Explicit `auth.loginUrl` / `auth.profileUrl` — the cookie-trusting consumer-Worker case (this section).\n2. `https://<account.domain>/login` — inferred when this project hosts its own Account SPA on a custom domain.\n3. `/account/login` — built-in fallback, when neither knob is set.\n\n### Independent from `account.domain`\n\n`account.domain` does *two* things: redirect targets *and* hostname-based asset routing for an Account SPA hosted by this project. Consumer Workers don't host Account at all — they only need the URL. `auth.loginUrl` is a redirect-target string with no routing side effects, which is why it's a separate knob.\n\n### When both are set\n\nSetting `auth.loginUrl` *and* `account.domain` is legal — the explicit override beats the inferred URL at the redirect site, while `account.domain` still drives the local Account SPA's hostname routing as usual. Useful when you want to host Account on one custom domain (`account.foo.com`) but redirect *somewhere else* for sign-in (e.g. an SSO surface at `auth.foo.com`)."
43
43
  },
44
44
  "compiler/config/bindings": {
45
45
  "title": "Custom Bindings",
@@ -63,7 +63,7 @@ export const DOCS = {
63
63
  },
64
64
  "compiler/config/security": {
65
65
  "title": "Security Headers",
66
- "content": "Every compiled Quickback Worker sets a baseline of security response-headers on every response: HSTS, `X-Content-Type-Options: nosniff`, a clickjacking CSP (`frame-ancestors 'self' …TRUSTED_ORIGINS`), `X-Frame-Options: SAMEORIGIN`, `Referrer-Policy`, and `Permissions-Policy`. Adding the `security` block lets you override individual headers, ship a fuller Content-Security-Policy, or suppress them all if an upstream gateway handles headers.\n\n## Default behavior\n\nOmit `security` entirely → the baseline above. No config change needed for clickjacking + HSTS protection.\n\n```ts title=\"quickback.config.ts\"\n\nexport default defineConfig({\n name: 'my-api',\n // ...\n // security defaults are applied automatically.\n});\n```\n\n## Suppress every security header\n\nFor Workers fronted by a gateway that owns headers:\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // ...\n security: false,\n});\n```\n\nThe compiler emits a no-op middleware comment so the route table still lines up with the rest of the generated code, but no `c.header(...)` calls fire.\n\n## Per-header overrides\n\nEach field on the `security` block accepts either a typed value or `false` to suppress that specific header. Defaults still apply for fields you don't set.\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // ...\n security: {\n // Suppress just CSP — keeps HSTS, referrer, permissions, etc.\n csp: false,\n\n // Or override individual fields:\n coop: 'same-origin',\n coep: 'credentialless',\n referrerPolicy: 'no-referrer',\n permissionsPolicy: { geolocation: [], microphone: [], camera: [], payment: [] },\n hsts: { maxAge: 63072000, includeSubDomains: true, preload: true },\n },\n});\n```\n\n## Content Security Policy\n\n`security.csp` accepts a typed object. Each `*Src` field is an array of source expressions. The compiler accepts both the `@`-prefixed sentinels (idiomatic, type-safe) and CSP wire-form keywords (`\"'self'\"`, `\"'unsafe-inline'\"`); both normalize to the same output.\n\n### Sentinels\n\n| Sentinel | Wire form | Notes |\n|---|---|---|\n| `@self` | `'self'` | Same-origin. |\n| `@none` | `'none'` | Empty-set keyword. |\n| `@unsafe-inline` | `'unsafe-inline'` | Allows inline scripts/styles — defeats most XSS mitigation when used in `script-src`. |\n| `@unsafe-eval` | `'unsafe-eval'` | Allows `eval()` and friends. |\n| `@trustedOrigins` | The `…TRUSTED_ORIGINS` constant at runtime | Resolves to `auth.trustedOrigins` as configured in `quickback.config.ts`. |\n| `@nonce` | `'nonce-…'` per request | Reserved for the per-request nonce middleware shipping in 0.10.15. Using this in 0.10.14 is a compile-time error. |\n\nUnknown `@…` tokens are rejected at compile rather than silently stringified into the wire CSP.\n\n### Example: paste-in CSP for a Quickback SPA project\n\nThe bundled CMS and Account SPAs load Google Fonts cross-origin, so the strict `'self'`-only CSP would white-screen them on load. This config is a known-working starting point for Quickback projects with the bundled SPAs:\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // ...\n security: {\n csp: {\n defaultSrc: ['@self'],\n // Tailwind dynamic styles + bundled Google Fonts CSS need\n // unsafe-inline + the gstatic / googleapis hosts. Tightening\n // styles to nonces ships in 0.10.15.\n styleSrc: ['@self', '@unsafe-inline', 'https://fonts.googleapis.com'],\n scriptSrc: ['@self'],\n fontSrc: ['@self', 'data:', 'https://fonts.gstatic.com'],\n imgSrc: ['@self', 'data:', 'blob:', 'https:'],\n connectSrc: ['@self', '@trustedOrigins'],\n frameAncestors: ['@self', '@trustedOrigins'],\n formAction: ['@self'],\n baseUri: ['@self'],\n objectSrc: ['@none'],\n upgradeInsecureRequests: true,\n },\n },\n});\n```\n\n### Troubleshooting CSP violations\n\nIf the browser console shows CSP errors after enabling `security.csp`, match the directive named in the error against this table — it maps the failure mode back to the directive that needs widening.\n\n| Console error | Directive | Why it happens | Fix |\n|---|---|---|---|\n| `Loading the stylesheet 'https://fonts.googleapis.com/...' violates 'style-src ...'` | `styleSrc` | Bundled CMS/Account SPAs `<link>` to Google Fonts CSS. | Add `'https://fonts.googleapis.com'` to `styleSrc`. |\n| `Refused to load the font 'https://fonts.gstatic.com/...' because it violates 'font-src ...'` | `fontSrc` | The CSS file from googleapis loads `.woff2` files from gstatic. | Add `'https://fonts.gstatic.com'` to `fontSrc`. |\n| `Connecting to 'https://api.your-domain/...' violates 'connect-src 'self''` | `connectSrc` | API on a sibling subdomain (e.g. SPA on `app.example.com`, API on `api.example.com`) — `'self'` only covers exact origin. | Use `connectSrc: ['@self', '@trustedOrigins']` so the same allowlist `cors()` enforces gets reused. |\n| `Refused to apply inline style because it violates 'style-src ...'` | `styleSrc` | TanStack Router / Tailwind's `style=\"...\"` attributes are inline. | Add `'@unsafe-inline'` to `styleSrc` until 0.10.15 ships per-request nonces. |\n| `Refused to load the image '...' because it violates 'img-src ...'` | `imgSrc` | User-uploaded avatars / R2-hosted assets / `data:` URIs from blob previews. | Widen `imgSrc` to `['@self', 'data:', 'blob:', 'https:']` (or list specific hosts). |\n| `Refused to connect to 'wss://...' because it violates 'connect-src ...'` | `connectSrc` | Realtime / Durable Object WebSockets. | The `@trustedOrigins` sentinel covers HTTPS only — add the explicit `wss://` origin if your DO lives elsewhere. |\n\nThe general rule: `'self'` means *exact origin* (scheme + host + port). Anything cross-origin needs an explicit host or the `@trustedOrigins` sentinel. The [paste-in recipe above](#example-paste-in-csp-for-a-quickback-spa-project) is a known-good baseline for a stock Quickback project — start there and tighten, rather than starting from `'self'`-only and chasing console errors.\n\n### Auto-derivations\n\nThe compiler applies these so config stays minimal:\n\n- **`csp.frameAncestors` defaults to `['@self', '@trustedOrigins']`** when `csp` is set but `frameAncestors` is omitted. Same allowlist as CORS.\n- **`X-Frame-Options` derives from `csp.frameAncestors`** (`['@none']` → `DENY`, contains `@self` → `SAMEORIGIN`, otherwise omitted — XFO can't represent arbitrary origins so CSP becomes the truth there). Override with `security.frameOptions`.\n- **`corp: 'same-origin'` is auto-emitted when `coep` is set.** `require-corp` without CORP breaks the ASSETS binding fetches on Cloudflare; the compiler couples them so users don't have to remember.\n\n### CSP auto-config (0.10.15+)\n\nWhen you opt into a `csp` object, the compiler additively widens directives based on which Quickback features your project has enabled. **Additive** means anything you already wrote stays; we only push values that aren't already present.\n\n| Trigger | Auto-added | To directive | Why |\n|---|---|---|---|\n| `cms: true` OR `account: true` | `'unsafe-inline'` | `styleSrc` | Tailwind / TanStack Router emit inline `style=` attributes |\n| `cms: true` OR `account: true` | `https://fonts.googleapis.com` | `styleSrc` | Bundled SPAs `<link>` to Google Fonts CSS |\n| `cms: true` OR `account: true` | `https://fonts.gstatic.com` | `fontSrc` | The googleapis CSS loads `.woff2` from gstatic |\n| `csp` set (always) | `@trustedOrigins` | `connectSrc` | XHR/fetch must reach the same allowlist `cors()` permits — covers cross-subdomain APIs without re-listing them |\n| `cms: true` OR `account: true` | `https://${domain}` for each `cms.domain` / `account.domain` / `domain` / inferred unified domain | `connectSrc` | The Vite bundle hardcodes `VITE_QUICKBACK_API_URL` at compile time, so the SPA fetches that exact URL even when the page is served from a different origin (e.g. localhost dev hitting prod-baked SPA). Emitted with the host's first letter capitalised (`https://Api.example.com`) so `wrangler dev`'s response-header rewrite can't mangle it — see [the `wrangler dev` note below](#why-the-spa-baked-origin-shows-up-capitalised-in-csp). |\n\n**Scaffold rule:** if you set `defaultSrc` but omit the target directive (e.g. you wrote `defaultSrc: ['@self']` and nothing for `connectSrc`), auto-config creates the new directive seeded with your `defaultSrc` values plus the addition. `defaultSrc` itself stays clean. So `defaultSrc: ['@self']` + auto-config produces:\n\n```\ndefault-src 'self'\nstyle-src 'self' 'unsafe-inline' https://fonts.googleapis.com\nfont-src 'self' https://fonts.gstatic.com\nconnect-src 'self' @trustedOrigins https://api.your-app.com\n```\n\nEach directive is scoped to exactly what it needs. `defaultSrc` is *not* widened with style-only or connect-only hosts — that would let those hosts also reach `script-src` / `img-src` / `media-src` via fall-back, which is wider than the bundled SPA actually needs. (This rule changed in 0.10.17 — earlier versions incorrectly pushed additions into defaultSrc.)\n\n**Visibility:** every applied addition prints to stderr at compile time — one line per addition with the directive, value, and reason. No silent magic. Loop's compile output now looks like:\n\n```\n[security] auto-added 'unsafe-inline' to csp.styleSrc — account: true → bundled Account SPA → inline style attributes from Tailwind / TanStack Router\n[security] auto-added https://fonts.googleapis.com to csp.styleSrc — account: true → bundled Account SPA → loads Google Fonts CSS cross-origin\n[security] auto-added https://fonts.gstatic.com to csp.fontSrc — account: true → bundled Account SPA → woff2 font files served from gstatic.com\n[security] auto-added @trustedOrigins to csp.connectSrc — CORS-trusted origins must be reachable from XHR/fetch (matches cors() allowlist)\n```\n\n**Opt-out:** `security: { cspAutoConfig: false, csp: { ... } }` for projects fronted by a CDN that injects its own CSP, or teams that want strict from-scratch control. With auto-config off, every value above must be authored by hand.\n\n#### Why the SPA-baked origin shows up capitalised in CSP\n\nProjects with `domain: \"...\"` + bundled CMS / Account SPAs will see `connect-src 'self' https://Api.example.com …` in their served CSP — note the capital `A`. That's deliberate (added in 0.10.19) and works around a `wrangler dev` quirk, not a typo on our end.\n\n`wrangler dev` rewrites the configured `custom_domain` host string in **every** response header value (Location, Content-Security-Policy, X-…) to the local hostname, with a case-sensitive substring matcher. Without the case-shift, the served CSP becomes `connect-src 'self' https://localhost:8787 …` and the bundled SPA's hardcoded `VITE_QUICKBACK_API_URL` fetches get blocked because the prod URL no longer appears in the allowlist.\n\nCSP host-source matching is ASCII case-insensitive per CSP3 (`Matching Source Expressions`), so browsers treat `https://Api.example.com` as identical to `https://api.example.com` for the purpose of CSP checks. Wrangler's matcher is case-sensitive, so the capitalised form slips past the rewrite and survives into the served header. End result: the SPA's lowercase fetch target matches the capitalised CSP entry, auth round-trips work in dev, and prod CSP behaviour is unchanged (browsers don't care).\n\nIf wrangler ever fixes the response-header rewrite, the capitalised form remains a valid CSP entry — no follow-up needed.\n\nWith auto-config on, the [paste-in recipe above](#example-paste-in-csp-for-a-quickback-spa-project) becomes much shorter — most users only need:\n\n```ts\nsecurity: {\n csp: {\n defaultSrc: ['@self'],\n scriptSrc: ['@self'],\n imgSrc: ['@self', 'data:', 'blob:', 'https:'],\n objectSrc: ['@none'],\n upgradeInsecureRequests: true,\n },\n}\n```\n\nThe compiler fills in the SPA-specific font hosts, inline-style allowance, and trusted-origin connect rules from the project's own feature flags.\n\n## Cross-origin window/embedder isolation\n\n```ts title=\"quickback.config.ts\"\nsecurity: {\n coop: 'same-origin', // Defends against window.opener back-references from popups.\n coep: 'credentialless', // Required for SharedArrayBuffer / cross-origin isolation.\n // corp auto-emits as 'same-origin' here.\n}\n```\n\n## HSTS\n\nDefault: `max-age=31536000; includeSubDomains; preload` (HSTS preload-list eligible).\n\n```ts title=\"quickback.config.ts\"\nsecurity: {\n hsts: { maxAge: 63072000, includeSubDomains: true, preload: true },\n}\n```\n\nThe generated middleware automatically suppresses HSTS on `localhost`, `127.0.0.1`, and `*.localhost` regardless of this config. Without that gate, `wrangler dev` would pin the developer's browser to HTTPS for `maxAge` seconds, which is observable across every project on that machine.\n\nTo submit to the [HSTS preload list](https://hstspreload.org), you need:\n\n- `maxAge` ≥ 31536000 (one year)\n- `includeSubDomains: true`\n- `preload: true`\n\nThe compiler warns at compile time if `preload: true` without the other two — the preload list rejects either anyway.\n\n## Permissions Policy\n\nMap of feature name → list of allowed origins.\n\n```ts title=\"quickback.config.ts\"\nsecurity: {\n permissionsPolicy: {\n geolocation: [], // disabled for everyone\n microphone: ['self'], // allowed only on own origin\n camera: ['self', 'https://meet.example.com'],\n payment: [],\n },\n}\n```\n\nThe compiler encodes the wire syntax (which differs from CSP — values use `()`, not space-separated tokens, with bareword `self` and quoted URLs).\n\n## Compile-time lint rules\n\nThe compiler walks the resolved config and emits warnings (or errors) for known footguns. Errors block compile; warnings print to stderr.\n\n| Code | Severity | Trigger |\n|---|---|---|\n| `csp/nonce-not-yet-supported` | error | `@nonce` sentinel used in 0.10.14. Per-request nonce middleware ships in 0.10.15. |\n| `csp/unsafe-inline-with-nonce` | error | `@unsafe-inline` and `@nonce` in the same directive (CSP3 silently ignores `unsafe-inline` when nonce is present). |\n| `csp/empty-resolved-directive` | error | `*Src` array contains only `@trustedOrigins` and `auth.trustedOrigins` is empty — would emit a directive Chrome reads as `'none'`. |\n| `csp/unsafe-inline-script` | warn | `@unsafe-inline` in `scriptSrc` defeats most XSS mitigations. |\n| `csp/open-source` | warn | Wildcard `*` or scheme-only `https:` / `http:` in any `*-src`. |\n| `csp/unsafe-eval-with-data` | warn | `@unsafe-eval` combined with any `data:` source — trivial bypass. |\n| `csp/missing-default-src` | warn | Other `*-src` set without `defaultSrc`. |\n| `csp/upgrade-with-http` | warn | `upgradeInsecureRequests: true` plus an `http://` source elsewhere. |\n| `csp/report-uri-only` | warn | `reportUri` set without `reportTo` (deprecated CSP2 path). |\n| `hsts/preload-needs-long-max-age` | warn | `preload: true` with `maxAge < 31536000`. |\n| `hsts/preload-needs-include-subdomains` | warn | `preload: true` without `includeSubDomains`. |\n\n## Verification\n\nSpin up the deployed Worker (or `wrangler dev`) and check the response headers:\n\n```bash\ncurl -sI https://my-api.example.com/health \\\n | grep -E '^(content-security-policy|x-frame-options|strict-transport-security|cross-origin-opener-policy|cross-origin-embedder-policy|cross-origin-resource-policy|referrer-policy|permissions-policy):'\n```\n\nUse [securityheaders.com](https://securityheaders.com) for an external grade — Quickback's defaults are A on the baseline and A+ once a fuller `csp` is configured."
66
+ "content": "Every compiled Quickback Worker sets a baseline of security response-headers on every response: HSTS, `X-Content-Type-Options: nosniff`, a clickjacking CSP (`frame-ancestors 'self' …TRUSTED_ORIGINS`), `X-Frame-Options: SAMEORIGIN`, `Referrer-Policy`, and `Permissions-Policy`. Adding the `security` block lets you override individual headers, ship a fuller Content-Security-Policy, or suppress them all if an upstream gateway handles headers.\n\n## Default behavior\n\nOmit `security` entirely → the baseline above. No config change needed for clickjacking + HSTS protection.\n\n```ts title=\"quickback.config.ts\"\n\nexport default defineConfig({\n name: 'my-api',\n // ...\n // security defaults are applied automatically.\n});\n```\n\n## Suppress every security header\n\nFor Workers fronted by a gateway that owns headers:\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // ...\n security: false,\n});\n```\n\nThe compiler emits a no-op middleware comment so the route table still lines up with the rest of the generated code, but no `c.header(...)` calls fire.\n\n## Per-header overrides\n\nEach field on the `security` block accepts either a typed value or `false` to suppress that specific header. Defaults still apply for fields you don't set.\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // ...\n security: {\n // Suppress just CSP — keeps HSTS, referrer, permissions, etc.\n csp: false,\n\n // Or override individual fields:\n coop: 'same-origin',\n coep: 'credentialless',\n referrerPolicy: 'no-referrer',\n permissionsPolicy: { geolocation: [], microphone: [], camera: [], payment: [] },\n hsts: { maxAge: 63072000, includeSubDomains: true, preload: true },\n },\n});\n```\n\n## Content Security Policy\n\n`security.csp` accepts a typed object. Each `*Src` field is an array of source expressions. The compiler accepts both the `@`-prefixed sentinels (idiomatic, type-safe) and CSP wire-form keywords (`\"'self'\"`, `\"'unsafe-inline'\"`); both normalize to the same output.\n\n### Sentinels\n\n| Sentinel | Wire form | Notes |\n|---|---|---|\n| `@self` | `'self'` | Same-origin. |\n| `@none` | `'none'` | Empty-set keyword. |\n| `@unsafe-inline` | `'unsafe-inline'` | Allows inline scripts/styles — defeats most XSS mitigation when used in `script-src`. |\n| `@unsafe-eval` | `'unsafe-eval'` | Allows `eval()` and friends. |\n| `@trustedOrigins` | The `…TRUSTED_ORIGINS` constant at runtime | Resolves to `auth.trustedOrigins` as configured in `quickback.config.ts`. |\n| `@nonce` | `'nonce-…'` per request | Reserved for the per-request nonce middleware shipping in 0.10.15. Using this in 0.10.14 is a compile-time error. |\n\nUnknown `@…` tokens are rejected at compile rather than silently stringified into the wire CSP.\n\n### Example: paste-in CSP for a Quickback SPA project\n\nThe bundled CMS and Account SPAs load Google Fonts cross-origin, so the strict `'self'`-only CSP would white-screen them on load. This config is a known-working starting point for Quickback projects with the bundled SPAs:\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // ...\n security: {\n csp: {\n defaultSrc: ['@self'],\n // Tailwind dynamic styles + bundled Google Fonts CSS need\n // unsafe-inline + the gstatic / googleapis hosts. Tightening\n // styles to nonces ships in 0.10.15.\n styleSrc: ['@self', '@unsafe-inline', 'https://fonts.googleapis.com'],\n scriptSrc: ['@self'],\n fontSrc: ['@self', 'data:', 'https://fonts.gstatic.com'],\n imgSrc: ['@self', 'data:', 'blob:', 'https:'],\n connectSrc: ['@self', '@trustedOrigins'],\n frameAncestors: ['@self', '@trustedOrigins'],\n formAction: ['@self'],\n baseUri: ['@self'],\n objectSrc: ['@none'],\n upgradeInsecureRequests: true,\n },\n },\n});\n```\n\n### Troubleshooting CSP violations\n\nIf the browser console shows CSP errors after enabling `security.csp`, match the directive named in the error against this table — it maps the failure mode back to the directive that needs widening.\n\n| Console error | Directive | Why it happens | Fix |\n|---|---|---|---|\n| `Loading the stylesheet 'https://fonts.googleapis.com/...' violates 'style-src ...'` | `styleSrc` | Bundled CMS/Account SPAs `<link>` to Google Fonts CSS. | Add `'https://fonts.googleapis.com'` to `styleSrc`. |\n| `Refused to load the font 'https://fonts.gstatic.com/...' because it violates 'font-src ...'` | `fontSrc` | The CSS file from googleapis loads `.woff2` files from gstatic. | Add `'https://fonts.gstatic.com'` to `fontSrc`. |\n| `Connecting to 'https://api.your-domain/...' violates 'connect-src 'self''` | `connectSrc` | API on a sibling subdomain (e.g. SPA on `app.example.com`, API on `api.example.com`) — `'self'` only covers exact origin. | Use `connectSrc: ['@self', '@trustedOrigins']` so the same allowlist `cors()` enforces gets reused. |\n| `Refused to apply inline style because it violates 'style-src ...'` | `styleSrc` | TanStack Router / Tailwind's `style=\"...\"` attributes are inline. | Add `'@unsafe-inline'` to `styleSrc` until 0.10.15 ships per-request nonces. |\n| `Refused to load the image '...' because it violates 'img-src ...'` | `imgSrc` | User-uploaded avatars / R2-hosted assets / `data:` URIs from blob previews. | Widen `imgSrc` to `['@self', 'data:', 'blob:', 'https:']` (or list specific hosts). |\n| `Refused to connect to 'wss://...' because it violates 'connect-src ...'` | `connectSrc` | Realtime / Durable Object WebSockets. | The `@trustedOrigins` sentinel covers HTTPS only — add the explicit `wss://` origin if your DO lives elsewhere. |\n\nThe general rule: `'self'` means *exact origin* (scheme + host + port). Anything cross-origin needs an explicit host or the `@trustedOrigins` sentinel. The [paste-in recipe above](#example-paste-in-csp-for-a-quickback-spa-project) is a known-good baseline for a stock Quickback project — start there and tighten, rather than starting from `'self'`-only and chasing console errors.\n\n### Auto-derivations\n\nThe compiler applies these so config stays minimal:\n\n- **`csp.frameAncestors` defaults to `['@self', '@trustedOrigins']`** when `csp` is set but `frameAncestors` is omitted. Same allowlist as CORS.\n- **`X-Frame-Options` derives from `csp.frameAncestors`** (`['@none']` → `DENY`, contains `@self` → `SAMEORIGIN`, otherwise omitted — XFO can't represent arbitrary origins so CSP becomes the truth there). Override with `security.frameOptions`.\n- **`corp: 'same-origin'` is auto-emitted when `coep` is set.** `require-corp` without CORP breaks the ASSETS binding fetches on Cloudflare; the compiler couples them so users don't have to remember.\n\n### CSP auto-config (0.10.15+)\n\nWhen you opt into a `csp` object, the compiler additively widens directives based on which Quickback features your project has enabled. **Additive** means anything you already wrote stays; we only push values that aren't already present.\n\n| Trigger | Auto-added | To directive | Why |\n|---|---|---|---|\n| `cms: true` OR `account: true` | `'unsafe-inline'` | `styleSrc` | Tailwind / TanStack Router emit inline `style=` attributes |\n| `cms: true` OR `account: true` | `https://fonts.googleapis.com` | `styleSrc` | Bundled SPAs `<link>` to Google Fonts CSS |\n| `cms: true` OR `account: true` | `https://fonts.gstatic.com` | `fontSrc` | The googleapis CSS loads `.woff2` from gstatic |\n| `csp` set (always) | `@trustedOrigins` | `connectSrc` | XHR/fetch must reach the same allowlist `cors()` permits — covers cross-subdomain APIs without re-listing them |\n| `cms: true` OR `account: true` | `https://${domain}` for each `cms.domain` / `account.domain` / `domain` / inferred unified domain | `connectSrc` | The Vite bundle hardcodes `VITE_QUICKBACK_API_URL` at compile time, so the SPA fetches that exact URL even when the page is served from a different origin (e.g. localhost dev hitting prod-baked SPA). Emitted with the host's first letter capitalised (`https://Api.example.com`) so `wrangler dev`'s response-header rewrite can't mangle it — see [the `wrangler dev` note below](#why-the-spa-baked-origin-shows-up-capitalised-in-csp). |\n\n**Scaffold rule:** if you set `defaultSrc` but omit the target directive (e.g. you wrote `defaultSrc: ['@self']` and nothing for `connectSrc`), auto-config creates the new directive seeded with your `defaultSrc` values plus the addition. `defaultSrc` itself stays clean. So `defaultSrc: ['@self']` + auto-config produces:\n\n```\ndefault-src 'self'\nstyle-src 'self' 'unsafe-inline' https://fonts.googleapis.com\nfont-src 'self' https://fonts.gstatic.com\nconnect-src 'self' @trustedOrigins https://api.your-app.com\n```\n\nEach directive is scoped to exactly what it needs. `defaultSrc` is *not* widened with style-only or connect-only hosts — that would let those hosts also reach `script-src` / `img-src` / `media-src` via fall-back, which is wider than the bundled SPA actually needs. (This rule changed in 0.10.17 — earlier versions incorrectly pushed additions into defaultSrc.)\n\n**Visibility:** every applied addition prints to stderr at compile time — one line per addition with the directive, value, and reason. No silent magic. Loop's compile output now looks like:\n\n```\n[security] auto-added 'unsafe-inline' to csp.styleSrc — account: true → bundled Account SPA → inline style attributes from Tailwind / TanStack Router\n[security] auto-added https://fonts.googleapis.com to csp.styleSrc — account: true → bundled Account SPA → loads Google Fonts CSS cross-origin\n[security] auto-added https://fonts.gstatic.com to csp.fontSrc — account: true → bundled Account SPA → woff2 font files served from gstatic.com\n[security] auto-added @trustedOrigins to csp.connectSrc — CORS-trusted origins must be reachable from XHR/fetch (matches cors() allowlist)\n```\n\n**Opt-out:** `security: { cspAutoConfig: false, csp: { ... } }` for projects fronted by a CDN that injects its own CSP, or teams that want strict from-scratch control. With auto-config off, every value above must be authored by hand.\n\n#### Why the SPA-baked origin shows up capitalised in CSP\n\nProjects with `domain: \"...\"` + bundled CMS / Account SPAs will see `connect-src 'self' https://Api.example.com …` in their served CSP — note the capital `A`. That's deliberate (added in 0.10.19) and works around a `wrangler dev` quirk, not a typo on our end.\n\n`wrangler dev` rewrites the configured `custom_domain` host string in **every** response header value (Location, Content-Security-Policy, X-…) to the local hostname, with a case-sensitive substring matcher. Without the case-shift, the served CSP becomes `connect-src 'self' https://localhost:8787 …` and the bundled SPA's hardcoded `VITE_QUICKBACK_API_URL` fetches get blocked because the prod URL no longer appears in the allowlist.\n\nCSP host-source matching is ASCII case-insensitive per CSP3 (`Matching Source Expressions`), so browsers treat `https://Api.example.com` as identical to `https://api.example.com` for the purpose of CSP checks. Wrangler's matcher is case-sensitive, so the capitalised form slips past the rewrite and survives into the served header. End result: the SPA's lowercase fetch target matches the capitalised CSP entry, auth round-trips work in dev, and prod CSP behaviour is unchanged (browsers don't care).\n\nIf wrangler ever fixes the response-header rewrite, the capitalised form remains a valid CSP entry — no follow-up needed.\n\nWith auto-config on, the [paste-in recipe above](#example-paste-in-csp-for-a-quickback-spa-project) becomes much shorter — most users only need:\n\n```ts\nsecurity: {\n csp: {\n defaultSrc: ['@self'],\n scriptSrc: ['@self'],\n imgSrc: ['@self', 'data:', 'blob:', 'https:'],\n objectSrc: ['@none'],\n upgradeInsecureRequests: true,\n },\n}\n```\n\nThe compiler fills in the SPA-specific font hosts, inline-style allowance, and trusted-origin connect rules from the project's own feature flags.\n\n## Cross-origin window/embedder isolation\n\n```ts title=\"quickback.config.ts\"\nsecurity: {\n coop: 'same-origin', // Defends against window.opener back-references from popups.\n coep: 'credentialless', // Required for SharedArrayBuffer / cross-origin isolation.\n // corp auto-emits as 'same-origin' here.\n}\n```\n\n## HSTS\n\nDefault: `max-age=31536000; includeSubDomains; preload` (HSTS preload-list eligible).\n\n```ts title=\"quickback.config.ts\"\nsecurity: {\n hsts: { maxAge: 63072000, includeSubDomains: true, preload: true },\n}\n```\n\nThe generated middleware automatically suppresses HSTS on `localhost`, `127.0.0.1`, and `*.localhost` regardless of this config. Without that gate, `wrangler dev` would pin the developer's browser to HTTPS for `maxAge` seconds, which is observable across every project on that machine.\n\nTo submit to the [HSTS preload list](https://hstspreload.org), you need:\n\n- `maxAge` ≥ 31536000 (one year)\n- `includeSubDomains: true`\n- `preload: true`\n\nThe compiler warns at compile time if `preload: true` without the other two — the preload list rejects either anyway.\n\n## Permissions Policy\n\nMap of feature name → list of allowed origins.\n\n```ts title=\"quickback.config.ts\"\nsecurity: {\n permissionsPolicy: {\n geolocation: [], // disabled for everyone\n microphone: ['self'], // allowed only on own origin\n camera: ['self', 'https://meet.example.com'],\n payment: [],\n },\n}\n```\n\nThe compiler encodes the wire syntax (which differs from CSP — values use `()`, not space-separated tokens, with bareword `self` and quoted URLs).\n\n## Custom response headers\n\n`security.headers` sets arbitrary response headers on every response, alongside the managed security headers. Keys are header names; values are static strings or templates that interpolate per-deploy Worker env vars via the `{{env.VAR_NAME}}` token.\n\n```ts title=\"quickback.config.ts\"\nsecurity: {\n headers: {\n // Stamp the deployed build identity. Read from Worker vars at runtime,\n // so the value tracks whatever you inject at deploy time.\n 'X-Server-Version': '{{env.SERVER_VERSION}}+{{env.SERVER_BUILD}}',\n\n // Static value — always emitted.\n 'X-Powered-By': 'Quickback',\n },\n}\n```\n\nThe canonical use case is exposing a build/version identity on every response so clients (`curl -I`, mobile apps, dashboards) can read the running build without a body request — and so you can detect drift between what's deployed and what git/CF report.\n\n### Omit-if-unset\n\nA header whose value references env vars is emitted **only when every referenced var is set** (non-`undefined`, non-empty string) at runtime. A version header on a Worker that forgot to inject the var simply doesn't appear — never `X-Server-Version: undefined`. Static headers (no `{{env…}}`) are always emitted.\n\nThe value is read from `c.env` per request, so you don't declare these vars at compile time — inject them as Worker vars (`[vars]` in `wrangler.toml`, or `--var` at deploy) and the header picks them up.\n\n### Generated middleware\n\nFor the config above, the compiler appends this to the security-headers middleware — no post-compile patching:\n\n```ts\n// Custom response headers (security.headers).\n{\n const v0 = (c.env as unknown as Record<string, string | undefined>)[\"SERVER_VERSION\"];\n const v1 = (c.env as unknown as Record<string, string | undefined>)[\"SERVER_BUILD\"];\n if (v0 != null && v0 !== '' && v1 != null && v1 !== '') {\n c.header(\"X-Server-Version\", `${v0}+${v1}`);\n }\n}\nc.header(\"X-Powered-By\", \"Quickback\");\n```\n\n### Rules\n\n- **Header names** must be valid HTTP field tokens. Names already managed by a dedicated `security` field — `Content-Security-Policy`, `Strict-Transport-Security`, `X-Frame-Options`, `X-Content-Type-Options`, `Cross-Origin-Opener-Policy`/`-Embedder-Policy`/`-Resource-Policy`, `Referrer-Policy`, `Permissions-Policy` — are rejected; use that field instead so the two emitters don't race.\n- **Only `{{env.VAR_NAME}}`** interpolation is supported (`VAR_NAME` is a valid env-var identifier). A malformed token (`{{env.FOO}`, `{{ENV.FOO}}`) is a compile-time error rather than leaking literal braces into the wire header.\n\n## Compile-time lint rules\n\nThe compiler walks the resolved config and emits warnings (or errors) for known footguns. Errors block compile; warnings print to stderr.\n\n| Code | Severity | Trigger |\n|---|---|---|\n| `csp/nonce-not-yet-supported` | error | `@nonce` sentinel used in 0.10.14. Per-request nonce middleware ships in 0.10.15. |\n| `csp/unsafe-inline-with-nonce` | error | `@unsafe-inline` and `@nonce` in the same directive (CSP3 silently ignores `unsafe-inline` when nonce is present). |\n| `csp/empty-resolved-directive` | error | `*Src` array contains only `@trustedOrigins` and `auth.trustedOrigins` is empty — would emit a directive Chrome reads as `'none'`. |\n| `csp/unsafe-inline-script` | warn | `@unsafe-inline` in `scriptSrc` defeats most XSS mitigations. |\n| `csp/open-source` | warn | Wildcard `*` or scheme-only `https:` / `http:` in any `*-src`. |\n| `csp/unsafe-eval-with-data` | warn | `@unsafe-eval` combined with any `data:` source — trivial bypass. |\n| `csp/missing-default-src` | warn | Other `*-src` set without `defaultSrc`. |\n| `csp/upgrade-with-http` | warn | `upgradeInsecureRequests: true` plus an `http://` source elsewhere. |\n| `csp/report-uri-only` | warn | `reportUri` set without `reportTo` (deprecated CSP2 path). |\n| `hsts/preload-needs-long-max-age` | warn | `preload: true` with `maxAge < 31536000`. |\n| `hsts/preload-needs-include-subdomains` | warn | `preload: true` without `includeSubDomains`. |\n\n## Verification\n\nSpin up the deployed Worker (or `wrangler dev`) and check the response headers:\n\n```bash\ncurl -sI https://my-api.example.com/health \\\n | grep -E '^(content-security-policy|x-frame-options|strict-transport-security|cross-origin-opener-policy|cross-origin-embedder-policy|cross-origin-resource-policy|referrer-policy|permissions-policy):'\n```\n\nUse [securityheaders.com](https://securityheaders.com) for an external grade — Quickback's defaults are A on the baseline and A+ once a fuller `csp` is configured."
67
67
  },
68
68
  "compiler/config/single-tenant": {
69
69
  "title": "Pinned Organization Mode",
@@ -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 / reserved markers (`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 roles | `\"owner\"`, `\"admin\"`, `\"member\"` |\n| `userRole` | `ctx.userRole` | The `user.role` column (Better Auth / platform control-plane roles) | `\"user\"`, `\"appmanager\"`, `\"sysadmin\"` |\n\nIn multi-tenant mode, **`roles: [\"admin\"]` means \"org admin\" — not a platform-wide role.** An org-admin of Acme Corp has no elevated rights across other orgs. If you want platform control-plane operators through regardless of org membership (CMS, Better Auth admin surfaces, support tooling), use `userRole: [\"appmanager\"]`. If you need true cross-tenant data-plane access, use `roles: [\"SYSADMIN\"]` (with `cms: { sysadmin: true }`).\n\nPinned organization mode does not change this split. `roles` still come from organization membership in the pinned org, while `userRole` still comes from Better Auth's `user.role` column.\n\n### When to use `userRole`\n\n```typescript\n// Platform control-plane users can see SSNs on every customer record, regardless of org\nmasking: {\n ssn: { type: 'ssn', show: { userRole: ['appmanager'] } },\n}\n\n// Platform ops (user.role === 'appmanager') OR the org owner can refund\naccess: {\n or: [\n { userRole: ['appmanager'] },\n { roles: ['owner'] },\n ],\n}\n\n// CMS-internal resource: only platform control-plane users\nread: { access: { userRole: ['appmanager'] } },\ncreate: { access: { userRole: ['appmanager'] } },\nupdate: { access: { userRole: ['appmanager'] } },\ndelete: { access: { userRole: ['appmanager'] } },\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\"`, `\"appmanager\"`, and `\"sysadmin\"`). If you've added custom user-table roles via Better Auth, list them explicitly.\n\n### Pseudo-roles\n\nQuickback ships five reserved UPPERCASE markers. Four are real pseudo-roles handled directly by the compiler; `ADMIN` is retained only as a reserved legacy marker so the compiler can fail loudly with migration guidance. The casing carries the boundary: UPPERCASE = compiler-owned marker, 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 | reserved legacy marker — compiler rejects it | `false` |\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 — appmanagers and sysadmins are excluded. If the same route should serve both, express it explicitly with `or: [{ roles: [\"USER\"] }, { userRole: [\"appmanager\"] }]`.\n\n#### `ADMIN` — legacy reserved marker (compile-time error)\n\n`roles: [\"ADMIN\"]` is no longer supported. The compiler fails hard on any use of `ADMIN` so platform and tenant roles can't be confused.\n\n```typescript\n// Platform control-plane audit log\nread: { access: { userRole: [\"appmanager\"] } }\n```\n\nUse one of these instead:\n\n- `userRole: [\"appmanager\"]` for platform control-plane access\n- `roles: [\"admin\"]` for org-membership admin access\n- `roles: [\"SYSADMIN\"]` for true cross-tenant access\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 distinct from `userRole: [\"appmanager\"]`. Appmanager is the platform control-plane tier (CMS shell, Better Auth admin surfaces, support tooling); sysadmin is the cross-tenant data-plane tier. 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 === 'appmanager'`; appmanagers still go through the firewall like everyone else.\n\nThis separation exists so Better Auth admin-plugin powers (user management, impersonation, org creation) and DB-admin powers (cross-tenant data inspection) stay decoupled. A user can have `user.role === 'appmanager'` 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 platform control-plane user can read\nread: { access: { or: [{ roles: [\"USER\"] }, { userRole: [\"appmanager\"] }] } }\n\n// Org owner OR sysadmin\ndelete: { access: { or: [{ roles: [\"owner\"] }, { roles: [\"SYSADMIN\"] }] } }\n```\n\n> Note: `userRole: [\"appmanager\"]` never bypasses a `userId` firewall scope. If you need cross-user visibility, expose a separate route with `firewall: { exception: true }` or a `SYSADMIN`-gated cross-tenant surface.\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// Platform control-plane\naccess: { userRole: [\"appmanager\"] }\n\n// Cross-tenant DB-admin tier\naccess: { roles: [\"SYSADMIN\"] }\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 / SYSADMIN) and `firewall: { exception: true }` still bypass the preconditions as before. `ADMIN` is now rejected at compile time.\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)"
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 / reserved markers (`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 roles | `\"owner\"`, `\"admin\"`, `\"member\"` |\n| `userRole` | `ctx.userRole` | The `user.role` column (Better Auth / platform control-plane roles) | `\"user\"`, `\"appmanager\"`, `\"sysadmin\"` |\n\nIn multi-tenant mode, **`roles: [\"admin\"]` means \"org admin\" — not a platform-wide role.** An org-admin of Acme Corp has no elevated rights across other orgs. If you want platform control-plane operators through regardless of org membership (CMS, Better Auth admin surfaces, support tooling), use `userRole: [\"appmanager\"]`. If you need true cross-tenant data-plane access, use `roles: [\"SYSADMIN\"]` (with `cms: { sysadmin: true }`).\n\nPinned organization mode does not change this split. `roles` still come from organization membership in the pinned org, while `userRole` still comes from Better Auth's `user.role` column.\n\n### When to use `userRole`\n\n```typescript\n// Platform control-plane users can see SSNs on every customer record, regardless of org\nmasking: {\n ssn: { type: 'ssn', show: { userRole: ['appmanager'] } },\n}\n\n// Platform ops (user.role === 'appmanager') OR the org owner can refund\naccess: {\n or: [\n { userRole: ['appmanager'] },\n { roles: ['owner'] },\n ],\n}\n\n// CMS-internal resource: only platform control-plane users\nread: { access: { userRole: ['appmanager'] } },\ncreate: { access: { userRole: ['appmanager'] } },\nupdate: { access: { userRole: ['appmanager'] } },\ndelete: { access: { userRole: ['appmanager'] } },\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\"`, `\"appmanager\"`, and `\"sysadmin\"`). If you've added custom user-table roles via Better Auth, list them explicitly.\n\n### Pseudo-roles\n\nQuickback ships five reserved UPPERCASE markers. Four are real pseudo-roles handled directly by the compiler; `ADMIN` is retained only as a reserved legacy marker so the compiler can fail loudly with migration guidance. The casing carries the boundary: UPPERCASE = compiler-owned marker, 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 | reserved legacy marker — compiler rejects it | `false` |\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 `403` 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 — appmanagers and sysadmins are excluded. If the same route should serve both, express it explicitly with `or: [{ roles: [\"USER\"] }, { userRole: [\"appmanager\"] }]`.\n\n#### `ADMIN` — legacy reserved marker (compile-time error)\n\n`roles: [\"ADMIN\"]` is no longer supported. The compiler fails hard on any use of `ADMIN` so platform and tenant roles can't be confused.\n\n```typescript\n// Platform control-plane audit log\nread: { access: { userRole: [\"appmanager\"] } }\n```\n\nUse one of these instead:\n\n- `userRole: [\"appmanager\"]` for platform control-plane access\n- `roles: [\"admin\"]` for org-membership admin access\n- `roles: [\"SYSADMIN\"]` for true cross-tenant access\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 distinct from `userRole: [\"appmanager\"]`. Appmanager is the platform control-plane tier (CMS shell, Better Auth admin surfaces, support tooling); sysadmin is the cross-tenant data-plane tier. 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 === 'appmanager'`; appmanagers still go through the firewall like everyone else.\n\nThis separation exists so Better Auth admin-plugin powers (user management, impersonation, org creation) and DB-admin powers (cross-tenant data inspection) stay decoupled. A user can have `user.role === 'appmanager'` 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 platform control-plane user can read\nread: { access: { or: [{ roles: [\"USER\"] }, { userRole: [\"appmanager\"] }] } }\n\n// Org owner OR sysadmin\ndelete: { access: { or: [{ roles: [\"owner\"] }, { roles: [\"SYSADMIN\"] }] } }\n```\n\n> Note: `userRole: [\"appmanager\"]` never bypasses a `userId` firewall scope. If you need cross-user visibility, expose a separate route with `firewall: { exception: true }` or a `SYSADMIN`-gated cross-tenant surface.\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// Platform control-plane\naccess: { userRole: [\"appmanager\"] }\n\n// Cross-tenant DB-admin tier\naccess: { roles: [\"SYSADMIN\"] }\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 / SYSADMIN) and `firewall: { exception: true }` still bypass the preconditions as before. `ADMIN` is now rejected at compile time.\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). 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- sysadmin gate (`ctx.userRole === \"sysadmin\"`)\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 organizationId: { equals: \"$ctx.activeOrgId\" }\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- sysadmin gate (`ctx.userRole === \"sysadmin\"`)\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, activeOrgId, activeTeamId, userRole)\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#### Reaching Better Auth tables (`authDb`)\n\nThe scoped `db` only sees your feature tables. To read Better Auth tables —\nusers, organizations, members — use the auth database connection from the\nHono context plus the generated `lib/org-access.ts` helper:\n\n```typescript\n// features/projects/actions/assign.ts — validate a userId is an org member\n\nexport default defineAction({\n description: \"Assign a project to an org member\",\n input: z.object({ assigneeId: z.string() }),\n access: { roles: [\"member\", \"admin\"] },\n async execute({ db, record, input, ctx, c, whereRecord }) {\n // getOrgMemberRole(authDb, userId, organizationId) → role string | null\n const role = await getOrgMemberRole(c.get(\"authDb\"), input.assigneeId, ctx.activeOrgId!);\n if (!role) {\n throw new ActionError(\"Assignee is not a member of this organization\", \"NOT_A_MEMBER\", 400);\n }\n const [updated] = await db\n .update(projects)\n .set({ assigneeId: input.assigneeId })\n .where(whereRecord!(projects))\n .returning();\n return updated;\n },\n});\n```\n\n`c.get(\"authDb\")` is the Drizzle connection to the auth database (in dual-DB\nmode it's a separate D1 from your features). For richer queries, import the\nauth schema tables from `../../../auth/schema` and query `authDb` directly.\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 = 400, details?)`. The compile step rewrites the `@quickback/compiler` import to the generated runtime class (`src/lib/types.ts`), and the route handler catches it by name and returns `{ error, code, details }` with your `statusCode`.\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/arrows": {
85
85
  "title": "Arrows",
@@ -131,7 +131,7 @@ export const DOCS = {
131
131
  },
132
132
  "compiler/definitions/scopes": {
133
133
  "title": "Scopes & Capability Grants",
134
- "content": "Org membership answers *\"which tenant is this caller in?\"* Scopes answer a different question: *\"this caller isn't an org member, but they're a **confirmed attendee of event E** — let them see exactly E's rows, as exactly the role they hold, and nothing else.\"*\n\nA **scope** is a tenant axis whose value is established by a **relationship you prove once** (at `POST /scope/v1/enter`) and then carry in a signed JWT claim — verified cryptographically on every later request with **no database round-trip**. It's the REST/JWT twin of the realtime ws-ticket.\n\n## When to use it\n\nReach for a scope when a principal must touch a bounded slice of an instance **without being an org member**:\n\n- **Event attendee** — reads their event's announcements / sessions, not the org.\n- **Shuttle driver** — sees only the passengers on *their* bus (a row slice), can DM them.\n- **F&B vendor** — reads dietary *counts*, zero attendee rows.\n- **Visiting nurse / carrier / contractor** — one patient's meds, one carrier's shipments.\n\nEach is *event-scoped* but a **distinct least-privilege role**. Org members are unaffected — they keep their normal tenant access.\n\n## The model\n\n### 1. Declare relationships + scopes\n\nA scope **kind** (`event`) declares named **roles**, each conferred by a relationship whose `from` row carries the role (and optionally a **sub-key** for row slicing):\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: { from: 'guests', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { status: 'confirmed' } },\n organizerOf: { from: 'staff', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { role: 'organizer' } },\n shuttleDriverOf: { from: 'staff', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { role: 'shuttleDriver' } },\n },\n scopes: {\n event: {\n requestField: 'eventId', // the body field the client sends to /enter\n roles: {\n attendee: { via: 'attendeeOf' },\n organizer: { via: 'organizerOf' },\n shuttleDriver: { via: 'shuttleDriverOf', subKeys: ['shuttleId'] }, // row-slice sub-key\n },\n },\n },\n}\n```\n\n### 2. Enter the scope\n\n```http\nPOST /scope/v1/enter (session OR existing JWT auth)\n{ \"eventId\": \"evt_123\" }\n```\n\nThe server probes **every declared role** for the proposed instance (one DB touch), and mints the proven roles + sub-keys into a signed JWT `scope` claim, returned via the `set-auth-token` header and the body:\n\n```jsonc\n// a shuttle driver who is also a confirmed guest\n\"scope\": { \"event\": { \"id\": \"evt_123\", \"roles\": [\"attendee\", \"shuttleDriver\"], \"shuttleId\": \"shA\" } }\n```\n\nThe client sends that JWT as `Authorization: Bearer …` on subsequent requests. The auth middleware verifies the signature and sets `ctx.scope` — **no DB**. The claim is carried forward on every authed call (rolling refresh) until you `enter` a different instance.\n\n> **Invariant:** the client only *proposes* the instance id (from the URL). The server proves membership before signing. No client-asserted scope is ever trusted.\n\n### 3. Gate the pillars\n\nScoped roles are referenced everywhere a pillar takes a role as the namespaced identifier **`scope:<kind>:<role>`**:\n\n```typescript\n// features/guests/guests.ts — the manifest, row-sliced + PII-masked\nexport default feature('guests', {\n columns: { /* … eventId, shuttleId, email, … */ },\n // org staff see the whole event; a shuttle driver sees only their bus\n firewall: {\n any: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { all: [\n { field: 'eventId', equals: 'ctx.scope.event' },\n { field: 'shuttleId', equals: 'ctx.scope.event.shuttleId' }, // sub-key row slice\n ] },\n ],\n },\n masking: {\n email: { type: 'email', show: { roles: ['admin', 'scope:event:organizer'] } }, // hidden from the driver\n },\n read: {\n views: {\n manifest: {\n fields: ['id', 'nameAtInvite', 'shuttleId', 'pickupLocation'],\n access: { roles: ['admin', 'scope:event:organizer', 'scope:event:shuttleDriver'] },\n },\n },\n },\n});\n```\n\n| Pillar | How it reads the scoped role |\n|--------|------------------------------|\n| **Firewall** (rows) | `all`/`any` arms keyed on `ctx.scope.<kind>` (+ sub-keys) — see [Firewall](/compiler/definitions/firewall) |\n| **Access** (verbs/views) | `access.roles: ['scope:event:shuttleDriver']` on CRUD, actions, and views |\n| **Masking** (fields) | `masking.<col>.show.roles` includes / excludes `scope:event:<role>` |\n\n## The org / scope split (security)\n\n**Scoped roles never merge into `ctx.roles`.** A `scope:*` identifier matches **only** the verified scope claim (`ctx.scope.<kind>.roles`); a bare org role (`admin`, `member`) matches **only** `ctx.roles`. The compiler enforces the split so an externally-provisioned `shuttleDriver` can **never** satisfy an `admin` gate by string coincidence, and a tampered scope claim can't impersonate an org role. This is the precondition for admitting limited outside users at all.\n\n## Sub-keys (row slicing)\n\nA role's `subKeys` name columns on the relationship's `from` row that are projected into the claim. A firewall arm then slices on them:\n\n```typescript\n{ field: 'shuttleId', equals: 'ctx.scope.event.shuttleId' }\n```\n\nBecause sub-key arms compose with `all`, an **absent** sub-key denies (`sql\\`1 = 0\\``) rather than widening — a driver can never see *all* shuttles by simply lacking the claim. The scope accessor is always emitted null-safe (`ctx.scope?.event?.shuttleId`), so an org caller who never entered the scope hits a clean deny, not a 500.\n\n### Set-valued sub-keys\n\nA driver may cover **more than one** bus. Append a `[]` marker to the\nsub-key name to project **every** matched `from` row's value into the claim\nas a `string[]`:\n\n```typescript\nroles: {\n shuttleDriver: { via: 'shuttleDriverOf', subKeys: ['shuttleId[]'] }, // set-valued\n}\n```\n\nThe `[]` is a marker only — it's stripped from the column name (the\nrelationship's `from` row still reads `shuttleId`). At `/scope/v1/enter` the\nproven rows union their values, so the claim carries an array:\n\n```jsonc\n\"scope\": { \"event\": { \"id\": \"evt_123\", \"roles\": [\"shuttleDriver\"], \"shuttleId\": [\"shA\", \"shC\"] } }\n```\n\nThe matching firewall arm — written exactly as for the scalar case\n(`{ field: 'shuttleId', equals: 'ctx.scope.event.shuttleId' }`) — is\n**rewritten by the compiler** to an `inArray` row-slice:\n\n```sql\nWHERE shuttle_id IN (ctx.scope?.event?.shuttleId ?? [])\n```\n\nThe `?? []` default makes an absent claim lower to `inArray(col, [])` — a\nclean DENY, never a malformed SQL fragment or a 500. A scalar sub-key (no\n`[]` marker) is untouched and keeps lowering to `eq`. You write the same\n`equals` arm either way; declaring `shuttleId[]` vs `shuttleId` in the scope\nrole is the only switch.\n\n## Auto-stamping the scope column on insert (`q.scope`)\n\n`q.scope('organization')` auto-stamps the tenant column on write, the same\nway `q.scope('owner')` stamps `ownerId`. A relationship-derived kind works\nidentically: `q.scope('event')` auto-stamps the column from the **verified\nscope claim** (`ctx.scope.event.id`) on insert — no need to pass `eventId`\nin the request body:\n\n```typescript\nexport const eventNotes = q.table('event_notes', {\n id: q.id(),\n eventId: q.scope('event'), // INSERT autofill from ctx.scope.event.id\n body: q.text().required(),\n organizationId: q.scope('organization'), // INSERT autofill from ctx.activeOrgId\n});\n```\n\nThe stamp is **insert-only** and null-safe — the generated CREATE handler\nwrites `eventId: ctx.scope?.event?.id`, so it never binds `undefined`. It\ndoes **not** add a read-time `WHERE` filter (that's the firewall's job; a\nread scoped to `eventId = ctx.scope.event.id` would be wrong here). Infra\nkinds map to their session fields (`organization` → `ctx.activeOrgId`,\n`owner` → `ctx.userId`, `team` → `ctx.activeTeamId`); any other kind maps to\n`ctx.scope.<kind>.id`.\n\n## Namespace scope-claim refresh\n\nA scope is normally minted at `POST /scope/v1/enter`. When you also mount a\n[namespace](/compiler/definitions/access#namespace-mounts-hoisted-relationship-middleware)\nthat gates `/event/:eventId/*` on the **same** relationship, the namespace\nresolver can refresh `ctx.scope.<kind>` in memory for the duration of that\nrequest — so an attendee hitting `/event/evt_123/announce` gets\n`ctx.scope.event = { id: 'evt_123', roles: ['attendee'] }` without a separate\n`enter` round-trip. The refresh runs **after** the gate (the gate proves the\nrelationship; the refresh stamps the proven role from the path param).\n\nThis is a strictly-guarded convenience, and it stamps **per matched lane**. The\nresolver records which `via:` lane opened the gate (first-match-wins) and stamps\n**only that lane's** scope role — an attendee who matched `attendeeOf` gets\n`roles: ['attendee']`; an organizer who matched `organizerOf` gets\n`roles: ['organizer']`. A caller can never receive a role they didn't prove this\nrequest.\n\n- **Relationship lanes** each confer their own scope role, stamped only when that exact lane matched — so a **multi-lane `via:`** (e.g. `via: ['attendeeOf', 'organizerOf']`) refreshes the matched lane's role, not an ambiguous union.\n- A **bulk-grant lane** (`{ roles: [...] }` or `{ team: true }`) confers **no** scope role — it opens the gate via the caller's org role *without* proving any relationship, so there is nothing to stamp (stamping one would forge it). The gate still passes; the caller is simply authorized by their org role.\n\nThe refresh described so far is in-memory and single-request. To also hand the\ncaller a **persisted** scope token, opt the namespace into `mintScope` — see\nbelow.\n\n### Gotcha: a namespace only emits its resolver when it claims a standalone action\n\nThis is the single most common surprise (it has tripped up a customer): **a\nnamespace emits its resolver — and therefore the scope refresh and the\n[`mintScope`](#mintscope-mint-the-scope-token-from-the-namespace-resolver)\nmint — only when at least one STANDALONE action's `path:` falls under the\nnamespace prefix.**\n\nA standalone action declares its own `path:` (e.g.\n`path: '/event/:eventId/home'`), so the compiler can match it against the\nnamespace prefix and hoist it into the synthetic namespace routes file.\n**Record-based actions are different** — they mount under their resource's CRUD\nroutes (`/api/v1/guests/:id/checkin`), which live *outside* the\n`/event/:eventId` prefix. They never match the prefix, so they never get\nclaimed.\n\nA namespace that contains **only** record-based actions is therefore **inert**:\nnothing matches the prefix, no synthetic routes file is emitted, and so there\nis **no resolver, no scope refresh, and no mint** — even though the namespace\nis declared and validates cleanly. The middleware you expected to gate\n`/event/:eventId/*` simply isn't there.\n\nThe fix is to give the namespace at least one standalone action under the\nprefix. In `q-events`, `eventHome` exists precisely for this — a standalone\n`GET /event/:eventId/home` that pulls the resolver (and the §5.3 mint) into\nexistence:\n\n```typescript\n// features/events/actions/eventHome.ts\nexport default defineAction({\n path: '/event/:eventId/home', // ← standalone path UNDER the namespace prefix\n method: 'GET',\n input: z.object({}),\n access: { roles: ['scope:event:attendee', 'scope:event:organizer', 'manager+'] },\n async execute({ db, ctx, c }) { /* … */ },\n});\n```\n\nWith that action present, the `eventScope` resolver is emitted, runs the\n`attendeeOf` probe once per `/event/:eventId/*` request, stamps\n`ctx.scope.event`, and (because the namespace sets `mintScope: true`) mints the\nscope token. Without a standalone action under the prefix, none of that fires.\n\n## `mintScope` — mint the scope token from the namespace resolver\n\nA scope is normally minted by an explicit `POST /scope/v1/enter` round-trip.\nSetting **`mintScope: true`** on a namespace folds that mint into the\nnamespace resolver: on a successful relationship probe the resolver MINTS a\npersisted scope JWT and returns it via the `set-auth-token` header — so a\nnative client hitting `/event/:eventId/*` gets a scope token **without ever\ncalling `/scope/v1/enter`**.\n\n```typescript\n// quickback.config.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: 'guests',\n exposeAs: 'guest',\n },\n },\n namespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: ['attendeeOf'], // one or more lanes — mints the matched lane's role\n mintScope: true, // ← fold the scope-token mint into the resolver\n },\n },\n}\n```\n\nA confirmed attendee then hits the standalone action under the prefix:\n\n```http\nGET /api/v1/event/evt_123/home\nAuthorization: Bearer <existing-jwt>\n\n200 OK\nset-auth-token: <new-scoped-jwt> ← carries scope.event.roles = [\"attendee\"]\n```\n\nThe client stores the `set-auth-token` value and sends it as the bearer on\nevery subsequent `/event/:eventId/*` request. The JWT carries\n`scope.event = { id: 'evt_123', roles: ['attendee'] }`, so the scoped-role\naccess checks (`scope:event:attendee`) pass with no DB touch and no second\n`enter` call.\n\n`mintScope` is **opt-in per namespace** and defaults to `false`. With it off,\nthe resolver does the in-memory `ctx.scope.<kind>` refresh only (the section\nabove); subsequent requests must still call `/scope/v1/enter` for a persisted\ntoken.\n\n### Per-matched-lane minting (forging safety)\n\nThe mint stamps the scope role of **whichever lane matched**, gated on the\nfirst-match-wins probe — the *same* per-lane discipline as the in-memory stamp,\napplied here with higher stakes: a minted token **persists for its whole TTL**,\nso it can only ever carry the role the caller actually proved this request.\n\n- A **multi-lane `via:`** (e.g. `via: ['attendeeOf', 'organizerOf']`) mints the matched lane's role — `attendeeOf` → `scope.event.roles = ['attendee']`, `organizerOf` → `['organizer']`. The resolver records which lane opened the gate, so there is no ambiguity.\n- A **bulk-grant lane** (`{ roles: [...] }` or `{ team: true }`) mints **no** scope role — it opens the gate via the caller's org role without proving a relationship. The gate passes; the caller carries their org role, not a minted scope role.\n\n> The realtime [ws-ticket](/stack/realtime/durable-objects#namespace-backed-tickets-per-matched-lane) can authorize through this same namespace `via:`, issuing a per-matched-lane WebSocket ticket — so the socket gate and the REST gate stay identical.\n\nIn every suppressed case the gate still authorizes the request; only the mint\n(and the in-memory refresh) are skipped, and those callers obtain a scope\ntoken through `/scope/v1/enter` as usual. Flipping `mintScope: true` can never\nforge a scope role — the guard, not the flag, is the gate.\n\n### TTL and best-effort semantics\n\n- **TTL is the scope-token TTL** — `auth.jwt.expiresIn` (default 180s), **clamped to a hard ≤180s ceiling** at the mint site. A longer-lived scope token would widen the post-revocation replay window past the spec bound, so the clamp is non-negotiable.\n- **The mint is gated by the same proven-relationship guard as the in-memory stamp.** It runs *after* the gate has granted access, reading the instance id from the proven path param (`:eventId`) — never from request input — so the minted `scope:<kind>:<role>` is backed by exactly the proof `/scope/v1/enter` requires. The token is **byte-identical** to one `/scope/v1/enter` would produce: same shared mint helper, same carry-forward of any *other* verified scope kinds already on the incoming token (the freshly-proven kind takes precedence; siblings survive the re-mint).\n- **The mint is best-effort.** A mint failure (e.g. a missing signing secret) **never fails the request** — the in-memory stamp already authorized it; the caller simply doesn't receive a refreshed token on that response and can fall back to `/scope/v1/enter`.\n\n## Revocation & TTL\n\nThe scope claim is trusted for the JWT TTL (default 180s, `auth.jwt.expiresIn`) — identical to how `orgId` / `role` claims already behave. Removing a guest/staff row takes effect within one TTL (the next `enter` won't re-mint the role). Immediate revocation (`auth.jwt.revocationCheck: 'kv'`) is on the roadmap.\n\n## Reference\n\n```typescript\n// AppContext (generated lib/types.ts)\nctx.scope?: Record<string, { id: string; roles?: string[]; [subKey: string]: string | string[] | undefined }>;\n\n// authz.scopes.<kind>\n{\n requestField: string; // body field carrying the instance id\n roles: Record<string, { via: string; subKeys?: string[] }>; // 'col' → eq, 'col[]' → inArray\n}\n```\n\n- `requestField` must equal every role-relationship's `resource.column`.\n- Each relationship's `from` table must exist and ship a generated firewall (it can't be `exception`).\n- A `subKeys` entry ending in `[]` is **set-valued** (lowers to `inArray`, minted as `string[]`); without the marker it's scalar (`eq`, minted as `string`).\n- `q.scope('<kind>')` auto-stamps the column from `ctx.scope.<kind>.id` on insert.\n- Generated route: `POST /scope/v1/enter` (mounted only when `authz.scopes` is declared)."
134
+ "content": "Org membership answers *\"which tenant is this caller in?\"* Scopes answer a different question: *\"this caller isn't an org member, but they're a **confirmed attendee of event E** — let them see exactly E's rows, as exactly the role they hold, and nothing else.\"*\n\nA **scope** is a tenant axis whose value is established by a **relationship you prove once** (at `POST /scope/v1/enter`) and then carry in a signed JWT claim — verified cryptographically on every later request with **no database round-trip**. It's the REST/JWT twin of the realtime ws-ticket.\n\n## When to use it\n\nReach for a scope when a principal must touch a bounded slice of an instance **without being an org member**:\n\n- **Event attendee** — reads their event's announcements / sessions, not the org.\n- **Shuttle driver** — sees only the passengers on *their* bus (a row slice), can DM them.\n- **F&B vendor** — reads dietary *counts*, zero attendee rows.\n- **Visiting nurse / carrier / contractor** — one patient's meds, one carrier's shipments.\n\nEach is *event-scoped* but a **distinct least-privilege role**. Org members are unaffected — they keep their normal tenant access.\n\n## The model\n\n### 1. Declare relationships + scopes\n\nA scope **kind** (`event`) declares named **roles**, each conferred by a relationship whose `from` row carries the role (and optionally a **sub-key** for row slicing):\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: { from: 'guests', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { status: 'confirmed' } },\n organizerOf: { from: 'staff', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { role: 'organizer' } },\n shuttleDriverOf: { from: 'staff', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { role: 'shuttleDriver' } },\n },\n scopes: {\n event: {\n requestField: 'eventId', // the body field the client sends to /enter\n roles: {\n attendee: { via: 'attendeeOf' },\n organizer: { via: 'organizerOf' },\n shuttleDriver: { via: 'shuttleDriverOf', subKeys: ['shuttleId'] }, // row-slice sub-key\n },\n },\n },\n}\n```\n\n### 2. Enter the scope\n\n```http\nPOST /scope/v1/enter (session OR existing JWT auth)\n{ \"eventId\": \"evt_123\" }\n```\n\nThe server probes **every declared role** for the proposed instance (one DB touch), and mints the proven roles + sub-keys into a signed JWT `scope` claim, returned via the `set-auth-token` header and the body:\n\n```jsonc\n// a shuttle driver who is also a confirmed guest\n\"scope\": { \"event\": { \"id\": \"evt_123\", \"roles\": [\"attendee\", \"shuttleDriver\"], \"shuttleId\": \"shA\" } }\n```\n\nThe client sends that JWT as `Authorization: Bearer …` on subsequent requests. The auth middleware verifies the signature and sets `ctx.scope` — **no DB**. The claim is carried forward on every authed call (rolling refresh) for up to **15 minutes from the last actual relationship proof** — the mint stamps a proof timestamp (`sct`) that the refresh carries forward verbatim and checks against the carry-forward cap. Past the cap the refresh stops, the token expires within one TTL, and the client re-proves via `enter` (or any namespace route that mints) to restart the window.\n\n> **Invariant:** the client only *proposes* the instance id (from the URL). The server proves membership before signing. No client-asserted scope is ever trusted.\n\n### 3. Gate the pillars\n\nScoped roles are referenced everywhere a pillar takes a role as the namespaced identifier **`scope:<kind>:<role>`**:\n\n```typescript\n// features/guests/guests.ts — the manifest, row-sliced + PII-masked\nexport default feature('guests', {\n columns: { /* … eventId, shuttleId, email, … */ },\n // org staff see the whole event; a shuttle driver sees only their bus\n firewall: {\n any: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { all: [\n { field: 'eventId', equals: 'ctx.scope.event' },\n { field: 'shuttleId', equals: 'ctx.scope.event.shuttleId' }, // sub-key row slice\n ] },\n ],\n },\n masking: {\n email: { type: 'email', show: { roles: ['admin', 'scope:event:organizer'] } }, // hidden from the driver\n },\n read: {\n views: {\n manifest: {\n fields: ['id', 'nameAtInvite', 'shuttleId', 'pickupLocation'],\n access: { roles: ['admin', 'scope:event:organizer', 'scope:event:shuttleDriver'] },\n },\n },\n },\n});\n```\n\n| Pillar | How it reads the scoped role |\n|--------|------------------------------|\n| **Firewall** (rows) | `all`/`any` arms keyed on `ctx.scope.<kind>` (+ sub-keys) — see [Firewall](/compiler/definitions/firewall) |\n| **Access** (verbs/views) | `access.roles: ['scope:event:shuttleDriver']` on CRUD, actions, and views |\n| **Masking** (fields) | `masking.<col>.show.roles` includes / excludes `scope:event:<role>` |\n\n## The org / scope split (security)\n\n**Scoped roles never merge into `ctx.roles`.** A `scope:*` identifier matches **only** the verified scope claim (`ctx.scope.<kind>.roles`); a bare org role (`admin`, `member`) matches **only** `ctx.roles`. The compiler enforces the split so an externally-provisioned `shuttleDriver` can **never** satisfy an `admin` gate by string coincidence, and a tampered scope claim can't impersonate an org role. This is the precondition for admitting limited outside users at all.\n\n## Sub-keys (row slicing)\n\nA role's `subKeys` name columns on the relationship's `from` row that are projected into the claim. A firewall arm then slices on them:\n\n```typescript\n{ field: 'shuttleId', equals: 'ctx.scope.event.shuttleId' }\n```\n\nBecause sub-key arms compose with `all`, an **absent** sub-key denies (`sql\\`1 = 0\\``) rather than widening — a driver can never see *all* shuttles by simply lacking the claim. The scope accessor is always emitted null-safe (`ctx.scope?.event?.shuttleId`), so an org caller who never entered the scope hits a clean deny, not a 500.\n\n### Set-valued sub-keys\n\nA driver may cover **more than one** bus. Append a `[]` marker to the\nsub-key name to project **every** matched `from` row's value into the claim\nas a `string[]`:\n\n```typescript\nroles: {\n shuttleDriver: { via: 'shuttleDriverOf', subKeys: ['shuttleId[]'] }, // set-valued\n}\n```\n\nThe `[]` is a marker only — it's stripped from the column name (the\nrelationship's `from` row still reads `shuttleId`). At `/scope/v1/enter` the\nproven rows union their values, so the claim carries an array:\n\n```jsonc\n\"scope\": { \"event\": { \"id\": \"evt_123\", \"roles\": [\"shuttleDriver\"], \"shuttleId\": [\"shA\", \"shC\"] } }\n```\n\nThe matching firewall arm — written exactly as for the scalar case\n(`{ field: 'shuttleId', equals: 'ctx.scope.event.shuttleId' }`) — is\n**rewritten by the compiler** to an `inArray` row-slice:\n\n```sql\nWHERE shuttle_id IN (ctx.scope?.event?.shuttleId ?? [])\n```\n\nThe `?? []` default makes an absent claim lower to `inArray(col, [])` — a\nclean DENY, never a malformed SQL fragment or a 500. A scalar sub-key (no\n`[]` marker) is untouched and keeps lowering to `eq`. You write the same\n`equals` arm either way; declaring `shuttleId[]` vs `shuttleId` in the scope\nrole is the only switch.\n\n## Auto-stamping the scope column on insert (`q.scope`)\n\n`q.scope('organization')` auto-stamps the tenant column on write, the same\nway `q.scope('owner')` stamps `ownerId`. A relationship-derived kind works\nidentically: `q.scope('event')` auto-stamps the column from the **verified\nscope claim** (`ctx.scope.event.id`) on insert — no need to pass `eventId`\nin the request body:\n\n```typescript\nexport const eventNotes = q.table('event_notes', {\n id: q.id(),\n eventId: q.scope('event'), // INSERT autofill from ctx.scope.event.id\n body: q.text().required(),\n organizationId: q.scope('organization'), // INSERT autofill from ctx.activeOrgId\n});\n```\n\nThe stamp is **insert-only** and null-safe — the generated CREATE handler\nwrites `eventId: ctx.scope?.event?.id`, so it never binds `undefined`. It\ndoes **not** add a read-time `WHERE` filter (that's the firewall's job; a\nread scoped to `eventId = ctx.scope.event.id` would be wrong here). Infra\nkinds map to their session fields (`organization` → `ctx.activeOrgId`,\n`owner` → `ctx.userId`, `team` → `ctx.activeTeamId`); any other kind maps to\n`ctx.scope.<kind>.id`.\n\n## Namespace scope-claim refresh\n\nA scope is normally minted at `POST /scope/v1/enter`. When you also mount a\n[namespace](/compiler/definitions/access#namespace-mounts-hoisted-relationship-middleware)\nthat gates `/event/:eventId/*` on the **same** relationship, the namespace\nresolver can refresh `ctx.scope.<kind>` in memory for the duration of that\nrequest — so an attendee hitting `/event/evt_123/announce` gets\n`ctx.scope.event = { id: 'evt_123', roles: ['attendee'] }` without a separate\n`enter` round-trip. The refresh runs **after** the gate (the gate proves the\nrelationship; the refresh stamps the proven role from the path param).\n\nThis is a strictly-guarded convenience, and it stamps **per matched lane**. The\nresolver records which `via:` lane opened the gate (first-match-wins) and stamps\n**only that lane's** scope role — an attendee who matched `attendeeOf` gets\n`roles: ['attendee']`; an organizer who matched `organizerOf` gets\n`roles: ['organizer']`. A caller can never receive a role they didn't prove this\nrequest.\n\n- **Relationship lanes** each confer their own scope role, stamped only when that exact lane matched — so a **multi-lane `via:`** (e.g. `via: ['attendeeOf', 'organizerOf']`) refreshes the matched lane's role, not an ambiguous union.\n- A **bulk-grant lane** (`{ roles: [...] }` or `{ team: true }`) confers **no** scope role — it opens the gate via the caller's org role *without* proving any relationship, so there is nothing to stamp (stamping one would forge it). The gate still passes; the caller is simply authorized by their org role.\n\nThe refresh described so far is in-memory and single-request. To also hand the\ncaller a **persisted** scope token, opt the namespace into `mintScope` — see\nbelow.\n\n### Gotcha: a namespace only emits its resolver when it claims a standalone action\n\nThis is the single most common surprise (it has tripped up a customer): **a\nnamespace emits its resolver — and therefore the scope refresh and the\n[`mintScope`](#mintscope-mint-the-scope-token-from-the-namespace-resolver)\nmint — only when at least one STANDALONE action's `path:` falls under the\nnamespace prefix.**\n\nA standalone action declares its own `path:` (e.g.\n`path: '/event/:eventId/home'`), so the compiler can match it against the\nnamespace prefix and hoist it into the synthetic namespace routes file.\n**Record-based actions are different** — they mount under their resource's CRUD\nroutes (`/api/v1/guests/:id/checkin`), which live *outside* the\n`/event/:eventId` prefix. They never match the prefix, so they never get\nclaimed.\n\nA namespace that contains **only** record-based actions is therefore **inert**:\nnothing matches the prefix, no synthetic routes file is emitted, and so there\nis **no resolver, no scope refresh, and no mint** — even though the namespace\nis declared and validates cleanly. The middleware you expected to gate\n`/event/:eventId/*` simply isn't there.\n\nThe fix is to give the namespace at least one standalone action under the\nprefix. In `q-events`, `eventHome` exists precisely for this — a standalone\n`GET /event/:eventId/home` that pulls the resolver (and the §5.3 mint) into\nexistence:\n\n```typescript\n// features/events/actions/eventHome.ts\nexport default defineAction({\n path: '/event/:eventId/home', // ← standalone path UNDER the namespace prefix\n method: 'GET',\n input: z.object({}),\n access: { roles: ['scope:event:attendee', 'scope:event:organizer', 'manager+'] },\n async execute({ db, ctx, c }) { /* … */ },\n});\n```\n\nWith that action present, the `eventScope` resolver is emitted, runs the\n`attendeeOf` probe once per `/event/:eventId/*` request, stamps\n`ctx.scope.event`, and (because the namespace sets `mintScope: true`) mints the\nscope token. Without a standalone action under the prefix, none of that fires.\n\n## `mintScope` — mint the scope token from the namespace resolver\n\nA scope is normally minted by an explicit `POST /scope/v1/enter` round-trip.\nSetting **`mintScope: true`** on a namespace folds that mint into the\nnamespace resolver: on a successful relationship probe the resolver MINTS a\npersisted scope JWT and returns it via the `set-auth-token` header — so a\nnative client hitting `/event/:eventId/*` gets a scope token **without ever\ncalling `/scope/v1/enter`**.\n\n```typescript\n// quickback.config.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: 'guests',\n exposeAs: 'guest',\n },\n },\n namespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: ['attendeeOf'], // one or more lanes — mints the matched lane's role\n mintScope: true, // ← fold the scope-token mint into the resolver\n },\n },\n}\n```\n\nA confirmed attendee then hits the standalone action under the prefix:\n\n```http\nGET /api/v1/event/evt_123/home\nAuthorization: Bearer <existing-jwt>\n\n200 OK\nset-auth-token: <new-scoped-jwt> ← carries scope.event.roles = [\"attendee\"]\n```\n\nThe client stores the `set-auth-token` value and sends it as the bearer on\nevery subsequent `/event/:eventId/*` request. The JWT carries\n`scope.event = { id: 'evt_123', roles: ['attendee'] }`, so the scoped-role\naccess checks (`scope:event:attendee`) pass with no DB touch and no second\n`enter` call.\n\n`mintScope` is **opt-in per namespace** and defaults to `false`. With it off,\nthe resolver does the in-memory `ctx.scope.<kind>` refresh only (the section\nabove); subsequent requests must still call `/scope/v1/enter` for a persisted\ntoken.\n\n### Per-matched-lane minting (forging safety)\n\nThe mint stamps the scope role of **whichever lane matched**, gated on the\nfirst-match-wins probe — the *same* per-lane discipline as the in-memory stamp,\napplied here with higher stakes: a minted token **persists for its whole TTL**,\nso it can only ever carry the role the caller actually proved this request.\n\n- A **multi-lane `via:`** (e.g. `via: ['attendeeOf', 'organizerOf']`) mints the matched lane's role — `attendeeOf` → `scope.event.roles = ['attendee']`, `organizerOf` → `['organizer']`. The resolver records which lane opened the gate, so there is no ambiguity.\n- A **bulk-grant lane** (`{ roles: [...] }` or `{ team: true }`) mints **no** scope role — it opens the gate via the caller's org role without proving a relationship. The gate passes; the caller carries their org role, not a minted scope role.\n\n> The realtime [ws-ticket](/stack/realtime/durable-objects#namespace-backed-tickets-per-matched-lane) can authorize through this same namespace `via:`, issuing a per-matched-lane WebSocket ticket — so the socket gate and the REST gate stay identical.\n\nIn every suppressed case the gate still authorizes the request; only the mint\n(and the in-memory refresh) are skipped, and those callers obtain a scope\ntoken through `/scope/v1/enter` as usual. Flipping `mintScope: true` can never\nforge a scope role — the guard, not the flag, is the gate.\n\n### TTL and best-effort semantics\n\n- **TTL is the scope-token TTL** — `auth.jwt.expiresIn` (default 180s), **clamped to a hard ≤180s ceiling** at every signing site that emits a scope claim: both proven mints (`/scope/v1/enter`, the namespace resolver) *and* the middleware's rolling refresh. A longer-lived scope token would widen the post-revocation replay window past the spec bound, so the clamp is non-negotiable — an `auth.jwt.expiresIn` above the ceiling applies to plain tokens but never survives into a scope-bearing one.\n- **The mint is gated by the same proven-relationship guard as the in-memory stamp.** It runs *after* the gate has granted access, reading the instance id from the proven path param (`:eventId`) — never from request input — so the minted `scope:<kind>:<role>` is backed by exactly the proof `/scope/v1/enter` requires. The token is **byte-identical** to one `/scope/v1/enter` would produce: same shared mint helper, same carry-forward of any *other* verified scope kinds already on the incoming token (the freshly-proven kind takes precedence; siblings survive the re-mint).\n- **The mint is best-effort.** A mint failure (e.g. a missing signing secret) **never fails the request** — the in-memory stamp already authorized it; the caller simply doesn't receive a refreshed token on that response and can fall back to `/scope/v1/enter`.\n\n## Revocation & TTL\n\nThe scope claim is trusted between proofs — it is never re-checked against the database while it rides. Two bounds keep that window finite:\n\n- **The TTL** (default 180s, `auth.jwt.expiresIn`, clamped ≤180s on scope-bearing tokens) bounds an *idle* client: a token that stops being used dies within one TTL.\n- **The carry-forward cap** (15 minutes) bounds an *active* client: the rolling refresh re-signs the claim on every authed call, but only while the claim's proof timestamp (`sct`, stamped exclusively by the proven mint sites) is younger than the cap. Past it the refresh refuses, the token expires, and the next `enter` (or namespace-route mint) re-probes the relationship — which won't re-mint a revoked role.\n\nSo removing a guest/staff row takes effect within **cap + one TTL** for a client that keeps polling, and within one TTL once it goes idle. Two ways to tighten that:\n\n- **`auth.jwt.revocationCheck: 'kv'`** (v0.45+, Cloudflare runtime) — sub-TTL revocation: updating or deleting a conferring relationship row stamps a revocation timestamp in KV, and the bearer fast-path rejects a carried scope claim whose proof (`sct`) predates it. See [auth config](/compiler/config/auth).\n- **`via` arms** — for tables where any caching is too wide, gate with a `via` arm instead of a bare `ctx.scope.<kind>` arm: `via` emits a live subquery against the relationship table on every request, immune to a stale claim entirely.\n\n## Reference\n\n```typescript\n// AppContext (generated lib/types.ts)\nctx.scope?: Record<string, { id: string; roles?: string[]; [subKey: string]: string | string[] | undefined }>;\n\n// authz.scopes.<kind>\n{\n requestField: string; // body field carrying the instance id\n roles: Record<string, { via: string; subKeys?: string[] }>; // 'col' → eq, 'col[]' → inArray\n}\n```\n\n- `requestField` must equal every role-relationship's `resource.column`.\n- Each relationship's `from` table must exist and ship a generated firewall (it can't be `exception`).\n- A `subKeys` entry ending in `[]` is **set-valued** (lowers to `inArray`, minted as `string[]`); without the marker it's scalar (`eq`, minted as `string`).\n- `q.scope('<kind>')` auto-stamps the column from `ctx.scope.<kind>.id` on insert.\n- Generated route: `POST /scope/v1/enter` (mounted only when `authz.scopes` is declared)."
135
135
  },
136
136
  "compiler/definitions/validation": {
137
137
  "title": "Validation",
@@ -147,7 +147,7 @@ export const DOCS = {
147
147
  },
148
148
  "compiler/getting-started/full-example": {
149
149
  "title": "Complete Example",
150
- "content": "This example shows a complete resource definition using all five security layers, and the production code Quickback generates from it.\n\n## What You Define\n\nA `candidates` resource for a multi-tenant recruitment application with:\n- Organization-level data isolation\n- Role-based write permissions\n- Field-level write protection\n- PII masking for sensitive fields\n- Column-level views for different access levels\n\n```typescript title=\"quickback/features/candidates/candidates.ts\"\n\nexport default feature('candidates', {\n columns: {\n id: q.id(),\n name: q.text().required(),\n email: q.text().required(),\n phone: q.text().optional(),\n resumeUrl: q.text().optional(),\n source: q.text().optional(), // e.g. \"linkedin\", \"referral\", \"careers-page\"\n internalNotes: q.text().optional(),\n organizationId: q.scope(\"organization\"),\n // Note: createdAt, createdBy, modifiedAt, modifiedBy are auto-injected\n },\n\n // firewall — auto-derived from q.scope(\"organization\") + soft-delete deletedAt;\n // explicit declaration is optional once a scope column is declared.\n\n // GUARDS — Field-level protection\n guards: {\n createable: ['name', 'email', 'phone', 'resumeUrl', 'source'],\n updatable: ['name', 'phone'],\n },\n\n // MASKING — PII redaction (query.roles defaults to show.roles)\n masking: {\n email: { type: 'email', show: { roles: ['hiring-manager', 'recruiter'] } },\n phone: { type: 'phone', show: { roles: ['hiring-manager', 'recruiter'] } },\n },\n\n // READ — Collection + per-id GET, plus named views\n read: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n pipeline: {\n fields: ['id', 'name', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'phone', 'resumeUrl', 'source', 'internalNotes'],\n access: { roles: ['hiring-manager', 'recruiter'] },\n },\n },\n },\n\n // WRITE OPERATIONS\n create: { access: { roles: ['hiring-manager', 'recruiter'] } },\n update: { access: { roles: ['hiring-manager', 'recruiter'] } },\n delete: { access: { roles: ['hiring-manager'] }, mode: 'hard' },\n});\n```\n\n> Prefer the explicit two-export form (or interop with existing Drizzle schemas)? See [feature() — single-export sugar](/compiler/definitions/feature) and [Schema: choosing between `q` and Drizzle](/compiler/definitions/schema#choosing-between-q-and-drizzle). All forms compile identically; mix freely per file.\n\n---\n\n## What Quickback Generates\n\nRun `quickback compile` and Quickback generates production-ready code.\n\n### Security Helpers\n\n```typescript title=\"src/features/candidates/candidates.resource.ts\"\n\n/**\n * Firewall conditions for candidates\n * Auto-derived from q.scope(\"organization\") + audit-injected deletedAt.\n * 2 predicates: tenant scope AND soft-delete filter.\n */\nexport function buildFirewallConditions(ctx: AppContext) {\n return and(\n eq(candidates.organizationId, ctx.activeOrgId!),\n isNull(candidates.deletedAt),\n );\n}\n\n/**\n * Guards configuration for field modification rules.\n * organizationId is added to systemManaged because q.scope(\"organization\")\n * is bound to ctx.activeOrgId — clients cannot submit it.\n */\nexport const GUARDS_CONFIG = {\n createable: new Set(['name', 'email', 'phone', 'resumeUrl', 'source']),\n updatable: new Set(['name', 'phone']),\n immutable: new Set([]),\n protected: {},\n systemManaged: new Set([\n 'createdAt', 'createdBy',\n 'modifiedAt', 'modifiedBy',\n 'deletedAt', 'deletedBy',\n 'organizationId', // ← added by q.scope(\"organization\")\n ]),\n};\n\n/**\n * Validates field input for CREATE operations.\n */\nexport function validateCreate(input: Record<string, any>) {\n const systemManaged: string[] = [];\n const protectedFields: Array<{ field: string; actions: string[] }> = [];\n const notCreateable: string[] = [];\n\n for (const field of Object.keys(input)) {\n if (GUARDS_CONFIG.systemManaged.has(field)) {\n systemManaged.push(field);\n continue;\n }\n if (field in GUARDS_CONFIG.protected) {\n const actions = [...GUARDS_CONFIG.protected[field]];\n protectedFields.push({ field, actions });\n continue;\n }\n if (!GUARDS_CONFIG.createable.has(field) && !GUARDS_CONFIG.immutable.has(field)) {\n notCreateable.push(field);\n }\n }\n\n const valid = systemManaged.length === 0 &&\n protectedFields.length === 0 &&\n notCreateable.length === 0;\n\n return { valid, systemManaged, protected: protectedFields, notCreateable };\n}\n\n/**\n * Validates field input for UPDATE operations.\n */\nexport function validateUpdate(input: Record<string, any>) {\n const systemManaged: string[] = [];\n const immutable: string[] = [];\n const protectedFields: Array<{ field: string; actions: string[] }> = [];\n const notUpdatable: string[] = [];\n\n for (const field of Object.keys(input)) {\n if (GUARDS_CONFIG.systemManaged.has(field)) {\n systemManaged.push(field);\n continue;\n }\n if (GUARDS_CONFIG.immutable.has(field)) {\n immutable.push(field);\n continue;\n }\n if (field in GUARDS_CONFIG.protected) {\n const actions = [...GUARDS_CONFIG.protected[field]];\n protectedFields.push({ field, actions });\n continue;\n }\n if (!GUARDS_CONFIG.updatable.has(field)) {\n notUpdatable.push(field);\n }\n }\n\n const valid = systemManaged.length === 0 &&\n immutable.length === 0 &&\n protectedFields.length === 0 &&\n notUpdatable.length === 0;\n\n return { valid, systemManaged, immutable, protected: protectedFields, notUpdatable };\n}\n\n/**\n * Masks sensitive fields based on user role\n */\nexport function maskCandidate<T extends Record<string, any>>(\n record: T,\n ctx: AppContext\n): T {\n const masked: any = { ...record };\n\n // email: show to hiring-manager, recruiter\n if (!ctx.roles?.some(r => ['hiring-manager', 'recruiter'].includes(r))) {\n if (masked['email'] != null) {\n masked['email'] = masks.email(masked['email']);\n }\n }\n\n // phone: show to hiring-manager, recruiter\n if (!ctx.roles?.some(r => ['hiring-manager', 'recruiter'].includes(r))) {\n if (masked['phone'] != null) {\n masked['phone'] = masks.phone(masked['phone']);\n }\n }\n\n return masked as T;\n}\n\nexport function maskCandidates<T extends Record<string, any>>(\n records: T[],\n ctx: AppContext\n): T[] {\n return records.map(r => maskCandidate(r, ctx));\n}\n\n// Write access configuration (internal normalized shape)\nexport const CRUD_ACCESS = {\n create: { access: { roles: ['hiring-manager', 'recruiter'] } },\n update: { access: { roles: ['hiring-manager', 'recruiter'] } },\n delete: { access: { roles: ['hiring-manager'] }, mode: 'hard' },\n};\n\n// Views configuration (read pipeline)\nexport const VIEWS_CONFIG = {\n pipeline: {\n fields: ['id', 'name', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'phone', 'resumeUrl', 'source', 'internalNotes'],\n access: { roles: ['hiring-manager', 'recruiter'] },\n },\n} as const;\n```\n\n### API Routes\n\nThe generated routes wire everything together:\n\n```typescript title=\"src/features/candidates/candidates.routes.ts\"\n\n buildFirewallConditions,\n validateCreate,\n validateUpdate,\n maskCandidate,\n maskCandidates,\n VIEWS_CONFIG,\n CRUD_ACCESS,\n} from './candidates.resource';\n\nconst app = new Hono();\n\n// GET /candidates/views/:viewName — named view projection\nconst READ_ACCESS = { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] };\n\napp.get('/views/:viewName', async (c) => {\n const ctx = c.get('ctx');\n const db = c.get('db');\n\n const viewName = c.req.param('viewName');\n const params = Object.fromEntries(new URL(c.req.url).searchParams);\n const view = VIEWS_CONFIG[viewName as keyof typeof VIEWS_CONFIG];\n if (!view) return c.json({ error: 'Unknown view', code: 'VIEW_NOT_FOUND' }, 400);\n\n // Per-view access gate (falls back to read-level access)\n if (!await evaluateAccess(view.access ?? READ_ACCESS, ctx)) {\n return c.json(AccessErrors.roleRequired(view.access?.roles ?? READ_ACCESS.roles, ctx.roles), 403);\n }\n\n // Query with firewall conditions, project view fields, mask, return.\n const results = await db.select(/* projected fields */).from(candidates)\n .where(buildFirewallConditions(ctx));\n\n return c.json({ data: maskCandidates(results, ctx), view: viewName });\n});\n\n// POST /candidates - Create with guards\napp.post('/', async (c) => {\n const ctx = c.get('ctx');\n const db = c.get('db');\n\n // Access check\n if (!await evaluateAccess(CRUD_ACCESS.create.access, ctx)) {\n return c.json(AccessErrors.roleRequired(\n CRUD_ACCESS.create.access.roles,\n ctx.roles\n ), 403);\n }\n\n const body = await c.req.json();\n\n // Guards validation\n const validation = validateCreate(body);\n if (!validation.valid) {\n if (validation.systemManaged.length > 0) {\n return c.json(GuardErrors.systemManaged(validation.systemManaged), 400);\n }\n if (validation.notCreateable.length > 0) {\n return c.json(GuardErrors.fieldNotCreateable(validation.notCreateable), 400);\n }\n }\n\n // Apply ownership and audit fields\n const data = {\n id: 'cnd_' + crypto.randomUUID().replace(/-/g, ''),\n ...body,\n organizationId: ctx.activeOrgId,\n createdAt: new Date().toISOString(),\n createdBy: ctx.userId,\n modifiedAt: new Date().toISOString(),\n modifiedBy: ctx.userId,\n };\n\n const result = await db.insert(candidates).values(data).returning();\n return c.json(maskCandidate(result[0], ctx), 201);\n});\n\n// PATCH /candidates/:id - Update with guards\napp.patch('/:id', async (c) => {\n const ctx = c.get('ctx');\n const db = c.get('db');\n const id = c.req.param('id');\n\n // Fetch with firewall\n const [record] = await db.select().from(candidates)\n .where(and(buildFirewallConditions(ctx), eq(candidates.id, id)));\n\n if (!record) {\n return c.json({ error: 'Not found', code: 'NOT_FOUND' }, 404);\n }\n\n // Access check\n if (!await evaluateAccess(CRUD_ACCESS.update.access, ctx)) {\n return c.json(AccessErrors.roleRequired(\n CRUD_ACCESS.update.access.roles,\n ctx.roles\n ), 403);\n }\n\n const body = await c.req.json();\n\n // Guards validation\n const validation = validateUpdate(body);\n if (!validation.valid) {\n if (validation.notUpdatable.length > 0) {\n return c.json(GuardErrors.fieldNotUpdatable(validation.notUpdatable), 400);\n }\n }\n\n // Apply audit fields\n const data = {\n ...body,\n modifiedAt: new Date().toISOString(),\n modifiedBy: ctx.userId,\n };\n\n const result = await db.update(candidates).set(data)\n .where(eq(candidates.id, id)).returning();\n\n return c.json(maskCandidate(result[0], ctx));\n});\n\nexport default app;\n```\n\n---\n\n## Runtime Behavior\n\n### Masking by Role\n\n| Role | `email` | `phone` |\n|------|---------|---------|\n| **hiring-manager** | `jane@example.com` | `555-123-4567` |\n| **recruiter** | `jane@example.com` | `555-123-4567` |\n| **interviewer** | `j***@e******.com` | `******4567` |\n\n### Views + Masking Interaction\n\nViews control **which fields are returned**. Masking controls **what values are shown**.\n\n| Endpoint | Role | `phone` in response? | `phone` value |\n|----------|------|--------------------|-------------|\n| `/candidates/views/pipeline` | interviewer | No | N/A |\n| `/candidates/views/pipeline` | recruiter | No | N/A |\n| `/candidates/views/full` | interviewer | No | N/A (no access) |\n| `/candidates/views/full` | recruiter | Yes | `555-123-4567` |\n\n### Guards Enforcement\n\n```bash\n# Allowed: Create with createable fields\nPOST /candidates\n{ \"name\": \"Jane Smith\", \"email\": \"jane@example.com\", \"source\": \"linkedin\" }\n\n# Rejected: Update non-updatable field\nPATCH /candidates/cnd_123\n{ \"email\": \"new@example.com\" }\n# -> 400: \"Field 'email' is not updatable\"\n\n# Rejected: Set system-managed field\nPOST /candidates\n{ \"name\": \"Jane Smith\", \"createdBy\": \"hacker\" }\n# -> 400: \"System-managed fields cannot be set: createdBy\"\n```\n\n---\n\n## Generated API Endpoints\n\n| Method | Endpoint | Access |\n|--------|----------|--------|\n| `GET` | `/candidates` | owner, hiring-manager, recruiter, interviewer |\n| `GET` | `/candidates/:id` | owner, hiring-manager, recruiter, interviewer |\n| `POST` | `/candidates` | hiring-manager, recruiter |\n| `PATCH` | `/candidates/:id` | hiring-manager, recruiter |\n| `DELETE` | `/candidates/:id` | hiring-manager |\n| `GET` | `/candidates/views/pipeline` | owner, hiring-manager, recruiter, interviewer |\n| `GET` | `/candidates/views/full` | hiring-manager, recruiter |\n\n---\n\n## Key Takeaways\n\n1. **~50 lines of configuration** generates **~500+ lines of production code**\n2. **Security is declarative** - you describe *what* you want, not *how*\n3. **All layers work together** - Firewall -> Access -> Guards -> Masking\n4. **Code is readable and auditable** - no magic, just TypeScript\n5. **Type-safe from definition to API** - Drizzle schema drives everything"
150
+ "content": "This example shows a complete resource definition using all five security layers, and the production code Quickback generates from it.\n\n## What You Define\n\nA `candidates` resource for a multi-tenant recruitment application with:\n- Organization-level data isolation\n- Role-based write permissions\n- Field-level write protection\n- PII masking for sensitive fields\n- Column-level views for different access levels\n\n```typescript title=\"quickback/features/candidates/candidates.ts\"\n\nexport default feature('candidates', {\n columns: {\n id: q.id(),\n name: q.text().required(),\n email: q.text().required(),\n phone: q.text().optional(),\n resumeUrl: q.text().optional(),\n source: q.text().optional(), // e.g. \"linkedin\", \"referral\", \"careers-page\"\n internalNotes: q.text().optional(),\n organizationId: q.scope(\"organization\"),\n // Note: createdAt, createdBy, modifiedAt, modifiedBy are auto-injected\n },\n\n // firewall — auto-derived from q.scope(\"organization\") + soft-delete deletedAt;\n // explicit declaration is optional once a scope column is declared.\n\n // GUARDS — Field-level protection\n guards: {\n createable: ['name', 'email', 'phone', 'resumeUrl', 'source'],\n updatable: ['name', 'phone'],\n },\n\n // MASKING — PII redaction (query.roles defaults to show.roles)\n masking: {\n email: { type: 'email', show: { roles: ['hiring-manager', 'recruiter'] } },\n phone: { type: 'phone', show: { roles: ['hiring-manager', 'recruiter'] } },\n },\n\n // READ — Collection + per-id GET, plus named views\n read: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n pipeline: {\n fields: ['id', 'name', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'phone', 'resumeUrl', 'source', 'internalNotes'],\n access: { roles: ['hiring-manager', 'recruiter'] },\n },\n },\n },\n\n // WRITE OPERATIONS\n create: { access: { roles: ['hiring-manager', 'recruiter'] } },\n update: { access: { roles: ['hiring-manager', 'recruiter'] } },\n delete: { access: { roles: ['hiring-manager'] }, mode: 'soft' },\n});\n```\n\n> `mode: 'hard'` is also available, but hard deletes erase the row — so they require the security-audit pipeline. On D1 that means setting `auditDatabaseId` on the database provider config (the compiler errors with setup instructions if it's missing).\n\n> Prefer the explicit two-export form (or interop with existing Drizzle schemas)? See [feature() — single-export sugar](/compiler/definitions/feature) and [Schema: choosing between `q` and Drizzle](/compiler/definitions/schema#choosing-between-q-and-drizzle). All forms compile identically; mix freely per file.\n\n---\n\n## What Quickback Generates\n\nRun `quickback compile` and Quickback generates production-ready code.\n\n### Security Helpers\n\n```typescript title=\"src/features/candidates/candidates.resource.ts\"\n\n/**\n * Firewall conditions for candidates\n * Auto-derived from q.scope(\"organization\") + audit-injected deletedAt.\n * 2 predicates: tenant scope AND soft-delete filter.\n */\nexport function buildFirewallConditions(ctx: AppContext) {\n return and(\n eq(candidates.organizationId, ctx.activeOrgId!),\n isNull(candidates.deletedAt),\n );\n}\n\n/**\n * Guards configuration for field modification rules.\n * organizationId is added to systemManaged because q.scope(\"organization\")\n * is bound to ctx.activeOrgId — clients cannot submit it.\n */\nexport const GUARDS_CONFIG = {\n createable: new Set(['name', 'email', 'phone', 'resumeUrl', 'source']),\n updatable: new Set(['name', 'phone']),\n immutable: new Set([]),\n protected: {},\n systemManaged: new Set([\n 'createdAt', 'createdBy',\n 'modifiedAt', 'modifiedBy',\n 'deletedAt', 'deletedBy',\n 'organizationId', // ← added by q.scope(\"organization\")\n ]),\n};\n\n/**\n * Validates field input for CREATE operations.\n */\nexport function validateCreate(input: Record<string, any>) {\n const systemManaged: string[] = [];\n const protectedFields: Array<{ field: string; actions: string[] }> = [];\n const notCreateable: string[] = [];\n\n for (const field of Object.keys(input)) {\n if (GUARDS_CONFIG.systemManaged.has(field)) {\n systemManaged.push(field);\n continue;\n }\n if (field in GUARDS_CONFIG.protected) {\n const actions = [...GUARDS_CONFIG.protected[field]];\n protectedFields.push({ field, actions });\n continue;\n }\n if (!GUARDS_CONFIG.createable.has(field) && !GUARDS_CONFIG.immutable.has(field)) {\n notCreateable.push(field);\n }\n }\n\n const valid = systemManaged.length === 0 &&\n protectedFields.length === 0 &&\n notCreateable.length === 0;\n\n return { valid, systemManaged, protected: protectedFields, notCreateable };\n}\n\n/**\n * Validates field input for UPDATE operations.\n */\nexport function validateUpdate(input: Record<string, any>) {\n const systemManaged: string[] = [];\n const immutable: string[] = [];\n const protectedFields: Array<{ field: string; actions: string[] }> = [];\n const notUpdatable: string[] = [];\n\n for (const field of Object.keys(input)) {\n if (GUARDS_CONFIG.systemManaged.has(field)) {\n systemManaged.push(field);\n continue;\n }\n if (GUARDS_CONFIG.immutable.has(field)) {\n immutable.push(field);\n continue;\n }\n if (field in GUARDS_CONFIG.protected) {\n const actions = [...GUARDS_CONFIG.protected[field]];\n protectedFields.push({ field, actions });\n continue;\n }\n if (!GUARDS_CONFIG.updatable.has(field)) {\n notUpdatable.push(field);\n }\n }\n\n const valid = systemManaged.length === 0 &&\n immutable.length === 0 &&\n protectedFields.length === 0 &&\n notUpdatable.length === 0;\n\n return { valid, systemManaged, immutable, protected: protectedFields, notUpdatable };\n}\n\n/**\n * Masks sensitive fields based on user role\n */\nexport function maskCandidate<T extends Record<string, any>>(\n record: T,\n ctx: AppContext\n): T {\n const masked: any = { ...record };\n\n // email: show to hiring-manager, recruiter\n if (!ctx.roles?.some(r => ['hiring-manager', 'recruiter'].includes(r))) {\n if (masked['email'] != null) {\n masked['email'] = masks.email(masked['email']);\n }\n }\n\n // phone: show to hiring-manager, recruiter\n if (!ctx.roles?.some(r => ['hiring-manager', 'recruiter'].includes(r))) {\n if (masked['phone'] != null) {\n masked['phone'] = masks.phone(masked['phone']);\n }\n }\n\n return masked as T;\n}\n\nexport function maskCandidates<T extends Record<string, any>>(\n records: T[],\n ctx: AppContext\n): T[] {\n return records.map(r => maskCandidate(r, ctx));\n}\n\n// Write access configuration (internal normalized shape)\nexport const CRUD_ACCESS = {\n create: { access: { roles: ['hiring-manager', 'recruiter'] } },\n update: { access: { roles: ['hiring-manager', 'recruiter'] } },\n delete: { access: { roles: ['hiring-manager'] }, mode: 'soft' },\n};\n\n// Views configuration (read pipeline)\nexport const VIEWS_CONFIG = {\n pipeline: {\n fields: ['id', 'name', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'phone', 'resumeUrl', 'source', 'internalNotes'],\n access: { roles: ['hiring-manager', 'recruiter'] },\n },\n} as const;\n```\n\n### API Routes\n\nThe generated routes wire everything together:\n\n```typescript title=\"src/features/candidates/candidates.routes.ts\"\n\n buildFirewallConditions,\n validateCreate,\n validateUpdate,\n maskCandidate,\n maskCandidates,\n VIEWS_CONFIG,\n CRUD_ACCESS,\n} from './candidates.resource';\n\nconst app = new Hono();\n\n// GET /candidates/views/:viewName — named view projection\nconst READ_ACCESS = { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] };\n\napp.get('/views/:viewName', async (c) => {\n const ctx = c.get('ctx');\n const db = c.get('db');\n\n const viewName = c.req.param('viewName');\n const params = Object.fromEntries(new URL(c.req.url).searchParams);\n const view = VIEWS_CONFIG[viewName as keyof typeof VIEWS_CONFIG];\n if (!view) return c.json({ error: 'Unknown view', code: 'VIEW_NOT_FOUND' }, 400);\n\n // Per-view access gate (falls back to read-level access)\n if (!await evaluateAccess(view.access ?? READ_ACCESS, ctx)) {\n return c.json(AccessErrors.roleRequired(view.access?.roles ?? READ_ACCESS.roles, ctx.roles), 403);\n }\n\n // Query with firewall conditions, project view fields, mask, return.\n const results = await db.select(/* projected fields */).from(candidates)\n .where(buildFirewallConditions(ctx));\n\n return c.json({ data: maskCandidates(results, ctx), view: viewName });\n});\n\n// POST /candidates - Create with guards\napp.post('/', async (c) => {\n const ctx = c.get('ctx');\n const db = c.get('db');\n\n // Access check\n if (!await evaluateAccess(CRUD_ACCESS.create.access, ctx)) {\n return c.json(AccessErrors.roleRequired(\n CRUD_ACCESS.create.access.roles,\n ctx.roles\n ), 403);\n }\n\n const body = await c.req.json();\n\n // Guards validation\n const validation = validateCreate(body);\n if (!validation.valid) {\n if (validation.systemManaged.length > 0) {\n return c.json(GuardErrors.systemManaged(validation.systemManaged), 400);\n }\n if (validation.notCreateable.length > 0) {\n return c.json(GuardErrors.fieldNotCreateable(validation.notCreateable), 400);\n }\n }\n\n // Apply ownership and audit fields\n const data = {\n id: 'cnd_' + crypto.randomUUID().replace(/-/g, ''),\n ...body,\n organizationId: ctx.activeOrgId,\n createdAt: new Date().toISOString(),\n createdBy: ctx.userId,\n modifiedAt: new Date().toISOString(),\n modifiedBy: ctx.userId,\n };\n\n const result = await db.insert(candidates).values(data).returning();\n return c.json(maskCandidate(result[0], ctx), 201);\n});\n\n// PATCH /candidates/:id - Update with guards\napp.patch('/:id', async (c) => {\n const ctx = c.get('ctx');\n const db = c.get('db');\n const id = c.req.param('id');\n\n // Fetch with firewall\n const [record] = await db.select().from(candidates)\n .where(and(buildFirewallConditions(ctx), eq(candidates.id, id)));\n\n if (!record) {\n return c.json({ error: 'Not found', code: 'NOT_FOUND' }, 404);\n }\n\n // Access check\n if (!await evaluateAccess(CRUD_ACCESS.update.access, ctx)) {\n return c.json(AccessErrors.roleRequired(\n CRUD_ACCESS.update.access.roles,\n ctx.roles\n ), 403);\n }\n\n const body = await c.req.json();\n\n // Guards validation\n const validation = validateUpdate(body);\n if (!validation.valid) {\n if (validation.notUpdatable.length > 0) {\n return c.json(GuardErrors.fieldNotUpdatable(validation.notUpdatable), 400);\n }\n }\n\n // Apply audit fields\n const data = {\n ...body,\n modifiedAt: new Date().toISOString(),\n modifiedBy: ctx.userId,\n };\n\n const result = await db.update(candidates).set(data)\n .where(eq(candidates.id, id)).returning();\n\n return c.json(maskCandidate(result[0], ctx));\n});\n\nexport default app;\n```\n\n---\n\n## Runtime Behavior\n\n### Masking by Role\n\n| Role | `email` | `phone` |\n|------|---------|---------|\n| **hiring-manager** | `jane@example.com` | `555-123-4567` |\n| **recruiter** | `jane@example.com` | `555-123-4567` |\n| **interviewer** | `j***@e******.com` | `******4567` |\n\n### Views + Masking Interaction\n\nViews control **which fields are returned**. Masking controls **what values are shown**.\n\n| Endpoint | Role | `phone` in response? | `phone` value |\n|----------|------|--------------------|-------------|\n| `/candidates/views/pipeline` | interviewer | No | N/A |\n| `/candidates/views/pipeline` | recruiter | No | N/A |\n| `/candidates/views/full` | interviewer | No | N/A (no access) |\n| `/candidates/views/full` | recruiter | Yes | `555-123-4567` |\n\n### Guards Enforcement\n\n```bash\n# Allowed: Create with createable fields\nPOST /candidates\n{ \"name\": \"Jane Smith\", \"email\": \"jane@example.com\", \"source\": \"linkedin\" }\n\n# Rejected: Update non-updatable field\nPATCH /candidates/cnd_123\n{ \"email\": \"new@example.com\" }\n# -> 400: \"Field 'email' is not updatable\"\n\n# Rejected: Set system-managed field\nPOST /candidates\n{ \"name\": \"Jane Smith\", \"createdBy\": \"hacker\" }\n# -> 400: \"System-managed fields cannot be set: createdBy\"\n```\n\n---\n\n## Generated API Endpoints\n\n| Method | Endpoint | Access |\n|--------|----------|--------|\n| `GET` | `/candidates` | owner, hiring-manager, recruiter, interviewer |\n| `GET` | `/candidates/:id` | owner, hiring-manager, recruiter, interviewer |\n| `POST` | `/candidates` | hiring-manager, recruiter |\n| `PATCH` | `/candidates/:id` | hiring-manager, recruiter |\n| `DELETE` | `/candidates/:id` | hiring-manager |\n| `GET` | `/candidates/views/pipeline` | owner, hiring-manager, recruiter, interviewer |\n| `GET` | `/candidates/views/full` | hiring-manager, recruiter |\n\n---\n\n## Key Takeaways\n\n1. **~50 lines of configuration** generates **~500+ lines of production code**\n2. **Security is declarative** - you describe *what* you want, not *how*\n3. **All layers work together** - Firewall -> Access -> Guards -> Masking\n4. **Code is readable and auditable** - no magic, just TypeScript\n5. **Type-safe from definition to API** - Drizzle schema drives everything"
151
151
  },
152
152
  "compiler/getting-started/hand-crafted": {
153
153
  "title": "Hand-Crafted Setup",
@@ -155,27 +155,27 @@ export const DOCS = {
155
155
  },
156
156
  "compiler/getting-started": {
157
157
  "title": "Getting Started",
158
- "content": "Get started with Quickback in minutes. This guide shows you how to define a complete table with security configuration.\n\n## Start a Project\n\n```bash\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n```\n\n`quickback start` is interactive — it asks for a template and project name, scaffolds the project on disk, and only prompts for an account just before compiling. If you cancel at the login prompt the scaffold stays put; finish later with `quickback login && quickback compile`.\n\nPrefer a scriptable form?\n\n```bash\nnpm install -g @quickback-dev/cli\nquickback create cloudflare my-app\ncd my-app\n```\n\nBoth paths scaffold the same project:\n- `quickback.config.ts` — Project configuration\n- `quickback/features/` — Your table definitions\n- Working example feature with full security configuration (when you pick `todos`/`blog`/`saas`)\n\n**Available templates:**\n- `cloudflare` — Cloudflare Workers + D1 + Better Auth, bare scaffold (free)\n- `todos` — Working CRUD example with masking + actions (free)\n- `blog` — Single-tenant blog, PUBLIC reads, admin writes (free)\n- `empty` — Cloudflare scaffold, no example features (free)\n- `saas` — Full B2B SaaS with orgs, R2 file storage, webhooks (pro)\n\n## File Structure\n\nEach table gets its own file with schema and security config together:\n\n```\nquickback/\n├── quickback.config.ts\n└── features/\n └── jobs/\n ├── jobs.ts # Table + security config\n ├── applications.ts # Related table + config\n ├── actions.ts # Custom actions (optional)\n └── handlers/ # Action handlers (optional)\n └── close-job.ts\n```\n\n## Complete Example\n\nHere's a complete `jobs` table with all security layers in a single `feature()` call:\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport default feature('jobs', {\n columns: {\n id: q.id(),\n title: q.text().required(),\n department: q.text().required(),\n status: q.text().default('draft').required(), // draft | open | closed\n salaryMin: q.int().optional(),\n salaryMax: q.int().optional(),\n // Ownership — required for firewall data isolation\n organizationId: q.scope(\"organization\"),\n },\n\n // 1. FIREWALL — Data isolation\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n\n // 2. GUARDS — Field modification rules\n guards: {\n createable: [\"title\", \"department\", \"status\", \"salaryMin\", \"salaryMax\"],\n updatable: [\"title\", \"department\", \"status\"],\n },\n\n // 3. READ — Collection + per-id GET (gates GET / and GET /:id)\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n pageSize: 25,\n },\n\n // 4. WRITE OPERATIONS\n create: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] }, mode: \"soft\" },\n});\n```\n\nOne import, one export, every security layer declared in one place. Secure by default — no write routes ship until you opt in with top-level `create`, `update`, `delete`, or `upsert`.\n\n### Alternatives — same result, different shape\n\nIf you'd rather split the table declaration from the security config (e.g. to reference the table in an action file), use the two-export form. Identical output:\n\n```typescript\n\nexport const jobs = q.table('jobs', {\n id: q.id(),\n title: q.text().required(),\n // … same columns\n});\n\nexport default defineTable(jobs, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n // … same config\n});\n\nexport type Job = typeof jobs.$infer;\n```\n\nOr if you're interop'ing with existing Drizzle schemas, you can author with `sqliteTable` / `pgTable` directly — the compiler dispatches per file, and all forms can coexist in the same project.\n\nSee [feature() — single-export sugar](/compiler/definitions/feature) and [Schema: choosing between `q` and Drizzle](/compiler/definitions/schema#choosing-between-q-and-drizzle) for the full picture.\n\n## What Each Layer Does\n\n1. **Firewall**: Automatically adds `WHERE organizationId = ?` to every query. Users in Org A can never see Org B's data.\n2. **Guards**: Controls which fields can be modified — `createable` for POST, `updatable` for PATCH, `protected` for action-only fields.\n3. **Write Access**: Role-based access control for each operation. All roles can read, only hiring managers can write.\n\n## Compile and Run\n\n```bash\n# Compile your definitions — prompts you to sign in or sign up\n# if you haven't already (no separate `quickback login` step needed)\nquickback compile\n\n# Run locally\nnpm run dev\n```\n\nThe first compile prompts for an account; subsequent compiles re-use the stored session.\n\n## Generated Endpoints\n\nQuickback generates these endpoints from the example above:\n\n| Method | Endpoint | Description |\n|--------|----------|-------------|\n| `GET` | `/api/v1/jobs` | List jobs (all roles) |\n| `GET` | `/api/v1/jobs/:id` | Get single job |\n| `POST` | `/api/v1/jobs` | Create job (hiring managers only) |\n| `PATCH` | `/api/v1/jobs/:id` | Update job (hiring managers only) |\n| `DELETE` | `/api/v1/jobs/:id` | Soft delete job (hiring managers only) |\n\n## Test Your API\n\nAfter `quickback compile` and `npm run dev`, your API is running locally. Open a second terminal and try these requests:\n\n```bash\n# 1. Create a user account\ncurl -X POST http://localhost:8787/api/auth/sign-up/email \\\n -H \"Content-Type: application/json\" \\\n -d '{\"email\": \"admin@example.com\", \"password\": \"securepassword123\", \"name\": \"Admin\"}'\n\n# 2. Sign in and get a session token\ncurl -X POST http://localhost:8787/api/auth/sign-in/email \\\n -H \"Content-Type: application/json\" \\\n -d '{\"email\": \"admin@example.com\", \"password\": \"securepassword123\"}'\n# → Response includes a session token in Set-Cookie header\n\n# 3. Create a record (use the session cookie from step 2)\ncurl -X POST http://localhost:8787/api/v1/jobs \\\n -H \"Content-Type: application/json\" \\\n -H \"Cookie: better-auth.session_token=<token>\" \\\n -d '{\"title\": \"Senior Engineer\", \"department\": \"Engineering\", \"status\": \"open\"}'\n\n# 4. List records\ncurl http://localhost:8787/api/v1/jobs \\\n -H \"Cookie: better-auth.session_token=<token>\"\n```\n\n## Next Steps\n\n- [Template Walkthroughs](/compiler/getting-started/templates) — Detailed setup guides\n- [Full Example](/compiler/getting-started/full-example) — Complete resource walkthrough\n- [Database Schema](/compiler/definitions/schema) — Column types, relations, audit fields\n- [Firewall](/compiler/definitions/firewall) — Data isolation patterns\n- [Access](/compiler/definitions/access) — Role & condition-based control\n- [Guards](/compiler/definitions/guards) — Field modification rules\n- [Masking](/compiler/definitions/masking) — Field redaction for sensitive data\n- [Actions](/compiler/definitions/actions) — Custom business logic endpoints\n\n## See Also\n\n- [Quickback Stack](/stack) — The runtime environment where your compiled API runs (D1, KV, R2, auth)\n- [Account UI](/stack/account-ui) — Pre-built authentication and account management UI\n- [Using the API](/compiler/targets/hono-api/using-the-api) — CRUD endpoints, filtering, and batch operations"
158
+ "content": "Get started with Quickback in minutes. This guide shows you how to define a complete table with security configuration.\n\n## Start a Project\n\n```bash\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n```\n\n`quickback start` is interactive — it asks for a template and project name, scaffolds the project on disk, and only prompts for an account just before compiling. If you cancel at the login prompt the scaffold stays put; finish later with `quickback login && quickback compile`.\n\nPrefer a scriptable form?\n\n```bash\nnpm install -g @quickback-dev/cli\nquickback create cloudflare my-app\ncd my-app\n```\n\nBoth paths scaffold the same project:\n- `quickback.config.ts` — Project configuration\n- `quickback/features/` — Your table definitions\n- Working example feature with full security configuration (when you pick `todos`/`blog`/`saas`)\n\n**Available templates:**\n- `cloudflare` — Cloudflare Workers + D1 + Better Auth, bare scaffold\n- `todos` — Working CRUD example with masking + actions\n- `blog` — Single-tenant blog, PUBLIC reads, admin writes\n- `empty` — Cloudflare scaffold, no example features\n- `saas` — Full B2B SaaS with orgs, R2 file storage, webhooks\n\n## File Structure\n\nEach table gets its own file with schema and security config together:\n\n```\nquickback/\n├── quickback.config.ts\n└── features/\n └── jobs/\n ├── jobs.ts # Table + security config\n ├── applications.ts # Related table + config\n ├── actions.ts # Custom actions (optional)\n └── handlers/ # Action handlers (optional)\n └── close-job.ts\n```\n\n## Complete Example\n\nHere's a complete `jobs` table with all security layers in a single `feature()` call:\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport default feature('jobs', {\n columns: {\n id: q.id(),\n title: q.text().required(),\n department: q.text().required(),\n status: q.text().default('draft').required(), // draft | open | closed\n salaryMin: q.int().optional(),\n salaryMax: q.int().optional(),\n // Ownership — required for firewall data isolation\n organizationId: q.scope(\"organization\"),\n },\n\n // 1. FIREWALL — Data isolation\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n\n // 2. GUARDS — Field modification rules\n guards: {\n createable: [\"title\", \"department\", \"status\", \"salaryMin\", \"salaryMax\"],\n updatable: [\"title\", \"department\", \"status\"],\n },\n\n // 3. READ — Collection + per-id GET (gates GET / and GET /:id)\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n pageSize: 25,\n },\n\n // 4. WRITE OPERATIONS\n create: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] }, mode: \"soft\" },\n});\n```\n\nOne import, one export, every security layer declared in one place. Secure by default — no write routes ship until you opt in with top-level `create`, `update`, `delete`, or `upsert`.\n\n### Alternatives — same result, different shape\n\nIf you'd rather split the table declaration from the security config (e.g. to reference the table in an action file), use the two-export form. Identical output:\n\n```typescript\n\nexport const jobs = q.table('jobs', {\n id: q.id(),\n title: q.text().required(),\n // … same columns\n});\n\nexport default defineTable(jobs, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n // … same config\n});\n\nexport type Job = typeof jobs.$infer;\n```\n\nOr if you're interop'ing with existing Drizzle schemas, you can author with `sqliteTable` / `pgTable` directly — the compiler dispatches per file, and all forms can coexist in the same project.\n\nSee [feature() — single-export sugar](/compiler/definitions/feature) and [Schema: choosing between `q` and Drizzle](/compiler/definitions/schema#choosing-between-q-and-drizzle) for the full picture.\n\n## What Each Layer Does\n\n1. **Firewall**: Automatically adds `WHERE organizationId = ?` to every query. Users in Org A can never see Org B's data.\n2. **Guards**: Controls which fields can be modified — `createable` for POST, `updatable` for PATCH, `protected` for action-only fields.\n3. **Write Access**: Role-based access control for each operation. All roles can read, only hiring managers can write.\n\n## Compile and Run\n\n```bash\n# Compile your definitions — prompts you to sign in or sign up\n# if you haven't already (no separate `quickback login` step needed)\nquickback compile\n\n# Run locally\nnpm run dev\n```\n\nThe first compile prompts for an account; subsequent compiles re-use the stored session.\n\n## Generated Endpoints\n\nQuickback generates these endpoints from the example above:\n\n| Method | Endpoint | Description |\n|--------|----------|-------------|\n| `GET` | `/api/v1/jobs` | List jobs (all roles) |\n| `GET` | `/api/v1/jobs/:id` | Get single job |\n| `POST` | `/api/v1/jobs` | Create job (hiring managers only) |\n| `PATCH` | `/api/v1/jobs/:id` | Update job (hiring managers only) |\n| `DELETE` | `/api/v1/jobs/:id` | Soft delete job (hiring managers only) |\n\n## Test Your API\n\nAfter `quickback compile` and `npm run dev`, your API is running locally. Open a second terminal and try these requests:\n\n```bash\n# 1. Create a user account\ncurl -X POST http://localhost:8787/auth/v1/sign-up/email \\\n -H \"Content-Type: application/json\" \\\n -d '{\"email\": \"admin@example.com\", \"password\": \"securepassword123\", \"name\": \"Admin\"}'\n\n# 2. Sign in and get a session token\ncurl -X POST http://localhost:8787/auth/v1/sign-in/email \\\n -H \"Content-Type: application/json\" \\\n -d '{\"email\": \"admin@example.com\", \"password\": \"securepassword123\"}'\n# → Response includes a session token in Set-Cookie header\n\n# 3. Create a record (use the session cookie from step 2)\ncurl -X POST http://localhost:8787/api/v1/jobs \\\n -H \"Content-Type: application/json\" \\\n -H \"Cookie: better-auth.session_token=<token>\" \\\n -d '{\"title\": \"Senior Engineer\", \"department\": \"Engineering\", \"status\": \"open\"}'\n\n# 4. List records\ncurl http://localhost:8787/api/v1/jobs \\\n -H \"Cookie: better-auth.session_token=<token>\"\n```\n\n## Next Steps\n\n- [Template Walkthroughs](/compiler/getting-started/templates) — Detailed setup guides\n- [Full Example](/compiler/getting-started/full-example) — Complete resource walkthrough\n- [Database Schema](/compiler/definitions/schema) — Column types, relations, audit fields\n- [Firewall](/compiler/definitions/firewall) — Data isolation patterns\n- [Access](/compiler/definitions/access) — Role & condition-based control\n- [Guards](/compiler/definitions/guards) — Field modification rules\n- [Masking](/compiler/definitions/masking) — Field redaction for sensitive data\n- [Actions](/compiler/definitions/actions) — Custom business logic endpoints\n\n## See Also\n\n- [Quickback Stack](/stack) — The runtime environment where your compiled API runs (D1, KV, R2, auth)\n- [Account UI](/stack/account-ui) — Pre-built authentication and account management UI\n- [Using the API](/compiler/targets/hono-api/using-the-api) — CRUD endpoints, filtering, and batch operations"
159
159
  },
160
160
  "compiler/getting-started/patterns": {
161
161
  "title": "Common Patterns",
162
- "content": "Quick recipes for common scenarios. Each pattern shows the complete `defineTable` configuration.\n\n## Public Read, Authenticated Write\n\nA job board where all team members can browse open positions but only hiring managers can create or edit jobs:\n\n```typescript\n// quickback/features/jobs/jobs.ts\nexport default defineTable(jobs, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"title\", \"department\", \"status\", \"salaryMin\", \"salaryMax\"],\n updatable: [\"title\", \"department\", \"status\"],\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n});\n```\n\n## User-Scoped Personal Data\n\nInterview notes that belong to a specific interviewer. Each interviewer only sees their own notes:\n\n```typescript\n// Schema includes both organizationId AND ownerId (q DSL)\n\nexport const interviewNotes = q.table(\"interview_notes\", {\n id: q.id(),\n candidateId: q.text().required(),\n content: q.text().required(),\n rating: q.int().optional(),\n organizationId: q.scope(\"organization\"),\n ownerId: q.text().required(),\n});\n\nexport default defineTable(interviewNotes, {\n firewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'ownerId', equals: 'ctx.userId' }, // Only the interviewer can see their own notes\n ],\n guards: {\n createable: [\"candidateId\", \"content\", \"rating\"],\n updatable: [\"content\", \"rating\"],\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] } },\n});\n```\n\nThe owner predicate (`{ field: 'ownerId', equals: 'ctx.userId' }`) means even hiring managers can only see notes they authored. To let hiring managers see all notes regardless of author, drop the owner predicate from the firewall and gate per-id access via record conditions instead.\n\n## Multi-Table Feature with Internal Tables\n\nA feature with a main table exposed via API and a junction table used only in actions:\n\n```typescript\n// quickback/features/applications/applications.ts — exposed via API\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"candidateId\", \"jobId\", \"stage\", \"notes\"],\n updatable: [\"notes\"],\n },\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```typescript\n// quickback/features/applications/interview-scores.ts — internal, no API routes\n// No default export = no routes generated\nexport const interviewScores = sqliteTable(\"interview_scores\", {\n applicationId: text(\"application_id\").notNull(),\n interviewerId: text(\"interviewer_id\").notNull(),\n score: integer(\"score\").notNull(),\n feedback: text(\"feedback\"),\n organizationId: text(\"organization_id\").notNull(), // Always scope junction tables\n});\n```\n\n```typescript\n// quickback/features/applications/actions.ts — uses the internal table\n\nexport default defineActions(applications, {\n submitScore: {\n type: \"record\",\n input: z.object({ score: z.number().min(1).max(5), feedback: z.string() }),\n access: { roles: [\"owner\", \"hiring-manager\", \"interviewer\"] },\n execute: async ({ db, record, input, ctx }) => {\n await db.insert(interviewScores).values({\n applicationId: record.id,\n interviewerId: ctx.userId,\n score: input.score,\n feedback: input.feedback,\n });\n return record;\n },\n },\n});\n```\n\n## Admin-Only Status Field\n\nA field that only hiring managers can modify, but everyone can see:\n\n```typescript\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"candidateId\", \"jobId\", \"notes\"],\n updatable: [\"notes\"], // Recruiters can only update notes\n protected: [\"stage\"], // Stage can only be changed via actions\n },\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: [\"hiring-manager\"] } },\n});\n```\n\nThen create an action that hiring managers use to change stage:\n\n```typescript\n// quickback/features/applications/actions.ts\nexport default defineActions(applications, {\n advanceStage: {\n type: \"record\",\n input: z.object({ stage: z.enum([\"applied\", \"screening\", \"interview\", \"offer\", \"hired\", \"rejected\"]) }),\n access: { roles: [\"hiring-manager\"] },\n execute: async ({ db, record, input }) => {\n await db.update(applications).set({ stage: input.stage }).where(eq(applications.id, record.id));\n return { ...record, stage: input.stage };\n },\n },\n});\n```\n\n## Sensitive Data with Role-Based Masking\n\nA candidate record where PII is masked differently per role:\n\n```typescript\nexport default defineTable(candidates, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"name\", \"email\", \"phone\", \"resumeUrl\", \"source\"],\n updatable: [\"name\", \"phone\"],\n },\n masking: {\n email: { type: \"email\", show: { roles: [\"hiring-manager\", \"recruiter\"] } },\n phone: { type: \"phone\", show: { roles: [\"hiring-manager\", \"recruiter\"] } },\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"hiring-manager\"] } },\n});\n```\n\n| Role | email | phone |\n|------|-------|-------|\n| hiring-manager | `jane@example.com` | `555-123-4567` |\n| recruiter | `jane@example.com` | `555-123-4567` |\n| interviewer | `j***@e******.com` | `***-***-4567` |\n\n## External System Sync\n\nAn import table for syncing candidates from an external ATS via upsert:\n\n```typescript\n// quickback/features/ats-imports/ats-imports.ts\nexport default defineTable(atsImports, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"externalId\", \"source\", \"candidateName\", \"candidateEmail\", \"rawPayload\"],\n updatable: [\"candidateName\", \"candidateEmail\", \"rawPayload\", \"syncedAt\"],\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n delete: { access: { roles: [\"owner\"] } },\n});\n```\n\n## See Also\n\n- [Full Example](/compiler/getting-started/full-example) — Complete walkthrough with generated code\n- [Firewall](/compiler/definitions/firewall) — All data isolation options\n- [Actions](/compiler/definitions/actions) — Custom business logic"
162
+ "content": "Quick recipes for common scenarios. Each pattern shows the complete `defineTable` configuration.\n\n## Team-Wide Read, Manager-Only Write\n\nA job board where all team members can browse open positions but only hiring managers can create or edit jobs:\n\n```typescript\n// quickback/features/jobs/jobs.ts\nexport default defineTable(jobs, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"title\", \"department\", \"status\", \"salaryMin\", \"salaryMax\"],\n updatable: [\"title\", \"department\", \"status\"],\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n});\n```\n\n## User-Scoped Personal Data\n\nInterview notes that belong to a specific interviewer. Each interviewer only sees their own notes:\n\n```typescript\n// Schema includes both organizationId AND ownerId (q DSL)\n\nexport const interviewNotes = q.table(\"interview_notes\", {\n id: q.id(),\n candidateId: q.text().required(),\n content: q.text().required(),\n rating: q.int().optional(),\n organizationId: q.scope(\"organization\"),\n ownerId: q.text().required(),\n});\n\nexport default defineTable(interviewNotes, {\n firewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'ownerId', equals: 'ctx.userId' }, // Only the interviewer can see their own notes\n ],\n guards: {\n createable: [\"candidateId\", \"content\", \"rating\"],\n updatable: [\"content\", \"rating\"],\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] } },\n});\n```\n\nThe owner predicate (`{ field: 'ownerId', equals: 'ctx.userId' }`) means even hiring managers can only see notes they authored. To let hiring managers see all notes regardless of author, drop the owner predicate from the firewall and gate per-id access via record conditions instead.\n\n## Multi-Table Feature with Internal Tables\n\nA feature with a main table exposed via API and a junction table used only in actions:\n\n```typescript\n// quickback/features/applications/applications.ts — exposed via API\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"candidateId\", \"jobId\", \"stage\", \"notes\"],\n updatable: [\"notes\"],\n },\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```typescript\n// quickback/features/applications/interview-scores.ts — internal, no API routes\n// No default export = no routes generated\nexport const interviewScores = sqliteTable(\"interview_scores\", {\n applicationId: text(\"application_id\").notNull(),\n interviewerId: text(\"interviewer_id\").notNull(),\n score: integer(\"score\").notNull(),\n feedback: text(\"feedback\"),\n organizationId: text(\"organization_id\").notNull(), // Always scope junction tables\n});\n```\n\n```typescript\n// quickback/features/applications/actions.ts — uses the internal table\n\nexport default defineActions(applications, {\n // No `path:` → record-based action, mounted at POST /applications/:id/submitScore\n submitScore: {\n input: z.object({ score: z.number().min(1).max(5), feedback: z.string() }),\n access: { roles: [\"owner\", \"hiring-manager\", \"interviewer\"] },\n execute: async ({ db, record, input, ctx }) => {\n // The scoped db auto-injects organizationId (and audit fields) on insert.\n await db.insert(interviewScores).values({\n applicationId: record.id,\n interviewerId: ctx.userId,\n score: input.score,\n feedback: input.feedback,\n });\n return record;\n },\n },\n});\n```\n\n## Referencing Users / Org Members (Assignees)\n\nAssignee-style features need to validate that a submitted `userId` is actually a member of the caller's organization. The scoped `db` only sees feature tables — reach the Better Auth tables via `c.get(\"authDb\")` and the generated `getOrgMemberRole` helper:\n\n```typescript\n// quickback/features/projects/actions/assign.ts\n\nexport default defineAction({\n description: \"Assign a project to an org member\",\n input: z.object({ assigneeId: z.string() }),\n access: { roles: [\"member+\"] },\n async execute({ db, record, input, ctx, c, whereRecord }) {\n const role = await getOrgMemberRole(c.get(\"authDb\"), input.assigneeId, ctx.activeOrgId!);\n if (!role) {\n throw new ActionError(\"Assignee is not a member of this organization\", \"NOT_A_MEMBER\", 400);\n }\n const [updated] = await db\n .update(projects)\n .set({ assigneeId: input.assigneeId })\n .where(whereRecord!(projects))\n .returning();\n return updated;\n },\n});\n```\n\nStore the assignee as a plain text column (e.g. `assigneeId: q.text().optional()`) — don't name it `userId`, which the firewall validator treats as an ownership column on feature tables.\n\n## Admin-Only Status Field\n\nA field that only hiring managers can modify, but everyone can see:\n\n```typescript\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"candidateId\", \"jobId\", \"notes\"],\n updatable: [\"notes\"], // Recruiters can only update notes\n protected: { stage: [\"advanceStage\"] }, // Stage only changes via the named action\n },\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: [\"hiring-manager\"] } },\n});\n```\n\nThen create an action that hiring managers use to change stage:\n\n```typescript\n// quickback/features/applications/actions.ts\nexport default defineActions(applications, {\n advanceStage: {\n input: z.object({ stage: z.enum([\"applied\", \"screening\", \"interview\", \"offer\", \"hired\", \"rejected\"]) }),\n access: { roles: [\"hiring-manager\"] },\n execute: async ({ db, record, input }) => {\n await db.update(applications).set({ stage: input.stage }).where(eq(applications.id, record.id));\n return { ...record, stage: input.stage };\n },\n },\n});\n```\n\n## Sensitive Data with Role-Based Masking\n\nA candidate record where PII is masked differently per role:\n\n```typescript\nexport default defineTable(candidates, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"name\", \"email\", \"phone\", \"resumeUrl\", \"source\"],\n updatable: [\"name\", \"phone\"],\n },\n masking: {\n email: { type: \"email\", show: { roles: [\"hiring-manager\", \"recruiter\"] } },\n phone: { type: \"phone\", show: { roles: [\"hiring-manager\", \"recruiter\"] } },\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"hiring-manager\"] } },\n});\n```\n\n| Role | email | phone |\n|------|-------|-------|\n| hiring-manager | `jane@example.com` | `555-123-4567` |\n| recruiter | `jane@example.com` | `555-123-4567` |\n| interviewer | `j***@e******.com` | `***-***-4567` |\n\n## External System Sync\n\nAn import table for syncing candidates from an external ATS via upsert:\n\n```typescript\n// quickback/features/ats-imports/ats-imports.ts\nexport default defineTable(atsImports, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"externalId\", \"source\", \"candidateName\", \"candidateEmail\", \"rawPayload\"],\n updatable: [\"candidateName\", \"candidateEmail\", \"rawPayload\", \"syncedAt\"],\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n delete: { access: { roles: [\"owner\"] } },\n});\n```\n\n## See Also\n\n- [Full Example](/compiler/getting-started/full-example) — Complete walkthrough with generated code\n- [Firewall](/compiler/definitions/firewall) — All data isolation options\n- [Actions](/compiler/definitions/actions) — Custom business logic"
163
163
  },
164
164
  "compiler/getting-started/template-blog": {
165
165
  "title": "Blog Template",
166
- "content": "The blog template creates a fixed-org backend for a blog or CMS, deployed to Cloudflare Workers with D1. Public visitors can read content without authentication, while admins manage posts through their membership in one pinned organization.\n\nThis template uses [pinned organization mode](/compiler/config/single-tenant). Organization support stays on, but the generated project hard-codes one organization id and hides org switching UI.\n\n## Create the Project\n\n```bash\nquickback create blog my-site\ncd my-site\n```\n\nThis scaffolds a project with:\n\n```\nmy-site/\n├── quickback/\n│ ├── quickback.config.ts # Pinned-organization config\n│ └── features/\n│ └── posts/\n│ ├── posts.ts # Schema + security (defineTable)\n│ └── actions.ts # Publish/unpublish actions\n├── src/ # Compiled output (generated)\n├── package.json\n├── tsconfig.json\n├── wrangler.toml\n└── drizzle.config.ts\n```\n\n## Generated Configuration\n\n### quickback.config.ts\n\n```typescript\nexport default {\n name: \"my-site\",\n template: \"hono\",\n features: {\n pinnedOrganizationId: \"org_replace_me\",\n },\n providers: {\n runtime: { name: \"cloudflare\", config: {} },\n database: {\n name: \"cloudflare-d1\",\n config: { binding: \"DB\" },\n },\n auth: { name: \"better-auth\", config: {} },\n },\n};\n```\n\nReplace `org_replace_me` with a real Better Auth organization id before deploying. Unlike the removed single-tenant mode, this template keeps the Better Auth organization plugin and resolves roles from membership in that pinned org. See [Pinned Organization Mode](/compiler/config/single-tenant) for details.\n\n### Posts Feature (posts.ts)\n\nThe template includes a `posts` feature with public read access and admin-only write access:\n\n```typescript\n\nexport const posts = sqliteTable(\"posts\", {\n id: text(\"id\").primaryKey(),\n title: text(\"title\").notNull(),\n slug: text(\"slug\").notNull().unique(),\n content: text(\"content\"),\n excerpt: text(\"excerpt\"),\n status: text(\"status\").notNull().default(\"draft\"),\n publishedAt: text(\"published_at\"),\n ownerId: text(\"owner_id\").notNull(),\n});\n\nexport default defineTable(posts, {\n firewall: [\n { field: 'ownerId', equals: 'ctx.userId' },\n { field: 'deletedAt', isNull: true },\n ],\n guards: {\n createable: [\"title\", \"slug\", \"content\", \"excerpt\", \"status\", \"publishedAt\"],\n updatable: [\"title\", \"slug\", \"content\", \"excerpt\", \"status\", \"publishedAt\"],\n immutable: [\"id\", \"ownerId\"],\n },\n read: {\n access: { roles: [\"PUBLIC\"] },\n },\n create: { access: { roles: [\"admin\"] } },\n update: { access: { roles: [\"admin\"] } },\n delete: { access: { roles: [\"admin\"] }, mode: \"soft\" },\n});\n```\n\n- **`PUBLIC`** role on `read.access` means no authentication required for `GET /` and `GET /:id`\n- **`admin`** role on `create`, `update`, and `delete` requires an authenticated user with `member.role === \"admin\"` in the pinned organization\n- **`owner`** firewall scope tracks who created each post via `ownerId`\n- **`softDelete`** marks posts as deleted rather than removing them from the database\n\n### Post Actions (actions.ts)\n\nThe template includes publish/unpublish actions with guard conditions:\n\n```typescript\n\nexport default defineActions(posts, {\n publish: {\n description: \"Publish a draft post\",\n input: z.object({}),\n guard: {\n roles: [\"admin\"],\n record: { status: { equals: \"draft\" } },\n },\n sideEffects: \"sync\",\n },\n unpublish: {\n description: \"Revert a published post to draft\",\n input: z.object({}),\n guard: {\n roles: [\"admin\"],\n record: { status: { equals: \"published\" } },\n },\n sideEffects: \"sync\",\n },\n});\n```\n\nThese actions are admin-only and include record-level guards — you can only publish drafts and unpublish published posts.\n\n## Setup Steps\n\n### 1. Install Dependencies\n\n```bash\nnpm install\n```\n\n### 2. Log In to the Compiler\n\n```bash\nquickback login\n```\n\n### 3. Compile Your Definitions\n\n```bash\nquickback compile\n```\n\n### 4. Create D1 Database\n\nThe blog template uses a single D1 database (no split databases):\n\n```bash\nnpx wrangler d1 create my-site\n```\n\nCopy the database ID from the output and update your `wrangler.toml`:\n\n```toml\n[[d1_databases]]\nbinding = \"DB\"\ndatabase_name = \"my-site\"\ndatabase_id = \"paste-id-here\"\n```\n\n### 5. Run Migrations (Local)\n\n```bash\nnpm run db:migrate:local\n```\n\n### 6. Start Development Server\n\n```bash\nnpm run dev\n```\n\nYour API is running at `http://localhost:8787`.\n\n## Using the API\n\n### Public Endpoints (No Auth Required)\n\n```bash\n# List all posts\ncurl http://localhost:8787/api/v1/posts\n\n# Get a single post\ncurl http://localhost:8787/api/v1/posts/post-id-here\n```\n\n### Admin Endpoints (Auth Required)\n\n```bash\n# Create a post (admin only)\ncurl -X POST http://localhost:8787/api/v1/posts \\\n -H \"Authorization: Bearer $TOKEN\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"title\": \"Hello World\", \"slug\": \"hello-world\", \"content\": \"...\"}'\n\n# Publish a post (admin only)\ncurl -X POST http://localhost:8787/api/v1/posts/post-id/actions/publish \\\n -H \"Authorization: Bearer $TOKEN\"\n```\n\n### Pairing with a Frontend\n\nSince this is 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', slug: 'new-post', content: '...' }),\n});\n```\n\n## Adding More Features\n\nAdd new content types by creating feature directories. For example, a `pages` feature for static pages:\n\n```typescript\n// quickback/features/pages/pages.ts\n\nexport const pages = sqliteTable(\"pages\", {\n id: text(\"id\").primaryKey(),\n title: text(\"title\").notNull(),\n slug: text(\"slug\").notNull().unique(),\n content: text(\"content\"),\n ownerId: text(\"owner_id\").notNull(),\n});\n\nexport default defineTable(pages, {\n firewall: [{ field: 'ownerId', equals: 'ctx.userId' }],\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\nThen recompile:\n\n```bash\nquickback compile\n```\n\n## Deploying to Production\n\n```bash\n# Apply remote migrations\nnpm run db:migrate:remote\n\n# Deploy to Cloudflare\nnpm run deploy\n```\n\n## Next Steps\n\n- [Pinned Organization Mode](/compiler/config/single-tenant) — How fixed-org mode works\n- [Access Control](/compiler/definitions/access) — PUBLIC role and role-based permissions\n- [Custom Actions](/compiler/definitions/actions) — Add business logic beyond CRUD\n- [Cloudflare Template](/compiler/getting-started/template-cloudflare) — Multi-tenant alternative"
166
+ "content": "The blog template creates a fixed-org backend for a blog or CMS, deployed to Cloudflare Workers with D1. Public visitors can read content without authentication, while admins manage posts through their membership in one pinned organization.\n\nThis template uses [pinned organization mode](/compiler/config/single-tenant). Organization support stays on, but the generated project hard-codes one organization id and hides org switching UI.\n\n## Create the Project\n\n```bash\nquickback create blog my-site\ncd my-site\n```\n\nThis scaffolds a project with:\n\n```\nmy-site/\n├── quickback/\n│ ├── quickback.config.ts # Pinned-organization config\n│ └── features/\n│ └── posts/\n│ ├── posts.ts # Schema + security (defineTable)\n│ └── actions/\n│ ├── publish.ts # Publish action\n│ └── unpublish.ts # Unpublish action\n├── src/ # Compiled output (generated)\n├── package.json\n├── tsconfig.json\n├── wrangler.toml\n└── drizzle.config.ts\n```\n\n## Generated Configuration\n\n### quickback.config.ts\n\n```typescript\nexport default {\n name: \"my-site\",\n template: \"hono\",\n features: {\n pinnedOrganizationId: \"org_replace_me\",\n },\n providers: {\n runtime: { name: \"cloudflare\", config: {} },\n database: {\n name: \"cloudflare-d1\",\n config: { binding: \"DB\" },\n },\n auth: { name: \"better-auth\", config: {} },\n },\n};\n```\n\nReplace `org_replace_me` with a real Better Auth organization id before deploying. Unlike the removed single-tenant mode, this template keeps the Better Auth organization plugin and resolves roles from membership in that pinned org. See [Pinned Organization Mode](/compiler/config/single-tenant) for details.\n\n### Posts Feature (posts.ts)\n\nThe template includes a `posts` feature with public read access and admin-only write access:\n\n```typescript\n\nexport const posts = sqliteTable(\"posts\", {\n id: text(\"id\").primaryKey(),\n title: text(\"title\").notNull(),\n slug: text(\"slug\").notNull().unique(),\n content: text(\"content\"),\n excerpt: text(\"excerpt\"),\n status: text(\"status\").notNull().default(\"draft\"),\n publishedAt: text(\"published_at\"),\n\n // Author tracking only — this is metadata, not access control.\n // Named \"authorId\" (not \"userId\") so the firewall validator does NOT\n // enter user-scoped RLS mode. Reads are gated by PUBLIC; writes by the\n // admin access check below.\n authorId: text(\"author_id\").notNull(),\n});\n\nexport default defineTable(posts, {\n // PUBLIC reads — no isolation predicate at the firewall layer.\n // Anonymous viewers have no ctx.userId, so a userId/orgId WHERE clause\n // would gate every row out. softDelete keeps deleted posts hidden.\n firewall: {\n softDelete: {},\n },\n guards: {\n createable: [\"title\", \"slug\", \"content\", \"excerpt\", \"status\", \"publishedAt\"],\n updatable: [\"title\", \"slug\", \"content\", \"excerpt\", \"status\", \"publishedAt\"],\n immutable: [\"id\", \"authorId\"],\n },\n read: {\n access: { roles: [\"PUBLIC\"] },\n },\n // \"admin\" = org-membership admin role, resolved from membership in\n // the pinned organization (features.pinnedOrganizationId).\n create: { access: { roles: [\"admin\"] } },\n update: { access: { roles: [\"admin\"] } },\n delete: { access: { roles: [\"admin\"] }, mode: \"soft\" },\n});\n```\n\n- **`PUBLIC`** role on `read.access` means no authentication required for `GET /` and `GET /:id`\n- **`admin`** is the org-membership admin role — an authenticated user whose membership in the pinned organization has `role: \"admin\"` (or above). For platform-wide roles stored on `user.role`, use `userRole: [...]` instead — see [Pinned Organization Mode](/compiler/config/single-tenant)\n- **`authorId`** is plain metadata recording who wrote the post — it is deliberately *not* a firewall scope, because an owner predicate would hide every post from anonymous readers\n- **`softDelete`** marks posts as deleted rather than removing them from the database\n\n### Post Actions (actions/publish.ts, actions/unpublish.ts)\n\nThe template scaffolds one file per action under `features/posts/actions/`. Each is a `defineAction` with a record-level access condition and an `execute` handler:\n\n```typescript\n// quickback/features/posts/actions/publish.ts\n\nexport default defineAction({\n description: \"Publish a draft post\",\n input: z.object({}),\n access: {\n roles: [\"admin\"],\n record: { status: { equals: \"draft\" } },\n },\n sideEffects: \"sync\",\n async execute({ db, record }) {\n const [updated] = await db\n .update(posts)\n .set({\n status: \"published\",\n publishedAt: new Date().toISOString(),\n })\n .where(eq(posts.id, record.id))\n .returning();\n return updated;\n },\n});\n```\n\n`unpublish.ts` is the mirror image — it requires `status: \"published\"` and reverts the post to draft. These actions are admin-only and include record-level access conditions: you can only publish drafts and unpublish published posts.\n\n## Setup Steps\n\n### 1. Install Dependencies\n\n```bash\nnpm install\n```\n\n### 2. Log In to the Compiler\n\n```bash\nquickback login\n```\n\n### 3. Compile Your Definitions\n\n```bash\nquickback compile\n```\n\n### 4. Create D1 Databases\n\nLike every D1 project, the blog template uses dual database mode by default — separate databases for auth and application data:\n\n```bash\nnpx wrangler d1 create my-site-auth\nnpx wrangler d1 create my-site-features\n```\n\nCopy the database IDs from the output and update your `wrangler.toml`:\n\n```toml\n[[d1_databases]]\nbinding = \"AUTH_DB\"\ndatabase_name = \"my-site-auth\"\ndatabase_id = \"paste-auth-id-here\"\n\n[[d1_databases]]\nbinding = \"DB\"\ndatabase_name = \"my-site-features\"\ndatabase_id = \"paste-features-id-here\"\n```\n\n### 5. Run Migrations (Local)\n\n```bash\nnpm run db:migrate:local\n```\n\n### 6. Start Development Server\n\n```bash\nnpm run dev\n```\n\nYour API is running at `http://localhost:8787`.\n\n## Using the API\n\n### Public Endpoints (No Auth Required)\n\n```bash\n# List all posts\ncurl http://localhost:8787/api/v1/posts\n\n# Get a single post\ncurl http://localhost:8787/api/v1/posts/post-id-here\n```\n\n### Admin Endpoints (Auth Required)\n\n```bash\n# Create a post (admin only)\ncurl -X POST http://localhost:8787/api/v1/posts \\\n -H \"Authorization: Bearer $TOKEN\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"title\": \"Hello World\", \"slug\": \"hello-world\", \"content\": \"...\"}'\n\n# Publish a post (admin only) — record actions mount at /:id/{actionName}\ncurl -X POST http://localhost:8787/api/v1/posts/post-id/publish \\\n -H \"Authorization: Bearer $TOKEN\"\n```\n\n### Pairing with a Frontend\n\nSince this is 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', slug: 'new-post', content: '...' }),\n});\n```\n\n## Adding More Features\n\nAdd new content types by creating feature directories. For example, a `pages` feature for static pages:\n\n```typescript\n// quickback/features/pages/pages.ts\n\nexport const pages = sqliteTable(\"pages\", {\n id: text(\"id\").primaryKey(),\n title: text(\"title\").notNull(),\n slug: text(\"slug\").notNull().unique(),\n content: text(\"content\"),\n authorId: text(\"author_id\").notNull(),\n});\n\nexport default defineTable(pages, {\n // PUBLIC reads need an open firewall — an owner predicate would hide\n // every row from anonymous visitors. softDelete still hides deletions.\n firewall: { softDelete: {} },\n read: {\n access: { roles: [\"PUBLIC\"] },\n },\n create: { access: { roles: [\"admin\"] } },\n update: { access: { roles: [\"admin\"] } },\n delete: { access: { roles: [\"admin\"] }, mode: \"soft\" },\n});\n```\n\nThen recompile:\n\n```bash\nquickback compile\n```\n\n## Deploying to Production\n\n```bash\n# Apply remote migrations\nnpm run db:migrate:remote\n\n# Deploy to Cloudflare\nnpm run deploy\n```\n\n## Next Steps\n\n- [Pinned Organization Mode](/compiler/config/single-tenant) — How fixed-org mode works\n- [Access Control](/compiler/definitions/access) — PUBLIC role and role-based permissions\n- [Custom Actions](/compiler/definitions/actions) — Add business logic beyond CRUD\n- [Cloudflare Template](/compiler/getting-started/template-cloudflare) — Multi-tenant alternative"
167
167
  },
168
168
  "compiler/getting-started/template-cloudflare": {
169
169
  "title": "Cloudflare Template",
170
- "content": "The Cloudflare template creates a production-ready backend running on Cloudflare Workers with D1 (SQLite at the edge), KV storage, and Better Auth.\n\n`cloudflare` is a **bare scaffold** — multi-tenant orgs + auth + DB are wired in, but there are no example features. Add your own feature files under `quickback/features/`. If you want a working example to read first, use the [todos template](/compiler/getting-started/templates#multi-tenant-scaffolds-free) — same providers, but with a complete `todos` feature ready to extend.\n\n## Create the Project\n\nThe fastest path is `start` — interactive, scaffold + login + compile in one flow:\n\n```bash\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n# pick \"Cloudflare (bare scaffold)\" at the prompt\n```\n\nScriptable equivalent:\n\n```bash\nquickback create cloudflare my-app # aliases: cf\ncd my-app\n```\n\nThis scaffolds a project with:\n\n```\nmy-app/\n├── quickback/\n│ ├── quickback.config.ts # Compiler configuration\n│ └── features/ # (empty — add your own)\n├── src/ # Compiled output (generated by `quickback compile`)\n├── package.json\n├── tsconfig.json\n├── wrangler.toml\n└── drizzle.config.ts\n```\n\n## Generated Configuration\n\n### quickback.config.ts\n\n```typescript\nexport default {\n name: \"my-app\",\n template: \"hono\",\n features: {\n organizations: true,\n },\n auth: {\n // Use \"role+\" in access rules to mean \"this role and above\".\n // e.g. roles: [\"member+\"] expands to [\"member\", \"admin\", \"owner\"].\n roleHierarchy: [\"member\", \"admin\", \"owner\"],\n },\n providers: {\n runtime: { name: \"cloudflare\", config: {} },\n database: {\n name: \"cloudflare-d1\",\n config: { binding: \"DB\", realtime: true },\n },\n auth: { name: \"better-auth\", config: {} },\n },\n};\n```\n\n### Adding your first feature\n\nCreate a file at `quickback/features/<name>/<name>.ts` and export a `defineTable(...)` default. The shape used by the `todos` template makes a good starting point — see [todos.ts in the template registry](/compiler/getting-started/templates#multi-tenant-scaffolds-free) for a full multi-tenant example with masking, actions, and a named view.\n\n```typescript\n// quickback/features/posts/posts.ts\n\nexport const posts = sqliteTable(\"posts\", {\n id: text(\"id\").primaryKey(),\n title: text(\"title\").notNull(),\n body: text(\"body\"),\n organizationId: text(\"organization_id\").notNull(),\n userId: text(\"user_id\").notNull(),\n});\n\nexport default defineTable(posts, {\n firewall: { organization: {}, owner: {}, softDelete: {} },\n guards: {\n createable: [\"title\", \"body\"],\n updatable: [\"title\", \"body\"],\n immutable: [\"id\", \"organizationId\", \"userId\"],\n },\n read: { access: { roles: [\"member+\"] } },\n create: { access: { roles: [\"member+\"] } },\n update: { access: { roles: [\"member+\"] } },\n delete: { access: { roles: [\"admin+\"] }, mode: \"soft\" },\n});\n```\n\n## Setup Steps\n\nIf you used `quickback start`, dependencies, the first compile, and login are already done — skip to step 4. If you used `quickback create`, run these:\n\n### 1. Install Dependencies\n\n```bash\nnpm install\n```\n\n### 2. Compile Your Definitions\n\n```bash\nquickback compile\n```\n\nThis prompts for an account on the first run (sign in or create one in the browser), then generates the full `src/` directory, migrations, and configuration files. Subsequent compiles re-use the stored session.\n\n### 3. Create D1 Databases\n\nThe Cloudflare template uses **dual database mode** by default — separate databases for auth and application data.\n\n```bash\n# Create the auth database\nnpx wrangler d1 create my-app-auth\n\n# Create the features database\nnpx wrangler d1 create my-app-features\n```\n\nCopy the database IDs from the output and update your `wrangler.toml`:\n\n```toml\n[[d1_databases]]\nbinding = \"AUTH_DB\"\ndatabase_name = \"my-app-auth\"\ndatabase_id = \"paste-auth-id-here\"\n\n[[d1_databases]]\nbinding = \"DB\"\ndatabase_name = \"my-app-features\"\ndatabase_id = \"paste-features-id-here\"\n```\n\n### 4. Run Migrations (Local)\n\n```bash\nnpm run db:migrate:local\n```\n\nThis applies migrations to both databases locally.\n\n### 5. Start Development Server\n\n```bash\nnpm run dev\n```\n\nYour API is running at `http://localhost:8787`.\n\n## Wrangler Configuration\n\nThe compiler generates a `wrangler.toml` with all required bindings:\n\n```toml\nname = \"my-app\"\nmain = \"src/index.ts\"\ncompatibility_date = \"2025-03-01\"\ncompatibility_flags = [\"nodejs_compat\"]\n\n[observability]\nenabled = true\n\n[placement]\nmode = \"smart\"\n\n# Auth database\n[[d1_databases]]\nbinding = \"AUTH_DB\"\ndatabase_name = \"my-app-auth\"\ndatabase_id = \"your-auth-db-id\"\n\n# Features database\n[[d1_databases]]\nbinding = \"DB\"\ndatabase_name = \"my-app-features\"\ndatabase_id = \"your-features-db-id\"\n\n# Key-value storage\n[[kv_namespaces]]\nbinding = \"KV\"\nid = \"your-kv-id\"\n```\n\n### Optional Bindings\n\nDepending on your configuration, the compiler may also generate bindings for:\n\n| Binding | Type | When Generated |\n|---------|------|----------------|\n| `R2_BUCKET` | R2 Bucket | `fileStorage` configured |\n| `AI` | Workers AI | `embeddings` configured on any feature |\n| `VECTORIZE` | Vectorize Index | `embeddings` configured |\n| `EMBEDDINGS_QUEUE` | Queue | `embeddings` configured |\n| `WEBHOOKS_DB` | D1 | Webhooks enabled |\n| `WEBHOOKS_QUEUE` | Queue | Webhooks enabled |\n| `BROADCASTER` | Service | `realtime` configured |\n\n## Dual Database Mode\n\nBy default, the Cloudflare template separates auth tables from application tables:\n\n- **`AUTH_DB`** — Better Auth tables (`users`, `sessions`, `accounts`, `organizations`, `members`)\n- **`DB`** — Your feature tables (`todos`, etc.)\n\nThis keeps auth data isolated and allows independent scaling. Each database gets its own migration directory:\n\n```\nquickback/drizzle/\n├── auth/ # Auth migrations\n│ ├── meta/\n│ └── 0000_*.sql\n└── features/ # Feature migrations\n ├── meta/\n └── 0000_*.sql\n```\n\n## Deploying to Production\n\n### 1. Apply Remote Migrations\n\n```bash\nnpm run db:migrate:remote\n```\n\n### 2. Deploy to Cloudflare\n\n```bash\nnpm run deploy\n```\n\nThis runs `wrangler deploy` to push your worker to Cloudflare's edge network.\n\n## Available Scripts\n\n| Script | Command | Description |\n|--------|---------|-------------|\n| `dev` | `wrangler dev` | Start local dev server |\n| `deploy` | `npm run db:migrate:remote && wrangler deploy` | Deploy to production |\n| `db:migrate:local` | Runs auth + features migrations locally | Apply migrations to local D1 |\n| `db:migrate:remote` | Runs auth + features migrations remotely | Apply migrations to production D1 |\n\n## Next Steps\n\n- [Add a new feature](/compiler/definitions/schema) — Define your own tables with security\n- [Configure access control](/compiler/definitions/access) — Set role-based permissions\n- [Add custom actions](/compiler/definitions/actions) — Business logic beyond CRUD\n- [Environment variables](/compiler/config/variables) — Configure secrets and bindings"
170
+ "content": "The Cloudflare template creates a production-ready backend running on Cloudflare Workers with D1 (SQLite at the edge), KV storage, and Better Auth.\n\n`cloudflare` is a **bare scaffold** — multi-tenant orgs + auth + DB are wired in, but there are no example features. Add your own feature files under `quickback/features/`. If you want a working example to read first, use the [todos template](/compiler/getting-started/templates#multi-tenant-scaffolds) — same providers, but with a complete `todos` feature ready to extend.\n\n## Create the Project\n\nThe fastest path is `start` — interactive, scaffold + login + compile in one flow:\n\n```bash\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n# pick \"Cloudflare (bare scaffold)\" at the prompt\n```\n\nScriptable equivalent:\n\n```bash\nquickback create cloudflare my-app # aliases: cf\ncd my-app\n```\n\nThis scaffolds a project with:\n\n```\nmy-app/\n├── quickback/\n│ ├── quickback.config.ts # Compiler configuration\n│ └── features/ # (empty — add your own)\n├── src/ # Compiled output (generated by `quickback compile`)\n├── package.json\n├── tsconfig.json\n├── wrangler.toml\n└── drizzle.config.ts\n```\n\n## Generated Configuration\n\n### quickback.config.ts\n\n```typescript\nexport default {\n name: \"my-app\",\n template: \"hono\",\n auth: {\n // Use \"role+\" in access rules to mean \"this role and above\".\n // e.g. roles: [\"member+\"] expands to [\"member\", \"admin\", \"owner\"].\n roleHierarchy: [\"member\", \"admin\", \"owner\"],\n },\n providers: {\n runtime: { name: \"cloudflare\", config: {} },\n database: {\n name: \"cloudflare-d1\",\n config: { binding: \"DB\", realtime: true },\n },\n auth: { name: \"better-auth\", config: {} },\n },\n};\n```\n\nMulti-tenant organizations are on by default — no flag needed. To build a single-tenant app instead, set `organizations: false` on the database provider config.\n\n### Adding your first feature\n\nCreate a file at `quickback/features/<name>/<name>.ts` and export a `defineTable(...)` default. The shape used by the `todos` template makes a good starting point — see [todos.ts in the template registry](/compiler/getting-started/templates#multi-tenant-scaffolds) for a full multi-tenant example with masking, actions, and a named view.\n\n```typescript\n// quickback/features/posts/posts.ts\n\nexport const posts = sqliteTable(\"posts\", {\n id: text(\"id\").primaryKey(),\n title: text(\"title\").notNull(),\n body: text(\"body\"),\n organizationId: text(\"organization_id\").notNull(),\n userId: text(\"user_id\").notNull(),\n});\n\nexport default defineTable(posts, {\n firewall: { organization: {}, owner: {}, softDelete: {} },\n guards: {\n createable: [\"title\", \"body\"],\n updatable: [\"title\", \"body\"],\n immutable: [\"id\", \"organizationId\", \"userId\"],\n },\n read: { access: { roles: [\"member+\"] } },\n create: { access: { roles: [\"member+\"] } },\n update: { access: { roles: [\"member+\"] } },\n delete: { access: { roles: [\"admin+\"] }, mode: \"soft\" },\n});\n```\n\n## Setup Steps\n\nIf you used `quickback start`, dependencies, the first compile, and login are already done — skip to step 4. If you used `quickback create`, run these:\n\n### 1. Install Dependencies\n\n```bash\nnpm install\n```\n\n### 2. Compile Your Definitions\n\n```bash\nquickback compile\n```\n\nThis prompts for an account on the first run (sign in or create one in the browser), then generates the full `src/` directory, migrations, and configuration files. Subsequent compiles re-use the stored session.\n\n### 3. Create D1 Databases\n\nThe Cloudflare template uses **dual database mode** by default — separate databases for auth and application data.\n\n```bash\n# Create the auth database\nnpx wrangler d1 create my-app-auth\n\n# Create the features database\nnpx wrangler d1 create my-app-features\n```\n\nCopy the database IDs from the output and update your `wrangler.toml`:\n\n```toml\n[[d1_databases]]\nbinding = \"AUTH_DB\"\ndatabase_name = \"my-app-auth\"\ndatabase_id = \"paste-auth-id-here\"\n\n[[d1_databases]]\nbinding = \"DB\"\ndatabase_name = \"my-app-features\"\ndatabase_id = \"paste-features-id-here\"\n```\n\n### 4. Run Migrations (Local)\n\n```bash\nnpm run db:migrate:local\n```\n\nThis applies migrations to both databases locally.\n\n### 5. Start Development Server\n\n```bash\nnpm run dev\n```\n\nYour API is running at `http://localhost:8787`.\n\n## Wrangler Configuration\n\nThe compiler generates a `wrangler.toml` with all required bindings:\n\n```toml\nname = \"my-app\"\nmain = \"src/index.ts\"\ncompatibility_date = \"2025-03-01\"\ncompatibility_flags = [\"nodejs_compat\"]\n\n[observability]\nenabled = true\n\n[placement]\nmode = \"smart\"\n\n# Auth database\n[[d1_databases]]\nbinding = \"AUTH_DB\"\ndatabase_name = \"my-app-auth\"\ndatabase_id = \"your-auth-db-id\"\n\n# Features database\n[[d1_databases]]\nbinding = \"DB\"\ndatabase_name = \"my-app-features\"\ndatabase_id = \"your-features-db-id\"\n\n# Key-value storage\n[[kv_namespaces]]\nbinding = \"KV\"\nid = \"your-kv-id\"\n```\n\n### Optional Bindings\n\nDepending on your configuration, the compiler may also generate bindings for:\n\n| Binding | Type | When Generated |\n|---------|------|----------------|\n| `R2_BUCKET` | R2 Bucket | `fileStorage` configured |\n| `AI` | Workers AI | `embeddings` configured on any feature |\n| `VECTORIZE` | Vectorize Index | `embeddings` configured |\n| `EMBEDDINGS_QUEUE` | Queue | `embeddings` configured |\n| `WEBHOOKS_DB` | D1 | Webhooks enabled |\n| `WEBHOOKS_QUEUE` | Queue | Webhooks enabled |\n| `BROADCASTER` | Service | `realtime` configured |\n\n## Dual Database Mode\n\nBy default, the Cloudflare template separates auth tables from application tables:\n\n- **`AUTH_DB`** — Better Auth tables (`users`, `sessions`, `accounts`, `organizations`, `members`)\n- **`DB`** — Your feature tables (`todos`, etc.)\n\nThis keeps auth data isolated and allows independent scaling. Each database gets its own migration directory:\n\n```\nquickback/drizzle/\n├── auth/ # Auth migrations\n│ ├── meta/\n│ └── 0000_*.sql\n└── features/ # Feature migrations\n ├── meta/\n └── 0000_*.sql\n```\n\n## Deploying to Production\n\n### 1. Apply Remote Migrations\n\n```bash\nnpm run db:migrate:remote\n```\n\n### 2. Deploy to Cloudflare\n\n```bash\nnpm run deploy\n```\n\nThis runs `wrangler deploy` to push your worker to Cloudflare's edge network.\n\n## Available Scripts\n\n| Script | Command | Description |\n|--------|---------|-------------|\n| `dev` | `wrangler dev` | Start local dev server |\n| `deploy` | `npm run db:migrate:remote && wrangler deploy` | Deploy to production |\n| `db:migrate:local` | Runs auth + features migrations locally | Apply migrations to local D1 |\n| `db:migrate:remote` | Runs auth + features migrations remotely | Apply migrations to production D1 |\n\n## Next Steps\n\n- [Add a new feature](/compiler/definitions/schema) — Define your own tables with security\n- [Configure access control](/compiler/definitions/access) — Set role-based permissions\n- [Add custom actions](/compiler/definitions/actions) — Business logic beyond CRUD\n- [Environment variables](/compiler/config/variables) — Configure secrets and bindings"
171
171
  },
172
172
  "compiler/getting-started/template-empty": {
173
173
  "title": "Empty Scaffolding Templates",
174
- "content": "The `empty` template creates a project with only the configuration file — no example features. Use this when you know exactly what you want to build and don't need starter code.\n\n## Available Empty Templates\n\n| Template | Runtime | Database | Command |\n|----------|---------|----------|---------|\n| `empty` | Cloudflare Workers | D1 | `quickback create empty my-app` |\n\nAlias: `quickback create scaffold my-app` (same as `empty`)\n\n## Create the Project\n\n```bash\nquickback create empty my-app\n```\n\nThis scaffolds a minimal project:\n\n```\nmy-app/\n├── quickback/\n│ ├── quickback.config.ts # Compiler configuration\n│ └── features/ # Empty — add your own\n├── package.json\n└── tsconfig.json\n```\n\n## Generated Configuration\n\n```typescript\nexport default {\n name: \"my-app\",\n template: \"hono\",\n providers: {\n runtime: { name: \"cloudflare\", config: {} },\n database: {\n name: \"cloudflare-d1\",\n config: { binding: \"DB\" },\n },\n auth: { name: \"better-auth\", config: {} },\n },\n};\n```\n\nOrganization-backed auth is the default. If you want a fixed-org deployment with no org switching UI, add `features.pinnedOrganizationId` as described in [Pinned Organization Mode](/compiler/config/single-tenant).\n\n## Adding Your First Feature\n\nCreate a feature directory with a schema file:\n\n```bash\nmkdir -p quickback/features/products\n```\n\n```typescript\n// quickback/features/products/products.ts\n\nexport const products = sqliteTable(\"products\", {\n id: text(\"id\").primaryKey(),\n name: text(\"name\").notNull(),\n description: text(\"description\"),\n price: integer(\"price\").notNull(),\n organizationId: text(\"organization_id\").notNull(),\n userId: text(\"user_id\").notNull(),\n});\n\nexport default defineTable(products, {\n firewall: {\n organization: {},\n owner: {},\n softDelete: {},\n },\n guards: {\n createable: [\"name\", \"description\", \"price\"],\n updatable: [\"name\", \"description\", \"price\"],\n },\n read: {\n access: { roles: [\"member+\"] },\n },\n create: { access: { roles: [\"member+\"] } },\n update: { access: { roles: [\"member+\"] } },\n delete: { access: { roles: [\"admin+\"] }, mode: \"soft\" },\n});\n```\n\nThen compile:\n\n```bash\nquickback login # First time only\nquickback compile\n```\n\n## Setup Steps\n\nFollow the same setup steps as the [Cloudflare template](/compiler/getting-started/template-cloudflare#setup-steps). The only difference is you'll need to add at least one feature before compiling.\n\n## Next Steps\n\n- [Schema Definitions](/compiler/definitions/schema) — Define tables with Drizzle ORM\n- [Firewall](/compiler/definitions/firewall) — Data isolation and tenant scoping\n- [Access Control](/compiler/definitions/access) — Role-based permissions\n- [Guards](/compiler/definitions/guards) — Field-level write protection\n- [Full Example](/compiler/getting-started/full-example) — Complete feature walkthrough"
174
+ "content": "The `empty` template creates a project with only the configuration file — no example features. Use this when you know exactly what you want to build and don't need starter code.\n\n## Available Empty Templates\n\n| Template | Runtime | Database | Command |\n|----------|---------|----------|---------|\n| `empty` | Cloudflare Workers | D1 | `quickback create empty my-app` |\n\nAlias: `quickback create scaffold my-app` (same as `empty`)\n\n## Create the Project\n\n```bash\nquickback create empty my-app\n```\n\nThis scaffolds a minimal project:\n\n```\nmy-app/\n├── quickback/\n│ ├── quickback.config.ts # Compiler configuration\n│ └── features/ # Empty — add your own\n├── package.json\n└── tsconfig.json\n```\n\n## Generated Configuration\n\n```typescript\nexport default {\n name: \"my-app\",\n template: \"hono\",\n auth: {\n // Role hierarchy: lowest → highest privilege.\n // Use \"role+\" in access rules to mean \"this role and above\".\n // e.g. roles: [\"member+\"] expands to [\"member\", \"admin\", \"owner\"].\n roleHierarchy: [\"member\", \"admin\", \"owner\"],\n },\n providers: {\n runtime: { name: \"cloudflare\", config: {} },\n database: {\n name: \"cloudflare-d1\",\n config: { binding: \"DB\" },\n },\n auth: { name: \"better-auth\", config: {} },\n },\n};\n```\n\nOrganization-backed auth is the default. If you want a fixed-org deployment with no org switching UI, add `features.pinnedOrganizationId` as described in [Pinned Organization Mode](/compiler/config/single-tenant).\n\n## Adding Your First Feature\n\nCreate a feature directory with a schema file:\n\n```bash\nmkdir -p quickback/features/products\n```\n\n```typescript\n// quickback/features/products/products.ts\n\nexport const products = sqliteTable(\"products\", {\n id: text(\"id\").primaryKey(),\n name: text(\"name\").notNull(),\n description: text(\"description\"),\n price: integer(\"price\").notNull(),\n organizationId: text(\"organization_id\").notNull(),\n userId: text(\"user_id\").notNull(),\n});\n\nexport default defineTable(products, {\n firewall: {\n organization: {},\n owner: {},\n softDelete: {},\n },\n guards: {\n createable: [\"name\", \"description\", \"price\"],\n updatable: [\"name\", \"description\", \"price\"],\n },\n read: {\n access: { roles: [\"member+\"] },\n },\n create: { access: { roles: [\"member+\"] } },\n update: { access: { roles: [\"member+\"] } },\n delete: { access: { roles: [\"admin+\"] }, mode: \"soft\" },\n});\n```\n\nThen compile:\n\n```bash\nquickback login # First time only\nquickback compile\n```\n\n## Setup Steps\n\nFollow the same setup steps as the [Cloudflare template](/compiler/getting-started/template-cloudflare#setup-steps). Compiling with zero features works (you get an auth-only API); add feature files as you go and recompile.\n\n## Next Steps\n\n- [Schema Definitions](/compiler/definitions/schema) — Define tables with Drizzle ORM\n- [Firewall](/compiler/definitions/firewall) — Data isolation and tenant scoping\n- [Access Control](/compiler/definitions/access) — Role-based permissions\n- [Guards](/compiler/definitions/guards) — Field-level write protection\n- [Full Example](/compiler/getting-started/full-example) — Complete feature walkthrough"
175
175
  },
176
176
  "compiler/getting-started/templates": {
177
177
  "title": "Templates",
178
- "content": "Quickback provides pre-configured templates to get you started quickly. Each template combines a runtime, database, and auth provider into a working project.\n\nThe fastest way to start is `quickback start` — an interactive picker that asks for a template + project name and scaffolds in the current directory if it's empty, otherwise creates a subfolder. Every template below can be reached either via `start`'s picker (free tier) or scriptably via `quickback create <template> <name>`.\n\n```bash\n# Interactive (recommended for first-time use)\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n```\n\n## Available Templates\n\n### Multi-tenant scaffolds (free)\n\nCloudflare Workers + D1 + Better Auth with the organization plugin and a `member` / `admin` / `owner` role hierarchy wired in.\n\n| Template | Includes | Command |\n|----------|----------|---------|\n| `cloudflare` | Bare scaffold — auth + DB + Hono, no example feature | `quickback create cloudflare my-app` |\n| `todos` | Working todos feature: schema, masking, two actions (`complete` / `uncomplete`), and a `dashboard` named view | `quickback create todos my-app` |\n\nThe **todos** template is the recommended first read — it exercises every security pillar (firewall, access, guards, masking) plus actions and views in ~80 lines you can scan in five minutes.\n\n### Fixed-org starter (free)\n\n| Template | Includes | Command |\n|----------|----------|---------|\n| `blog` | Blog with PUBLIC reads, admin writes, `publish` / `unpublish` actions, and a pinned organization id placeholder | `quickback create blog my-site` |\n\nThe **blog** template uses [pinned organization mode](/compiler/config/single-tenant) and scaffolds `features.pinnedOrganizationId: \"org_replace_me\"`.\n\n### Empty scaffold (free)\n\n| Template | Includes | Command |\n|----------|----------|---------|\n| `empty` | `quickback.config.ts` only — no example features | `quickback create empty my-app` |\n\nThe empty template creates the project structure with `quickback.config.ts` only. Add your first feature by creating a file under `quickback/features/<name>/<name>.ts` exporting `defineTable(...)` — there is no separate `init` step.\n\n### B2B SaaS (Pro)\n\n| Template | Includes | Command |\n|----------|----------|---------|\n| `saas` | Multi-tenant + **R2 file storage** + **outbound webhooks** + split databases + realtime + named views | `quickback create saas my-app` |\n\n## What Each Template Includes\n\nThe `cloudflare`, `todos`, `blog`, and `saas` templates all scaffold:\n\n- **`quickback.config.ts`** — Pre-configured with the right providers\n- **`quickback/features/`** — Feature definitions (empty for `cloudflare`; populated for `todos` / `blog` / `saas`)\n- **Deployment scripts** — `npm run deploy` for Cloudflare via wrangler\n\nThe `empty` template includes only:\n\n- **`quickback.config.ts`**\n- **`package.json`** — dependencies ready to install\n\n## Choosing a Template\n\n### Cloudflare bare scaffold\n\nBest when you already know the conventions and want empty walls. Multi-tenant orgs are wired in; you add your own feature files.\n\n### Todos (recommended for newcomers)\n\nBest for learning by reading. Full multi-tenant security pillars, two actions, a named view (`/api/v1/todos/views/dashboard`), and field masking on the `description` column — all in a single ~80-line file you can copy-edit into your own table.\n\n### Blog (pinned-organization CMS)\n\nBest for personal sites, blogs, or any app that only needs one organization at runtime. Uses [pinned organization mode](/compiler/config/single-tenant) — organization support stays on, but the generated app hard-codes one org id and hides org switching.\n\n- Public JSON API for content\n- Admin-only editing\n- Pair with any frontend (Astro, Next.js, SvelteKit, etc.)\n\n### Empty\n\nBest when you know exactly what you want to build. Gets you the project structure and config without any opinionated features.\n\n### SaaS (Pro)\n\nBest for production B2B work. Adds R2 file uploads, outbound webhooks (with retry/dedupe), split auth/features/webhooks databases, realtime broadcast, and named views.\n\n## Template Aliases\n\nFor convenience, templates have short aliases:\n\n| Alias | Full id |\n|-------|---------|\n| `cloudflare` / `cf` | `betterauth-d1-cloudflare` |\n| `todos` | `todos-cloudflare` |\n| `blog` | `blog-cloudflare` |\n| `saas` | `b2bsaas-cloudflare` |\n| `empty` / `scaffold` | `empty-cloudflare` |\n\n## After Scaffolding\n\n`quickback start` runs scaffold + login + compile + install + drizzle in one flow. If you used the scriptable `quickback create` instead (or cancelled at the login prompt), finish setup with:\n\n```bash\ncd my-app\nquickback compile # prompts for login on first run; reuses session after\nnpm run dev\n```\n\nSee the individual template guides for detailed setup:\n- [Cloudflare Template](/compiler/getting-started/template-cloudflare)\n- [Blog Template](/compiler/getting-started/template-blog)\n- [Empty Scaffolding](/compiler/getting-started/template-empty)\n- [Pinned Organization Mode](/compiler/config/single-tenant)"
178
+ "content": "Quickback provides pre-configured templates to get you started quickly. Each template combines a runtime, database, and auth provider into a working project.\n\nThe fastest way to start is `quickback start` — an interactive picker that asks for a template + project name and scaffolds in the current directory if it's empty, otherwise creates a subfolder. The picker offers `cloudflare`, `todos`, `blog`, and `empty`; every template (including `saas`) is available scriptably via `quickback create <template> <name>`.\n\n```bash\n# Interactive (recommended for first-time use)\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n```\n\n## Available Templates\n\n### Multi-tenant scaffolds\n\nCloudflare Workers + D1 + Better Auth with the organization plugin and a `member` / `admin` / `owner` role hierarchy wired in.\n\n| Template | Includes | Command |\n|----------|----------|---------|\n| `cloudflare` | Bare scaffold — auth + DB + Hono, no example feature | `quickback create cloudflare my-app` |\n| `todos` | Working todos feature: schema, masking, two actions (`complete` / `uncomplete`), and a `dashboard` named view | `quickback create todos my-app` |\n\nThe **todos** template is the recommended first read — it exercises every security pillar (firewall, access, guards, masking) plus actions and views in ~80 lines you can scan in five minutes.\n\n### Fixed-org starter\n\n| Template | Includes | Command |\n|----------|----------|---------|\n| `blog` | Blog with PUBLIC reads, admin writes, `publish` / `unpublish` actions, and a pinned organization id placeholder | `quickback create blog my-site` |\n\nThe **blog** template uses [pinned organization mode](/compiler/config/single-tenant) and scaffolds `features.pinnedOrganizationId: \"org_replace_me\"`.\n\n### Empty scaffold\n\n| Template | Includes | Command |\n|----------|----------|---------|\n| `empty` | `quickback.config.ts` only — no example features | `quickback create empty my-app` |\n\nThe empty template creates the project structure with `quickback.config.ts` only. Add your first feature by creating a file under `quickback/features/<name>/<name>.ts` exporting `defineTable(...)` — there is no separate `init` step.\n\n### B2B SaaS\n\n| Template | Includes | Command |\n|----------|----------|---------|\n| `saas` | Multi-tenant + **R2 file storage** + **outbound webhooks** + split databases + realtime + named views | `quickback create saas my-app` |\n\n## What Each Template Includes\n\nThe `cloudflare`, `todos`, `blog`, and `saas` templates all scaffold:\n\n- **`quickback.config.ts`** — Pre-configured with the right providers\n- **`quickback/features/`** — Feature definitions (empty for `cloudflare`; populated for `todos` / `blog` / `saas`)\n- **Deployment scripts** — `npm run deploy` for Cloudflare via wrangler\n\nThe `empty` template includes only:\n\n- **`quickback.config.ts`**\n- **`package.json`** — dependencies ready to install\n\n## Choosing a Template\n\n### Cloudflare bare scaffold\n\nBest when you already know the conventions and want empty walls. Multi-tenant orgs are wired in; you add your own feature files.\n\n### Todos (recommended for newcomers)\n\nBest for learning by reading. Full multi-tenant security pillars, two actions, a named view (`/api/v1/todos/views/dashboard`), and field masking on the `description` column — all in a single ~80-line file you can copy-edit into your own table.\n\n### Blog (pinned-organization CMS)\n\nBest for personal sites, blogs, or any app that only needs one organization at runtime. Uses [pinned organization mode](/compiler/config/single-tenant) — organization support stays on, but the generated app hard-codes one org id and hides org switching.\n\n- Public JSON API for content\n- Admin-only editing\n- Pair with any frontend (Astro, Next.js, SvelteKit, etc.)\n\n### Empty\n\nBest when you know exactly what you want to build. Gets you the project structure and config without any opinionated features.\n\n### SaaS\n\nBest for production B2B work. Adds R2 file uploads, outbound webhooks (with retry/dedupe), split auth/features/webhooks databases, realtime broadcast, and named views.\n\n## Template Aliases\n\nFor convenience, templates have short aliases:\n\n| Alias | Full id |\n|-------|---------|\n| `cloudflare` / `cf` | `betterauth-d1-cloudflare` |\n| `todos` | `todos-cloudflare` |\n| `blog` | `blog-cloudflare` |\n| `saas` | `b2bsaas-cloudflare` |\n| `empty` / `scaffold` | `empty-cloudflare` |\n\n## After Scaffolding\n\n`quickback start` runs scaffold + login + compile + install + drizzle in one flow. If you used the scriptable `quickback create` instead (or cancelled at the login prompt), finish setup with:\n\n```bash\ncd my-app\nquickback compile # prompts for login on first run; reuses session after\nnpm run dev\n```\n\nSee the individual template guides for detailed setup:\n- [Cloudflare Template](/compiler/getting-started/template-cloudflare)\n- [Blog Template](/compiler/getting-started/template-blog)\n- [Empty Scaffolding](/compiler/getting-started/template-empty)\n- [Pinned Organization Mode](/compiler/config/single-tenant)"
179
179
  },
180
180
  "compiler": {
181
181
  "title": "Quickback Compiler",
@@ -231,7 +231,7 @@ export const DOCS = {
231
231
  },
232
232
  "compiler/targets/hono-api/using-the-api/openapi": {
233
233
  "title": "OpenAPI Spec",
234
- "content": "The compiler generates an [OpenAPI 3.1](https://spec.openapis.org/oas/v3.1.0) specification from your feature definitions. By default it's both written to `openapi.json` at your project root and served as a runtime route.\n\n## Endpoint\n\n```\nGET /openapi.json\n```\n\nReturns the full OpenAPI spec as JSON.\n\n```bash\ncurl https://your-api.example.com/openapi.json\n```\n\n## What's included\n\nThe generated spec documents every route the compiler produces:\n\n- CRUD endpoints (list, get, create, update, delete)\n- Batch operations\n- Views\n- Actions (including standalone actions)\n- Auth routes (`/api/auth/**`)\n- Storage, embeddings, and webhook routes (when configured)\n\nEach endpoint includes request/response schemas derived from your Drizzle column types, access control metadata, and error responses.\n\n### Schema fidelity\n\nThe generated component schemas carry enough type information that strict validators (zod, openapi-typescript, openapi-fetch) produce non-optional, narrowed types out of the box:\n\n- **`required[]` on response components** — every non-nullable column is listed, so generated SDKs treat them as guaranteed-present rather than optional.\n- **Closed enums on `text(_, { enum: [...] })` columns** — emitted as `{ type: \"string\", enum: [...] }`, narrowing to a literal union in TS.\n- **`Error.code` is a closed enum** — every `code` value the API can emit (`AUTH_MISSING`, `DB_UNIQUE_VIOLATION`, `BATCH_SIZE_EXCEEDED`, …) is enumerated so consumers can `switch` exhaustively.\n- **ID `format`** — only emitted as `format: \"uuid\"` when your project's `generateId` actually produces UUIDs. cuid2 / prefixed / nanoid / serial generators get plain `{ type: \"string\" }`, keeping strict OpenAPI validators happy.\n\n### Action input schemas\n\nActions defined with [`defineAction({ input: z.object(...) })`](/compiler/definitions/actions) get their full input schema lifted into the operation's `requestBody`. Simple `z.object({...})` shapes are extracted at compile time; for discriminated unions, refinements, recursive schemas, and bare-identifier references (`input: createPersonInput`), the compiler runs your action file through Zod 4's native `z.toJSONSchema()` during compilation so the OpenAPI request body and the MCP tool's `inputSchema` round-trip exactly what your Zod expression declares — no static translator to maintain.\n\n## Configuration\n\nBoth generation and publishing default to `true`. You can control them independently in `quickback.config.ts`:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n // ...\n openapi: {\n generate: true, // write openapi.json to project root\n publish: true, // serve GET /openapi.json at runtime\n },\n});\n```\n\n| Option | Default | Description |\n|--------|---------|-------------|\n| `generate` | `true` | Write `openapi.json` to the project root during compilation |\n| `publish` | `true` | Serve the spec at `GET /openapi.json` (requires `generate: true`) |\n| `docs` | `false` | Mount an interactive API browser at `GET /docs` — `\"scalar\"`, `\"swagger\"`, or `false` |\n\nOmitting the `openapi` key entirely is equivalent to `generate: true, publish: true, docs: false`.\n\n### Generate only (no runtime route)\n\n```typescript\nopenapi: {\n generate: true,\n publish: false,\n}\n```\n\nThe file is still written so you can use it in CI or commit it to your repo, but no route is added to the app.\n\n### Disable entirely\n\n```typescript\nopenapi: {\n generate: false,\n}\n```\n\nNo file is written and no route is served.\n\n### Interactive API browser at `/docs`\n\nMount an in-browser API reference by setting `openapi.docs`:\n\n```typescript\nopenapi: {\n docs: 'scalar', // or 'swagger'\n}\n```\n\n| Value | UI | Notes |\n|---|---|---|\n| `\"scalar\"` | [Scalar API Reference](https://scalar.com/) — modern, lightweight | Recommended default |\n| `\"swagger\"` | [Swagger UI](https://swagger.io/tools/swagger-ui/) — the familiar standard | Good if your team expects it |\n| `false` / unset | No `/docs` route | Default |\n\nBoth UIs are loaded from CDN in a generated static HTML route — **no npm package is added to your project, no Hono middleware is installed, and the runtime bundle stays the same size**. The flag is purely compile-time: it toggles whether a `/docs` route is emitted.\n\nRequires `publish: true` (the default). When `publish` is off, `/docs` is silently skipped — there's no spec for it to read.\n\n## Usage with tools\n\n### Import into Postman\n\n1. Open Postman and click **Import**\n2. Paste the URL `https://your-api.example.com/openapi.json` or upload the file\n3. Postman creates a collection with every endpoint pre-configured\n\n### Generated TypeScript types (`api-types.gen.ts`)\n\nThe compiler emits `api-types.gen.ts` next to `openapi.json` by default — a fully typed view of every route, request body, and response, ready to import in client code:\n\n```typescript\n\ntype Job = components['schemas']['Job'];\ntype ListJobsResponse = paths['/api/v1/jobs']['get']['responses']['200']['content']['application/json'];\n```\n\nPair it with [`openapi-fetch`](https://github.com/openapi-ts/openapi-typescript/tree/main/packages/openapi-fetch) for a fully typed client:\n\n```typescript\n\nconst client = createClient<paths>({ baseUrl: 'https://your-api.example.com' });\nconst { data, error } = await client.GET('/api/v1/jobs', { params: { query: { limit: 25 } } });\n```\n\n#### Configuration\n\n| `openapi.types` | Behavior |\n|---|---|\n| `true` (default) | Write `api-types.gen.ts` to the project root |\n| `false` | Don't emit the types file |\n| `\"src/lib/api-types.ts\"` | Custom output path (relative to project root) |\n| `[\"api-types.gen.ts\", \"apps/web/src/lib/api-types.gen.ts\"]` | Write the same generated types to multiple paths in one compile |\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n // ...\n openapi: {\n types: ['api-types.gen.ts', 'apps/web/src/lib/api-types.gen.ts'],\n },\n});\n```\n\nThe file is generated by piping the in-memory spec through [openapi-typescript](https://github.com/openapi-ts/openapi-typescript) — you can keep running it manually if you want a different output path or version, but for the typical case there's nothing to wire up. If your API project and SPA live in the same repo, prefer multiple `openapi.types` outputs over a second manual `codegen:api` step so one `quickback compile` keeps both copies in sync. Skipped automatically when `openapi.generate` is `false`.\n\nThe bundled Quickback CMS and Account SPAs do not import `api-types.gen.ts`. CMS is driven by `schema-registry.json`, and Account uses Better Auth plus small hand-written fetch helpers. Use `openapi.types` for your own colocated client apps.\n\n### External viewer\n\nPoint any OpenAPI-compatible viewer at the endpoint:\n\n```\nhttps://petstore.swagger.io/?url=https://your-api.example.com/openapi.json\n```\n\nOr enable the in-project browser via the [`docs` config option](#interactive-api-browser-at-docs) above and visit `/docs` directly.\n\n## Example output (excerpt)\n\n```json\n{\n \"openapi\": \"3.1.0\",\n \"info\": {\n \"title\": \"my-app API\",\n \"version\": \"1.0.0\"\n },\n \"paths\": {\n \"/api/v1/jobs\": {\n \"get\": {\n \"summary\": \"List jobs\",\n \"operationId\": \"listJobs\",\n \"parameters\": [\n { \"name\": \"limit\", \"in\": \"query\", \"schema\": { \"type\": \"integer\" } },\n { \"name\": \"offset\", \"in\": \"query\", \"schema\": { \"type\": \"integer\" } }\n ],\n \"responses\": {\n \"200\": {\n \"description\": \"Success\",\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"data\": { \"type\": \"array\", \"items\": { \"$ref\": \"#/components/schemas/Job\" } }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```"
234
+ "content": "The compiler generates an [OpenAPI 3.1](https://spec.openapis.org/oas/v3.1.0) specification from your feature definitions. By default it's both written to `openapi.json` at your project root and served as a runtime route.\n\n## Endpoint\n\n```\nGET /openapi.json\n```\n\nReturns the full OpenAPI spec as JSON.\n\n```bash\ncurl https://your-api.example.com/openapi.json\n```\n\n## What's included\n\nThe generated spec documents every route the compiler produces:\n\n- CRUD endpoints (list, get, create, update, delete)\n- Batch operations\n- Views\n- Actions (including standalone actions)\n- Auth routes (`/api/auth/**`)\n- Storage, embeddings, and webhook routes (when configured)\n\nEach endpoint includes request/response schemas derived from your Drizzle column types, access control metadata, and error responses.\n\n### Schema fidelity\n\nThe generated component schemas carry enough type information that strict validators (zod, openapi-typescript, openapi-fetch) produce non-optional, narrowed types out of the box:\n\n- **`required[]` on response components** — every non-nullable column is listed, so generated SDKs treat them as guaranteed-present rather than optional.\n- **Closed enums on `text(_, { enum: [...] })` columns** — emitted as `{ type: \"string\", enum: [...] }`, narrowing to a literal union in TS.\n- **`Error.code` is a closed enum** — every `code` value the API can emit (`AUTH_MISSING`, `DB_UNIQUE_VIOLATION`, `BATCH_SIZE_EXCEEDED`, …) is enumerated so consumers can `switch` exhaustively.\n- **ID `format`** — only emitted as `format: \"uuid\"` when your project's `generateId` actually produces UUIDs. cuid2 / prefixed / nanoid / serial generators get plain `{ type: \"string\" }`, keeping strict OpenAPI validators happy.\n\n### Action input schemas\n\nActions defined with [`defineAction({ input: z.object(...) })`](/compiler/definitions/actions) get their full input schema lifted into the operation's `requestBody`. Simple `z.object({...})` shapes are extracted at compile time; for discriminated unions, refinements, recursive schemas, and bare-identifier references (`input: createPersonInput`), the compiler runs your action file through Zod 4's native `z.toJSONSchema()` during compilation so the OpenAPI request body and the MCP tool's `inputSchema` round-trip exactly what your Zod expression declares — no static translator to maintain.\n\n## Configuration\n\nBoth generation and publishing default to `true`. You can control them independently in `quickback.config.ts`:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n // ...\n openapi: {\n generate: true, // write openapi.json to project root\n publish: true, // serve GET /openapi.json at runtime\n },\n});\n```\n\n| Option | Default | Description |\n|--------|---------|-------------|\n| `generate` | `true` | Write `openapi.json` to the project root during compilation |\n| `publish` | `true` | Serve the spec at `GET /openapi.json` (requires `generate: true`) |\n| `docs` | `false` | Mount an interactive API browser at `GET /docs` — `\"scalar\"`, `\"swagger\"`, or `false` |\n\nOmitting the `openapi` key entirely is equivalent to `generate: true, publish: true, docs: false`.\n\n### Generate only (no runtime route)\n\n```typescript\nopenapi: {\n generate: true,\n publish: false,\n}\n```\n\nThe file is still written so you can use it in CI or commit it to your repo, but no route is added to the app.\n\n### Disable entirely\n\n```typescript\nopenapi: {\n generate: false,\n}\n```\n\nNo file is written and no route is served.\n\n### Interactive API browser at `/docs`\n\nMount an in-browser API reference by setting `openapi.docs`:\n\n```typescript\nopenapi: {\n docs: 'scalar', // or 'swagger'\n}\n```\n\n| Value | UI | Notes |\n|---|---|---|\n| `\"scalar\"` | [Scalar API Reference](https://scalar.com/) — modern, lightweight | Recommended default |\n| `\"swagger\"` | [Swagger UI](https://swagger.io/tools/swagger-ui/) — the familiar standard | Good if your team expects it |\n| `false` / unset | No `/docs` route | Default |\n\nBoth UIs are loaded from CDN in a generated static HTML route — **no npm package is added to your project, no Hono middleware is installed, and the runtime bundle stays the same size**. The flag is purely compile-time: it toggles whether a `/docs` route is emitted.\n\nRequires `publish: true` (the default). When `publish` is off, `/docs` is silently skipped — there's no spec for it to read.\n\n## Usage with tools\n\n### Import into Postman\n\n1. Open Postman and click **Import**\n2. Paste the URL `https://your-api.example.com/openapi.json` or upload the file\n3. Postman creates a collection with every endpoint pre-configured\n\n### Generated TypeScript types (`api-types.gen.ts`)\n\nThe compiler emits `api-types.gen.ts` next to `openapi.json` by default — a fully typed view of every route, request body, and response, ready to import in client code:\n\n```typescript\n\ntype Job = components['schemas']['Job'];\ntype ListJobsResponse = paths['/api/v1/jobs']['get']['responses']['200']['content']['application/json'];\n```\n\nPair it with [`openapi-fetch`](https://github.com/openapi-ts/openapi-typescript/tree/main/packages/openapi-fetch) for a fully typed client:\n\n```typescript\n\nconst client = createClient<paths>({ baseUrl: 'https://your-api.example.com' });\nconst { data, error } = await client.GET('/api/v1/jobs', { params: { query: { limit: 25 } } });\n```\n\n#### Configuration\n\n| `openapi.types` | Behavior |\n|---|---|\n| `true` (default) | Write `api-types.gen.ts` to the project root |\n| `false` | Don't emit the types file |\n| `\"src/lib/api-types.ts\"` | Custom output path (relative to project root) |\n| `[\"api-types.gen.ts\", \"apps/web/src/lib/api-types.gen.ts\"]` | Write the same generated types to multiple paths in one compile |\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n // ...\n openapi: {\n types: ['api-types.gen.ts', 'apps/web/src/lib/api-types.gen.ts'],\n },\n});\n```\n\nThe file is generated by piping the in-memory spec through [openapi-typescript](https://github.com/openapi-ts/openapi-typescript) — you can keep running it manually if you want a different output path or version, but for the typical case there's nothing to wire up. If your API project and SPA live in the same repo, prefer multiple `openapi.types` outputs over a second manual `codegen:api` step so one `quickback compile` keeps both copies in sync. Skipped automatically when `openapi.generate` is `false`.\n\nThe bundled Quickback CMS and Account SPAs do not import `api-types.gen.ts`. CMS is driven by `schema-registry.json`, and Account uses Better Auth plus small hand-written fetch helpers. Use `openapi.types` for your own colocated client apps.\n\n### External viewer\n\nPoint any OpenAPI-compatible viewer at the endpoint:\n\n```\nhttps://petstore.swagger.io/?url=https://your-api.example.com/openapi.json\n```\n\nOr enable the in-project browser via the [`docs` config option](#interactive-api-browser-at-docs) above and visit `/docs` directly.\n\n## Example output (excerpt)\n\n```json\n{\n \"openapi\": \"3.1.0\",\n \"info\": {\n \"title\": \"my-app API\",\n \"version\": \"1.0.0\"\n },\n \"paths\": {\n \"/api/v1/jobs\": {\n \"get\": {\n \"summary\": \"List jobs\",\n \"operationId\": \"listJobs\",\n \"parameters\": [\n { \"name\": \"limit\", \"in\": \"query\", \"schema\": { \"type\": \"integer\" } },\n { \"name\": \"offset\", \"in\": \"query\", \"schema\": { \"type\": \"integer\" } }\n ],\n \"responses\": {\n \"200\": {\n \"description\": \"Success\",\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"data\": { \"type\": \"array\", \"items\": { \"$ref\": \"#/components/schemas/Job\" } }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n## Operations manifest\n\nAlongside the spec, every compile writes `reports/operations.manifest.json` — a\nstable, machine-readable index of the full route surface (resource, action,\nview, and auth routes):\n\n```json\n[\n { \"operationId\": \"listCustomers\", \"method\": \"GET\", \"path\": \"/api/v1/customers\", \"auth\": \"session\", \"feature\": \"customers\", \"kind\": \"crud\" }\n]\n```\n\nThe manifest is a public contract: entries are sorted by `operationId`, carry\nno timestamps, and the shape is extend-only — new fields may be added, existing\nones won't change meaning. `operationId`s are stable across compiles for the\nsame configuration, which makes the manifest the recommended integration point\nfor agent/MCP tooling, route inventories, and diff-based change review.\n\nA sibling artifact, `reports/conformance.manifest.json`, enumerates the\nexpected authorization outcome for every route × principal class (derived from\nthe same compiler model that emits the enforcement code). The compiler's own CI\nexecutes it against a running build on every change."
235
235
  },
236
236
  "compiler/targets/hono-api/using-the-api/query-params": {
237
237
  "title": "Query Parameters",
@@ -291,7 +291,7 @@ export const DOCS = {
291
291
  },
292
292
  "stack/account-ui/features/passwordless": {
293
293
  "title": "Passwordless Authentication",
294
- "content": "Account UI supports passwordless authentication via email OTP and magic links.\n\n## Email OTP\n\nWhen `ENABLE_EMAIL_OTP=true`:\n\n- Users enter their email address\n- A one-time password is sent via email\n- User enters the OTP code to authenticate\n\n## Magic Links\n\nWhen `ENABLE_MAGIC_LINK=true`:\n\n- Users enter their email address\n- A login link is sent via email\n- Clicking the link authenticates the user\n\n## Combo Auth\n\nWhen both are enabled, Account UI uses the `@quickback-dev/better-auth-combo-auth` plugin to combine them into a single flow — the email contains both a clickable link and a code.\n\n## Related\n\n- [Auth Plugins](/stack/auth/plugins) — Plugin configuration\n- [Environment Variables](/stack/account-ui/environment-variables)"
294
+ "content": "Account UI supports passwordless authentication via email OTP.\n\n## Email OTP\n\nWhen `ENABLE_EMAIL_OTP=true`:\n\n- Users enter their email address\n- A one-time password is sent via email\n- User enters the OTP code to authenticate\n\nThe sign-in email contains the six-digit code only — no magic-link companion. Mail-client URL prefetching burns single-use links, so a code the user types is the reliable path.\n\n## What about magic links?\n\nAccount UI does not offer a magic-link sign-in flow. The `magicLink` Better Auth plugin is still available at the API level (see [Auth Plugins](/stack/auth/plugins#magic-links)) for apps that build their own sign-in UI, but the bundled Account SPA is OTP-only by design.\n\n## Related\n\n- [Auth Plugins](/stack/auth/plugins) — Plugin configuration\n- [Environment Variables](/stack/account-ui/environment-variables)"
295
295
  },
296
296
  "stack/account-ui/features/sessions": {
297
297
  "title": "Session Management",
@@ -299,7 +299,7 @@ export const DOCS = {
299
299
  },
300
300
  "stack/account-ui/hooks": {
301
301
  "title": "Auth Hooks",
302
- "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)"
302
+ "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 `403 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| `resolve-oauth-context.ts` | OAuth bearer middleware | OAuth identity + session | Partial `AppContext` tenant fields |\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## OAuth context resolver\n\nFirst-class MCP OAuth validates the access token and live Better Auth session\nbefore calling `quickback/hooks/resolve-oauth-context.ts`. Use this trusted\nserver hook when tenant selection cannot be derived solely from the session's\nactive organization.\n\n```ts title=\"quickback/hooks/resolve-oauth-context.ts\"\nexport default async ({ token, session, user, context }, { authDb, authSchema, env }) => {\n return {\n activeOrgId: session.activeOrganizationId ?? null,\n activeTeamId: session.activeTeamId ?? null,\n tenantId: session.activeOrganizationId ?? null,\n roles: context.roles,\n };\n};\n```\n\nThe returned object is merged into the standard `AppContext`. The compiler\nalways preserves the validated `authenticated`, `userId`, and `user` fields,\nso this hook cannot replace the OAuth identity.\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)"
303
303
  },
304
304
  "stack/account-ui": {
305
305
  "title": "Account UI",
@@ -331,23 +331,15 @@ export const DOCS = {
331
331
  },
332
332
  "stack/auth/plugins/aws-ses": {
333
333
  "title": "AWS SES Plugin",
334
- "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"
334
+ "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| Delete account | Account deletion confirmation |\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 }),\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- [Auth Configuration](/compiler/config/providers) — Configuring auth plugins"
335
335
  },
336
336
  "stack/auth/plugins/aws-sns": {
337
337
  "title": "AWS SNS Plugin (SMS OTP)",
338
338
  "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."
339
339
  },
340
- "stack/auth/plugins/combo-auth": {
341
- "title": "Combo Auth Plugin",
342
- "content": "`@quickback-dev/better-auth-combo-auth` provides a combined authentication flow that sends both a magic link and an OTP code in a single email. Users can click the link (one-click) or enter the 6-digit OTP code — whichever is more convenient.\n\n## Installation\n\n```bash\nnpm install @quickback-dev/better-auth-combo-auth\n```\n\n## Server Setup\n\nAdd the plugin to your Better Auth configuration:\n\n```typescript\n\nexport const auth = betterAuth({\n plugins: [\n comboAuth({\n sendComboAuth: async ({ email, otp, url }) => {\n // Send email with both the magic link (url) and OTP code (otp)\n await sendEmail({\n to: email,\n subject: \"Sign in to My App\",\n html: `\n <p>Click the link below to sign in:</p>\n <a href=\"${url}\">Sign in to My App</a>\n <p>Or enter this code: <strong>${otp}</strong></p>\n `,\n });\n },\n }),\n ],\n});\n```\n\n## Client Usage\n\n```typescript\n\nconst authClient = createAuthClient({\n plugins: [comboAuthClient()],\n});\n\n// Request authentication — sends email with link + OTP\nawait authClient.signIn.comboAuth({\n email: \"user@example.com\",\n});\n\n// Verify with OTP code (if user enters it manually)\nawait authClient.signIn.comboAuth({\n email: \"user@example.com\",\n otp: \"123456\",\n});\n```\n\n## How It Works\n\n1. User enters their email and requests sign-in\n2. A single email is sent containing both a magic link and a 6-digit OTP\n3. **Option A:** User clicks the magic link — authenticated immediately\n4. **Option B:** User enters the OTP code — authenticated after verification\n\nThis provides the best of both worlds: convenience of magic links with the reliability of OTP codes (useful when magic links don't work well, e.g., opening email on a different device).\n\n## See Also\n\n- [Auth Plugins](/stack/auth/plugins) — All authentication plugin options\n- [Upgrade Anonymous](/stack/auth/plugins/upgrade-anonymous) — Convert anonymous sessions to full accounts\n- [AWS SES](/stack/auth/plugins/aws-ses) — Email delivery for auth flows"
343
- },
344
340
  "stack/auth/plugins": {
345
341
  "title": "Auth Plugins",
346
- "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```"
347
- },
348
- "stack/auth/plugins/upgrade-anonymous": {
349
- "title": "Upgrade Anonymous Plugin",
350
- "content": "`@quickback-dev/better-auth-upgrade-anonymous` provides a single endpoint to convert anonymous users into full authenticated users. It flips the `isAnonymous` flag, optionally updates email and name, and refreshes the session — no re-authentication required.\n\n## Installation\n\n```bash\nnpm install @quickback-dev/better-auth-upgrade-anonymous\n```\n\n## Configuration\n\nEnable both the `anonymous` and `upgradeAnonymous` plugins:\n\n```typescript\nauth: defineAuth(\"better-auth\", {\n plugins: [\"anonymous\", \"upgradeAnonymous\"],\n})\n```\n\nThe plugin accepts optional configuration:\n\n```typescript\n\nupgradeAnonymous({\n emailConfigured: true, // Whether email delivery is available\n requireEmailVerification: true, // Whether to require email verification\n})\n```\n\n| Option | Default | Description |\n|--------|---------|-------------|\n| `emailConfigured` | `false` | When `true` and an email is provided, `emailVerified` is set based on `requireEmailVerification` |\n| `requireEmailVerification` | `true` | When `true`, provided emails are marked unverified (requiring OTP). When `false`, emails are marked verified immediately |\n\n## Endpoint\n\n```\nPOST /auth/v1/upgrade-anonymous\n```\n\n### Flow\n\n1. Validates the user's session (returns `401` if not authenticated)\n2. Checks if the user is already upgraded (returns success immediately if so)\n3. If an email is provided, checks for duplicates (returns `400` if email is taken)\n4. Updates `isAnonymous` to `false`, plus optional `email`, `name`, and `emailVerified` fields\n5. Refreshes the session cookie with the updated user object\n6. Returns the updated user, session, and `verificationRequired` flag\n\n### Request\n\nThe body is optional. When provided, it accepts:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `email` | `string` (email) | Optional. Real email to replace the anonymous placeholder |\n| `name` | `string` | Optional. User's display name |\n\n```bash\n# Minimal — just upgrade, no email/name\ncurl -X POST https://api.example.com/auth/v1/upgrade-anonymous \\\n -H \"Cookie: better-auth.session_token=...\"\n\n# With email and name\ncurl -X POST https://api.example.com/auth/v1/upgrade-anonymous \\\n -H \"Cookie: better-auth.session_token=...\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"email\": \"jane@example.com\", \"name\": \"Jane\"}'\n```\n\n### Response\n\n```json\n{\n \"success\": true,\n \"verificationRequired\": true,\n \"user\": {\n \"id\": \"usr_abc123\",\n \"email\": \"jane@example.com\",\n \"isAnonymous\": false\n },\n \"session\": {\n \"id\": \"sess_xyz\",\n \"userId\": \"usr_abc123\"\n }\n}\n```\n\nThe `verificationRequired` field is `true` when all three conditions are met:\n- An email was provided in the request body\n- `emailConfigured` is `true` in plugin config\n- `requireEmailVerification` is `true` in plugin config\n\nWhen `verificationRequired` is `true`, the frontend should send a verification OTP and redirect the user to verify their email.\n\n## How It Works\n\nThe plugin is designed to be flexible:\n\n- **Minimal by default** — With no body, only changes `isAnonymous` from `true` to `false`\n- **Optional email/name** — Can update email and name in the same request\n- **Duplicate protection** — Rejects emails already associated with another account\n- **Verification-aware** — Returns `verificationRequired` so the frontend knows whether to trigger OTP\n- **Session preserved** — Same session ID, no re-authentication needed\n- **Idempotent** — Calling on an already-upgraded user returns success immediately\n\n## Typical Flows\n\n### Passkey Signup (no email)\n\n1. User creates anonymous session\n2. User registers a passkey\n3. App calls `POST /auth/v1/upgrade-anonymous` with no body\n4. User is now a full user with passkey auth — no email on file\n\n### Passkey Signup (with email)\n\n1. User creates anonymous session\n2. User registers a passkey\n3. User optionally enters email/name on the email collection step\n4. App calls `POST /auth/v1/upgrade-anonymous` with `{ email, name }`\n5. If `verificationRequired`: app sends OTP, user verifies, then redirects to dashboard\n6. Otherwise: user goes straight to dashboard\n\n### Email Signup\n\n1. User starts as anonymous (created via Better Auth's `anonymous` plugin)\n2. User provides email/password through your UI (via combo auth or signup)\n3. Your app calls `POST /auth/v1/upgrade-anonymous`\n4. User is now a full user with the same ID and all their data intact\n\n### Client Plugin\n\n```typescript\n\nconst authClient = createAuthClient({\n plugins: [upgradeAnonymousClient()],\n});\n\n// Upgrade the current anonymous user\nawait authClient.upgradeAnonymous();\n```\n\n## See Also\n\n- [Combo Auth Plugin](/stack/auth/plugins/combo-auth) — Combined magic link + OTP for collecting credentials\n- [Auth Configuration](/compiler/config/providers) — Configuring auth plugins"
342
+ "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 your email provider. When `emailOtp` is enabled, the compiler emits an OTP-only sign-in email — a six-digit code, no magic-link companion.\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**Disabling sign-up via OTP:**\n\nBy default the Email OTP plugin **auto-creates an account** when a code is\nverified for an unknown email — verifying an OTP doubles as registration. This\nis a separate code path from `emailAndPassword.disableSignUp` (which only gates\n`POST /auth/v1/sign-up/email`), so disabling password sign-up alone does *not*\nclose the OTP path.\n\nTo make OTP sign-in only (existing users can sign in; unknown emails are\nrejected instead of registered), use the object form:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: {\n emailOtp: { disableSignUp: true },\n },\n}),\n```\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**Disabling sign-up via magic link:**\n\nLike Email OTP, the magic-link plugin **auto-creates an account** when a link is\nverified for an unknown email, on a code path independent of\n`emailAndPassword.disableSignUp`. Gate it with the object form:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: {\n magicLink: { disableSignUp: true }, // sign-in only; unknown emails rejected\n },\n}),\n```\n\nIt inherits the global signup gate the same way `emailOtp.disableSignUp` does:\n`account.auth.signup: false` gates the magic-link path automatically; set\n`magicLink: { disableSignUp: false }` to opt it back open.\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 oauth: {\n enabled: true,\n issuerUrl: {\n env: \"OAUTH_ISSUER_URL\",\n fallback: \"http://localhost:8787/auth/v1\",\n },\n loginPage: {\n env: \"OAUTH_LOGIN_URL\",\n fallback: \"http://localhost:8787/account/login\",\n },\n consentPage: {\n env: \"OAUTH_CONSENT_URL\",\n fallback: \"http://localhost:8787/account/consent\",\n },\n scopes: [\"openid\", \"profile\", \"email\", \"offline_access\"],\n audiences: [\n { env: \"OAUTH_API_AUDIENCE\", fallback: \"http://localhost:8787\" },\n { env: \"OAUTH_MCP_AUDIENCE\", fallback: \"http://localhost:8787/mcp\" },\n ],\n allowDynamicClientRegistration: true,\n },\n}),\n```\n\nThe compiler auto-includes Better Auth's `oauthProvider`, `jwt`, and bearer\nplugins, protects `POST /mcp`, emits RFC 8414 and RFC 9728 discovery, and\naccepts the provider's JWKS-signed access tokens in the standard Quickback\nauth middleware.\n\nThe legacy plugin object remains available for provider-specific options:\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-authorization-server/auth/v1` — RFC 8414 path-insert discovery\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**Token and tenant context:**\n\nGenerated middleware validates the provider JWKS, canonical issuer, configured\naudience, expiration, subject, and backing Better Auth session. It then builds\nthe same `AppContext` used by session and Quickback JWT authentication.\nOrganization membership and role hierarchy are resolved automatically.\n\nFor application-specific tenant selection, add\n`quickback/hooks/resolve-oauth-context.ts`; see\n[Auth Hooks](/stack/account-ui/hooks#oauth-context-resolver).\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```"
351
343
  },
352
344
  "stack/auth/security": {
353
345
  "title": "Authentication Security",
@@ -451,7 +443,7 @@ export const DOCS = {
451
443
  },
452
444
  "stack/storage/r2": {
453
445
  "title": "File Storage (R2)",
454
- "content": "Quickback provides built-in file storage using Cloudflare R2.\n\n## Two modes\n\n`defineFileStorage(\"cloudflare-r2\")` has two modes:\n\n- **Presign-only (default)** — emits just the `ctx.storage` signer (presigned\n PUT/GET URLs straight to R2). **No new D1, no `/storage/v1/*` endpoints, no\n files worker.** You compute keys and store file references in your own table.\n This is the recommended path for most apps and the lightest way to add\n uploads — see [Presigned uploads](#presigned-uploads-recommended).\n- **Managed (`managed: true`)** — adds the turnkey subsystem on top: a FILES_DB\n metadata database (buckets + objects), the `/storage/v1/*` upload/download/\n manage endpoints, and a public files worker for serving. Opt in only when you\n want buckets/objects handled for you instead of bringing your own media table.\n\n```ts\n// Presign-only (default) — ctx.storage against a bucket, nothing else\ndefineFileStorage(\"cloudflare-r2\", { bucketName: \"my-app-media\" })\n\n// Managed subsystem — adds FILES_DB + /storage/v1/* + files worker\ndefineFileStorage(\"cloudflare-r2\", { managed: true, bucketName: \"my-app-files\" })\n```\n\nNew projects can omit `bucketName` — it defaults to `<project>-media`, so the\nonly setup is `wrangler r2 bucket create <name>` once plus the R2 API-token\nsecrets. Existing projects set `bucketName` to a bucket they already have.\n\nThe sections below document the **managed** subsystem; for the default\npresign-only path jump to [Presigned uploads](#presigned-uploads-recommended).\n\n## Architecture\n\n```\n┌─────────────────────────────────────────────────────────────────────┐\n│ Your Application │\n│ │\n│ Upload/Manage Files Serve Files │\n│ ───────────────────── ────────────── │\n│ api.yourdomain.com files.yourdomain.com │\n│ /storage/v1/* /* │\n│ │\n│ ┌─────────────────────┐ ┌─────────────────────┐ │\n│ │ API Worker │ │ Files Worker │ │\n│ │ │ │ │ │\n│ │ POST /bucket │ │ GET /public/* │ │\n│ │ GET /bucket │ │ → No auth │ │\n│ │ POST /object/* │ │ │ │\n│ │ DELETE /object/* │ │ GET /* │ │\n│ │ │ │ → Session + RBAC │ │\n│ └──────────┬──────────┘ └──────────┬──────────┘ │\n│ │ │ │\n│ └───────────┬───────────────────┘ │\n│ │ │\n│ ▼ │\n│ ┌─────────────────────┐ │\n│ │ R2 Bucket │ │\n│ │ quickback-files │ │\n│ └─────────────────────┘ │\n└─────────────────────────────────────────────────────────────────────┘\n```\n\n## Enabling File Storage\n\nAdd the `fileStorage` provider to your `quickback.config.ts`:\n\n```typescript\nexport default {\n name: 'my-app',\n providers: {\n runtime: { name: 'cloudflare' },\n database: { name: 'cloudflare-d1' },\n auth: { name: 'better-auth' },\n fileStorage: {\n name: 'cloudflare-r2',\n config: {\n binding: 'R2_BUCKET',\n bucketName: 'my-app-files',\n filesBinding: 'FILES_DB',\n maxFileSize: 10 * 1024 * 1024, // 10MB\n allowedTypes: ['image/jpeg', 'image/png', 'image/webp'],\n },\n },\n },\n};\n```\n\n## API Endpoints\n\n### Storage API (api.yourdomain.com/storage/v1)\n\n| Method | Endpoint | Description |\n|--------|----------|-------------|\n| POST | `/bucket` | Create a bucket |\n| GET | `/bucket` | List buckets |\n| GET | `/bucket/:name` | Get bucket info |\n| DELETE | `/bucket/:name` | Delete bucket (must be empty) |\n| POST | `/object/:bucket/*path` | Upload file (bytes through the Worker) |\n| POST | `/presign/:bucket/*path` | **Presigned upload URL (bytes direct to R2)** |\n| POST | `/confirm/:bucket/*path` | Confirm a presigned upload (reconcile size + etag) |\n| GET | `/object/:bucket/*path` | Download file |\n| HEAD | `/object/:bucket/*path` | Get file metadata |\n| DELETE | `/object/:bucket/*path` | Delete file (soft delete) |\n| GET | `/object` | List objects |\n| POST | `/url` | Get file URL for serving |\n\n### Files Worker (files.yourdomain.com)\n\n| Method | Path | Auth Required |\n|--------|------|---------------|\n| GET/HEAD | `/public/*` | No |\n| GET/HEAD | `/*` | Yes (session + RBAC) |\n\n## Buckets\n\nBuckets organize files and define access control policies.\n\n### Creating a Bucket\n\n```bash\nPOST /storage/v1/bucket\n{\n \"name\": \"avatars\",\n \"readScope\": \"organization\",\n \"writeScope\": \"organization\",\n \"readRoles\": [\"admin\", \"member\"],\n \"writeRoles\": [\"admin\"],\n \"deleteRoles\": [\"admin\"]\n}\n```\n\n### Scope Options\n\n| Scope | Read Behavior | Write Behavior |\n|-------|---------------|----------------|\n| `public` | Anyone can read | N/A |\n| `organization` | Org members only | Org members only |\n| `user` | Owner only | Owner only |\n\n### Role-Based Access\n\nYou can restrict operations to specific roles:\n\n```json\n{\n \"readRoles\": [\"admin\", \"member\"],\n \"writeRoles\": [\"admin\", \"editor\"],\n \"deleteRoles\": [\"admin\"]\n}\n```\n\nAn empty array `[]` means no role restriction (all authenticated users).\n\n## Uploading Files\n\n```bash\nPOST /storage/v1/object/avatars/profile.jpg\nContent-Type: image/jpeg\nContent-Length: 12345\n\n<binary data>\n```\n\nResponse:\n```json\n{\n \"id\": \"obj_123\",\n \"key\": \"org_abc/avatars/profile.jpg\",\n \"bucket\": \"avatars\",\n \"name\": \"profile.jpg\",\n \"size\": 12345,\n \"mimeType\": \"image/jpeg\",\n \"readScope\": \"organization\"\n}\n```\n\n## Presigned uploads (recommended)\n\nStreaming bytes through the Worker (`POST /object`) is fine for small files, but\nit puts every byte on the Worker's request path — subject to the body-size cap,\nand billed as Worker CPU/duration. For media (video, audio, large PDFs), use a\n**presigned URL**: the Worker runs all the access checks and hands back a\nshort-lived URL the client uploads to **directly**. The bytes never touch your\nWorker.\n\n```bash\n# 1. Ask the API to sign an upload URL (auth + bucket + role checks run here)\ncurl -X POST https://api.example.com/storage/v1/presign/videos/clip.mp4 \\\n -H \"Authorization: Bearer <token>\" \\\n -H \"Content-Type: application/json\" \\\n -d '{ \"contentType\": \"video/mp4\", \"size\": 73400320 }'\n\n# Response:\n# {\n# \"id\": \"obj_abc\",\n# \"key\": \"org_abc/videos/clip.mp4\",\n# \"uploadUrl\": \"https://<account>.r2.cloudflarestorage.com/...&X-Amz-Signature=...\",\n# \"method\": \"PUT\",\n# \"headers\": { \"Content-Type\": \"video/mp4\" },\n# \"expiresAt\": \"2026-06-02T12:10:00.000Z\"\n# }\n\n# 2. Upload the bytes straight to R2 (replay the returned headers verbatim)\ncurl -X PUT \"<uploadUrl>\" -H \"Content-Type: video/mp4\" --data-binary @clip.mp4\n\n# 3. Confirm — reconciles the recorded size + etag against what actually landed\ncurl -X POST https://api.example.com/storage/v1/confirm/videos/clip.mp4 \\\n -H \"Authorization: Bearer <token>\"\n```\n\n### Required secrets\n\nPresigning uses R2's S3-compatible API, which needs an **R2 API token** — the\nWorkers bucket binding alone cannot presign. Create a token in the Cloudflare\ndashboard (R2 → Manage API Tokens) and set:\n\n```bash\nwrangler secret put R2_ACCOUNT_ID # your Cloudflare account id\nwrangler secret put R2_ACCESS_KEY_ID # R2 API token access key id\nwrangler secret put R2_SECRET_ACCESS_KEY # R2 API token secret\n# Optional: wrangler secret put R2_S3_ENDPOINT # override the derived endpoint\n```\n\n### Signing from your own action\n\nThe same signer is exposed as `ctx.storage` inside any\n[`defineAction`](/compiler/definitions/actions) — so you can author an upload endpoint that\nruns your own access rules (org, team, relationship/scoped roles) and stores the\nkey in **your own table**, instead of the generic `buckets`/`objects` metadata:\n\n```typescript\nexport default defineAction({\n path: '/event/:eventId/media/sign-upload',\n method: 'POST',\n input: z.object({ filename: z.string(), contentType: z.string() }),\n access: { roles: ['admin', 'member', 'scope:event:attendee'] },\n async execute({ input, ctx, db, storage }) {\n // Tenant-scoped key — secure by construction\n const key = `org/${ctx.activeOrgId}/event/${input.eventId}/${crypto.randomUUID()}-${input.filename}`;\n const upload = await storage.signPutUrl(key, {\n contentType: input.contentType,\n expiresIn: 600,\n });\n await db.insert(images).values({ key, eventId: input.eventId /* … */ });\n return { uploadUrl: upload.url, key, headers: upload.headers };\n },\n});\n```\n\n`storage` exposes:\n\n| Method | Returns | Use |\n|--------|---------|-----|\n| `signPutUrl(key, { contentType?, expiresIn? })` | `{ url, method, headers, key, expiresAt }` | Client uploads directly to R2 |\n| `signGetUrl(key, { expiresIn?, downloadFilename? })` | `string` | Client downloads directly from R2 |\n\nThis is the supported replacement for streaming a raw binary body through an\naction — the JSON body parser and its ~1 MiB cap stay on for every other route.\n\n## Serving Files\n\n### Public Files\n\nFiles in buckets with `readScope: \"public\"` are stored with a `public/` prefix:\n\n```\nhttps://files.yourdomain.com/public/org_abc/avatars/logo.png\n```\n\nNo authentication required.\n\n### Private Files\n\nPrivate files require a valid Better Auth session cookie:\n\n```\nhttps://files.yourdomain.com/org_abc/documents/report.pdf\n```\n\nThe files worker:\n1. Validates the session token\n2. Checks the user's organization matches\n3. Verifies role permissions (if `readRoles` configured)\n4. Serves the file or returns 403\n\n## Generated Files\n\nWhen file storage is configured, the compiler generates:\n\n| File | Purpose |\n|------|---------|\n| `src/storage/routes.ts` | Storage API routes (upload, presign, confirm, download) |\n| `src/storage/presign.ts` | R2 presigned-URL signer (`createPresigner`, backs `ctx.storage`) |\n| `src/files/schema.ts` | Files database schema (buckets, objects) |\n| `cloudflare-workers/files/index.ts` | Files worker for serving |\n| `cloudflare-workers/files/wrangler.toml` | Files worker config |\n\nThe compiler also adds [`aws4fetch`](https://github.com/mhart/aws4fetch) to your\n`package.json` (used by the presigner) and the R2 presign secrets to your\ngenerated `CloudflareBindings` type.\n\n## Deployment\n\nAfter compiling:\n\n1. **Create the R2 bucket:**\n ```bash\n wrangler r2 bucket create my-app-files\n ```\n\n2. **Create the files database:**\n ```bash\n wrangler d1 create my-app-files\n ```\n\n3. **Run migrations:**\n ```bash\n wrangler d1 migrations apply my-app-files --local\n wrangler d1 migrations apply my-app-files --remote\n ```\n\n4. **Deploy the API:**\n ```bash\n wrangler deploy\n ```\n\n5. **Deploy the files worker:**\n ```bash\n cd cloudflare-workers/files\n wrangler deploy\n ```\n\n6. **Set the R2 presign secrets** (only if you use presigned uploads — see\n [Presigned uploads](#presigned-uploads-recommended)):\n ```bash\n wrangler secret put R2_ACCOUNT_ID\n wrangler secret put R2_ACCESS_KEY_ID\n wrangler secret put R2_SECRET_ACCESS_KEY\n ```\n\n## Configuration Reference\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `binding` | `string` | `R2_BUCKET` | R2 bucket binding name |\n| `bucketName` | `string` | Required | R2 bucket name |\n| `filesBinding` | `string` | `FILES_DB` | Files metadata D1 binding |\n| `maxFileSize` | `number` | 10MB | Max upload size in bytes |\n| `allowedTypes` | `string[]` | Images only | Allowed MIME types |\n| `publicDomain` | `string` | - | Custom domain for files worker |\n\n## Security Model\n\n- **Upload security**: Enforced by API worker (auth middleware, org check, role check)\n- **Serve security**: Enforced by files worker (session validation, metadata RBAC)\n- **Soft deletes**: Files are marked deleted in metadata but retained in R2\n- **Tenant isolation**: All files are prefixed with organization ID"
446
+ "content": "Quickback provides built-in file storage using Cloudflare R2.\n\n## Two modes\n\n`defineFileStorage(\"cloudflare-r2\")` has two modes:\n\n- **Presign-only (default)** — emits just the `ctx.storage` signer (presigned\n PUT/GET URLs straight to R2). **No new D1, no `/storage/v1/*` endpoints, no\n files worker.** You compute keys and store file references in your own table.\n This is the recommended path for most apps and the lightest way to add\n uploads — see [Presigned uploads](#presigned-uploads-recommended).\n- **Managed (`managed: true`)** — adds the turnkey subsystem on top: a FILES_DB\n metadata database (buckets + objects), the `/storage/v1/*` upload/download/\n manage endpoints, and a public files worker for serving. Opt in only when you\n want buckets/objects handled for you instead of bringing your own media table.\n\n```ts\n// Presign-only (default) — ctx.storage against a bucket, nothing else\ndefineFileStorage(\"cloudflare-r2\", { bucketName: \"my-app-media\" })\n\n// Managed subsystem — adds FILES_DB + /storage/v1/* + files worker\ndefineFileStorage(\"cloudflare-r2\", { managed: true, bucketName: \"my-app-files\" })\n```\n\nNew projects can omit `bucketName` — it defaults to `<project>-media`, so the\nonly setup is `wrangler r2 bucket create <name>` once plus the R2 API-token\nsecrets. Existing projects set `bucketName` to a bucket they already have.\n\nThe sections below document the **managed** subsystem; for the default\npresign-only path jump to [Presigned uploads](#presigned-uploads-recommended).\n\n## Architecture\n\n```\n┌─────────────────────────────────────────────────────────────────────┐\n│ Your Application │\n│ │\n│ Upload/Manage Files Serve Files │\n│ ───────────────────── ────────────── │\n│ api.yourdomain.com files.yourdomain.com │\n│ /storage/v1/* /* │\n│ │\n│ ┌─────────────────────┐ ┌─────────────────────┐ │\n│ │ API Worker │ │ Files Worker │ │\n│ │ │ │ │ │\n│ │ POST /bucket │ │ GET /public/* │ │\n│ │ GET /bucket │ │ → No auth │ │\n│ │ POST /object/* │ │ │ │\n│ │ DELETE /object/* │ │ GET /* │ │\n│ │ │ │ → Session + RBAC │ │\n│ └──────────┬──────────┘ └──────────┬──────────┘ │\n│ │ │ │\n│ └───────────┬───────────────────┘ │\n│ │ │\n│ ▼ │\n│ ┌─────────────────────┐ │\n│ │ R2 Bucket │ │\n│ │ quickback-files │ │\n│ └─────────────────────┘ │\n└─────────────────────────────────────────────────────────────────────┘\n```\n\n## Enabling File Storage\n\nAdd the `fileStorage` provider to your `quickback.config.ts`:\n\n```typescript\nexport default {\n name: 'my-app',\n providers: {\n runtime: { name: 'cloudflare' },\n database: { name: 'cloudflare-d1' },\n auth: { name: 'better-auth' },\n fileStorage: {\n name: 'cloudflare-r2',\n config: {\n binding: 'R2_BUCKET',\n bucketName: 'my-app-files',\n filesBinding: 'FILES_DB',\n maxFileSize: 10 * 1024 * 1024, // 10MB\n allowedTypes: ['image/jpeg', 'image/png', 'image/webp'],\n },\n },\n },\n};\n```\n\n## API Endpoints\n\n### Storage API (api.yourdomain.com/storage/v1)\n\n| Method | Endpoint | Description |\n|--------|----------|-------------|\n| POST | `/bucket` | Create a bucket |\n| GET | `/bucket` | List buckets |\n| GET | `/bucket/:name` | Get bucket info |\n| DELETE | `/bucket/:name` | Delete bucket (must be empty) |\n| POST | `/object/:bucket/*path` | Upload file (bytes through the Worker) |\n| POST | `/presign/:bucket/*path` | **Presigned upload URL (bytes direct to R2)** |\n| POST | `/confirm/:bucket/*path` | Confirm a presigned upload (reconcile size + etag) |\n| GET | `/object/:bucket/*path` | Download file |\n| HEAD | `/object/:bucket/*path` | Get file metadata |\n| DELETE | `/object/:bucket/*path` | Delete file (soft delete) |\n| GET | `/object` | List objects |\n| POST | `/url` | Get file URL for serving |\n\n### Files Worker (files.yourdomain.com)\n\n| Method | Path | Auth Required |\n|--------|------|---------------|\n| GET/HEAD | `/public/*` | No |\n| GET/HEAD | `/*` | Yes (session + RBAC) |\n\n## Buckets\n\nBuckets organize files and define access control policies.\n\n### Creating a Bucket\n\n```bash\nPOST /storage/v1/bucket\n{\n \"name\": \"avatars\",\n \"readScope\": \"organization\",\n \"writeScope\": \"organization\",\n \"readRoles\": [\"admin\", \"member\"],\n \"writeRoles\": [\"admin\"],\n \"deleteRoles\": [\"admin\"]\n}\n```\n\n### Scope Options\n\n| Scope | Read Behavior | Write Behavior |\n|-------|---------------|----------------|\n| `public` | Anyone can read | N/A |\n| `organization` | Org members only | Org members only |\n| `user` | Owner only | Owner only |\n\n### Role-Based Access\n\nYou can restrict operations to specific roles:\n\n```json\n{\n \"readRoles\": [\"admin\", \"member\"],\n \"writeRoles\": [\"admin\", \"editor\"],\n \"deleteRoles\": [\"admin\"]\n}\n```\n\nAn empty array `[]` means no role restriction (all authenticated users).\n\n## Uploading Files\n\n```bash\nPOST /storage/v1/object/avatars/profile.jpg\nContent-Type: image/jpeg\nContent-Length: 12345\n\n<binary data>\n```\n\nResponse:\n```json\n{\n \"id\": \"obj_123\",\n \"key\": \"org_abc/avatars/profile.jpg\",\n \"bucket\": \"avatars\",\n \"name\": \"profile.jpg\",\n \"size\": 12345,\n \"mimeType\": \"image/jpeg\",\n \"readScope\": \"organization\"\n}\n```\n\n## Presigned uploads (recommended)\n\nStreaming bytes through the Worker (`POST /object`) is fine for small files, but\nit puts every byte on the Worker's request path — subject to the body-size cap,\nand billed as Worker CPU/duration. For media (video, audio, large PDFs), use a\n**presigned URL**: the Worker runs all the access checks and hands back a\nshort-lived URL the client uploads to **directly**. The bytes never touch your\nWorker.\n\n```bash\n# 1. Ask the API to sign an upload URL (auth + bucket + role checks run here)\ncurl -X POST https://api.example.com/storage/v1/presign/videos/clip.mp4 \\\n -H \"Authorization: Bearer <token>\" \\\n -H \"Content-Type: application/json\" \\\n -d '{ \"contentType\": \"video/mp4\", \"size\": 73400320 }'\n\n# Response:\n# {\n# \"id\": \"obj_abc\",\n# \"key\": \"org_abc/videos/clip.mp4\",\n# \"uploadUrl\": \"https://<account>.r2.cloudflarestorage.com/...&X-Amz-Signature=...\",\n# \"method\": \"PUT\",\n# \"headers\": { \"Content-Type\": \"video/mp4\" },\n# \"expiresAt\": \"2026-06-02T12:10:00.000Z\"\n# }\n\n# 2. Upload the bytes straight to R2 (replay the returned headers verbatim)\ncurl -X PUT \"<uploadUrl>\" -H \"Content-Type: video/mp4\" --data-binary @clip.mp4\n\n# 3. Confirm — reconciles the recorded size + etag against what actually landed\ncurl -X POST https://api.example.com/storage/v1/confirm/videos/clip.mp4 \\\n -H \"Authorization: Bearer <token>\"\n```\n\n### Required secrets\n\nPresigning uses R2's S3-compatible API, which needs an **R2 API token** — the\nWorkers bucket binding alone cannot presign. Create a token in the Cloudflare\ndashboard (R2 → Manage API Tokens) and set:\n\n```bash\nwrangler secret put R2_ACCOUNT_ID # your Cloudflare account id\nwrangler secret put R2_ACCESS_KEY_ID # R2 API token access key id\nwrangler secret put R2_SECRET_ACCESS_KEY # R2 API token secret\n# Optional: wrangler secret put R2_S3_ENDPOINT # override the derived endpoint\n```\n\n### Signing from your own action\n\nThe same signer is exposed as `ctx.storage` inside any\n[`defineAction`](/compiler/definitions/actions) — so you can author an upload endpoint that\nruns your own access rules (org, team, relationship/scoped roles) and stores the\nkey in **your own table**, instead of the generic `buckets`/`objects` metadata:\n\n```typescript\nexport default defineAction({\n path: '/event/:eventId/media/sign-upload',\n method: 'POST',\n input: z.object({ filename: z.string(), contentType: z.string() }),\n access: { roles: ['admin', 'member', 'scope:event:attendee'] },\n async execute({ input, ctx, db, storage }) {\n // Tenant-scoped key — secure by construction\n const key = `org/${ctx.activeOrgId}/event/${input.eventId}/${crypto.randomUUID()}-${input.filename}`;\n const upload = await storage.signPutUrl(key, {\n contentType: input.contentType,\n expiresIn: 600,\n });\n await db.insert(images).values({ key, eventId: input.eventId /* … */ });\n return { uploadUrl: upload.url, key, headers: upload.headers };\n },\n});\n```\n\n`storage` exposes:\n\n| Method | Returns | Use |\n|--------|---------|-----|\n| `signPutUrl(key, { contentType?, expiresIn? })` | `{ url, method, headers, key, expiresAt }` | Client uploads directly to R2 |\n| `signGetUrl(key, { expiresIn?, downloadFilename? })` | `string` | Client downloads directly from R2 |\n\nThis is the supported replacement for streaming a raw binary body through an\naction — the JSON body parser and its ~1 MiB cap stay on for every other route.\n\n## Serving Files\n\n### Public Files\n\nFiles in buckets with `readScope: \"public\"` are stored with a `public/` prefix:\n\n```\nhttps://files.yourdomain.com/public/org_abc/avatars/logo.png\n```\n\nNo authentication required.\n\n### Private Files\n\nPrivate files require a valid Better Auth session cookie:\n\n```\nhttps://files.yourdomain.com/org_abc/documents/report.pdf\n```\n\nThe files worker:\n1. Validates the session token\n2. Checks the user's organization matches\n3. Verifies role permissions (if `readRoles` configured)\n4. Serves the file or returns 403\n\n## Generated Files\n\nWhen file storage is configured, the compiler generates:\n\n| File | Purpose |\n|------|---------|\n| `src/storage/routes.ts` | Storage API routes (upload, presign, confirm, download) |\n| `src/storage/presign.ts` | R2 presigned-URL signer (`createPresigner`, backs `ctx.storage`) |\n| `src/files/schema.ts` | Files database schema (buckets, objects) |\n| `cloudflare-workers/files/index.ts` | Files worker for serving |\n| `cloudflare-workers/files/wrangler.toml` | Files worker config |\n\nThe compiler also adds [`aws4fetch`](https://github.com/mhart/aws4fetch) to your\n`package.json` (used by the presigner) and the R2 presign secrets to your\ngenerated `CloudflareBindings` type.\n\n## Deployment\n\nAfter compiling:\n\n1. **Create the R2 bucket:**\n ```bash\n wrangler r2 bucket create my-app-files\n ```\n\n2. **Create the files database:**\n ```bash\n wrangler d1 create my-app-files\n ```\n\n3. **Run migrations:**\n ```bash\n wrangler d1 migrations apply my-app-files --local\n wrangler d1 migrations apply my-app-files --remote\n ```\n\n4. **Deploy the API:**\n ```bash\n wrangler deploy\n ```\n\n5. **Deploy the files worker:**\n ```bash\n cd cloudflare-workers/files\n wrangler deploy\n ```\n\n6. **Set the R2 presign secrets** (only if you use presigned uploads — see\n [Presigned uploads](#presigned-uploads-recommended)):\n ```bash\n wrangler secret put R2_ACCOUNT_ID\n wrangler secret put R2_ACCESS_KEY_ID\n wrangler secret put R2_SECRET_ACCESS_KEY\n ```\n\n## Configuration Reference\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `managed` | `boolean` | `false` | Opt into the FILES_DB subsystem + `/storage/v1/*` + files worker. Off = presign-only. |\n| `bucketName` | `string` | `<project>-media` | R2 bucket the signer targets (override per-call with `signPutUrl(key, { bucket })`) |\n| `presign` | `object` | - | Env-var name overrides: `{ accountIdEnv, accessKeyIdEnv, secretAccessKeyEnv, endpointEnv }` |\n| `binding` | `string` | `R2_BUCKET` | R2 bucket binding name (managed mode) |\n| `filesBinding` | `string` | `FILES_DB` | Files metadata D1 binding (managed mode) |\n| `maxFileSize` | `number \\| string` | 10MB | Max upload size — bytes or `\"100mb\"` (managed mode) |\n| `allowedTypes` | `string[]` | Images only | Allowed MIME types (managed mode) |\n| `publicDomain` | `string` | - | Custom domain for files worker (managed mode) |\n\n## Security Model\n\n- **Upload security**: Enforced by API worker (auth middleware, org check, role check)\n- **Serve security**: Enforced by files worker (session validation, metadata RBAC)\n- **Soft deletes**: Files are marked deleted in metadata but retained in R2\n- **Tenant isolation**: All files are prefixed with organization ID"
455
447
  },
456
448
  "stack/storage/using-kv": {
457
449
  "title": "Using KV",
@@ -459,7 +451,7 @@ export const DOCS = {
459
451
  },
460
452
  "stack/storage/using-r2": {
461
453
  "title": "Using R2",
462
- "content": "Cloudflare R2 provides S3-compatible object storage for file uploads in the Quickback Stack.\n\n## Upload Flow\n\nThe generated API provides a two-step **presigned** upload — the file bytes go\ndirectly to R2 and never stream through your Worker:\n\n1. **Request a presigned URL** — Client calls `/storage/v1/presign/...`; the\n Worker runs auth + bucket + role checks and returns a time-limited URL\n2. **Upload directly to R2** — Client `PUT`s the bytes to R2 (bypasses your Worker)\n3. **Confirm** — `/storage/v1/confirm/...` reconciles the recorded size + etag\n\n```bash\n# 1. Request a presigned upload URL\ncurl -X POST https://api.example.com/storage/v1/presign/documents/report.pdf \\\n -H \"Authorization: Bearer <token>\" \\\n -H \"Content-Type: application/json\" \\\n -d '{ \"contentType\": \"application/pdf\", \"size\": 248000 }'\n\n# Response:\n# {\n# \"id\": \"obj_abc123\",\n# \"key\": \"org_abc/documents/report.pdf\",\n# \"uploadUrl\": \"https://<account>.r2.cloudflarestorage.com/...&X-Amz-Signature=...\",\n# \"method\": \"PUT\",\n# \"headers\": { \"Content-Type\": \"application/pdf\" },\n# \"expiresAt\": \"2026-06-02T12:10:00.000Z\"\n# }\n\n# 2. Upload directly to R2 using the presigned URL (replay the returned headers)\ncurl -X PUT \"<uploadUrl>\" \\\n -H \"Content-Type: application/pdf\" \\\n --data-binary @report.pdf\n\n# 3. Confirm the upload\ncurl -X POST https://api.example.com/storage/v1/confirm/documents/report.pdf \\\n -H \"Authorization: Bearer <token>\"\n```\n\nPresigning needs an R2 API token — set the `R2_ACCOUNT_ID`, `R2_ACCESS_KEY_ID`,\nand `R2_SECRET_ACCESS_KEY` secrets. See [R2 Setup → Presigned uploads](/stack/storage/r2#presigned-uploads-recommended).\n\nFor uploads that should land in **your own table** (with your own access rules),\nsign the URL from inside a `defineAction` via `ctx.storage` — see\n[Signing from your own action](/stack/storage/r2#signing-from-your-own-action).\n\n## Download Flow\n\nFiles are served through your Worker with security checks applied:\n\n```bash\n# Download a file (auth + firewall enforced)\ncurl https://api.example.com/api/v1/files/file_abc123/download \\\n -H \"Authorization: Bearer <token>\"\n```\n\nThe download endpoint:\n1. Validates the user's session\n2. Checks firewall — the file must belong to the user's organization\n3. Checks access — the user must have the required role\n4. Streams the file from R2\n\n## Role-Based Access\n\nFile access respects the same security layers as your API:\n\n- **Firewall** — Users can only access files belonging to their organization\n- **Access** — Role-based download permissions\n\n## See Also\n\n- [R2 Setup](/stack/storage/r2) — Bucket creation, wrangler bindings, and configuration\n- [Avatars](/stack/account-ui/features/avatars) — Avatar upload UI integration"
454
+ "content": "Cloudflare R2 provides S3-compatible object storage for file uploads in the Quickback Stack.\n\nBy default `defineFileStorage(\"cloudflare-r2\")` is **presign-only**: you get the\n`ctx.storage` signer and nothing else. The `/storage/v1/*` endpoints shown\nfurther down only exist in the [managed subsystem](/stack/storage/r2#two-modes)\n(`managed: true`).\n\n## Upload Flow (default — `ctx.storage`)\n\nWrite a normal `defineAction` that signs a presigned URL and stores the key in\n**your own table**. Bytes go directly to R2 — the Worker only signs.\n\n```ts\nexport default defineAction({\n path: \"/media/sign-upload\",\n method: \"POST\",\n input: z.object({ filename: z.string(), contentType: z.string() }),\n access: { roles: [\"member\"] },\n async execute({ input, ctx, db, storage }) {\n const key = `org/${ctx.activeOrgId}/${crypto.randomUUID()}-${input.filename}`;\n const upload = await storage.signPutUrl(key, { contentType: input.contentType, expiresIn: 600 });\n await db.insert(media).values({ key /* … */ });\n return { uploadUrl: upload.url, key, headers: upload.headers };\n },\n});\n```\n\n```bash\n# 1. Ask your action for a signed URL (your auth/roles run here)\ncurl -X POST https://api.example.com/api/v1/media/sign-upload \\\n -H \"Authorization: Bearer <token>\" -H \"Content-Type: application/json\" \\\n -d '{ \"filename\": \"report.pdf\", \"contentType\": \"application/pdf\" }'\n# → { \"uploadUrl\": \"https://<account>.r2.cloudflarestorage.com/...&X-Amz-Signature=...\", \"key\": \"...\", \"headers\": { \"Content-Type\": \"application/pdf\" } }\n\n# 2. Upload the bytes straight to R2 (replay the returned headers)\ncurl -X PUT \"<uploadUrl>\" -H \"Content-Type: application/pdf\" --data-binary @report.pdf\n```\n\n`storage.signPutUrl(key, { contentType?, expiresIn?, bucket? })` returns\n`{ url, method, headers, key, expiresAt }`; `storage.signGetUrl(key, { expiresIn?, downloadFilename?, bucket? })`\nreturns a presigned GET URL. Pass `bucket` to target a bucket other than the\nconfigured default.\n\nPresigning needs an R2 API token — set the `R2_ACCOUNT_ID`, `R2_ACCESS_KEY_ID`,\nand `R2_SECRET_ACCESS_KEY` secrets. See [R2 Setup → Presigned uploads](/stack/storage/r2#presigned-uploads-recommended).\n\n## Upload Flow (managed mode — `/storage/v1/*`)\n\nWith `managed: true`, the generated API also exposes turnkey presigned\nendpoints backed by the FILES_DB metadata system:\n\n```bash\n# 1. Request a presigned upload URL\ncurl -X POST https://api.example.com/storage/v1/presign/documents/report.pdf \\\n -H \"Authorization: Bearer <token>\" -H \"Content-Type: application/json\" \\\n -d '{ \"contentType\": \"application/pdf\", \"size\": 248000 }'\n# → { \"id\": \"obj_abc\", \"key\": \"...\", \"uploadUrl\": \"...\", \"headers\": {...}, \"expiresAt\": \"...\" }\n\n# 2. Upload directly to R2\ncurl -X PUT \"<uploadUrl>\" -H \"Content-Type: application/pdf\" --data-binary @report.pdf\n\n# 3. Confirm (reconciles size + etag)\ncurl -X POST https://api.example.com/storage/v1/confirm/documents/report.pdf \\\n -H \"Authorization: Bearer <token>\"\n```\n\n## Download Flow\n\nIn **presign-only** mode, mint a short-lived download URL with\n`storage.signGetUrl(key, { downloadFilename })` from your action and hand it to\nthe client — the bytes come straight from R2.\n\nIn **managed** mode, files are also served through the worker with security\nchecks applied:\n\n```bash\n# Download a file (auth + firewall enforced)\ncurl https://api.example.com/api/v1/files/file_abc123/download \\\n -H \"Authorization: Bearer <token>\"\n```\n\nThe download endpoint:\n1. Validates the user's session\n2. Checks firewall — the file must belong to the user's organization\n3. Checks access — the user must have the required role\n4. Streams the file from R2\n\n## Role-Based Access\n\nFile access respects the same security layers as your API:\n\n- **Firewall** — Users can only access files belonging to their organization\n- **Access** — Role-based download permissions\n\n## See Also\n\n- [R2 Setup](/stack/storage/r2) — Bucket creation, wrangler bindings, and configuration\n- [Avatars](/stack/account-ui/features/avatars) — Avatar upload UI integration"
463
455
  },
464
456
  "stack/vector/embeddings": {
465
457
  "title": "Automatic Embeddings",
@@ -571,9 +563,7 @@ export const TOPIC_LIST = [
571
563
  "stack/auth/plugins/agent-auth",
572
564
  "stack/auth/plugins/aws-ses",
573
565
  "stack/auth/plugins/aws-sns",
574
- "stack/auth/plugins/combo-auth",
575
566
  "stack/auth/plugins",
576
- "stack/auth/plugins/upgrade-anonymous",
577
567
  "stack/auth/security",
578
568
  "stack/auth/using-auth",
579
569
  "stack/cms/actions",