@quickback-dev/cli 0.40.0 → 0.40.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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.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",
@@ -343,7 +343,7 @@ export const DOCS = {
343
343
  },
344
344
  "stack/auth/plugins": {
345
345
  "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```"
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**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### 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**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 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
347
  },
348
348
  "stack/auth/plugins/upgrade-anonymous": {
349
349
  "title": "Upgrade Anonymous Plugin",
@@ -451,7 +451,7 @@ export const DOCS = {
451
451
  },
452
452
  "stack/storage/r2": {
453
453
  "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"
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| `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
455
  },
456
456
  "stack/storage/using-kv": {
457
457
  "title": "Using KV",
@@ -459,7 +459,7 @@ export const DOCS = {
459
459
  },
460
460
  "stack/storage/using-r2": {
461
461
  "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"
462
+ "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
463
  },
464
464
  "stack/vector/embeddings": {
465
465
  "title": "Automatic Embeddings",
@@ -1 +1 @@
1
- {"version":3,"file":"content.js","sourceRoot":"","sources":["../../src/docs/content.ts"],"names":[],"mappings":"AAAA,+BAA+B;AAC/B,0DAA0D;AAO1D,MAAM,CAAC,MAAM,IAAI,GAA6B;IAC5C,WAAW,EAAE;QACX,OAAO,EAAE,WAAW;QACpB,SAAS,EAAE,wogEAAwogE;KACppgE;IACD,4BAA4B,EAAE;QAC5B,OAAO,EAAE,oBAAoB;QAC7B,SAAS,EAAE,giRAAgiR;KAC5iR;IACD,wCAAwC,EAAE;QACxC,OAAO,EAAE,gBAAgB;QACzB,SAAS,EAAE,2nEAA2nE;KACvoE;IACD,6BAA6B,EAAE;QAC7B,OAAO,EAAE,eAAe;QACxB,SAAS,EAAE,ypSAAypS;KACrqS;IACD,mCAAmC,EAAE;QACnC,OAAO,EAAE,WAAW;QACpB,SAAS,EAAE,iuGAAiuG;KAC7uG;IACD,yBAAyB,EAAE;QACzB,OAAO,EAAE,gBAAgB;QACzB,SAAS,EAAE,4kFAA4kF;KACxlF;IACD,wCAAwC,EAAE;QACxC,OAAO,EAAE,gBAA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jC,oCAAoC;IACpC,mCAAmC;IACnC,yCAAyC;IACzC,2BAA2B;IAC3B,yCAAyC;IACzC,oCAAoC;IACpC,wCAAwC;IACxC,oCAAoC;IACpC,wBAAwB;IACxB,kBAAkB;IAClB,iCAAiC;IACjC,qBAAqB;IACrB,wBAAwB;IACxB,YAAY;IACZ,6BAA6B;IAC7B,+BAA+B;IAC/B,4BAA4B;IAC5B,4BAA4B;IAC5B,+BAA+B;IAC/B,oBAAoB;IACpB,sCAAsC;IACtC,qBAAqB;IACrB,uBAAuB;IACvB,mBAAmB;IACnB,sBAAsB;IACtB,sBAAsB;IACtB,qBAAqB;IACrB,WAAW;IACX,0BAA0B;IAC1B,iBAAiB;IACjB,0BAA0B;IAC1B,yBAAyB;IACzB,2BAA2B;IAC3B,oBAAoB;IACpB,uBAAuB;IACvB,OAAO;IACP,uBAAuB;IACvB,cAAc;IACd,2BAA2B;IAC3B,gCAAgC;IAChC,gBAAgB;IAChB,2BAA2B;IAC3B,kCAAkC;IAClC,+BAA+B;IAC/B,eAAe;IACf,kBAAkB;IAClB,kBAAkB;IAClB,wBAAwB;IACxB,wBAAwB;IACxB,yBAAyB;IACzB,cAAc;IACd,+BAA+B;IAC/B,wBAAwB;IACxB,gBAAgB;IAChB,yBAAyB;CAC1B,CAAC"}
package/dist/index.js CHANGED
@@ -10,7 +10,7 @@
10
10
  */
11
11
  import pc from "picocolors";
12
12
  // Version injected at build time by scripts/inject-version.ts
13
- const CLI_VERSION = "0.40.0";
13
+ const CLI_VERSION = "0.40.2";
14
14
  function getPackageVersion() {
15
15
  return CLI_VERSION;
16
16
  }
@@ -1,5 +1,41 @@
1
1
  # Changelog
2
2
 
3
+ ## v0.40.2 — June 3, 2026
4
+
5
+ ### Passwordless plugins can no longer bypass the signup gate
6
+
7
+ Better Auth's `emailOtp` and `magicLink` plugins auto-create an account when a
8
+ code/link is verified for an unknown email — and that path is independent of
9
+ `emailAndPassword.disableSignUp`. As a result, `account.auth.signup: false`
10
+ closed `POST /auth/v1/sign-up/email` but left OTP / magic-link verification as an
11
+ open back-door for account creation.
12
+
13
+ The compiler now emits each plugin's own `disableSignUp` flag, and new
14
+ per-plugin options expose it directly:
15
+
16
+ ```ts
17
+ auth: defineAuth("better-auth", {
18
+ emailAndPassword: { enabled: true },
19
+ plugins: {
20
+ emailOtp: { disableSignUp: true }, // OTP sign-in only; unknown emails rejected
21
+ magicLink: { disableSignUp: true }, // same for magic links
22
+ },
23
+ }),
24
+ ```
25
+
26
+ Both default to following the global gate: setting `account.auth.signup: false`
27
+ (→ `emailAndPassword.disableSignUp: true`) now also gates the OTP and magic-link
28
+ paths automatically. Set `{ disableSignUp: false }` on a plugin explicitly to
29
+ keep its sign-up open while password sign-up stays closed.
30
+
31
+ ## v0.40.1 — June 2, 2026
32
+
33
+ - The generated `wrangler.toml` and `Env` type now emit the `ASSETS` binding
34
+ type for projects that mount SPAs (CMS / Account), so handler code that
35
+ references `c.env.ASSETS` typechecks.
36
+ - Compiler Docker builds preserve their layer cache across rebuilds, cutting
37
+ local recompile time.
38
+
3
39
  ## v0.40.0 — June 2, 2026
4
40
 
5
41
  R2 file storage is now **presign-only by default**. Adding
@@ -46,6 +46,33 @@ Use this to show UI warnings when SES isn't configured.
46
46
  - `GET /api/v1/system/email-status`
47
47
  - Response: `{ "emailConfigured": true|false }`
48
48
 
49
+ **Disabling sign-up via OTP:**
50
+
51
+ By default the Email OTP plugin **auto-creates an account** when a code is
52
+ verified for an unknown email — verifying an OTP doubles as registration. This
53
+ is a separate code path from `emailAndPassword.disableSignUp` (which only gates
54
+ `POST /auth/v1/sign-up/email`), so disabling password sign-up alone does *not*
55
+ close the OTP path.
56
+
57
+ To make OTP sign-in only (existing users can sign in; unknown emails are
58
+ rejected instead of registered), use the object form:
59
+
60
+ ```ts
61
+ auth: defineAuth("better-auth", {
62
+ emailAndPassword: { enabled: true },
63
+ plugins: {
64
+ emailOtp: { disableSignUp: true },
65
+ },
66
+ }),
67
+ ```
68
+
69
+ > `emailOtp.disableSignUp` **inherits the global signup gate**: when
70
+ > `account.auth.signup: false` (i.e. `emailAndPassword.disableSignUp: true`) is
71
+ > set, the OTP plugin is gated automatically so it can't be used to bypass it. Set
72
+ > `emailOtp: { disableSignUp: false }` explicitly to opt the OTP path back open
73
+ > while password sign-up stays closed.
74
+
75
+
49
76
  ### Upgrade Anonymous
50
77
 
51
78
  Adds a first-class endpoint to convert an anonymous user into a full user. This flips `isAnonymous` to `false` and refreshes the session cache immediately.
@@ -129,6 +156,25 @@ auth: defineAuth("better-auth", {
129
156
  - `POST /auth/v1/magic-link/send` - Send magic link email
130
157
  - `GET /auth/v1/magic-link/verify` - Verify magic link token
131
158
 
159
+ **Disabling sign-up via magic link:**
160
+
161
+ Like Email OTP, the magic-link plugin **auto-creates an account** when a link is
162
+ verified for an unknown email, on a code path independent of
163
+ `emailAndPassword.disableSignUp`. Gate it with the object form:
164
+
165
+ ```ts
166
+ auth: defineAuth("better-auth", {
167
+ emailAndPassword: { enabled: true },
168
+ plugins: {
169
+ magicLink: { disableSignUp: true }, // sign-in only; unknown emails rejected
170
+ },
171
+ }),
172
+ ```
173
+
174
+ It inherits the global signup gate the same way `emailOtp.disableSignUp` does:
175
+ `account.auth.signup: false` gates the magic-link path automatically; set
176
+ `magicLink: { disableSignUp: false }` to opt it back open.
177
+
132
178
  **Email customization:**
133
179
 
134
180
  Magic link emails use the same AWS SES configuration as Email OTP. Customize the email template via environment variables:
@@ -355,12 +355,14 @@ After compiling:
355
355
 
356
356
  | Option | Type | Default | Description |
357
357
  |--------|------|---------|-------------|
358
- | `binding` | `string` | `R2_BUCKET` | R2 bucket binding name |
359
- | `bucketName` | `string` | Required | R2 bucket name |
360
- | `filesBinding` | `string` | `FILES_DB` | Files metadata D1 binding |
361
- | `maxFileSize` | `number` | 10MB | Max upload size in bytes |
362
- | `allowedTypes` | `string[]` | Images only | Allowed MIME types |
363
- | `publicDomain` | `string` | - | Custom domain for files worker |
358
+ | `managed` | `boolean` | `false` | Opt into the FILES_DB subsystem + `/storage/v1/*` + files worker. Off = presign-only. |
359
+ | `bucketName` | `string` | `<project>-media` | R2 bucket the signer targets (override per-call with `signPutUrl(key, { bucket })`) |
360
+ | `presign` | `object` | - | Env-var name overrides: `{ accountIdEnv, accessKeyIdEnv, secretAccessKeyEnv, endpointEnv }` |
361
+ | `binding` | `string` | `R2_BUCKET` | R2 bucket binding name (managed mode) |
362
+ | `filesBinding` | `string` | `FILES_DB` | Files metadata D1 binding (managed mode) |
363
+ | `maxFileSize` | `number \| string` | 10MB | Max upload size — bytes or `"100mb"` (managed mode) |
364
+ | `allowedTypes` | `string[]` | Images only | Allowed MIME types (managed mode) |
365
+ | `publicDomain` | `string` | - | Custom domain for files worker (managed mode) |
364
366
 
365
367
  ## Security Model
366
368
 
@@ -2,53 +2,78 @@
2
2
 
3
3
  Cloudflare R2 provides S3-compatible object storage for file uploads in the Quickback Stack.
4
4
 
5
- ## Upload Flow
5
+ By default `defineFileStorage("cloudflare-r2")` is **presign-only**: you get the
6
+ `ctx.storage` signer and nothing else. The `/storage/v1/*` endpoints shown
7
+ further down only exist in the [managed subsystem](/stack/storage/r2#two-modes)
8
+ (`managed: true`).
9
+
10
+ ## Upload Flow (default — `ctx.storage`)
11
+
12
+ Write a normal `defineAction` that signs a presigned URL and stores the key in
13
+ **your own table**. Bytes go directly to R2 — the Worker only signs.
14
+
15
+ ```ts
16
+ export default defineAction({
17
+ path: "/media/sign-upload",
18
+ method: "POST",
19
+ input: z.object({ filename: z.string(), contentType: z.string() }),
20
+ access: { roles: ["member"] },
21
+ async execute({ input, ctx, db, storage }) {
22
+ const key = `org/${ctx.activeOrgId}/${crypto.randomUUID()}-${input.filename}`;
23
+ const upload = await storage.signPutUrl(key, { contentType: input.contentType, expiresIn: 600 });
24
+ await db.insert(media).values({ key /* … */ });
25
+ return { uploadUrl: upload.url, key, headers: upload.headers };
26
+ },
27
+ });
28
+ ```
29
+
30
+ ```bash
31
+ # 1. Ask your action for a signed URL (your auth/roles run here)
32
+ curl -X POST https://api.example.com/api/v1/media/sign-upload \
33
+ -H "Authorization: Bearer <token>" -H "Content-Type: application/json" \
34
+ -d '{ "filename": "report.pdf", "contentType": "application/pdf" }'
35
+ # → { "uploadUrl": "https://<account>.r2.cloudflarestorage.com/...&X-Amz-Signature=...", "key": "...", "headers": { "Content-Type": "application/pdf" } }
36
+
37
+ # 2. Upload the bytes straight to R2 (replay the returned headers)
38
+ curl -X PUT "<uploadUrl>" -H "Content-Type: application/pdf" --data-binary @report.pdf
39
+ ```
40
+
41
+ `storage.signPutUrl(key, { contentType?, expiresIn?, bucket? })` returns
42
+ `{ url, method, headers, key, expiresAt }`; `storage.signGetUrl(key, { expiresIn?, downloadFilename?, bucket? })`
43
+ returns a presigned GET URL. Pass `bucket` to target a bucket other than the
44
+ configured default.
45
+
46
+ Presigning needs an R2 API token — set the `R2_ACCOUNT_ID`, `R2_ACCESS_KEY_ID`,
47
+ and `R2_SECRET_ACCESS_KEY` secrets. See [R2 Setup → Presigned uploads](/stack/storage/r2#presigned-uploads-recommended).
6
48
 
7
- The generated API provides a two-step **presigned** upload — the file bytes go
8
- directly to R2 and never stream through your Worker:
49
+ ## Upload Flow (managed mode — `/storage/v1/*`)
9
50
 
10
- 1. **Request a presigned URL** — Client calls `/storage/v1/presign/...`; the
11
- Worker runs auth + bucket + role checks and returns a time-limited URL
12
- 2. **Upload directly to R2** — Client `PUT`s the bytes to R2 (bypasses your Worker)
13
- 3. **Confirm** — `/storage/v1/confirm/...` reconciles the recorded size + etag
51
+ With `managed: true`, the generated API also exposes turnkey presigned
52
+ endpoints backed by the FILES_DB metadata system:
14
53
 
15
54
  ```bash
16
55
  # 1. Request a presigned upload URL
17
56
  curl -X POST https://api.example.com/storage/v1/presign/documents/report.pdf \
18
- -H "Authorization: Bearer <token>" \
19
- -H "Content-Type: application/json" \
57
+ -H "Authorization: Bearer <token>" -H "Content-Type: application/json" \
20
58
  -d '{ "contentType": "application/pdf", "size": 248000 }'
59
+ # → { "id": "obj_abc", "key": "...", "uploadUrl": "...", "headers": {...}, "expiresAt": "..." }
60
+
61
+ # 2. Upload directly to R2
62
+ curl -X PUT "<uploadUrl>" -H "Content-Type: application/pdf" --data-binary @report.pdf
21
63
 
22
- # Response:
23
- # {
24
- # "id": "obj_abc123",
25
- # "key": "org_abc/documents/report.pdf",
26
- # "uploadUrl": "https://<account>.r2.cloudflarestorage.com/...&X-Amz-Signature=...",
27
- # "method": "PUT",
28
- # "headers": { "Content-Type": "application/pdf" },
29
- # "expiresAt": "2026-06-02T12:10:00.000Z"
30
- # }
31
-
32
- # 2. Upload directly to R2 using the presigned URL (replay the returned headers)
33
- curl -X PUT "<uploadUrl>" \
34
- -H "Content-Type: application/pdf" \
35
- --data-binary @report.pdf
36
-
37
- # 3. Confirm the upload
64
+ # 3. Confirm (reconciles size + etag)
38
65
  curl -X POST https://api.example.com/storage/v1/confirm/documents/report.pdf \
39
66
  -H "Authorization: Bearer <token>"
40
67
  ```
41
68
 
42
- Presigning needs an R2 API token — set the `R2_ACCOUNT_ID`, `R2_ACCESS_KEY_ID`,
43
- and `R2_SECRET_ACCESS_KEY` secrets. See [R2 Setup → Presigned uploads](/stack/storage/r2#presigned-uploads-recommended).
44
-
45
- For uploads that should land in **your own table** (with your own access rules),
46
- sign the URL from inside a `defineAction` via `ctx.storage` — see
47
- [Signing from your own action](/stack/storage/r2#signing-from-your-own-action).
48
-
49
69
  ## Download Flow
50
70
 
51
- Files are served through your Worker with security checks applied:
71
+ In **presign-only** mode, mint a short-lived download URL with
72
+ `storage.signGetUrl(key, { downloadFilename })` from your action and hand it to
73
+ the client — the bytes come straight from R2.
74
+
75
+ In **managed** mode, files are also served through the worker with security
76
+ checks applied:
52
77
 
53
78
  ```bash
54
79
  # Download a file (auth + firewall enforced)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quickback-dev/cli",
3
- "version": "0.40.0",
3
+ "version": "0.40.2",
4
4
  "description": "CLI for Quickback — define your backend in TypeScript, compile to a fully wired Cloudflare Worker (or Bun / Node) with auth, database, migrations, security, CMS, and Account UI.",
5
5
  "author": "Kardoe Incorporated <paul@kardoe.com>",
6
6
  "license": "MIT",
@@ -1,5 +1,41 @@
1
1
  # Changelog
2
2
 
3
+ ## v0.40.2 — June 3, 2026
4
+
5
+ ### Passwordless plugins can no longer bypass the signup gate
6
+
7
+ Better Auth's `emailOtp` and `magicLink` plugins auto-create an account when a
8
+ code/link is verified for an unknown email — and that path is independent of
9
+ `emailAndPassword.disableSignUp`. As a result, `account.auth.signup: false`
10
+ closed `POST /auth/v1/sign-up/email` but left OTP / magic-link verification as an
11
+ open back-door for account creation.
12
+
13
+ The compiler now emits each plugin's own `disableSignUp` flag, and new
14
+ per-plugin options expose it directly:
15
+
16
+ ```ts
17
+ auth: defineAuth("better-auth", {
18
+ emailAndPassword: { enabled: true },
19
+ plugins: {
20
+ emailOtp: { disableSignUp: true }, // OTP sign-in only; unknown emails rejected
21
+ magicLink: { disableSignUp: true }, // same for magic links
22
+ },
23
+ }),
24
+ ```
25
+
26
+ Both default to following the global gate: setting `account.auth.signup: false`
27
+ (→ `emailAndPassword.disableSignUp: true`) now also gates the OTP and magic-link
28
+ paths automatically. Set `{ disableSignUp: false }` on a plugin explicitly to
29
+ keep its sign-up open while password sign-up stays closed.
30
+
31
+ ## v0.40.1 — June 2, 2026
32
+
33
+ - The generated `wrangler.toml` and `Env` type now emit the `ASSETS` binding
34
+ type for projects that mount SPAs (CMS / Account), so handler code that
35
+ references `c.env.ASSETS` typechecks.
36
+ - Compiler Docker builds preserve their layer cache across rebuilds, cutting
37
+ local recompile time.
38
+
3
39
  ## v0.40.0 — June 2, 2026
4
40
 
5
41
  R2 file storage is now **presign-only by default**. Adding
@@ -46,6 +46,33 @@ Use this to show UI warnings when SES isn't configured.
46
46
  - `GET /api/v1/system/email-status`
47
47
  - Response: `{ "emailConfigured": true|false }`
48
48
 
49
+ **Disabling sign-up via OTP:**
50
+
51
+ By default the Email OTP plugin **auto-creates an account** when a code is
52
+ verified for an unknown email — verifying an OTP doubles as registration. This
53
+ is a separate code path from `emailAndPassword.disableSignUp` (which only gates
54
+ `POST /auth/v1/sign-up/email`), so disabling password sign-up alone does *not*
55
+ close the OTP path.
56
+
57
+ To make OTP sign-in only (existing users can sign in; unknown emails are
58
+ rejected instead of registered), use the object form:
59
+
60
+ ```ts
61
+ auth: defineAuth("better-auth", {
62
+ emailAndPassword: { enabled: true },
63
+ plugins: {
64
+ emailOtp: { disableSignUp: true },
65
+ },
66
+ }),
67
+ ```
68
+
69
+ > `emailOtp.disableSignUp` **inherits the global signup gate**: when
70
+ > `account.auth.signup: false` (i.e. `emailAndPassword.disableSignUp: true`) is
71
+ > set, the OTP plugin is gated automatically so it can't be used to bypass it. Set
72
+ > `emailOtp: { disableSignUp: false }` explicitly to opt the OTP path back open
73
+ > while password sign-up stays closed.
74
+
75
+
49
76
  ### Upgrade Anonymous
50
77
 
51
78
  Adds a first-class endpoint to convert an anonymous user into a full user. This flips `isAnonymous` to `false` and refreshes the session cache immediately.
@@ -129,6 +156,25 @@ auth: defineAuth("better-auth", {
129
156
  - `POST /auth/v1/magic-link/send` - Send magic link email
130
157
  - `GET /auth/v1/magic-link/verify` - Verify magic link token
131
158
 
159
+ **Disabling sign-up via magic link:**
160
+
161
+ Like Email OTP, the magic-link plugin **auto-creates an account** when a link is
162
+ verified for an unknown email, on a code path independent of
163
+ `emailAndPassword.disableSignUp`. Gate it with the object form:
164
+
165
+ ```ts
166
+ auth: defineAuth("better-auth", {
167
+ emailAndPassword: { enabled: true },
168
+ plugins: {
169
+ magicLink: { disableSignUp: true }, // sign-in only; unknown emails rejected
170
+ },
171
+ }),
172
+ ```
173
+
174
+ It inherits the global signup gate the same way `emailOtp.disableSignUp` does:
175
+ `account.auth.signup: false` gates the magic-link path automatically; set
176
+ `magicLink: { disableSignUp: false }` to opt it back open.
177
+
132
178
  **Email customization:**
133
179
 
134
180
  Magic link emails use the same AWS SES configuration as Email OTP. Customize the email template via environment variables:
@@ -355,12 +355,14 @@ After compiling:
355
355
 
356
356
  | Option | Type | Default | Description |
357
357
  |--------|------|---------|-------------|
358
- | `binding` | `string` | `R2_BUCKET` | R2 bucket binding name |
359
- | `bucketName` | `string` | Required | R2 bucket name |
360
- | `filesBinding` | `string` | `FILES_DB` | Files metadata D1 binding |
361
- | `maxFileSize` | `number` | 10MB | Max upload size in bytes |
362
- | `allowedTypes` | `string[]` | Images only | Allowed MIME types |
363
- | `publicDomain` | `string` | - | Custom domain for files worker |
358
+ | `managed` | `boolean` | `false` | Opt into the FILES_DB subsystem + `/storage/v1/*` + files worker. Off = presign-only. |
359
+ | `bucketName` | `string` | `<project>-media` | R2 bucket the signer targets (override per-call with `signPutUrl(key, { bucket })`) |
360
+ | `presign` | `object` | - | Env-var name overrides: `{ accountIdEnv, accessKeyIdEnv, secretAccessKeyEnv, endpointEnv }` |
361
+ | `binding` | `string` | `R2_BUCKET` | R2 bucket binding name (managed mode) |
362
+ | `filesBinding` | `string` | `FILES_DB` | Files metadata D1 binding (managed mode) |
363
+ | `maxFileSize` | `number \| string` | 10MB | Max upload size — bytes or `"100mb"` (managed mode) |
364
+ | `allowedTypes` | `string[]` | Images only | Allowed MIME types (managed mode) |
365
+ | `publicDomain` | `string` | - | Custom domain for files worker (managed mode) |
364
366
 
365
367
  ## Security Model
366
368
 
@@ -2,53 +2,78 @@
2
2
 
3
3
  Cloudflare R2 provides S3-compatible object storage for file uploads in the Quickback Stack.
4
4
 
5
- ## Upload Flow
5
+ By default `defineFileStorage("cloudflare-r2")` is **presign-only**: you get the
6
+ `ctx.storage` signer and nothing else. The `/storage/v1/*` endpoints shown
7
+ further down only exist in the [managed subsystem](/stack/storage/r2#two-modes)
8
+ (`managed: true`).
9
+
10
+ ## Upload Flow (default — `ctx.storage`)
11
+
12
+ Write a normal `defineAction` that signs a presigned URL and stores the key in
13
+ **your own table**. Bytes go directly to R2 — the Worker only signs.
14
+
15
+ ```ts
16
+ export default defineAction({
17
+ path: "/media/sign-upload",
18
+ method: "POST",
19
+ input: z.object({ filename: z.string(), contentType: z.string() }),
20
+ access: { roles: ["member"] },
21
+ async execute({ input, ctx, db, storage }) {
22
+ const key = `org/${ctx.activeOrgId}/${crypto.randomUUID()}-${input.filename}`;
23
+ const upload = await storage.signPutUrl(key, { contentType: input.contentType, expiresIn: 600 });
24
+ await db.insert(media).values({ key /* … */ });
25
+ return { uploadUrl: upload.url, key, headers: upload.headers };
26
+ },
27
+ });
28
+ ```
29
+
30
+ ```bash
31
+ # 1. Ask your action for a signed URL (your auth/roles run here)
32
+ curl -X POST https://api.example.com/api/v1/media/sign-upload \
33
+ -H "Authorization: Bearer <token>" -H "Content-Type: application/json" \
34
+ -d '{ "filename": "report.pdf", "contentType": "application/pdf" }'
35
+ # → { "uploadUrl": "https://<account>.r2.cloudflarestorage.com/...&X-Amz-Signature=...", "key": "...", "headers": { "Content-Type": "application/pdf" } }
36
+
37
+ # 2. Upload the bytes straight to R2 (replay the returned headers)
38
+ curl -X PUT "<uploadUrl>" -H "Content-Type: application/pdf" --data-binary @report.pdf
39
+ ```
40
+
41
+ `storage.signPutUrl(key, { contentType?, expiresIn?, bucket? })` returns
42
+ `{ url, method, headers, key, expiresAt }`; `storage.signGetUrl(key, { expiresIn?, downloadFilename?, bucket? })`
43
+ returns a presigned GET URL. Pass `bucket` to target a bucket other than the
44
+ configured default.
45
+
46
+ Presigning needs an R2 API token — set the `R2_ACCOUNT_ID`, `R2_ACCESS_KEY_ID`,
47
+ and `R2_SECRET_ACCESS_KEY` secrets. See [R2 Setup → Presigned uploads](/stack/storage/r2#presigned-uploads-recommended).
6
48
 
7
- The generated API provides a two-step **presigned** upload — the file bytes go
8
- directly to R2 and never stream through your Worker:
49
+ ## Upload Flow (managed mode — `/storage/v1/*`)
9
50
 
10
- 1. **Request a presigned URL** — Client calls `/storage/v1/presign/...`; the
11
- Worker runs auth + bucket + role checks and returns a time-limited URL
12
- 2. **Upload directly to R2** — Client `PUT`s the bytes to R2 (bypasses your Worker)
13
- 3. **Confirm** — `/storage/v1/confirm/...` reconciles the recorded size + etag
51
+ With `managed: true`, the generated API also exposes turnkey presigned
52
+ endpoints backed by the FILES_DB metadata system:
14
53
 
15
54
  ```bash
16
55
  # 1. Request a presigned upload URL
17
56
  curl -X POST https://api.example.com/storage/v1/presign/documents/report.pdf \
18
- -H "Authorization: Bearer <token>" \
19
- -H "Content-Type: application/json" \
57
+ -H "Authorization: Bearer <token>" -H "Content-Type: application/json" \
20
58
  -d '{ "contentType": "application/pdf", "size": 248000 }'
59
+ # → { "id": "obj_abc", "key": "...", "uploadUrl": "...", "headers": {...}, "expiresAt": "..." }
60
+
61
+ # 2. Upload directly to R2
62
+ curl -X PUT "<uploadUrl>" -H "Content-Type: application/pdf" --data-binary @report.pdf
21
63
 
22
- # Response:
23
- # {
24
- # "id": "obj_abc123",
25
- # "key": "org_abc/documents/report.pdf",
26
- # "uploadUrl": "https://<account>.r2.cloudflarestorage.com/...&X-Amz-Signature=...",
27
- # "method": "PUT",
28
- # "headers": { "Content-Type": "application/pdf" },
29
- # "expiresAt": "2026-06-02T12:10:00.000Z"
30
- # }
31
-
32
- # 2. Upload directly to R2 using the presigned URL (replay the returned headers)
33
- curl -X PUT "<uploadUrl>" \
34
- -H "Content-Type: application/pdf" \
35
- --data-binary @report.pdf
36
-
37
- # 3. Confirm the upload
64
+ # 3. Confirm (reconciles size + etag)
38
65
  curl -X POST https://api.example.com/storage/v1/confirm/documents/report.pdf \
39
66
  -H "Authorization: Bearer <token>"
40
67
  ```
41
68
 
42
- Presigning needs an R2 API token — set the `R2_ACCOUNT_ID`, `R2_ACCESS_KEY_ID`,
43
- and `R2_SECRET_ACCESS_KEY` secrets. See [R2 Setup → Presigned uploads](/stack/storage/r2#presigned-uploads-recommended).
44
-
45
- For uploads that should land in **your own table** (with your own access rules),
46
- sign the URL from inside a `defineAction` via `ctx.storage` — see
47
- [Signing from your own action](/stack/storage/r2#signing-from-your-own-action).
48
-
49
69
  ## Download Flow
50
70
 
51
- Files are served through your Worker with security checks applied:
71
+ In **presign-only** mode, mint a short-lived download URL with
72
+ `storage.signGetUrl(key, { downloadFilename })` from your action and hand it to
73
+ the client — the bytes come straight from R2.
74
+
75
+ In **managed** mode, files are also served through the worker with security
76
+ checks applied:
52
77
 
53
78
  ```bash
54
79
  # Download a file (auth + firewall enforced)