@quickback-dev/cli 0.50.7 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,7 +3,7 @@
3
3
  export const DOCS = {
4
4
  "changelog": {
5
5
  "title": "Changelog",
6
- "content": "## Unreleased\n\n### Neon hyperdrive: generated `env.d.ts` now types the `HYPERDRIVE` binding\n\n`connectionMode: \"hyperdrive\"` projects emit a `[[hyperdrive]] binding =\n\"HYPERDRIVE\"` wrangler block and a db runtime that requires\n`env.HYPERDRIVE.connectionString` — but the generated `src/env.d.ts` omitted\nthe binding, so every generated `createDb(c.env)` / `createServiceDb(c.env)`\ncall site (middleware, routes, webhooks, seal routes) failed `tsc` with\n`Property 'HYPERDRIVE' is missing in type 'CloudflareBindings'`. The Env\ninterface now declares `HYPERDRIVE: Hyperdrive` (the `@cloudflare/workers-types`\nglobal) whenever the resolved Neon connection mode is `hyperdrive`. The\nwrangler-binding completeness matrix gained neon http/hyperdrive cases pinning\n`env.d.ts` ↔ `wrangler.toml` agreement, and a new test typechecks the real\nemitted env/db files with the exact generated call shape.\n\n### Neon hyperdrive: typed action `db` accepts explicit values for defaulted columns\n\nOn the hyperdrive typed action surface, `db.insert(table).values({ id: ..., ... })`\nfailed `tsc` with `'id' does not exist in type 'QbPgScopedInsertValue<…>'` for\nany column with a schema default — explicit ids on `$defaultFn` primary keys,\nexplicit `status` on defaulted enums, explicit audit timestamps. The scoped\ninsert model was derived from drizzle's `PgInsertValue\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": "## Unreleased\n\n### Action rate limits now emit — documented since the rate-limit pillar, wired now\n\nThe [rate-limit docs](/compiler/definitions/rate-limit#actions) have described\nper-action rate limiting since the pillar shipped: record-based actions inherit\nthe resource's `update` bucket, standalone actions inherit the project-default\n`update` bucket, and actions may declare a `rateLimit` override or opt out with\n`rateLimit: false`. The generated routes never contained the checks. They now\ndo, exactly per the documented contract:\n\n- Record-based actions (and their bulk variants, which share the same counter —\n one token per batch request) are keyed\n `<resource>:action:<name>:<user>`; standalone actions are keyed\n `standalone:<declaredPath>:<user>`. The `:action:`/`standalone:` infixes mean\n action counters never collide with CRUD counters.\n- `rateLimit: { limit, period }` on an action emits its own binding\n (deduped by tuple, same `RL_<limit>_<period>` scheme); `rateLimit: false`\n opts the action out entirely.\n- Record-based action routes are now **exempted** from the per-resource CRUD\n catch-all middleware. Previously a `POST /:id/approve` was incidentally\n counted against the resource's `create` bucket — wrong bucket, wrong key.\n- Actions-only (tableless) projects now provision the project-default binding;\n previously they shipped with none.\n\n**Behavior change:** standalone actions were previously *unlimited*; they now\ninherit the project-default `update` bucket (200 requests / 60s per user/IP\nwith shipped defaults). PUBLIC webhook-style endpoints that absorb provider\nbursts should declare their own budget (`rateLimit: { limit: 1000, period: 10 }`)\nor opt out (`rateLimit: false`). The compiler emits a warning when a PUBLIC\nstandalone action silently inherits the default, so affected actions are\nflagged at compile time.\n\n### Better Auth CLI pinned and shipped as a generated devDependency\n\nThe generated `auth:schema` script runs `npx better-auth generate`, but the\n`better-auth` runtime package ships no executable — the `better-auth` bin\nlives in the npm package `auth` (the official Better Auth CLI; the team took\nover that name at 1.5.0, superseding the frozen `@better-auth/cli`). Generated\nprojects now declare `auth` as a devDependency pinned to the runtime's minor\nline, so `npm run build` resolves the CLI locally instead of requiring a\nglobal install. The compiler image's global CLI is pinned to the same version,\neliminating silent skew between the CLI on `latest` and the pinned runtime.\n\n### Compile warning when an action's input schema degrades to untyped\n\nWhen action input schemas aren't harvested client-side (older CLI, or a direct\n`/compile` API call), the static Zod parser supplies OpenAPI/MCP input schemas\n— and silently degrades unrecognized constructs (discriminated unions,\nrefinements, `z.record`, transforms) to the accept-anything `{}`. That\ndegradation is no longer silent: the compile result now carries a warning per\naffected action naming the route, source file, and the exact untyped field\npaths. Actions covered by the CLI harvest are never warned on, and actions\nthat declare no input are skipped.\n\n### Auth docs: JWT security posture stated up front\n\nThe [Auth & JWT page](/compiler/config/auth) now leads with the posture\nsummary instead of burying it: the default 180-second auto-refreshed TTL plus\n`revocationCheck: 'kv'` (seconds-level revocation, auto-stamped on ban /\nmember removal / role change / scope-conferring row changes) is the\nrecommended configuration and covers the vast majority of deployments — with\nthe residual trade-offs (per-principal granularity, fail-open on KV outage,\n~60s cross-PoP propagation) stated explicitly for strict threat models.\n\n### Neon via-user reads: generated list handlers now typecheck against the concretely-typed service handle\n\nOn Neon, a read firewall carrying a via-user multi-hop relationship predicate\nroutes the generated read handlers to `createServiceDb(c.env)` — a genuine\n`NeonHttpDatabase<typeof schema>` — instead of the loosely-typed request db.\nThe list handler's query construction declared drizzle select builders with\n`let` and reassigned them (`query = query.where(…)`, `.orderBy(…)`,\n`.limit(…).offset(…)`, and the count/aggregation/group-by variants), which is\na type error against drizzle's immutable builder typing: `.where()` returns\n`Omit\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",
@@ -43,7 +43,7 @@ export const DOCS = {
43
43
  },
44
44
  "compiler/config/auth": {
45
45
  "title": "Auth & JWT",
46
- "content": "The top-level `auth` config block holds provider-agnostic auth knobs that affect how Quickback emits the auth middleware, JWT helpers, and access-rule expansion.\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // ...\n auth: {\n roleHierarchy: ['member', 'admin', 'owner'],\n jwt: {\n expiresIn: 60,\n issuer: 'my-api',\n // audience, secretEnv, algorithm, revocationCheck...\n },\n },\n});\n```\n\n## `auth.roleHierarchy`\n\nLowest-to-highest privilege list. Lets access rules use `'role+'` shorthand to mean \"this role and above\". Documented in detail under [Access — Role hierarchy](/compiler/definitions/access#role-hierarchy).\n\n## `auth.jwt` — JWT bearer-token fast-path\n\nQuickback ships its own custom HMAC-SHA256 JWT (not Better Auth's JWT plugin) so it can embed `orgId` and `role` claims the fast-path needs to reconstruct `AppContext` without a database round-trip. The signing secret is shared with Better Auth (`BETTER_AUTH_SECRET`) by default — users only manage one secret.\n\n### Behavior recap\n\n1. The browser SPA gets a JWT via the `set-auth-token` response header on every authenticated call.\n2. On subsequent requests the SPA sends `Authorization: Bearer <jwt>`.\n3. The auth middleware's **fast-path** verifies the signature only — no DB query, no session lookup. `AppContext` is reconstructed from JWT claims.\n4. If verification fails (or no JWT is present), the middleware falls back to session auth.\n5. After successful session auth, a fresh JWT is minted and returned via `set-auth-token`. The cycle continues.\n\nThe fast-path is intentionally stateless: it trusts the claims for the full TTL. **Stolen or pre-revocation tokens are valid until they expire.** That's the trade-off the fast-path makes — and the reason `expiresIn` is the most-tuned knob below.\n\n### `expiresIn?: number` — TTL in seconds\n\nDefault `180` (3 minutes).\n\nLowering this shrinks the worst-case window where a stolen / pre-revocation token still works. Browser SPAs auto-refresh via `set-auth-token` on every authed call, so a low TTL is invisible to logged-in users; only stale server-to-server bearer tokens feel it.\n\n```ts\nauth: { jwt: { expiresIn: 30 } } // 30s — tight post-revocation window\nauth: { jwt: { expiresIn: 3600 } } // 1h — longer-lived tokens for CLI / CI\n```\n\n### `issuer?: string` — `iss` claim\n\nDefault omitted.\n\nSet this when other services need to distinguish JWTs minted by this Worker from other issuers. The compiler bakes the issuer into both the mint side (added to claims) and the verify side (rejects tokens with mismatched `iss`).\n\n### `audience?: string` — `aud` claim\n\nDefault omitted.\n\nSet this when this Worker's JWTs are consumed by a sibling service that should reject tokens minted for a different audience. Same mint-and-verify treatment as `issuer`.\n\n### `secretEnv?: string` — signing secret env var\n\nDefault `'BETTER_AUTH_SECRET'`.\n\nOverride this if you want JWT signing isolated from the Better Auth secret (e.g. rotating one without invalidating the other).\n\n```ts\nauth: { jwt: { secretEnv: 'CUSTOM_JWT_SECRET' } }\n```\n\nThe compiler emits `c.env.CUSTOM_JWT_SECRET` (or `process.env.CUSTOM_JWT_SECRET` on Bun/Node) in the auth middleware's verify and mint sites and the `/api/v1/token` endpoint.\n\n> **Note:** the files-worker (separate Worker for R2 access) still reads `BETTER_AUTH_SECRET` directly. If you override `secretEnv`, set both env vars to the same value or the files worker's JWT verification will fall back to DB session lookup. Threading `secretEnv` through the files worker is on the roadmap.\n\n### `algorithm?: 'HS256'`\n\nOnly `HS256` is supported in 0.10.14. `RS256` (asymmetric, public-key verify / private-key sign) is on the roadmap.\n\n### `revocationCheck?: 'none' | 'kv'` — token revocation strategy\n\nDefault `'none'`.\n\n| Value | Behavior | Cost per verify |\n|---|---|---|\n| `'none'` | No revocation check. Stolen / pre-revocation tokens valid until TTL expires (scope claims: until the carry-forward cap). Use a low `expiresIn` to bound the replay window. | 0 |\n| `'kv'` | Fast-path checks per-principal revocation timestamps in the project's existing `KV` binding before trusting a verified token. | 2+ KV reads (~5-15ms, edge-cached) |\n\n`'kv'` (v0.45+, **Cloudflare runtime only**) keeps the fast-path stateless against the auth DB (still 0 D1 queries). There is nothing extra to provision — entries ride the `KV` binding every project already has, prefixed `qbrev:` and self-expiring after the maximum token lifetime, so the store never accumulates.\n\nA token is rejected when its mint timestamp (`iat`, or `sct` for the relationship-scope claim) predates the stored timestamp for any principal key it rides on:\n\n| Key | Revokes | Written automatically on |\n|---|---|---|\n| `qbrev:user:<userId>` | every JWT for the user | user ban (`databaseHooks.user.update.after` — flipping `banned` stamps the key and, when outbound webhooks are enabled, emits a `user.banned` event). Call `revokeUserTokens` for custom flows (revoke-all, etc.) |\n| `qbrev:member:<userId>:<orgId>` | the user's org-membership claims | member removal / role change (Better Auth `organizationHooks`) |\n| `qbrev:scope:<userId>:<kind>:<id>` | the user's carried scope claim | UPDATE/DELETE of a scope-conferring relationship row (audit-wrapper chokepoint + the single DELETE route) |\n\n`src/lib/jwt-revocation.ts` exports `revokeUserTokens` / `revokeMemberTokens` / `revokeScopeTokens` for explicit calls from actions. A rejected token falls through to session auth, which re-checks membership and re-mints — an active legitimate session recovers transparently.\n\nSemantics worth knowing:\n\n- **Revoke-on-touch for scopes:** any update or delete of a conferring row stamps the revocation, without evaluating whether the change actually ended the relationship. A false positive just forces a cheap re-prove (`/scope/v1/enter` or a minting namespace route).\n- **Fails open:** a missing binding or KV outage skips the check (logged) — revocation degrades to the TTL / carry-forward-cap bound rather than locking every bearer out.\n- **Eventual consistency:** KV propagates cross-PoP in ~60s. \"Immediate\" means seconds at the writing location, bounded-seconds globally — still far inside the 15-minute carry-forward cap that bounds revocation without this check.\n- **Coverage gap:** batch *hard* deletes don't return rows through the chokepoint; call `revokeScopeTokens` explicitly if you bulk-hard-delete conferring rows.\n\n## Defaults preserve 0.10.13 behavior\n\nAdding the `auth.jwt` block without setting any field is a no-op vs. the 0.10.13 baseline. Each missing field falls back to its hardcoded value:\n\n| Field | Default |\n|---|---|\n| `expiresIn` | 180 |\n| `issuer` | omitted |\n| `audience` | omitted |\n| `secretEnv` | `'BETTER_AUTH_SECRET'` |\n| `algorithm` | `'HS256'` |\n| `revocationCheck` | `'none'` |\n\n## Tuning recommendations\n\n- **B2C SaaS, mostly browser traffic:** keep defaults. The 180s TTL + auto-refresh model just works.\n- **Pentest engagement / enterprise compliance:** set `expiresIn: 30`. Tokens stay invisible to logged-in users (auto-refreshed every authed call) but stolen-token windows shrink to 30s.\n- **CLI-heavy / long-running CI tokens:** `expiresIn: 3600` for one-hour bearer tokens. Pair with `issuer` / `audience` if multiple services consume the same JWT.\n- **Need immediate revocation:** set `revocationCheck: 'kv'` (Cloudflare runtime). Or drop TTL to ~30s — similar effect with bounded delay and zero KV reads.\n\n## `auth.loginUrl` / `auth.profileUrl` — external sign-in for consumer Workers\n\nWhen a Quickback Worker doesn't host its own Account SPA — e.g. an internal-app mesh where one Worker on the parent domain owns identity (`auth.example.com`) and other Workers share cookies — the compiler-emitted CMS access gates need to redirect unauthenticated visitors to the central sign-in surface, not the local `/account/login` (which doesn't exist there).\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // ...\n auth: {\n loginUrl: 'https://auth.example.com/login',\n profileUrl: 'https://auth.example.com/profile',\n },\n});\n```\n\nBoth fields override compiler-emitted browser redirects in the CMS shell:\n\n- **Unauthenticated visitor hits a CMS route** → `302 → <loginUrl>?redirect=<original-url>`\n- **Authenticated user fails the `cms.access: 'admin'` platform-role check** → `302 → <profileUrl>`\n\nThe `?redirect=…` query param is preserved unchanged so the central sign-in surface can bounce the user back after authentication.\n\n### Resolution precedence\n\nMost-specific wins:\n\n1. Explicit `auth.loginUrl` / `auth.profileUrl` — the cookie-trusting consumer-Worker case (this section).\n2. `https://<account.domain>/login` — inferred when this project hosts its own Account SPA on a custom domain.\n3. `/account/login` — built-in fallback, when neither knob is set.\n\n### Independent from `account.domain`\n\n`account.domain` does *two* things: redirect targets *and* hostname-based asset routing for an Account SPA hosted by this project. Consumer Workers don't host Account at all — they only need the URL. `auth.loginUrl` is a redirect-target string with no routing side effects, which is why it's a separate knob.\n\n### When both are set\n\nSetting `auth.loginUrl` *and* `account.domain` is legal — the explicit override beats the inferred URL at the redirect site, while `account.domain` still drives the local Account SPA's hostname routing as usual. Useful when you want to host Account on one custom domain (`account.foo.com`) but redirect *somewhere else* for sign-in (e.g. an SSO surface at `auth.foo.com`)."
46
+ "content": "The top-level `auth` config block holds provider-agnostic auth knobs that affect how Quickback emits the auth middleware, JWT helpers, and access-rule expansion.\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // ...\n auth: {\n roleHierarchy: ['member', 'admin', 'owner'],\n jwt: {\n expiresIn: 60,\n issuer: 'my-api',\n // audience, secretEnv, algorithm, revocationCheck...\n },\n },\n});\n```\n\n## `auth.roleHierarchy`\n\nLowest-to-highest privilege list. Lets access rules use `'role+'` shorthand to mean \"this role and above\". Documented in detail under [Access — Role hierarchy](/compiler/definitions/access#role-hierarchy).\n\n## `auth.jwt` — JWT bearer-token fast-path\n\nQuickback ships its own custom HMAC-SHA256 JWT (not Better Auth's JWT plugin) so it can embed `orgId` and `role` claims the fast-path needs to reconstruct `AppContext` without a database round-trip. The signing secret is shared with Better Auth (`BETTER_AUTH_SECRET`) by default — users only manage one secret.\n\n### Security posture at a glance\n\nThe short version, before the knob-by-knob detail:\n\n- **Default: 180-second TTL, auto-refreshed.** Every authenticated call returns a fresh token via the `set-auth-token` header, so the low TTL is invisible to logged-in users. The worst-case window for a stolen or pre-revocation token is 3 minutes — and you can shrink it to 30 seconds with one config line.\n- **Need revocation faster than the TTL?** Set [`revocationCheck: 'kv'`](#revocationcheck-none--kv--token-revocation-strategy). Revoked tokens are rejected within seconds; revocation stamps are written automatically on user ban, org-member removal, role change, and changes to scope-conferring relationship rows.\n\nThose two knobs — `expiresIn` and `revocationCheck` — cover the vast majority of deployments. The honest residual for the strictest threat models: the KV check revokes per-principal (not per-session), fails open if KV is unreachable (degrading to the TTL bound), and propagates cross-PoP in ~60s. If you need fail-closed, per-session kill semantics, set `expiresIn: 30` for a hard 30-second ceiling — and [tell us about your use case](https://github.com/kardoe/quickback/issues); an opaque-session mode is under consideration.\n\n### Behavior recap\n\n1. The browser SPA gets a JWT via the `set-auth-token` response header on every authenticated call.\n2. On subsequent requests the SPA sends `Authorization: Bearer <jwt>`.\n3. The auth middleware's **fast-path** verifies the signature only — no DB query, no session lookup. `AppContext` is reconstructed from JWT claims.\n4. If verification fails (or no JWT is present), the middleware falls back to session auth.\n5. After successful session auth, a fresh JWT is minted and returned via `set-auth-token`. The cycle continues.\n\nThe fast-path is intentionally stateless: it trusts the claims for the full TTL. **Stolen or pre-revocation tokens are valid until they expire.** That's the trade-off the fast-path makes — and the reason `expiresIn` and `revocationCheck` are the two most-tuned knobs below: the first bounds the window, the second shrinks it to seconds.\n\n### `expiresIn?: number` — TTL in seconds\n\nDefault `180` (3 minutes).\n\nLowering this shrinks the worst-case window where a stolen / pre-revocation token still works. Browser SPAs auto-refresh via `set-auth-token` on every authed call, so a low TTL is invisible to logged-in users; only stale server-to-server bearer tokens feel it.\n\n```ts\nauth: { jwt: { expiresIn: 30 } } // 30s — tight post-revocation window\nauth: { jwt: { expiresIn: 3600 } } // 1h — longer-lived tokens for CLI / CI\n```\n\n### `issuer?: string` — `iss` claim\n\nDefault omitted.\n\nSet this when other services need to distinguish JWTs minted by this Worker from other issuers. The compiler bakes the issuer into both the mint side (added to claims) and the verify side (rejects tokens with mismatched `iss`).\n\n### `audience?: string` — `aud` claim\n\nDefault omitted.\n\nSet this when this Worker's JWTs are consumed by a sibling service that should reject tokens minted for a different audience. Same mint-and-verify treatment as `issuer`.\n\n### `secretEnv?: string` — signing secret env var\n\nDefault `'BETTER_AUTH_SECRET'`.\n\nOverride this if you want JWT signing isolated from the Better Auth secret (e.g. rotating one without invalidating the other).\n\n```ts\nauth: { jwt: { secretEnv: 'CUSTOM_JWT_SECRET' } }\n```\n\nThe compiler emits `c.env.CUSTOM_JWT_SECRET` (or `process.env.CUSTOM_JWT_SECRET` on Bun/Node) in the auth middleware's verify and mint sites and the `/api/v1/token` endpoint.\n\n> **Note:** the files-worker (separate Worker for R2 access) still reads `BETTER_AUTH_SECRET` directly. If you override `secretEnv`, set both env vars to the same value or the files worker's JWT verification will fall back to DB session lookup. Threading `secretEnv` through the files worker is on the roadmap.\n\n### `algorithm?: 'HS256'`\n\nOnly `HS256` is supported in 0.10.14. `RS256` (asymmetric, public-key verify / private-key sign) is on the roadmap.\n\n### `revocationCheck?: 'none' | 'kv'` — token revocation strategy\n\nDefault `'none'`.\n\n| Value | Behavior | Cost per verify |\n|---|---|---|\n| `'none'` | No revocation check. Stolen / pre-revocation tokens valid until TTL expires (scope claims: until the carry-forward cap). Use a low `expiresIn` to bound the replay window. | 0 |\n| `'kv'` | Fast-path checks per-principal revocation timestamps in the project's existing `KV` binding before trusting a verified token. | 2+ KV reads (~5-15ms, edge-cached) |\n\n`'kv'` (v0.45+, **Cloudflare runtime only**) keeps the fast-path stateless against the auth DB (still 0 D1 queries). There is nothing extra to provision — entries ride the `KV` binding every project already has, prefixed `qbrev:` and self-expiring after the maximum token lifetime, so the store never accumulates.\n\nA token is rejected when its mint timestamp (`iat`, or `sct` for the relationship-scope claim) predates the stored timestamp for any principal key it rides on:\n\n| Key | Revokes | Written automatically on |\n|---|---|---|\n| `qbrev:user:<userId>` | every JWT for the user | user ban (`databaseHooks.user.update.after` — flipping `banned` stamps the key and, when outbound webhooks are enabled, emits a `user.banned` event). Call `revokeUserTokens` for custom flows (revoke-all, etc.) |\n| `qbrev:member:<userId>:<orgId>` | the user's org-membership claims | member removal / role change (Better Auth `organizationHooks`) |\n| `qbrev:scope:<userId>:<kind>:<id>` | the user's carried scope claim | UPDATE/DELETE of a scope-conferring relationship row (audit-wrapper chokepoint + the single DELETE route) |\n\n`src/lib/jwt-revocation.ts` exports `revokeUserTokens` / `revokeMemberTokens` / `revokeScopeTokens` for explicit calls from actions. A rejected token falls through to session auth, which re-checks membership and re-mints — an active legitimate session recovers transparently.\n\nSemantics worth knowing:\n\n- **Revoke-on-touch for scopes:** any update or delete of a conferring row stamps the revocation, without evaluating whether the change actually ended the relationship. A false positive just forces a cheap re-prove (`/scope/v1/enter` or a minting namespace route).\n- **Fails open:** a missing binding or KV outage skips the check (logged) — revocation degrades to the TTL / carry-forward-cap bound rather than locking every bearer out.\n- **Eventual consistency:** KV propagates cross-PoP in ~60s. \"Immediate\" means seconds at the writing location, bounded-seconds globally — still far inside the 15-minute carry-forward cap that bounds revocation without this check.\n- **Coverage gap:** batch *hard* deletes don't return rows through the chokepoint; call `revokeScopeTokens` explicitly if you bulk-hard-delete conferring rows.\n\n## Defaults preserve 0.10.13 behavior\n\nAdding the `auth.jwt` block without setting any field is a no-op vs. the 0.10.13 baseline. Each missing field falls back to its hardcoded value:\n\n| Field | Default |\n|---|---|\n| `expiresIn` | 180 |\n| `issuer` | omitted |\n| `audience` | omitted |\n| `secretEnv` | `'BETTER_AUTH_SECRET'` |\n| `algorithm` | `'HS256'` |\n| `revocationCheck` | `'none'` |\n\n## Tuning recommendations\n\n- **B2C SaaS, mostly browser traffic:** keep defaults. The 180s TTL + auto-refresh model just works.\n- **Pentest engagement / enterprise compliance:** set `expiresIn: 30`. Tokens stay invisible to logged-in users (auto-refreshed every authed call) but stolen-token windows shrink to 30s.\n- **CLI-heavy / long-running CI tokens:** `expiresIn: 3600` for one-hour bearer tokens. Pair with `issuer` / `audience` if multiple services consume the same JWT.\n- **Need immediate revocation:** set `revocationCheck: 'kv'` (Cloudflare runtime) — revoked tokens are rejected within seconds, and stamps are written automatically on user ban, member removal, role change, and scope-conferring row changes (see the [scope revocation notes](/compiler/definitions/scopes#revocation--ttl)). Or drop TTL to ~30s — similar effect with bounded delay and zero KV reads.\n\n## `auth.loginUrl` / `auth.profileUrl` — external sign-in for consumer Workers\n\nWhen a Quickback Worker doesn't host its own Account SPA — e.g. an internal-app mesh where one Worker on the parent domain owns identity (`auth.example.com`) and other Workers share cookies — the compiler-emitted CMS access gates need to redirect unauthenticated visitors to the central sign-in surface, not the local `/account/login` (which doesn't exist there).\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // ...\n auth: {\n loginUrl: 'https://auth.example.com/login',\n profileUrl: 'https://auth.example.com/profile',\n },\n});\n```\n\nBoth fields override compiler-emitted browser redirects in the CMS shell:\n\n- **Unauthenticated visitor hits a CMS route** → `302 → <loginUrl>?redirect=<original-url>`\n- **Authenticated user fails the `cms.access: 'admin'` platform-role check** → `302 → <profileUrl>`\n\nThe `?redirect=…` query param is preserved unchanged so the central sign-in surface can bounce the user back after authentication.\n\n### Resolution precedence\n\nMost-specific wins:\n\n1. Explicit `auth.loginUrl` / `auth.profileUrl` — the cookie-trusting consumer-Worker case (this section).\n2. `https://<account.domain>/login` — inferred when this project hosts its own Account SPA on a custom domain.\n3. `/account/login` — built-in fallback, when neither knob is set.\n\n### Independent from `account.domain`\n\n`account.domain` does *two* things: redirect targets *and* hostname-based asset routing for an Account SPA hosted by this project. Consumer Workers don't host Account at all — they only need the URL. `auth.loginUrl` is a redirect-target string with no routing side effects, which is why it's a separate knob.\n\n### When both are set\n\nSetting `auth.loginUrl` *and* `account.domain` is legal — the explicit override beats the inferred URL at the redirect site, while `account.domain` still drives the local Account SPA's hostname routing as usual. Useful when you want to host Account on one custom domain (`account.foo.com`) but redirect *somewhere else* for sign-in (e.g. an SSO surface at `auth.foo.com`)."
47
47
  },
48
48
  "compiler/config/bindings": {
49
49
  "title": "Custom Bindings",
@@ -63,7 +63,7 @@ export const DOCS = {
63
63
  },
64
64
  "compiler/config/providers": {
65
65
  "title": "Providers",
66
- "content": "Providers configure which services your compiled backend targets.\n\n## Runtime Providers\n\nThe Quickback Stack is **Cloudflare-only**. `cloudflare` is the single supported runtime.\n\n```typescript\n\nproviders: {\n runtime: defineRuntime(\"cloudflare\"),\n}\n```\n\n### Runtime Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `compatibilityDate` | `string` | Emits Cloudflare `compatibility_date` in `wrangler.toml`. |\n| `placement.mode` | `\"smart\" \\| \"standard\"` | Emits Cloudflare's `[placement]` block. |\n| `observability.enabled` | `boolean` | Emits top-level Workers Logs persistence under `[observability]`. |\n| `observability.headSamplingRate` | `number` | Top-level Workers Logs sample rate from `0` to `1`. |\n| `observability.logs.enabled` | `boolean` | Emits `[observability.logs]`. |\n| `observability.logs.invocationLogs` | `boolean` | Enables or suppresses invocation logs. |\n| `observability.logs.destinations` | `string[]` | Named log export destinations configured in Cloudflare. |\n| `observability.logs.headSamplingRate` | `number` | Workers Logs sample rate from `0` to `1`. |\n| `observability.logs.persist` | `boolean` | Keeps exported logs in the Cloudflare dashboard. |\n| `observability.traces.enabled` | `boolean` | Emits `[observability.traces]`. |\n| `observability.traces.destinations` | `string[]` | Named trace export destinations configured in Cloudflare. |\n| `observability.traces.headSamplingRate` | `number` | Workers Traces sample rate from `0` to `1`. |\n| `observability.traces.persist` | `boolean` | Keeps exported traces in the Cloudflare dashboard. |\n| `routes` | `{ pattern, custom_domain? }[]` | Custom domain routes for the generated Worker. |\n\n```typescript\nproviders: {\n runtime: defineRuntime(\"cloudflare\", {\n compatibilityDate: \"2026-05-13\",\n placement: { mode: \"smart\" },\n observability: {\n enabled: true,\n logs: {\n enabled: true,\n invocationLogs: false,\n destinations: [\"logs-prod\"],\n headSamplingRate: 0.6,\n },\n traces: {\n enabled: true,\n destinations: [\"otel-prod\"],\n headSamplingRate: 0.05,\n persist: false,\n },\n },\n }),\n}\n```\n\n## Database Providers\n\nTwo databases are supported, both Cloudflare-native:\n\n| Provider | Description |\n|----------|-------------|\n| `cloudflare-d1` | Cloudflare D1 (SQLite at the edge) |\n| `neon` | Neon serverless PostgreSQL (`@neondatabase/serverless` over HTTP) |\n\nOne database provider per app: auth tables and feature tables always share the\nselected database. On `neon`, Better Auth uses its PostgreSQL/Drizzle adapter\nin the same Postgres database as your features; on `cloudflare-d1`, both use\nD1. A per-service map (`database: { auth: ..., features: ... }`) is rejected at\ncompile time — mixed database providers are not supported.\n\n```typescript\n\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n generateId: \"prefixed\", // \"uuid\" | \"cuid\" | \"nanoid\" | \"prefixed\" | \"serial\" | false\n namingConvention: \"snake_case\", // \"camelCase\" | \"snake_case\"\n usePlurals: false, // Auth table names: \"users\" vs \"user\"\n }),\n}\n```\n\n### Database Options\n\nOptions from `splitDatabases` down apply to `cloudflare-d1` only — Neon uses a\nsingle Postgres database with no bindings or split mode (see\n[Neon options](#neon-options) below).\n\n| Option | Type | Default (D1) | Description |\n|--------|------|---------|-------------|\n| `generateId` | `string \\| false` | `\"prefixed\"` | ID generation strategy |\n| `namingConvention` | `string` | `\"snake_case\"` | Column naming convention |\n| `usePlurals` | `boolean` | `false` | Pluralize auth table names (e.g. `user` vs `users`) |\n| `splitDatabases` | `boolean` | `true` | Separate auth and features databases (D1 only) |\n| `authBinding` | `string` | `\"AUTH_DB\"` | Binding name for auth database |\n| `featuresBinding` | `string` | `\"DB\"` | Binding name for features database |\n| `databaseId` | `string` | — | D1 database ID for the features database (used in generated wrangler.toml) |\n| `authDatabaseId` | `string` | — | D1 database ID for the auth database |\n| `featuresDatabaseId` | `string` | — | Explicit features DB ID (falls back to `databaseId`) |\n| `filesDatabaseId` | `string` | — | D1 database ID for the files metadata database |\n| `webhooksDatabaseId` | `string` | — | D1 database ID for the webhooks database |\n| `auditBinding` | `string` | `\"AUDIT_DB\"` | Binding name for the security audit database |\n| `auditDatabaseName` | `string` | `\"{app}-audit\"` | D1 database name for audit events |\n| `auditDatabaseId` | `string` | — | Explicit D1 database ID for audit events |\n| `experimentalRemote` | `{ auth?, features?, audit?, webhooks?, files? }` | `{}` | Per-binding `experimental_remote = true` flag for `wrangler dev` (see [below](#sharing-deployed-d1-in-dev-experimental_remote)) |\n| `realtime` | `boolean \\| { enabled?, wsTicket? }` | `false` | Enables the Broadcaster Durable Object and optional resource-scoped ws-ticket auth (see [below](#realtime-broadcast-config)) |\n| `webhookAdminRoles` | `string[]` | `[\"owner\", \"admin\"]` | Org roles allowed to manage webhook endpoints |\n\n#### Neon Options\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `connectionMode` | `\"auto\" \\| \"http\" \\| \"websocket\"` | `\"auto\"` | How the generated runtime connects (`auto` detects the runtime) |\n| `pooled` | `boolean` | `true` | Use the pooled Neon connection string (recommended for Workers) |\n\nThe Worker connects through a single `DATABASE_URL` secret — auth and feature\nqueries share it. See [Neon](/compiler/targets/hono-api/database/neon) for\nconnection modes, RLS, and the migration workflow.\n\n#### Audit Database\n\nCross-tenant `unsafe` actions (see [Actions → Unsafe mode](/compiler/definitions/actions#unsafe-mode)) write mandatory audit events. Those events land in a dedicated D1 database — separate from your features DB — so audit history stays isolated from application data and can't be tampered with through a normal CRUD route.\n\nYou don't need to do anything to enable it — the compiler wires up the binding automatically if your project declares any unsafe action. To override defaults:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n auditBinding: \"MY_AUDIT_DB\", // default: AUDIT_DB\n auditDatabaseName: \"my-app-audit-prod\", // default: {app}-audit\n auditDatabaseId: \"c3b8866b-cc4f-4e51-8382-0af244584d93\",\n }),\n}\n```\n\nThe binding name must match what your Worker reads at runtime. If you don't declare any unsafe actions, no audit DB is provisioned and these options have no effect.\n\n#### Setting Database IDs for Deployment\n\nWhen deploying to production, set your D1 database IDs so the compiler generates a ready-to-deploy `wrangler.toml`:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n authDatabaseId: \"fe6c77c4-2131-40be-a8fc-3649eef2a38c\",\n databaseId: \"bba22981-cb6e-43d6-bf32-4193513c60b1\",\n filesDatabaseId: \"c3b8866b-cc4f-4e51-8382-0af244584d93\",\n }),\n}\n```\n\nIf these are omitted, the compiler uses local-dev placeholders and you'll need to manually edit `wrangler.toml` before deploying.\n\n#### Sharing deployed D1 in dev (`experimental_remote`)\n\nWrangler can read or write the **deployed** D1 for a specific binding while `wrangler dev` runs locally. A common workflow: share the production auth DB in dev so real sessions and users work against the running local Worker, while feature writes stay sandboxed in the local SQLite shadow.\n\nQuickback regenerates `wrangler.toml` on every compile, so flags like `experimental_remote = true` need to live in `quickback.config.ts`:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n authDatabaseId: \"fe6c77c4-2131-40be-a8fc-3649eef2a38c\",\n experimentalRemote: { auth: true },\n }),\n}\n```\n\nKeys map to logical bindings, not the runtime binding string:\n\n| Key | Binding affected |\n|-----|------------------|\n| `auth` | `AUTH_DB` (also applied to the files worker's auth binding) |\n| `features` | `DB` (or the legacy single-DB binding when `splitDatabases: false`) |\n| `audit` | `AUDIT_DB` |\n| `webhooks` | `WEBHOOKS_DB` |\n| `files` | `FILES_DB` (also applied to the files worker) |\n\nOnly `true` flips the flag on; `false` or omitted leaves the binding local. Off by default — only enable against databases you intend to share.\n\n#### Realtime Broadcast Config\n\nSet `realtime: true` to enable the generated Broadcaster Durable Object with the default organization-scoped routing model:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: true,\n }),\n}\n```\n\nFor relationship-authorized resource scopes, use the object form:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: {\n wsTicket: {\n role: \"attendee\",\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n },\n }),\n}\n```\n\n`wsTicket` tells the compiler how to authorize `/broadcast/v1/ws-ticket` and what scope to stamp into the short-lived websocket ticket:\n\n- `role`: an authz role declared under `authz.roles` that uses a direct relationship (`{ via: \"...\" }`)\n- `requestField`: the JSON body field the client posts to `/broadcast/v1/ws-ticket`\n- `scopeTable`: the parent resource table that defines the broadcast scope key\n\nIn other words: the relationship table proves access, and the `scopeTable` row defines the channel. For an attendee flow, `guests` (or RSVP) would be the relationship evidence and `events` would be the `scopeTable`.\n\nQuickback keeps Better Auth as the front door, then mints its own 60-second websocket ticket after the authz check succeeds. The generated `createRealtime()` helper and Broadcaster share the same targeting model:\n\n- string target: historical `organizationId` shorthand\n- object target: `{ scopeKey?, organizationId?, userId? }`\n\nSee [Realtime](/stack/realtime) for the client-side connection flow and helper examples.\n\n### ID Generation Options\n\n| Value | Description | Example |\n|-------|-------------|---------|\n| `\"uuid\"` | Server generates UUID | `550e8400-e29b-41d4-a716-446655440000` |\n| `\"cuid\"` | Server generates CUID | `clh2v8k9g0000l508h5gx8j1a` |\n| `\"nanoid\"` | Server generates nanoid (21-char, URL-safe) | `V1StGXR8_Z5jdHi6B-myT` |\n| `\"short\"` | 6-char alphanumeric (nanoid `customAlphabet`) | `a3F9xK` |\n| `\"prefixed\"` | Prefixed ID from table name | `room_abc123` |\n| `\"serial\"` | Database auto-increments | `1`, `2`, `3` |\n| `false` | Client provides ID (enables PUT/upsert) | Any string |\n\n## Auth Providers\n\n| Provider | Description |\n|----------|-------------|\n| `better-auth` | Better Auth with plugins (default) |\n| `external` | External auth via Cloudflare service binding |\n\n```typescript\n\nproviders: {\n auth: defineAuth(\"better-auth\", {\n session: {\n expiresInDays: 7,\n updateAgeInDays: 1,\n },\n rateLimit: {\n enabled: true,\n window: 60,\n max: 100,\n },\n }),\n}\n```\n\n### Better Auth Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `session.expiresInDays` | `number` | Session expiration in days |\n| `session.updateAgeInDays` | `number` | Session refresh interval in days |\n| `rateLimit.enabled` | `boolean` | Enable rate limiting |\n| `rateLimit.window` | `number` | Rate limit window in seconds |\n| `rateLimit.max` | `number` | Max requests per window |\n| `socialProviders` | `object` | Social login providers (`google`, `github`, `discord`) |\n| `debugLogs` | `boolean` | Enable auth debug logging |\n\n### Better Auth Plugins\n\nWhen `features: [\"organizations\"]` is set in your config, the compiler automatically enables organization-related plugins. Additional plugins can be configured:\n\n| Plugin | Description |\n|--------|-------------|\n| `organization` | Multi-tenant organizations |\n| `admin` | Admin panel access |\n| `apiKey` | API key authentication |\n| `anonymous` | Anonymous sessions |\n| `upgradeAnonymous` | Convert anonymous to full accounts |\n| `twoFactor` | Two-factor authentication |\n| `passkey` | WebAuthn passkey login |\n| `magicLink` | Email magic link login |\n| `emailOtp` | Email one-time password |\n| `deviceAuthorization` | Device auth flow (CLI tools) |\n| `jwt` | JWT token support |\n| `openAPI` | OpenAPI spec generation |\n\n## Storage Providers\n\n```typescript\n\nproviders: {\n storage: defineStorage(\"kv\", {\n binding: \"KV_STORE\",\n namespaceId: \"7ed0f824a8c54c388713d9fdf63cd004\",\n }),\n fileStorage: defineFileStorage(\"r2\", {\n binding: \"FILES\",\n maxFileSize: \"10mb\",\n allowedTypes: [\"image/png\", \"image/jpeg\", \"application/pdf\"],\n publicDomain: \"files.example.com\",\n }),\n}\n```\n\n### Storage Types\n\n| Type | Description |\n|------|-------------|\n| `kv` | Key-value storage (Cloudflare KV, Redis) |\n| `r2` | Object storage (Cloudflare R2) |\n| `memory` | In-memory storage (development only) |\n| `redis` | Redis storage |\n\n### File Storage Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `binding` | `string` | R2 bucket binding name |\n| `maxFileSize` | `string` | Maximum file size (e.g. `\"10mb\"`) |\n| `allowedTypes` | `string[]` | Allowed MIME types |\n| `publicDomain` | `string` | Public domain for file URLs |\n| `userScopedBuckets` | `boolean` | Scope files by user |"
66
+ "content": "Providers configure which services your compiled backend targets.\n\n## Runtime Providers\n\nThe Quickback Stack is **Cloudflare-only**. `cloudflare` is the single supported runtime.\n\n```typescript\n\nproviders: {\n runtime: defineRuntime(\"cloudflare\"),\n}\n```\n\n### Runtime Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `compatibilityDate` | `string` | Emits Cloudflare `compatibility_date` in `wrangler.toml`. |\n| `placement.mode` | `\"smart\" \\| \"standard\"` | Emits Cloudflare's `[placement]` block. |\n| `observability.enabled` | `boolean` | Emits top-level Workers Logs persistence under `[observability]`. |\n| `observability.headSamplingRate` | `number` | Top-level Workers Logs sample rate from `0` to `1`. |\n| `observability.logs.enabled` | `boolean` | Emits `[observability.logs]`. |\n| `observability.logs.invocationLogs` | `boolean` | Enables or suppresses invocation logs. |\n| `observability.logs.destinations` | `string[]` | Named log export destinations configured in Cloudflare. |\n| `observability.logs.headSamplingRate` | `number` | Workers Logs sample rate from `0` to `1`. |\n| `observability.logs.persist` | `boolean` | Keeps exported logs in the Cloudflare dashboard. |\n| `observability.traces.enabled` | `boolean` | Emits `[observability.traces]`. |\n| `observability.traces.destinations` | `string[]` | Named trace export destinations configured in Cloudflare. |\n| `observability.traces.headSamplingRate` | `number` | Workers Traces sample rate from `0` to `1`. |\n| `observability.traces.persist` | `boolean` | Keeps exported traces in the Cloudflare dashboard. |\n| `routes` | `{ pattern, custom_domain? }[]` | Custom domain routes for the generated Worker. |\n\n```typescript\nproviders: {\n runtime: defineRuntime(\"cloudflare\", {\n compatibilityDate: \"2026-05-13\",\n placement: { mode: \"smart\" },\n observability: {\n enabled: true,\n logs: {\n enabled: true,\n invocationLogs: false,\n destinations: [\"logs-prod\"],\n headSamplingRate: 0.6,\n },\n traces: {\n enabled: true,\n destinations: [\"otel-prod\"],\n headSamplingRate: 0.05,\n persist: false,\n },\n },\n }),\n}\n```\n\n## Database Providers\n\nTwo databases are supported, both Cloudflare-native:\n\n| Provider | Description |\n|----------|-------------|\n| `cloudflare-d1` | Cloudflare D1 (SQLite at the edge) |\n| `neon` | Neon serverless PostgreSQL (`@neondatabase/serverless` over HTTP) |\n\nOne database provider per app: auth tables and feature tables always share the\nselected database. On `neon`, Better Auth uses its PostgreSQL/Drizzle adapter\nin the same Postgres database as your features; on `cloudflare-d1`, both use\nD1. A per-service map (`database: { auth: ..., features: ... }`) is rejected at\ncompile time — mixed database providers are not supported.\n\n```typescript\n\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n generateId: \"prefixed\", // \"uuid\" | \"cuid\" | \"nanoid\" | \"prefixed\" | \"serial\" | false\n namingConvention: \"snake_case\", // \"camelCase\" | \"snake_case\"\n usePlurals: false, // Auth table names: \"users\" vs \"user\"\n }),\n}\n```\n\n### Database Options\n\nOptions from `splitDatabases` down apply to `cloudflare-d1` only — Neon uses a\nsingle Postgres database with no bindings or split mode (see\n[Neon options](#neon-options) below).\n\n| Option | Type | Default (D1) | Description |\n|--------|------|---------|-------------|\n| `generateId` | `string \\| false` | `\"prefixed\"` | ID generation strategy |\n| `namingConvention` | `string` | `\"snake_case\"` | Column naming convention |\n| `usePlurals` | `boolean` | `false` | Pluralize auth table names (e.g. `user` vs `users`) |\n| `splitDatabases` | `boolean` | `true` | Separate auth and features databases (D1 only) |\n| `authBinding` | `string` | `\"AUTH_DB\"` | Binding name for auth database |\n| `featuresBinding` | `string` | `\"DB\"` | Binding name for features database |\n| `databaseId` | `string` | — | D1 database ID for the features database (used in generated wrangler.toml) |\n| `authDatabaseId` | `string` | — | D1 database ID for the auth database |\n| `featuresDatabaseId` | `string` | — | Explicit features DB ID (falls back to `databaseId`) |\n| `filesDatabaseId` | `string` | — | D1 database ID for the files metadata database |\n| `webhooksDatabaseId` | `string` | — | D1 database ID for the webhooks database |\n| `auditBinding` | `string` | `\"AUDIT_DB\"` | Binding name for the security audit database |\n| `auditDatabaseName` | `string` | `\"{app}-audit\"` | D1 database name for audit events |\n| `auditDatabaseId` | `string` | — | Explicit D1 database ID for audit events |\n| `experimentalRemote` | `{ auth?, features?, audit?, webhooks?, files? }` | `{}` | Per-binding `experimental_remote = true` flag for `wrangler dev` (see [below](#sharing-deployed-d1-in-dev-experimental_remote)) |\n| `realtime` | `boolean \\| { enabled?, wsTicket? }` | `false` | Enables the Broadcaster Durable Object and optional resource-scoped ws-ticket auth (see [below](#realtime-broadcast-config)) |\n| `webhookAdminRoles` | `string[]` | `[\"owner\", \"admin\"]` | Org roles allowed to manage webhook endpoints |\n\n#### Neon Options\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `connectionMode` | `\"auto\" \\| \"http\" \\| \"websocket\"` | `\"auto\"` | How the generated runtime connects (`auto` detects the runtime) |\n| `pooled` | `boolean` | `true` | Use the pooled Neon connection string (recommended for Workers) |\n\nThe Worker connects through a single `DATABASE_URL` secret — auth and feature\nqueries share it. See [Neon](/compiler/targets/hono-api/database/neon) for\nconnection modes, RLS, and the migration workflow.\n\n#### Audit Database\n\nCross-tenant `unsafe` actions (see [Actions → Unsafe mode](/compiler/definitions/actions#unsafe-mode)) write mandatory audit events. Those events land in a dedicated D1 database — separate from your features DB — so audit history stays isolated from application data and can't be tampered with through a normal CRUD route.\n\nYou don't need to do anything to enable it — the compiler wires up the binding automatically if your project declares any unsafe action. To override defaults:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n auditBinding: \"MY_AUDIT_DB\", // default: AUDIT_DB\n auditDatabaseName: \"my-app-audit-prod\", // default: {app}-audit\n auditDatabaseId: \"c3b8866b-cc4f-4e51-8382-0af244584d93\",\n }),\n}\n```\n\nThe binding name must match what your Worker reads at runtime. If you don't declare any unsafe actions, no audit DB is provisioned and these options have no effect.\n\n#### Setting Database IDs for Deployment\n\nWhen deploying to production, set your D1 database IDs so the compiler generates a ready-to-deploy `wrangler.toml`:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n authDatabaseId: \"fe6c77c4-2131-40be-a8fc-3649eef2a38c\",\n databaseId: \"bba22981-cb6e-43d6-bf32-4193513c60b1\",\n filesDatabaseId: \"c3b8866b-cc4f-4e51-8382-0af244584d93\",\n }),\n}\n```\n\nIf these are omitted, the compiler uses local-dev placeholders and you'll need to manually edit `wrangler.toml` before deploying.\n\n#### Sharing deployed D1 in dev (`experimental_remote`)\n\nWrangler can read or write the **deployed** D1 for a specific binding while `wrangler dev` runs locally. A common workflow: share the production auth DB in dev so real sessions and users work against the running local Worker, while feature writes stay sandboxed in the local SQLite shadow.\n\nQuickback regenerates `wrangler.toml` on every compile, so flags like `experimental_remote = true` need to live in `quickback.config.ts`:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n authDatabaseId: \"fe6c77c4-2131-40be-a8fc-3649eef2a38c\",\n experimentalRemote: { auth: true },\n }),\n}\n```\n\nKeys map to logical bindings, not the runtime binding string:\n\n| Key | Binding affected |\n|-----|------------------|\n| `auth` | `AUTH_DB` (also applied to the files worker's auth binding) |\n| `features` | `DB` (or the legacy single-DB binding when `splitDatabases: false`) |\n| `audit` | `AUDIT_DB` |\n| `webhooks` | `WEBHOOKS_DB` |\n| `files` | `FILES_DB` (also applied to the files worker) |\n\nOnly `true` flips the flag on; `false` or omitted leaves the binding local. Off by default — only enable against databases you intend to share.\n\n#### Realtime Broadcast Config\n\nSet `realtime: true` to enable the generated Broadcaster Durable Object with the default organization-scoped routing model:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: true,\n }),\n}\n```\n\nFor resource-scoped tickets, use the object form. The mint gate is a discriminated `access` union — exactly one arm:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: {\n wsTicket: {\n access: { authzRole: \"attendee\" }, // or { roles: [\"member+\"] } or { fga: { relation, object } }\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n },\n }),\n}\n```\n\n`wsTicket` tells the compiler how to authorize `/broadcast/v1/ws-ticket` and what scope to stamp into the short-lived websocket ticket:\n\n- `access`: the mint gate — one of `{ roles: [\"member+\"] }` (org-membership roles with hierarchy expansion; also verifies the scope row is in the caller's active org), `{ authzRole: \"attendee\" }` (an authz role declared under `authz.roles` with a direct relationship `{ via: \"...\" }`), or `{ fga: { relation: \"viewer\", object: \"event:{id}\" } }` (an FGA relation on the object derived from the scope row). The legacy `role: \"attendee\"` string is the shorthand for `{ authzRole }`.\n- `requestField`: the JSON body field the client posts to `/broadcast/v1/ws-ticket`\n- `scopeTable`: the parent resource table that defines the broadcast scope key\n\nIn other words: the declared gate proves access, and the `scopeTable` row defines the channel. For an attendee flow, `guests` (or RSVP) would be the relationship evidence and `events` would be the `scopeTable`; see [Realtime](/stack/realtime#enabling-realtime) for the full per-arm semantics.\n\nQuickback keeps Better Auth as the front door, then mints its own 60-second websocket ticket after the authz check succeeds. The generated `createRealtime()` helper and Broadcaster share the same targeting model:\n\n- string target: historical `organizationId` shorthand\n- object target: `{ scopeKey?, organizationId?, userId? }`\n\nSee [Realtime](/stack/realtime) for the client-side connection flow and helper examples.\n\n### ID Generation Options\n\n| Value | Description | Example |\n|-------|-------------|---------|\n| `\"uuid\"` | Server generates UUID | `550e8400-e29b-41d4-a716-446655440000` |\n| `\"cuid\"` | Server generates CUID | `clh2v8k9g0000l508h5gx8j1a` |\n| `\"nanoid\"` | Server generates nanoid (21-char, URL-safe) | `V1StGXR8_Z5jdHi6B-myT` |\n| `\"short\"` | 6-char alphanumeric (nanoid `customAlphabet`) | `a3F9xK` |\n| `\"prefixed\"` | Prefixed ID from table name | `room_abc123` |\n| `\"serial\"` | Database auto-increments | `1`, `2`, `3` |\n| `false` | Client provides ID (enables PUT/upsert) | Any string |\n\n## Auth Providers\n\n| Provider | Description |\n|----------|-------------|\n| `better-auth` | Better Auth with plugins (default) |\n| `external` | External auth via Cloudflare service binding |\n\n```typescript\n\nproviders: {\n auth: defineAuth(\"better-auth\", {\n session: {\n expiresInDays: 7,\n updateAgeInDays: 1,\n },\n rateLimit: {\n enabled: true,\n window: 60,\n max: 100,\n },\n }),\n}\n```\n\n### Better Auth Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `session.expiresInDays` | `number` | Session expiration in days |\n| `session.updateAgeInDays` | `number` | Session refresh interval in days |\n| `rateLimit.enabled` | `boolean` | Enable rate limiting |\n| `rateLimit.window` | `number` | Rate limit window in seconds |\n| `rateLimit.max` | `number` | Max requests per window |\n| `socialProviders` | `object` | Social login providers (`google`, `github`, `discord`) |\n| `debugLogs` | `boolean` | Enable auth debug logging |\n\n### Better Auth Plugins\n\nWhen `features: [\"organizations\"]` is set in your config, the compiler automatically enables organization-related plugins. Additional plugins can be configured:\n\n| Plugin | Description |\n|--------|-------------|\n| `organization` | Multi-tenant organizations |\n| `admin` | Admin panel access |\n| `apiKey` | API key authentication |\n| `anonymous` | Anonymous sessions |\n| `upgradeAnonymous` | Convert anonymous to full accounts |\n| `twoFactor` | Two-factor authentication |\n| `passkey` | WebAuthn passkey login |\n| `magicLink` | Email magic link login |\n| `emailOtp` | Email one-time password |\n| `deviceAuthorization` | Device auth flow (CLI tools) |\n| `jwt` | JWT token support |\n| `openAPI` | OpenAPI spec generation |\n\n## Storage Providers\n\n```typescript\n\nproviders: {\n storage: defineStorage(\"kv\", {\n binding: \"KV_STORE\",\n namespaceId: \"7ed0f824a8c54c388713d9fdf63cd004\",\n }),\n fileStorage: defineFileStorage(\"r2\", {\n binding: \"FILES\",\n maxFileSize: \"10mb\",\n allowedTypes: [\"image/png\", \"image/jpeg\", \"application/pdf\"],\n publicDomain: \"files.example.com\",\n }),\n}\n```\n\n### Storage Types\n\n| Type | Description |\n|------|-------------|\n| `kv` | Key-value storage (Cloudflare KV, Redis) |\n| `r2` | Object storage (Cloudflare R2) |\n| `memory` | In-memory storage (development only) |\n| `redis` | Redis storage |\n\n### File Storage Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `binding` | `string` | R2 bucket binding name |\n| `maxFileSize` | `string` | Maximum file size (e.g. `\"10mb\"`) |\n| `allowedTypes` | `string[]` | Allowed MIME types |\n| `publicDomain` | `string` | Public domain for file URLs |\n| `userScopedBuckets` | `boolean` | Scope files by user |"
67
67
  },
68
68
  "compiler/config/security": {
69
69
  "title": "Security Headers",
@@ -131,7 +131,7 @@ export const DOCS = {
131
131
  },
132
132
  "compiler/definitions/rate-limit": {
133
133
  "title": "Rate Limit - Per-Operation Request Caps",
134
- "content": "Per-operation request caps for every CRUD endpoint. Backed by Cloudflare's native [Rate Limiting binding](https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/) — no extra storage, no third-party libraries.\n\n## Defaults\n\nEvery resource gets these limits automatically (per authenticated user, per minute):\n\n| Operation | Default |\n|-----------|---------|\n| `read` | 1000 / 60s |\n| `create` | 200 / 60s |\n| `update` | 200 / 60s |\n| `delete` | 200 / 60s |\n\nNumbers are loose enough that no legitimate user-driven traffic hits them, but tight enough to catch a runaway script before it burns the day's D1 budget. Override per-op or opt out wherever the defaults don't fit.\n\n## Override one operation\n\n```typescript\n// features/claims/claims.ts\nexport default defineTable(claims, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n rateLimit: {\n delete: { limit: 5, period: 60 }, // tighter than the 200/60s default\n },\n // read / create / update keep shipped defaults\n});\n```\n\n## Disable rate-limiting on a resource\n\n```typescript\n// features/telemetry/events.ts\nexport default defineTable(telemetryEvents, {\n rateLimit: false, // high-volume sink, skip enforcement\n});\n```\n\n## Project-wide overrides\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n // ...\n rateLimit: {\n read: { limit: 500, period: 60 }, // tighter project-wide read default\n },\n});\n```\n\n## Disable globally\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n // ...\n rateLimit: false, // e.g. when behind a WAF that handles request shaping\n});\n```\n\n## Configuration shape\n\n```typescript\nrateLimit?: {\n read?: { limit: number, period: 10 | 60 };\n create?: { limit: number, period: 10 | 60 };\n update?: { limit: number, period: 10 | 60 };\n delete?: { limit: number, period: 10 | 60 };\n} | false\n```\n\n- `period` must be `10` or `60` (Cloudflare binding constraint — anything else is a compile-time error).\n- `limit` is a positive integer.\n- Omit an op to inherit the project default (or shipped default).\n- Set `false` at resource or project level to opt out.\n\n## Resolution order\n\n1. Project `rateLimit: false` → no enforcement anywhere\n2. Resource `rateLimit: false` → no enforcement on this resource\n3. Resource per-op override\n4. Project per-op default\n5. Quickback shipped defaults (1000 / 200 above)\n\nDefault-using resources collapse onto two shared bindings (`RL_1000_60`, `RL_200_60`), so a project that never declares `rateLimit` still ships exactly two rate-limit bindings — not one per resource.\n\n## How requests are keyed\n\nEach handler composes a key as `<resource>:<op>:<userId>`. For routes that opt into PUBLIC access (no `userId`), the key falls back to the client's `cf-connecting-ip` header, then to the literal `'anon'` if that header is absent too.\n\nThis means:\n\n- A single user is rate-limited per resource per op — heavy `read` traffic on `claims` doesn't slow their `update` traffic on `applications`.\n- One noisy user can't starve another — keys are scoped by `userId`.\n- Anonymous traffic hitting PUBLIC routes is keyed by IP, which works behind a CDN but is trivially bypassed by a botnet — pair PUBLIC routes with auth-required mutations or a Cloudflare WAF rule for hostile traffic.\n\n## How limits compile\n\nThe compiler walks every resource, collects unique `(limit, period)` tuples, and emits one Cloudflare binding per tuple to `wrangler.toml`:\n\n```toml\n[[unsafe.bindings]]\nname = \"RL_1000_60\"\ntype = \"ratelimit\"\nnamespace_id = \"60001000\"\nsimple = { limit = 1000, period = 60 }\n\n[[unsafe.bindings]]\nname = \"RL_200_60\"\ntype = \"ratelimit\"\nnamespace_id = \"60000200\"\nsimple = { limit = 200, period = 60 }\n```\n\nEach generated CRUD handler invokes `c.env.RL_<L>_<P>.limit({ key })` between the auth gate and the access check. Hitting the limit returns:\n\n```http\nHTTP/1.1 429 Too Many Requests\nRetry-After: 60\nContent-Type: application/json\n\n{ \"error\": \"Rate limit exceeded\", \"code\": \"RATE_LIMITED\", \"retryAfter\": 60 }\n```\n\n## Batch endpoints\n\nBatch routes (`POST /batch`, `PATCH /batch`, `DELETE /batch`, `PUT /batch`) count as **a single request** against their op's limit, not N. A batch of 100 records consumes one token, not one hundred. This matches how most rate-limit configurations are actually written (caps on request volume, not row volume).\n\n## Actions\n\nCustom actions (record-based and standalone) inherit rate limits without configuration:\n\n- **Record-based actions** (e.g. `POST /api/v1/claims/:id/approve`) inherit the resource's `update` (write) bucket. A user who hits the write limit on `claims` is also blocked from `approve`.\n- **Standalone actions** (e.g. `POST /api/v1/twilioIncoming`) inherit the project-default `update` bucket — they don't belong to a resource.\n\nOverride either with the action's `rateLimit` field:\n\n```typescript\n// features/claims/actions/approve.ts\nexport default defineAction({\n description: 'Approve a claim',\n input: z.object({ claimId: z.string() }),\n access: { roles: ['admin'] },\n rateLimit: { limit: 5, period: 60 }, // tighter than resource update bucket\n execute: async ({ db, input }) => { /* ... */ },\n});\n```\n\n```typescript\n// features/integrations/actions/twilioIncoming.ts\nexport default defineAction({\n description: 'Webhook from Twilio',\n path: '/twilioIncoming',\n method: 'POST',\n input: z.object({ /* ... */ }),\n access: { roles: ['PUBLIC'] },\n rateLimit: { limit: 1000, period: 10 }, // tolerate burst from Twilio\n execute: async ({ input }) => { /* ... */ },\n});\n```\n\nSet `rateLimit: false` to opt the action out of enforcement entirely.\n\n**Key composition** — actions get their own keyspace so a generic resource bucket and an action's bucket never share counters:\n\n| Action kind | Key shape |\n|-------------|-----------|\n| Record-based | `<resource>:action:<actionName>:<userId\\|cf-connecting-ip\\|anon>` |\n| Standalone | `standalone:<path>:<userId\\|cf-connecting-ip\\|anon>` |\n\nThe `:action:` infix is what keeps `update` (resource bucket) and `approve` (action bucket) from sharing counters when they happen to land on the same binding name.\n\n## Cardinality — how many bindings ship\n\nCloudflare bindings are sized at compile time (limit + period are baked in), so the compiler emits one binding per **unique `(limit, period)` tuple**, not one per resource. A project of 50 resources that all use the defaults still ships exactly two rate-limit bindings.\n\n| Configuration | Bindings emitted |\n|---------------|------------------|\n| All defaults | 2 (`RL_1000_60` for reads, `RL_200_60` for writes) |\n| One project-wide read override (`read: { limit: 500, period: 60 }`) | 3 (`RL_500_60`, `RL_1000_60` ← only if some resource opts back into the default, `RL_200_60`) |\n| Five resources tightening `delete` to `{ limit: 5, period: 60 }` | 3 (defaults + `RL_5_60` shared) |\n| Ten distinct per-action overrides at unique tuples | 12 (defaults + ten action buckets) |\n\n**Practical caps.** Cloudflare workers have generous binding limits (hundreds), so this is unlikely to be a real ceiling — but it's the reason every distinct `(limit, period)` you write on a `rateLimit` config widens the binding set, even when the same resource declares the same tuple multiple times. Resource-level configs that share a tuple share a binding and simply produce different runtime keys.\n\n**Key cardinality is separate.** Each binding holds an independent counter per key. A binding called via `claims:read:user_123` and `applications:read:user_123` consumes two separate counters in the same binding — fan-out cost lives in Cloudflare's distributed counter store, not in your binding count. The user-perceivable limit is \"per (resource, op, user)\", regardless of how many resources share the binding.\n\n## Runtime support\n\n| Runtime | Rate limiting |\n|---------|---------------|\n| `cloudflare` | Backed by Cloudflare's native [Rate Limiting binding](https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/) |\n| `bun` | In-process fixed-window counter (`src/lib/rate-limit-memory.ts`). Same generated check code, same 429 response — single-instance only |\n\nOn Bun, the compiler emits `src/lib/rate-limit-memory.ts` and wires up a per-binding shim in the server's fetch handler. Each `RL_<limit>_<period>` shim delegates to a process-memory token bucket, so the same `c.env.RL_*.limit({ key })` call site that targets the Cloudflare binding works unchanged.\n\n**Multi-instance Bun deployments** need either a load balancer with sticky sessions (so the same user keeps hitting the same instance and its bucket) or the Cloudflare runtime (which has cross-instance counters out of the box). The in-memory shim does not coordinate across processes.\n\n## Compile-time validation\n\nThe compiler errors on:\n\n1. `period` other than `10` or `60`\n2. Non-integer or non-positive `limit`\n3. Unknown ops (e.g. `list` instead of `read`)\n\n## Disabling vs. tightening — when to use which\n\n| Goal | Configuration |\n|------|---------------|\n| One op needs a tighter cap (e.g. `delete`) | Resource override on that op only |\n| One op needs a looser cap (high-volume reads) | Resource override raising the limit |\n| One resource is a high-volume sink | `rateLimit: false` on the resource |\n| Whole project is behind a WAF | `rateLimit: false` at project level |\n| App-wide tighter default (e.g. expensive reads) | Project-level override of that op |"
134
+ "content": "Per-operation request caps for every CRUD endpoint. Backed by Cloudflare's native [Rate Limiting binding](https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/) — no extra storage, no third-party libraries.\n\n## Defaults\n\nEvery resource gets these limits automatically (per authenticated user, per minute):\n\n| Operation | Default |\n|-----------|---------|\n| `read` | 1000 / 60s |\n| `create` | 200 / 60s |\n| `update` | 200 / 60s |\n| `delete` | 200 / 60s |\n\nNumbers are loose enough that no legitimate user-driven traffic hits them, but tight enough to catch a runaway script before it burns the day's D1 budget. Override per-op or opt out wherever the defaults don't fit.\n\n## Override one operation\n\n```typescript\n// features/claims/claims.ts\nexport default defineTable(claims, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n rateLimit: {\n delete: { limit: 5, period: 60 }, // tighter than the 200/60s default\n },\n // read / create / update keep shipped defaults\n});\n```\n\n## Disable rate-limiting on a resource\n\n```typescript\n// features/telemetry/events.ts\nexport default defineTable(telemetryEvents, {\n rateLimit: false, // high-volume sink, skip enforcement\n});\n```\n\n## Project-wide overrides\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n // ...\n rateLimit: {\n read: { limit: 500, period: 60 }, // tighter project-wide read default\n },\n});\n```\n\n## Disable globally\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n // ...\n rateLimit: false, // e.g. when behind a WAF that handles request shaping\n});\n```\n\n## Configuration shape\n\n```typescript\nrateLimit?: {\n read?: { limit: number, period: 10 | 60 };\n create?: { limit: number, period: 10 | 60 };\n update?: { limit: number, period: 10 | 60 };\n delete?: { limit: number, period: 10 | 60 };\n} | false\n```\n\n- `period` must be `10` or `60` (Cloudflare binding constraint — anything else is a compile-time error).\n- `limit` is a positive integer.\n- Omit an op to inherit the project default (or shipped default).\n- Set `false` at resource or project level to opt out.\n\n## Resolution order\n\n1. Project `rateLimit: false` → no enforcement anywhere\n2. Resource `rateLimit: false` → no enforcement on this resource\n3. Resource per-op override\n4. Project per-op default\n5. Quickback shipped defaults (1000 / 200 above)\n\nDefault-using resources collapse onto two shared bindings (`RL_1000_60`, `RL_200_60`), so a project that never declares `rateLimit` still ships exactly two rate-limit bindings — not one per resource.\n\n## How requests are keyed\n\nEach handler composes a key as `<resource>:<op>:<userId>`. For routes that opt into PUBLIC access (no `userId`), the key falls back to the client's `cf-connecting-ip` header, then to the literal `'anon'` if that header is absent too.\n\nThis means:\n\n- A single user is rate-limited per resource per op — heavy `read` traffic on `claims` doesn't slow their `update` traffic on `applications`.\n- One noisy user can't starve another — keys are scoped by `userId`.\n- Anonymous traffic hitting PUBLIC routes is keyed by IP, which works behind a CDN but is trivially bypassed by a botnet — pair PUBLIC routes with auth-required mutations or a Cloudflare WAF rule for hostile traffic.\n\n## How limits compile\n\nThe compiler walks every resource, collects unique `(limit, period)` tuples, and emits one Cloudflare binding per tuple to `wrangler.toml`:\n\n```toml\n[[ratelimits]]\nname = \"RL_1000_60\"\nnamespace_id = \"60002000\"\nsimple = { limit = 1000, period = 60 }\n\n[[ratelimits]]\nname = \"RL_200_60\"\nnamespace_id = \"60001200\"\nsimple = { limit = 200, period = 60 }\n```\n\n`namespace_id` is a stable per-tuple integer (`1000 + period * 1_000_000 + limit`), so it survives resource reordering and never drifts across recompiles.\n\nEach generated CRUD handler invokes `c.env.RL_<L>_<P>.limit({ key })` between the auth gate and the access check. Hitting the limit returns:\n\n```http\nHTTP/1.1 429 Too Many Requests\nRetry-After: 60\nContent-Type: application/json\n\n{ \"error\": \"Rate limit exceeded\", \"code\": \"RATE_LIMITED\", \"retryAfter\": 60 }\n```\n\n## Batch endpoints\n\nBatch routes (`POST /batch`, `PATCH /batch`, `DELETE /batch`, `PUT /batch`) count as **a single request** against their op's limit, not N. A batch of 100 records consumes one token, not one hundred. This matches how most rate-limit configurations are actually written (caps on request volume, not row volume).\n\n## Actions\n\nCustom actions (record-based and standalone) inherit rate limits without configuration:\n\n- **Record-based actions** (e.g. `POST /api/v1/claims/:id/approve`) inherit the resource's `update` (write) bucket. A user who hits the write limit on `claims` is also blocked from `approve`.\n- **Standalone actions** (e.g. `POST /api/v1/twilioIncoming`) inherit the project-default `update` bucket — they don't belong to a resource.\n\nOverride either with the action's `rateLimit` field:\n\n```typescript\n// features/claims/actions/approve.ts\nexport default defineAction({\n description: 'Approve a claim',\n input: z.object({ claimId: z.string() }),\n access: { roles: ['admin'] },\n rateLimit: { limit: 5, period: 60 }, // tighter than resource update bucket\n execute: async ({ db, input }) => { /* ... */ },\n});\n```\n\n```typescript\n// features/integrations/actions/twilioIncoming.ts\nexport default defineAction({\n description: 'Webhook from Twilio',\n path: '/twilioIncoming',\n method: 'POST',\n input: z.object({ /* ... */ }),\n access: { roles: ['PUBLIC'] },\n rateLimit: { limit: 1000, period: 10 }, // tolerate burst from Twilio\n execute: async ({ input }) => { /* ... */ },\n});\n```\n\nSet `rateLimit: false` to opt the action out of enforcement entirely.\n\n**Key composition** — actions get their own keyspace so a generic resource bucket and an action's bucket never share counters:\n\n| Action kind | Key shape |\n|-------------|-----------|\n| Record-based | `<resource>:action:<actionName>:<userId\\|cf-connecting-ip\\|anon>` |\n| Standalone | `standalone:<path>:<userId\\|cf-connecting-ip\\|anon>` |\n\nThe `:action:` infix is what keeps `update` (resource bucket) and `approve` (action bucket) from sharing counters when they happen to land on the same binding name.\n\nA record action's bulk variant (`POST /<resource>/batch/<action>`) shares its single-record sibling's key exactly, so a batch of N records consumes **one** token from the action's bucket per request — not N.\n\n## Cardinality — how many bindings ship\n\nCloudflare bindings are sized at compile time (limit + period are baked in), so the compiler emits one binding per **unique `(limit, period)` tuple**, not one per resource. A project of 50 resources that all use the defaults still ships exactly two rate-limit bindings.\n\n| Configuration | Bindings emitted |\n|---------------|------------------|\n| All defaults | 2 (`RL_1000_60` for reads, `RL_200_60` for writes) |\n| One project-wide read override (`read: { limit: 500, period: 60 }`) | 3 (`RL_500_60`, `RL_1000_60` ← only if some resource opts back into the default, `RL_200_60`) |\n| Five resources tightening `delete` to `{ limit: 5, period: 60 }` | 3 (defaults + `RL_5_60` shared) |\n| Ten distinct per-action overrides at unique tuples | 12 (defaults + ten action buckets) |\n\n**Practical caps.** Cloudflare workers have generous binding limits (hundreds), so this is unlikely to be a real ceiling — but it's the reason every distinct `(limit, period)` you write on a `rateLimit` config widens the binding set, even when the same resource declares the same tuple multiple times. Resource-level configs that share a tuple share a binding and simply produce different runtime keys.\n\n**Key cardinality is separate.** Each binding holds an independent counter per key. A binding called via `claims:read:user_123` and `applications:read:user_123` consumes two separate counters in the same binding — fan-out cost lives in Cloudflare's distributed counter store, not in your binding count. The user-perceivable limit is \"per (resource, op, user)\", regardless of how many resources share the binding.\n\n## Runtime support\n\n| Runtime | Rate limiting |\n|---------|---------------|\n| `cloudflare` | Backed by Cloudflare's native [Rate Limiting binding](https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/) |\n| non-Cloudflare (`bun`, `node`) | Degrades safely — the check no-ops when the binding is absent from `c.env` |\n\nEvery generated rate-limit call site — CRUD middleware and custom actions alike — first looks up `c.env.RL_<limit>_<period>` and only calls `.limit({ key })` when the binding is present. On the Cloudflare runtime it always is. On other runtimes it isn't, so the check no-ops and the request proceeds — generated code never hard-depends on the binding.\n\n**Roadmap — Bun in-process shim.** An in-memory fixed-window shim (`src/lib/rate-limit-memory.ts`) that backs the same `c.env.RL_*.limit({ key })` call site with a process-memory token bucket is planned but **not yet emitted**. Until it lands, non-Cloudflare deployments that need enforcement should sit behind a Cloudflare WAF rule or an upstream rate limiter. A multi-instance Bun shim would additionally need sticky sessions (same user → same instance → same bucket), since a process-memory counter can't coordinate across processes.\n\n## Compile-time validation\n\nThe compiler errors on:\n\n1. `period` other than `10` or `60`\n2. Non-integer or non-positive `limit`\n3. Unknown ops (e.g. `list` instead of `read`)\n\n## Disabling vs. tightening — when to use which\n\n| Goal | Configuration |\n|------|---------------|\n| One op needs a tighter cap (e.g. `delete`) | Resource override on that op only |\n| One op needs a looser cap (high-volume reads) | Resource override raising the limit |\n| One resource is a high-volume sink | `rateLimit: false` on the resource |\n| Whole project is behind a WAF | `rateLimit: false` at project level |\n| App-wide tighter default (e.g. expensive reads) | Project-level override of that op |"
135
135
  },
136
136
  "compiler/definitions/read": {
137
137
  "title": "Read - Unified Read Pipeline",
@@ -215,7 +215,7 @@ export const DOCS = {
215
215
  },
216
216
  "compiler/targets/hono-api/database/neon": {
217
217
  "title": "Neon",
218
- "content": "Neon provides serverless PostgreSQL that works with Cloudflare Workers via HTTP connections. Choose Neon when you need PostgreSQL features (JSON operators, full-text search, advanced indexing) or want database-level Row Level Security alongside the generated Hono API.\n\n## Why Neon\n\n- **Full PostgreSQL** — Advanced queries, joins, PostGIS, full-text search\n- **Database-level security** — RLS policies enforce access even if the API is bypassed\n- **Serverless** — HTTP connection mode (`@neondatabase/serverless`) for Cloudflare Workers\n- **Worker-scoped RLS** — the Worker verifies each caller, then writes the trusted user/org/team context into transaction-local Postgres settings that RLS policies read (see [How Worker-scoped RLS works](#how-worker-scoped-rls-works))\n- **Better Auth integration** — Works seamlessly with the Quickback auth provider\n\n## One database for auth and features\n\nQuickback uses a single database provider per app. On Neon, Better Auth tables\nand feature tables live in the same Postgres database: Better Auth runs on its\nPostgreSQL/Drizzle adapter, and everything connects through one `DATABASE_URL`.\nThere is no `AUTH_DATABASE_URL`, and split-database mode is a D1-only option.\n\nMixing providers — for example D1 for auth with Neon for features — is not\nsupported. The per-service config form is rejected at compile time:\n\n```\nproviders.database service-map form is not supported in v2.\nConfigure one database provider; auth and feature data use the same database.\n```\n\n## Configuration\n\n```typescript title=\"quickback/quickback.config.ts\"\n\nexport default defineConfig({\n name: \"my-app\",\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"neon\", {\n connectionMode: \"auto\", // detects runtime\n pooled: true,\n }),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## Connection modes\n\n| Mode | Best for | How it works |\n|------|----------|--------------|\n| **HTTP** (default) | Cloudflare Workers — batch writes | Stateless HTTP queries via `@neondatabase/serverless` |\n| **Hyperdrive** | Cloudflare Workers — interactive transactions | `postgres.js` over a Cloudflare Hyperdrive binding (`drizzle-orm/postgres-js`) |\n| **WebSocket** *(deprecated)* | Node.js, Bun | Persistent WebSocket (`drizzle-orm/neon-serverless`) — superseded by Hyperdrive |\n| **Auto** | Mixed environments | Detects runtime: `http` on `cloudflare`, `websocket` on Node/Bun |\n\nOn the Cloudflare runtime, `auto` resolves to **HTTP** — batch-only, no binding,\nand the mode the rest of this page assumes. Opt a project up to\n`connectionMode: 'hyperdrive'` when its actions need real interactive\ntransactions (see [Interactive transactions](#interactive-transactions)).\n\n## Environment variables\n\nThree connection points, each read by a different tool:\n\n| Where | File / store | Read by |\n|-------|--------------|---------|\n| Migrations (local/CI) | `.env` | `drizzle-kit` |\n| `wrangler dev` (local Worker) | `.dev.vars` | Wrangler |\n| Production Worker | `wrangler secret put` | The deployed Worker |\n\nThe compiler emits `.env.neon.example` and `.dev.vars.example` as templates,\nand gitignores `.dev.vars` so local secrets are never committed.\n\n```bash\n# Migrations read .env — copy the template and fill it in:\ncp .env.neon.example .env\n# .env holds:\n# DATABASE_URL — pooled quickback (runtime) role URL\n# DATABASE_MIGRATION_URL — unpooled quickback_admin role URL (optional)\n\n# wrangler dev reads .dev.vars (NOT .env) — copy the template:\ncp .dev.vars.example .dev.vars # gitignored; holds DATABASE_URL + BETTER_AUTH_SECRET\n\n# Production: secrets live in Worker secrets, never in files:\nnpx wrangler secret put DATABASE_URL # pooled quickback role URL\nnpx wrangler secret put BETTER_AUTH_SECRET\n```\n\n`DATABASE_URL` is the only connection string the Worker needs at runtime — auth\nand feature queries share it. `DATABASE_MIGRATION_URL` is used **only** by\n`drizzle-kit`: the generated `drizzle.config.ts` reads\n`process.env.DATABASE_MIGRATION_URL ?? process.env.DATABASE_URL`, so migrations\nrun as the privileged `quickback_admin` role when it is set and fall back to\n`DATABASE_URL` when it is not. Never deploy `DATABASE_MIGRATION_URL` to the\nWorker.\n\n## Better Auth schema generation\n\n`src/auth/schema.ts` is owned by the Better Auth CLI. The generated `build`\nscript regenerates it before typechecking:\n\n```bash\nnpm run build # runs auth:schema, then tsc\n```\n\n`auth:schema` expands to:\n\n```bash\nnpx better-auth generate --config ./src/lib/auth.ts --output ./src/auth/schema.ts --yes \\\n && node scripts/quickback-qualify-auth-schema.mjs\n```\n\nThe qualifier script adjusts the CLI output for Postgres schema placement.\nDon't hand-edit `src/auth/schema.ts` — regenerate it instead.\n\n## Migrations\n\nNeon uses PostgreSQL migrations, distinct from D1's SQLite migrations. One\nDrizzle journal covers auth tables, feature tables, indexes, FK/cascade\nsemantics, and the RLS layer:\n\n```bash\nquickback compile # generates migrations under quickback/drizzle/\nnpm run db:migrate # applies schema AND the RLS layer, in order\n```\n\nThe RLS layer (helper functions, policies, triggers) rides the same\njournaled migration set as your schema: the compiler appends a\ncontent-addressed `<idx>_quickback_rls_<hash>` migration, so one\n`db:migrate` applies everything in order. The RLS migration is idempotent\n(`DROP POLICY IF EXISTS` + re-create) and only a *changed* security config\nappends a new entry — recompiles with unchanged security append nothing. No\nmanual SQL application step exists.\n\n## How Worker-scoped RLS works\n\nQuickback does **not** send browser or mobile clients directly to Neon, and it\ndoes **not** use Neon Authorize / a JWKS endpoint. Clients authenticate with the\nCloudflare Worker; the Worker verifies the Better Auth session or API key, runs\nthe access checks, and then performs the database call as a trusted proxy.\n\nFor every feature-table query, the generated database client opens a Neon HTTP\nbatch (an implicit transaction) whose **first** statement writes the verified\ncaller context into transaction-local Postgres settings:\n\n```sql\n-- Injected by the Worker as the batch's first statement (is_local = true):\nSELECT\n set_config('quickback.service_role', '', true),\n set_config('request.jwt.claim.sub', 'usr_123', true),\n set_config('request.jwt.claim.org_id', 'org_abc', true),\n set_config('request.jwt.claim.team_id', '', true);\n```\n\nRLS policies read those settings through Quickback-defined helper functions —\nthere is no external JWT verification and no persisted session state in the\ndatabase. `auth.user_id()` is a compiler-generated shim, not a Neon Authorize\nfunction:\n\n```sql\n-- Generated by Quickback (granted to the quickback runtime role):\nCREATE OR REPLACE FUNCTION auth.user_id()\nRETURNS TEXT AS $$\n SELECT NULLIF(current_setting('request.jwt.claim.sub', true), '')\n$$ LANGUAGE SQL STABLE SET search_path = public;\n```\n\nBecause the settings are transaction-local (`set_config(..., true)`), they\napply only to the current batch and never leak between requests. If the Worker\nnever stamps a user id, `auth.user_id()` returns `NULL` and the restrictive\n`deny_anon` policy blocks the query — fail closed.\n\n## Row Level Security\n\nQuickback emits RLS policies from your `firewall` and `access` config. Neon's\npolicies read the transaction-local claims described above via `auth.user_id()`\nand the `get_active_org_id()` / `has_any_role()` helpers (the Supabase target\nuses `auth.uid()` instead — same pattern, different function).\n\n```typescript\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n]\n```\n\n```sql\nCREATE POLICY \"documents_select\" ON documents FOR SELECT\nUSING (\n organization_id = public.get_active_org_id()\n AND (public.is_admin() OR user_id = auth.user_id())\n);\n```\n\nEvery feature table also gets a restrictive `deny_anon` policy (blocks queries\nwith no stamped user id) and a `service_role` policy (admits Worker-internal\ncontexts — see [Background jobs and cross-tenant actions](#background-jobs-and-cross-tenant-actions)).\n\n### Firewall patterns\n\n**Organization-scoped:**\n\n```sql\nCREATE POLICY \"projects_select\" ON projects FOR SELECT\nUSING (organization_id = public.get_active_org_id());\n```\n\n**User-scoped:**\n\n```sql\nCREATE POLICY \"preferences_select\" ON preferences FOR SELECT\nUSING (user_id = auth.user_id());\n```\n\n**Public tables:**\n\n```sql\nCREATE POLICY \"categories_deny_anon\" ON categories FOR ALL TO anon USING (false);\nCREATE POLICY \"categories_all\" ON categories FOR ALL TO authenticated USING (true) WITH CHECK (true);\n```\n\n### Helper functions\n\n| Function | Purpose |\n|----------|---------|\n| `auth.user_id()` | Reads the verified user id from the transaction-local `request.jwt.claim.sub` setting |\n| `get_active_org_id()` | Reads the request-scoped org from the transaction-local `request.jwt.claim.org_id` setting |\n| `get_active_team_id()` | Reads the request-scoped team from `request.jwt.claim.team_id` (teams mode) |\n| `has_any_role(roles[])` | Checks if the user has any specified role in the request org |\n| `has_org_role(role)` | Checks for a single specific role |\n| `is_org_member()` | Checks org membership in the request org |\n| `is_owner(owner_id)` | Checks record ownership against `auth.user_id()` |\n| `is_admin()` | Checks the `auth.admins` table (admin mode) |\n\nAll helpers are TEXT-typed to match Better Auth's prefixed ids (`org_abc123`).\nThe request org/team scope is passed by the Worker **per transaction**, not read\nfrom a persisted mirror. There is no compiler-owned `user_sessions` table and no\nsession hook that syncs the active organization into the database — switching to\n\"no org\" simply means the Worker stamps an empty `request.jwt.claim.org_id`, and\nSQL-side access is revoked immediately. Fail closed.\n\nThe only compiler-owned support tables the RLS layer reads live in\n`src/db/rls-support.schema.ts`: a `profiles` table (populated by the\n`sync_profile_display_name()` trigger and protected by the `profiles_*`\npolicies) and, when admin/sysadmin helpers are emitted, an `admins` table (read\nby `is_admin()` / `is_sysadmin()`). Better Auth's own `sessions` table may still\ncarry an `active_organization_id`, but Quickback RLS never reads it.\n\nRLS coverage includes Better Auth's own tables — including those the compiler\nforce-enables (organization, admin, `apikeys`; plus the OAuth/agent table\nfamilies when those surfaces are on, locked to service-role only).\n\n## Background jobs and cross-tenant actions\n\nSome code runs with no HTTP request and therefore no caller claims: queue\nconsumers, cron schedules, and cross-tenant `unsafe` actions. These acquire the\n**service-role handle** `createServiceDb(env)` from the generated `src/db`\nindex. Instead of caller claims, it sets `quickback.service_role = 'true'` (with\nall request claims cleared) — the same marker the Better Auth adapter's\ntransactions use. Every feature table carries a `<table>_service_role` RLS\npolicy that admits exactly that context, so background work can reach rows\nacross tenants while the request-scoped `createDb()` client stays caller-scoped.\n\nThe service-role marker is only ever set by Worker-internal chokepoints\n(`createServiceDb`, the Better Auth adapter) — it is never derived from request\ninput. Unsafe actions keep their mandatory audit contract: cross-tenant writes\nstill land audit events (the `audit` Postgres schema), unchanged from D1.\n\n## Reads through a user-anchored relationship\n\nSome resources are readable not because you own them or belong to their org, but\nbecause you are reachable from them through a **chain of tables** anchored on the\ncaller's user id. A conference attendee, for example, can read their own\nregistrations even though they are not an org member — the grant travels\n`person_account_links.user_id = ctx.userId → people → event_people →\nregistrations`.\n\nDeclare the chain once as an `authz.relationships` entry using the `hops` form\n(each hop names the joined `table`, the column it is joined `on`, and the `prev`\ncolumn on the previous table that points at it). The terminal hop's `table` is\nthe **anchor** — the table carrying the caller's user id:\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeReachable: {\n from: 'person_account_links', // the anchor table\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventPersonId' }, // the column on the resource this constrains\n hops: [\n { table: 'event_people', on: 'id', prev: 'eventPersonId' },\n { table: 'people', on: 'id', prev: 'personId' },\n { table: 'person_account_links', on: 'personId', prev: 'id' },\n ],\n },\n },\n},\n```\n\nA resource opts into the grant by referencing the relationship from its\n`firewall` — typically as one arm of an `any:` group so org members keep their\nown path in:\n\n```typescript\n// features/registrations/registrations.ts\nfirewall: [\n {\n any: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' }, // org-member grant\n { field: 'eventPersonId', via: 'attendeeReachable' }, // reachable-attendee grant\n ],\n },\n],\n```\n\n### The anchor must be non-forgeable (fail closed on both targets)\n\nThe reachability chain terminates in `anchor.user_id = ctx.userId`, so whoever\ncan **write** an anchor row can mint themselves reachability to a victim's data.\nQuickback therefore refuses to compile a user-anchored multi-hop relationship\nunless the anchor table is:\n\n- **caller-read-own on the subject column** — its firewall scopes reads to\n `ctx.userId` (e.g. `firewall: [{ field: 'userId', equals: 'ctx.userId' }]`), and\n- **service-role-write-only** — it exposes no caller-reachable `create` / `update`\n / `delete` endpoint, so the link can only be created by Worker-internal code.\n\nThis check is **target-independent**: it fires identically on Neon and D1,\nbecause the reachability join runs in the app layer on both. A forgeable anchor\nis a compile error everywhere, not a Neon-only concern.\n\n### How the read is served\n\nOn **Neon**, a via-relationship reachability predicate cannot be expressed as an\nRLS policy — the correlated multi-hop join reaches across intermediate tables\nthat each `FORCE ROW LEVEL SECURITY`, so caller-claims RLS would deny the attendee\nto *zero* rows before the app-layer WHERE ever runs. Quickback resolves this by\nrouting that resource's **read** handlers through the service-role handle\n(`createServiceDb(c.env)`) instead of the caller-claims client. RLS stops denying,\nand the compiled `buildFirewallConditions(...)` reachability WHERE — the exact\nsame clause D1 uses — becomes the **sole** row filter.\n\nThis is the D1 trust model, applied to Neon for exactly these reads: the\napplication layer is the firewall, and RLS is a coarse tenant backstop that steps\naside where it cannot express the grant. It is surgical and fail-closed:\n\n- Only the affected resource's reads swap handles. **Org / owner / team reads keep\n caller claims + the RLS backstop** — they resolve to policies RLS *can* express.\n- The swap is gated on a non-empty firewall carrying the reachability predicate;\n a service-handle read with no WHERE is a compile error (it would return every\n tenant's rows). Fail closed.\n- It applies to the **collection `GET /`, `GET /:id`, and views** alike. **Writes\n are unchanged** — creates/updates/deletes keep caller claims and the RLS\n backstop.\n\nThe **same config compiles identically on D1**, where there is no RLS to bypass:\nthe read handlers keep `c.get('db')` and the app-layer reachability WHERE was\nalready the whole story.\n\n## Webhooks on Neon\n\nWebhooks are supported on Neon over HTTP. The store (`webhook_events`,\n`webhook_endpoints`, `webhook_deliveries`) lives in a dedicated `webhooks`\nPostgres schema of the **same** database — following the `audit` schema\nprecedent — so there is no separate `WEBHOOKS_DB` binding.\n\n- Set `webhooksBinding` to enable webhooks. On Neon its value is a pure enable\n flag (no D1 binding is emitted); the queue names stay provider-neutral.\n- The D1-only keys `webhooksDatabaseId` and `webhooksDatabaseName` are rejected\n at compile time — they name a D1 database that cannot exist on Neon.\n- The webhook store is Worker-internal (endpoint signing secrets live there):\n every table in the `webhooks` schema has RLS enabled with a single\n service-role-only policy, so only `createWebhooksDb()` (which wraps\n `createServiceDb`) can touch it. Route handlers gate access at the app layer\n (`requireOrgMember` / endpoint-ownership checks) before querying.\n- Webhooks require `connectionMode: 'http'`.\n\n## Encryption on Neon\n\nThe encryption pillar — `.encrypted()` (envelope) and `.sealed()` /\n`q.vaultRef()` (sealed) columns — is supported on Neon over HTTP. The\n`org_data_keys` and seal-vault tables fold into the single journaled migration\nset, and the encryption RLS section rides the journaled RLS migration:\n`org_data_keys` gets org-scoped RLS (the envelope DEK path needs caller claims),\nand the vault spine is locked to service-role-only. The seal chokepoints\nacquire `createServiceDb`.\n\nBoth tiers require `connectionMode: 'http'`; under WebSocket mode they are a\nfail-closed compile error.\n\n## Batch transactions\n\nWhether a batch handler (`PATCH /batch`, `DELETE /batch`, …) is truly atomic\ndepends on the connection mode, and the response advertises the guarantee via\n`meta.transactional`:\n\n| Mode | `meta.transactional` | Behavior |\n|------|----------------------|----------|\n| Neon HTTP (Cloudflare default) | `false` | Fail-fast per-record loop, no rollback — `drizzle-orm/neon-http` has no interactive transactions, so this matches D1's semantics honestly |\n| Neon Hyperdrive (Cloudflare) | `true` | `db.transaction()` wraps the loop; any failure rolls back every write in the batch |\n| Neon WebSocket (Node/Bun) | `true` | `db.transaction()` wraps the loop; any failure rolls back every write in the batch |\n\n`drizzle-orm/neon-http` throws \"No transactions support in neon-http driver\" at\nruntime, so the HTTP path deliberately treats batches like D1 (fail-fast,\nnon-transactional) rather than emitting code that would 500 on every failed\nbatch. Honest advertisement over runtime surprises. For true atomic batches and\ninteractive transactions on Cloudflare, use\n[`connectionMode: 'hyperdrive'`](#interactive-transactions).\n\n## Interactive transactions\n\n`connectionMode: 'hyperdrive'` runs the feature database over a Cloudflare\n[Hyperdrive](https://developers.cloudflare.com/hyperdrive/) binding using\n`postgres.js` (`drizzle-orm/postgres-js`), which supports **real interactive\ntransactions** — read current state, lock it, decide in TypeScript, then write\ndependent rows, all committed atomically:\n\n```ts\nexport default defineAction({\n input: z.object({ registrationId: z.string() }),\n async execute({ db, input }) {\n return db.transaction(async (tx) => { // tx is fully typed\n const [reg] = await tx.select()\n .from(registrations)\n .where(eq(registrations.id, input.registrationId))\n .for(\"update\"); // row lock held to commit\n if (!reg) throw new ActionError(\"Not found\", \"NOT_FOUND\", 404); // → rollback\n const [updated] = await tx.update(registrations)\n .set({ status: nextStatus(reg) })\n .where(eq(registrations.id, reg.id))\n .returning();\n await tx.insert(registrationEvents).values({ registrationId: updated.id });\n return updated; // atomic commit\n });\n },\n});\n```\n\nNote the `tx.select()…for(\"update\")` form: Drizzle's relational query API\n(`tx.query.<table>.findFirst`) is [blocked on the scoped\n`db`/`tx`](/compiler/definitions/actions#relational-queries-are-blocked-fail-closed)\nbecause the tenant firewall can't be injected into relational queries. The\nselect builder gives you the same row lock with scope conditions applied\nautomatically.\n\nConfigure it on the database provider:\n\n```ts\nproviders: {\n database: {\n provider: \"neon\",\n config: { connectionMode: \"hyperdrive\", hyperdrive: { id: \"<binding-id>\" } },\n },\n}\n```\n\nThe compiler emits the `[[hyperdrive]]` wrangler binding pointing at your Neon\n**direct** connection string.\n\n**Security is preserved, unchanged.** The verified caller claims run as the\nfirst transaction-local statement inside the transaction (the same\n`set_config(..., true)` preamble batches use), so RLS enforces inside the\ncallback and the claims reset at commit/rollback — they never leak across\nHyperdrive's connection pool.\n\n## Capability limits (fail closed)\n\nAnything not yet ported to Postgres is a compile-time error on Neon, never\nsilently-broken output:\n\n- **Managed file storage** (`fileStorage` with `managed: true`) is rejected — its\n metadata store is a D1 database. Use presign-only R2 (the default, without\n `managed`), which is provider-neutral and works on Neon today.\n- **The Better Auth `subscriptions` plugin** is rejected until it gets\n provider-aware db acquisition and a Postgres dialect schema.\n- **Raw `sqliteTable` interop sources** on a Postgres target are rejected — write\n child tables with `pgTable` (see [below](#raw-drizzle-interop-tables-must-use-pg-core)).\n- **WebSocket mode** (deprecated) rejects webhooks, cross-tenant `unsafe`\n actions, and encrypted/sealed columns. Use\n [`connectionMode: 'hyperdrive'`](#interactive-transactions) instead — it is the\n full-capability interactive-transaction path and supersedes WebSocket.\n\nMixed database providers (e.g. D1 auth + Neon features) remain unsupported.\n\n## Deploying\n\nThe generated `deploy` script runs migrations, then ships the Worker:\n\n```bash\nnpm run deploy # runs db:migrate (drizzle-kit) then wrangler deploy\n```\n\nBefore the first deploy, put the runtime secrets in Worker secrets and make sure\nthe Worker's KV namespace (used by Better Auth for sessions and JWT revocation)\nis provisioned:\n\n```bash\nnpx wrangler secret put DATABASE_URL # pooled quickback role URL\nnpx wrangler secret put BETTER_AUTH_SECRET\n```\n\nThe generated Neon client fails fast at boot if `DATABASE_URL` is missing, so a\nmisconfigured deploy surfaces immediately rather than on the first query.\n\n## Generated files\n\n```\nquickback/drizzle/\n├── 0000_<name>.sql # schema migrations (drizzle-kit)\n├── 0001_quickback_rls_<hash>.sql # journaled RLS layer (content-addressed)\n└── meta/_journal.json # one journal covers both\nsrc/\n├── db/index.ts # createDb / createServiceDb (claim-scoped clients)\n├── db/schema.ts # Drizzle schema barrel\n├── db/rls-support.schema.ts # profiles (+ admins) — RLS support tables\n└── auth/schema.ts # Better Auth schema (owned by the BA CLI)\n.env.neon.example # migration connection strings (copy to .env)\n.dev.vars.example # wrangler dev secrets (copy to .dev.vars)\ndocs/neon-setup.md # role bootstrap + deploy walkthrough\n```\n\n## Raw Drizzle interop tables must use `pg-core`\n\nInternal child tables authored as raw Drizzle (a table file with **no**\n`export default defineTable(...)`) are not dialect-translated by the\ncompiler — on Neon they must be written with `pgTable` from\n`drizzle-orm/pg-core`. A `sqliteTable` interop source on a Postgres target\nis a **compile-time error**: the mechanical sqlite→pg rewrite would leave\nSQLite-shaped audit columns (`text` ISO strings instead of `timestamptz`,\nwhich the RLS audit triggers stamp) and SQLite-only column options in the\nPostgres schema.\n\n```typescript\n// quickback/features/interviews/interview_scores.ts\n// @quickback-internal — child table, no CRUD routes\n\nexport const interviewScores = pgTable('interview_scores', {\n id: text('id').primaryKey(),\n interviewId: text('interview_id').notNull(),\n rating: integer('rating').notNull(),\n});\n```\n\nTables **with** `defineTable(...)` are unaffected — existing `sqliteTable`\nsources with a resource config still compile to the Postgres dialect\nautomatically.\n\n## When to choose Neon vs D1\n\n| Factor | Neon | D1 |\n|--------|------|-----|\n| SQL dialect | PostgreSQL | SQLite |\n| Security model | RLS + application-layer | Application-layer only |\n| Multi-region | Built-in replication | Single region per database |\n| Pricing | Free tier, then usage-based | Free tier, then usage-based |\n| Best for | Complex queries, existing Postgres apps | Edge-first, simple schemas |\n\n## See also\n\n- [D1](/compiler/targets/hono-api/database/d1) — SQLite at the edge\n- [Providers](/compiler/config/providers) — All database provider options"
218
+ "content": "Neon provides serverless PostgreSQL that works with Cloudflare Workers via HTTP connections. Choose Neon when you need PostgreSQL features (JSON operators, full-text search, advanced indexing) or want database-level Row Level Security alongside the generated Hono API.\n\n## Why Neon\n\n- **Full PostgreSQL** — Advanced queries, joins, PostGIS, full-text search\n- **Database-level security** — RLS policies enforce access even if the API is bypassed\n- **Serverless** — HTTP connection mode (`@neondatabase/serverless`) for Cloudflare Workers\n- **Worker-scoped RLS** — the Worker verifies each caller, then writes the trusted user/org/team context into transaction-local Postgres settings that RLS policies read (see [How Worker-scoped RLS works](#how-worker-scoped-rls-works))\n- **Better Auth integration** — Works seamlessly with the Quickback auth provider\n\n## One database for auth and features\n\nQuickback uses a single database provider per app. On Neon, Better Auth tables\nand feature tables live in the same Postgres database: Better Auth runs on its\nPostgreSQL/Drizzle adapter, and everything connects through one `DATABASE_URL`.\nThere is no `AUTH_DATABASE_URL`, and split-database mode is a D1-only option.\n\nMixing providers — for example D1 for auth with Neon for features — is not\nsupported. The per-service config form is rejected at compile time:\n\n```\nproviders.database service-map form is not supported in v2.\nConfigure one database provider; auth and feature data use the same database.\n```\n\n## Configuration\n\n```typescript title=\"quickback/quickback.config.ts\"\n\nexport default defineConfig({\n name: \"my-app\",\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"neon\", {\n connectionMode: \"auto\", // detects runtime\n pooled: true,\n }),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## Connection modes\n\n| Mode | Best for | How it works |\n|------|----------|--------------|\n| **HTTP** (default) | Cloudflare Workers — batch writes | Stateless HTTP queries via `@neondatabase/serverless` |\n| **Hyperdrive** | Cloudflare Workers — interactive transactions | `postgres.js` over a Cloudflare Hyperdrive binding (`drizzle-orm/postgres-js`) |\n| **WebSocket** *(deprecated)* | Node.js, Bun | Persistent WebSocket (`drizzle-orm/neon-serverless`) — superseded by Hyperdrive |\n| **Auto** | Mixed environments | Detects runtime: `http` on `cloudflare`, `websocket` on Node/Bun |\n\nOn the Cloudflare runtime, `auto` resolves to **HTTP** — batch-only, no binding,\nand the mode the rest of this page assumes. Opt a project up to\n`connectionMode: 'hyperdrive'` when its actions need real interactive\ntransactions (see [Interactive transactions](#interactive-transactions)).\n\n## Environment variables\n\nThree connection points, each read by a different tool:\n\n| Where | File / store | Read by |\n|-------|--------------|---------|\n| Migrations (local/CI) | `.env` | `drizzle-kit` |\n| `wrangler dev` (local Worker) | `.dev.vars` | Wrangler |\n| Production Worker | `wrangler secret put` | The deployed Worker |\n\nThe compiler emits `.env.neon.example` and `.dev.vars.example` as templates,\nand gitignores `.dev.vars` so local secrets are never committed.\n\n```bash\n# Migrations read .env — copy the template and fill it in:\ncp .env.neon.example .env\n# .env holds:\n# DATABASE_URL — pooled quickback (runtime) role URL\n# DATABASE_MIGRATION_URL — unpooled quickback_admin role URL (optional)\n\n# wrangler dev reads .dev.vars (NOT .env) — copy the template:\ncp .dev.vars.example .dev.vars # gitignored; holds DATABASE_URL + BETTER_AUTH_SECRET\n\n# Production: secrets live in Worker secrets, never in files:\nnpx wrangler secret put DATABASE_URL # pooled quickback role URL\nnpx wrangler secret put BETTER_AUTH_SECRET\n```\n\n`DATABASE_URL` is the only connection string the Worker needs at runtime — auth\nand feature queries share it. `DATABASE_MIGRATION_URL` is used **only** by\n`drizzle-kit`: the generated `drizzle.config.ts` reads\n`process.env.DATABASE_MIGRATION_URL ?? process.env.DATABASE_URL`, so migrations\nrun as the privileged `quickback_admin` role when it is set and fall back to\n`DATABASE_URL` when it is not. Never deploy `DATABASE_MIGRATION_URL` to the\nWorker.\n\n## Better Auth schema generation\n\n`src/auth/schema.ts` is owned by the Better Auth CLI. The generated `build`\nscript regenerates it before typechecking:\n\n```bash\nnpm run build # runs auth:schema, then tsc\n```\n\n`auth:schema` expands to:\n\n```bash\nnpx better-auth generate --config ./src/lib/auth.ts --output ./src/auth/schema.ts --yes \\\n && node scripts/quickback-qualify-auth-schema.mjs\n```\n\nThe `better-auth` executable comes from the `auth` devDependency in the\ngenerated `package.json` — that's the Better Auth CLI package (the\n`better-auth` runtime package ships no bin).\n\nThe qualifier script adjusts the CLI output for Postgres schema placement.\nDon't hand-edit `src/auth/schema.ts` — regenerate it instead.\n\n## Migrations\n\nNeon uses PostgreSQL migrations, distinct from D1's SQLite migrations. One\nDrizzle journal covers auth tables, feature tables, indexes, FK/cascade\nsemantics, and the RLS layer:\n\n```bash\nquickback compile # generates migrations under quickback/drizzle/\nnpm run db:migrate # applies schema AND the RLS layer, in order\n```\n\nThe RLS layer (helper functions, policies, triggers) rides the same\njournaled migration set as your schema: the compiler appends a\ncontent-addressed `<idx>_quickback_rls_<hash>` migration, so one\n`db:migrate` applies everything in order. The RLS migration is idempotent\n(`DROP POLICY IF EXISTS` + re-create) and only a *changed* security config\nappends a new entry — recompiles with unchanged security append nothing. No\nmanual SQL application step exists.\n\n## How Worker-scoped RLS works\n\nQuickback does **not** send browser or mobile clients directly to Neon, and it\ndoes **not** use Neon Authorize / a JWKS endpoint. Clients authenticate with the\nCloudflare Worker; the Worker verifies the Better Auth session or API key, runs\nthe access checks, and then performs the database call as a trusted proxy.\n\nFor every feature-table query, the generated database client opens a Neon HTTP\nbatch (an implicit transaction) whose **first** statement writes the verified\ncaller context into transaction-local Postgres settings:\n\n```sql\n-- Injected by the Worker as the batch's first statement (is_local = true):\nSELECT\n set_config('quickback.service_role', '', true),\n set_config('request.jwt.claim.sub', 'usr_123', true),\n set_config('request.jwt.claim.org_id', 'org_abc', true),\n set_config('request.jwt.claim.team_id', '', true);\n```\n\nRLS policies read those settings through Quickback-defined helper functions —\nthere is no external JWT verification and no persisted session state in the\ndatabase. `auth.user_id()` is a compiler-generated shim, not a Neon Authorize\nfunction:\n\n```sql\n-- Generated by Quickback (granted to the quickback runtime role):\nCREATE OR REPLACE FUNCTION auth.user_id()\nRETURNS TEXT AS $$\n SELECT NULLIF(current_setting('request.jwt.claim.sub', true), '')\n$$ LANGUAGE SQL STABLE SET search_path = public;\n```\n\nBecause the settings are transaction-local (`set_config(..., true)`), they\napply only to the current batch and never leak between requests. If the Worker\nnever stamps a user id, `auth.user_id()` returns `NULL` and the restrictive\n`deny_anon` policy blocks the query — fail closed.\n\n## Row Level Security\n\nQuickback emits RLS policies from your `firewall` and `access` config. Neon's\npolicies read the transaction-local claims described above via `auth.user_id()`\nand the `get_active_org_id()` / `has_any_role()` helpers (the Supabase target\nuses `auth.uid()` instead — same pattern, different function).\n\n```typescript\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n]\n```\n\n```sql\nCREATE POLICY \"documents_select\" ON documents FOR SELECT\nUSING (\n organization_id = public.get_active_org_id()\n AND (public.is_admin() OR user_id = auth.user_id())\n);\n```\n\nEvery feature table also gets a restrictive `deny_anon` policy (blocks queries\nwith no stamped user id) and a `service_role` policy (admits Worker-internal\ncontexts — see [Background jobs and cross-tenant actions](#background-jobs-and-cross-tenant-actions)).\n\n### Firewall patterns\n\n**Organization-scoped:**\n\n```sql\nCREATE POLICY \"projects_select\" ON projects FOR SELECT\nUSING (organization_id = public.get_active_org_id());\n```\n\n**User-scoped:**\n\n```sql\nCREATE POLICY \"preferences_select\" ON preferences FOR SELECT\nUSING (user_id = auth.user_id());\n```\n\n**Public tables:**\n\n```sql\nCREATE POLICY \"categories_deny_anon\" ON categories FOR ALL TO anon USING (false);\nCREATE POLICY \"categories_all\" ON categories FOR ALL TO authenticated USING (true) WITH CHECK (true);\n```\n\n### Helper functions\n\n| Function | Purpose |\n|----------|---------|\n| `auth.user_id()` | Reads the verified user id from the transaction-local `request.jwt.claim.sub` setting |\n| `get_active_org_id()` | Reads the request-scoped org from the transaction-local `request.jwt.claim.org_id` setting |\n| `get_active_team_id()` | Reads the request-scoped team from `request.jwt.claim.team_id` (teams mode) |\n| `has_any_role(roles[])` | Checks if the user has any specified role in the request org |\n| `has_org_role(role)` | Checks for a single specific role |\n| `is_org_member()` | Checks org membership in the request org |\n| `is_owner(owner_id)` | Checks record ownership against `auth.user_id()` |\n| `is_admin()` | Checks the `auth.admins` table (admin mode) |\n\nAll helpers are TEXT-typed to match Better Auth's prefixed ids (`org_abc123`).\nThe request org/team scope is passed by the Worker **per transaction**, not read\nfrom a persisted mirror. There is no compiler-owned `user_sessions` table and no\nsession hook that syncs the active organization into the database — switching to\n\"no org\" simply means the Worker stamps an empty `request.jwt.claim.org_id`, and\nSQL-side access is revoked immediately. Fail closed.\n\nThe only compiler-owned support tables the RLS layer reads live in\n`src/db/rls-support.schema.ts`: a `profiles` table (populated by the\n`sync_profile_display_name()` trigger and protected by the `profiles_*`\npolicies) and, when admin/sysadmin helpers are emitted, an `admins` table (read\nby `is_admin()` / `is_sysadmin()`). Better Auth's own `sessions` table may still\ncarry an `active_organization_id`, but Quickback RLS never reads it.\n\nRLS coverage includes Better Auth's own tables — including those the compiler\nforce-enables (organization, admin, `apikeys`; plus the OAuth/agent table\nfamilies when those surfaces are on, locked to service-role only).\n\n## Background jobs and cross-tenant actions\n\nSome code runs with no HTTP request and therefore no caller claims: queue\nconsumers, cron schedules, and cross-tenant `unsafe` actions. These acquire the\n**service-role handle** `createServiceDb(env)` from the generated `src/db`\nindex. Instead of caller claims, it sets `quickback.service_role = 'true'` (with\nall request claims cleared) — the same marker the Better Auth adapter's\ntransactions use. Every feature table carries a `<table>_service_role` RLS\npolicy that admits exactly that context, so background work can reach rows\nacross tenants while the request-scoped `createDb()` client stays caller-scoped.\n\nThe service-role marker is only ever set by Worker-internal chokepoints\n(`createServiceDb`, the Better Auth adapter) — it is never derived from request\ninput. Unsafe actions keep their mandatory audit contract: cross-tenant writes\nstill land audit events (the `audit` Postgres schema), unchanged from D1.\n\n## Reads through a user-anchored relationship\n\nSome resources are readable not because you own them or belong to their org, but\nbecause you are reachable from them through a **chain of tables** anchored on the\ncaller's user id. A conference attendee, for example, can read their own\nregistrations even though they are not an org member — the grant travels\n`person_account_links.user_id = ctx.userId → people → event_people →\nregistrations`.\n\nDeclare the chain once as an `authz.relationships` entry using the `hops` form\n(each hop names the joined `table`, the column it is joined `on`, and the `prev`\ncolumn on the previous table that points at it). The terminal hop's `table` is\nthe **anchor** — the table carrying the caller's user id:\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeReachable: {\n from: 'person_account_links', // the anchor table\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventPersonId' }, // the column on the resource this constrains\n hops: [\n { table: 'event_people', on: 'id', prev: 'eventPersonId' },\n { table: 'people', on: 'id', prev: 'personId' },\n { table: 'person_account_links', on: 'personId', prev: 'id' },\n ],\n },\n },\n},\n```\n\nA resource opts into the grant by referencing the relationship from its\n`firewall` — typically as one arm of an `any:` group so org members keep their\nown path in:\n\n```typescript\n// features/registrations/registrations.ts\nfirewall: [\n {\n any: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' }, // org-member grant\n { field: 'eventPersonId', via: 'attendeeReachable' }, // reachable-attendee grant\n ],\n },\n],\n```\n\n### The anchor must be non-forgeable (fail closed on both targets)\n\nThe reachability chain terminates in `anchor.user_id = ctx.userId`, so whoever\ncan **write** an anchor row can mint themselves reachability to a victim's data.\nQuickback therefore refuses to compile a user-anchored multi-hop relationship\nunless the anchor table is:\n\n- **caller-read-own on the subject column** — its firewall scopes reads to\n `ctx.userId` (e.g. `firewall: [{ field: 'userId', equals: 'ctx.userId' }]`), and\n- **service-role-write-only** — it exposes no caller-reachable `create` / `update`\n / `delete` endpoint, so the link can only be created by Worker-internal code.\n\nThis check is **target-independent**: it fires identically on Neon and D1,\nbecause the reachability join runs in the app layer on both. A forgeable anchor\nis a compile error everywhere, not a Neon-only concern.\n\n### How the read is served\n\nOn **Neon**, a via-relationship reachability predicate cannot be expressed as an\nRLS policy — the correlated multi-hop join reaches across intermediate tables\nthat each `FORCE ROW LEVEL SECURITY`, so caller-claims RLS would deny the attendee\nto *zero* rows before the app-layer WHERE ever runs. Quickback resolves this by\nrouting that resource's **read** handlers through the service-role handle\n(`createServiceDb(c.env)`) instead of the caller-claims client. RLS stops denying,\nand the compiled `buildFirewallConditions(...)` reachability WHERE — the exact\nsame clause D1 uses — becomes the **sole** row filter.\n\nThis is the D1 trust model, applied to Neon for exactly these reads: the\napplication layer is the firewall, and RLS is a coarse tenant backstop that steps\naside where it cannot express the grant. It is surgical and fail-closed:\n\n- Only the affected resource's reads swap handles. **Org / owner / team reads keep\n caller claims + the RLS backstop** — they resolve to policies RLS *can* express.\n- The swap is gated on a non-empty firewall carrying the reachability predicate;\n a service-handle read with no WHERE is a compile error (it would return every\n tenant's rows). Fail closed.\n- It applies to the **collection `GET /`, `GET /:id`, and views** alike. **Writes\n are unchanged** — creates/updates/deletes keep caller claims and the RLS\n backstop.\n\nThe **same config compiles identically on D1**, where there is no RLS to bypass:\nthe read handlers keep `c.get('db')` and the app-layer reachability WHERE was\nalready the whole story.\n\n## Webhooks on Neon\n\nWebhooks are supported on Neon over HTTP. The store (`webhook_events`,\n`webhook_endpoints`, `webhook_deliveries`) lives in a dedicated `webhooks`\nPostgres schema of the **same** database — following the `audit` schema\nprecedent — so there is no separate `WEBHOOKS_DB` binding.\n\n- Set `webhooksBinding` to enable webhooks. On Neon its value is a pure enable\n flag (no D1 binding is emitted); the queue names stay provider-neutral.\n- The D1-only keys `webhooksDatabaseId` and `webhooksDatabaseName` are rejected\n at compile time — they name a D1 database that cannot exist on Neon.\n- The webhook store is Worker-internal (endpoint signing secrets live there):\n every table in the `webhooks` schema has RLS enabled with a single\n service-role-only policy, so only `createWebhooksDb()` (which wraps\n `createServiceDb`) can touch it. Route handlers gate access at the app layer\n (`requireOrgMember` / endpoint-ownership checks) before querying.\n- Webhooks require `connectionMode: 'http'`.\n\n## Encryption on Neon\n\nThe encryption pillar — `.encrypted()` (envelope) and `.sealed()` /\n`q.vaultRef()` (sealed) columns — is supported on Neon over HTTP. The\n`org_data_keys` and seal-vault tables fold into the single journaled migration\nset, and the encryption RLS section rides the journaled RLS migration:\n`org_data_keys` gets org-scoped RLS (the envelope DEK path needs caller claims),\nand the vault spine is locked to service-role-only. The seal chokepoints\nacquire `createServiceDb`.\n\nBoth tiers require `connectionMode: 'http'`; under WebSocket mode they are a\nfail-closed compile error.\n\n## Batch transactions\n\nWhether a batch handler (`PATCH /batch`, `DELETE /batch`, …) is truly atomic\ndepends on the connection mode, and the response advertises the guarantee via\n`meta.transactional`:\n\n| Mode | `meta.transactional` | Behavior |\n|------|----------------------|----------|\n| Neon HTTP (Cloudflare default) | `false` | Fail-fast per-record loop, no rollback — `drizzle-orm/neon-http` has no interactive transactions, so this matches D1's semantics honestly |\n| Neon Hyperdrive (Cloudflare) | `true` | `db.transaction()` wraps the loop; any failure rolls back every write in the batch |\n| Neon WebSocket (Node/Bun) | `true` | `db.transaction()` wraps the loop; any failure rolls back every write in the batch |\n\n`drizzle-orm/neon-http` throws \"No transactions support in neon-http driver\" at\nruntime, so the HTTP path deliberately treats batches like D1 (fail-fast,\nnon-transactional) rather than emitting code that would 500 on every failed\nbatch. Honest advertisement over runtime surprises. For true atomic batches and\ninteractive transactions on Cloudflare, use\n[`connectionMode: 'hyperdrive'`](#interactive-transactions).\n\n## Interactive transactions\n\n`connectionMode: 'hyperdrive'` runs the feature database over a Cloudflare\n[Hyperdrive](https://developers.cloudflare.com/hyperdrive/) binding using\n`postgres.js` (`drizzle-orm/postgres-js`), which supports **real interactive\ntransactions** — read current state, lock it, decide in TypeScript, then write\ndependent rows, all committed atomically:\n\n```ts\nexport default defineAction({\n input: z.object({ registrationId: z.string() }),\n async execute({ db, input }) {\n return db.transaction(async (tx) => { // tx is fully typed\n const [reg] = await tx.select()\n .from(registrations)\n .where(eq(registrations.id, input.registrationId))\n .for(\"update\"); // row lock held to commit\n if (!reg) throw new ActionError(\"Not found\", \"NOT_FOUND\", 404); // → rollback\n const [updated] = await tx.update(registrations)\n .set({ status: nextStatus(reg) })\n .where(eq(registrations.id, reg.id))\n .returning();\n await tx.insert(registrationEvents).values({ registrationId: updated.id });\n return updated; // atomic commit\n });\n },\n});\n```\n\nNote the `tx.select()…for(\"update\")` form: Drizzle's relational query API\n(`tx.query.<table>.findFirst`) is [blocked on the scoped\n`db`/`tx`](/compiler/definitions/actions#relational-queries-are-blocked-fail-closed)\nbecause the tenant firewall can't be injected into relational queries. The\nselect builder gives you the same row lock with scope conditions applied\nautomatically.\n\nConfigure it on the database provider:\n\n```ts\nproviders: {\n database: {\n provider: \"neon\",\n config: { connectionMode: \"hyperdrive\", hyperdrive: { id: \"<binding-id>\" } },\n },\n}\n```\n\nThe compiler emits the `[[hyperdrive]]` wrangler binding pointing at your Neon\n**direct** connection string.\n\n**Security is preserved, unchanged.** The verified caller claims run as the\nfirst transaction-local statement inside the transaction (the same\n`set_config(..., true)` preamble batches use), so RLS enforces inside the\ncallback and the claims reset at commit/rollback — they never leak across\nHyperdrive's connection pool.\n\n## Capability limits (fail closed)\n\nAnything not yet ported to Postgres is a compile-time error on Neon, never\nsilently-broken output:\n\n- **Managed file storage** (`fileStorage` with `managed: true`) is rejected — its\n metadata store is a D1 database. Use presign-only R2 (the default, without\n `managed`), which is provider-neutral and works on Neon today.\n- **The Better Auth `subscriptions` plugin** is rejected until it gets\n provider-aware db acquisition and a Postgres dialect schema.\n- **Raw `sqliteTable` interop sources** on a Postgres target are rejected — write\n child tables with `pgTable` (see [below](#raw-drizzle-interop-tables-must-use-pg-core)).\n- **WebSocket mode** (deprecated) rejects webhooks, cross-tenant `unsafe`\n actions, and encrypted/sealed columns. Use\n [`connectionMode: 'hyperdrive'`](#interactive-transactions) instead — it is the\n full-capability interactive-transaction path and supersedes WebSocket.\n\nMixed database providers (e.g. D1 auth + Neon features) remain unsupported.\n\n## Deploying\n\nThe generated `deploy` script runs migrations, then ships the Worker:\n\n```bash\nnpm run deploy # runs db:migrate (drizzle-kit) then wrangler deploy\n```\n\nBefore the first deploy, put the runtime secrets in Worker secrets and make sure\nthe Worker's KV namespace (used by Better Auth for sessions and JWT revocation)\nis provisioned:\n\n```bash\nnpx wrangler secret put DATABASE_URL # pooled quickback role URL\nnpx wrangler secret put BETTER_AUTH_SECRET\n```\n\nThe generated Neon client fails fast at boot if `DATABASE_URL` is missing, so a\nmisconfigured deploy surfaces immediately rather than on the first query.\n\n## Generated files\n\n```\nquickback/drizzle/\n├── 0000_<name>.sql # schema migrations (drizzle-kit)\n├── 0001_quickback_rls_<hash>.sql # journaled RLS layer (content-addressed)\n└── meta/_journal.json # one journal covers both\nsrc/\n├── db/index.ts # createDb / createServiceDb (claim-scoped clients)\n├── db/schema.ts # Drizzle schema barrel\n├── db/rls-support.schema.ts # profiles (+ admins) — RLS support tables\n└── auth/schema.ts # Better Auth schema (owned by the BA CLI)\n.env.neon.example # migration connection strings (copy to .env)\n.dev.vars.example # wrangler dev secrets (copy to .dev.vars)\ndocs/neon-setup.md # role bootstrap + deploy walkthrough\n```\n\n## Raw Drizzle interop tables must use `pg-core`\n\nInternal child tables authored as raw Drizzle (a table file with **no**\n`export default defineTable(...)`) are not dialect-translated by the\ncompiler — on Neon they must be written with `pgTable` from\n`drizzle-orm/pg-core`. A `sqliteTable` interop source on a Postgres target\nis a **compile-time error**: the mechanical sqlite→pg rewrite would leave\nSQLite-shaped audit columns (`text` ISO strings instead of `timestamptz`,\nwhich the RLS audit triggers stamp) and SQLite-only column options in the\nPostgres schema.\n\n```typescript\n// quickback/features/interviews/interview_scores.ts\n// @quickback-internal — child table, no CRUD routes\n\nexport const interviewScores = pgTable('interview_scores', {\n id: text('id').primaryKey(),\n interviewId: text('interview_id').notNull(),\n rating: integer('rating').notNull(),\n});\n```\n\nTables **with** `defineTable(...)` are unaffected — existing `sqliteTable`\nsources with a resource config still compile to the Postgres dialect\nautomatically.\n\n## When to choose Neon vs D1\n\n| Factor | Neon | D1 |\n|--------|------|-----|\n| SQL dialect | PostgreSQL | SQLite |\n| Security model | RLS + application-layer | Application-layer only |\n| Multi-region | Built-in replication | Single region per database |\n| Pricing | Free tier, then usage-based | Free tier, then usage-based |\n| Best for | Complex queries, existing Postgres apps | Edge-first, simple schemas |\n\n## See also\n\n- [D1](/compiler/targets/hono-api/database/d1) — SQLite at the edge\n- [Providers](/compiler/config/providers) — All database provider options"
219
219
  },
220
220
  "compiler/targets/hono-api/database/using-d1": {
221
221
  "title": "Using D1",
@@ -435,11 +435,11 @@ export const DOCS = {
435
435
  },
436
436
  "stack/realtime/durable-objects": {
437
437
  "title": "Realtime",
438
- "content": "Quickback can generate realtime notification helpers for broadcasting changes to connected clients. This enables live updates via WebSocket using Cloudflare Durable Objects.\n\nThe targeting model is shared across ws tickets, websocket attachment, and server-side broadcasts:\n\n- string target: historical `organizationId` shorthand\n- object target: `{ scopeKey?, organizationId?, userId? }`\n\nThat means the same mental model drives both `createRealtime()` and the generated Broadcaster filter path.\n\n## Enabling Realtime\n\nAdd `realtime` configuration to individual table definitions:\n\n```typescript\n// features/applications/applications.ts\n\nexport const applications = sqliteTable(\"applications\", {\n id: text(\"id\").primaryKey(),\n candidateId: text(\"candidate_id\").notNull(),\n jobId: text(\"job_id\").notNull(),\n stage: text(\"stage\").notNull(),\n organizationId: text(\"organization_id\").notNull(),\n});\n\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n realtime: {\n enabled: true, // Enable realtime broadcasts for this table\n onInsert: true, // Broadcast on INSERT (default: true)\n onUpdate: true, // Broadcast on UPDATE (default: true)\n onDelete: true, // Broadcast on DELETE (default: true)\n access: { roles: [\"recruiter\", \"hiring-manager\"] }, // Audience — MANDATORY, fail-closed\n fields: [\"id\", \"candidateId\", \"stage\"], // Fields to include (optional)\n },\n // ... guards, crud\n});\n```\n\nWhen any table has realtime enabled, the compiler generates `src/lib/realtime.ts` with helper functions for sending notifications.\n\nAt the project level, `providers.database.config.realtime` can stay boolean or become object-shaped when you need relationship-authorized resource tickets:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: {\n wsTicket: {\n role: \"attendee\",\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n },\n }),\n}\n```\n\nThat tells `/broadcast/v1/ws-ticket` to authenticate with Better Auth, verify the `attendee` relationship role against `body.eventId`, and mint a short-lived ticket scoped to the resolved `events:<id>` lane.\n\n### Namespace-backed tickets (per-matched-lane)\n\nThe single-`role` form above authorizes the ticket through **one** relationship.\nWhen the room is gated by an [authz namespace](/compiler/definitions/scopes#mintscope-mint-the-scope-token-from-the-namespace-resolver)\nwith a **multi-lane `via:`** — e.g. an event reachable by attendees, organizers,\ncontractors, *and* org admins — point the ticket at the namespace instead, and it\nauthorizes through the namespace's full `via` (per-matched-lane):\n\n```typescript\nrealtime: {\n wsTicket: {\n namespace: \"eventScope\", // authorize via this namespace's full multi-lane `via`\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n},\n```\n\n`/broadcast/v1/ws-ticket` now runs the **same first-match-wins gate** the\nnamespace uses, and issues the ticket for whichever lane matched:\n\n| Caller matched via | Ticket role |\n|---|---|\n| `attendeeOf` (relationship lane) | `attendee` |\n| `organizerOf` | `organizer` |\n| `contractorOf` | `contractor` |\n| `{ roles: [\"admin\",\"owner\"] }` (bulk lane) | the caller's **org/membership roles** — no scope role |\n\nThis closes the gap where the single-`role` form denied (`403`) an org admin who\ncould legitimately reach the room through the bulk lane but isn't a confirmed\nattendee — their realtime socket now opens.\n\n## When auto-broadcast fires (and when you call it manually)\n\nQuickback emits auto-broadcasts in **only one place**: the generated CRUD route handlers (`POST /` create, `PATCH /:id` update, `DELETE /:id` delete) for resources that **explicitly declare** a `realtime.enabled` block. The project-level `dbConfig.realtime` switch wires the *transport* (Broadcaster DO + ws-ticket route) but does **not** auto-enable broadcasting on any resource — broadcasting is opt-in per resource, like CRUD. Those handlers wrap each successful write with a `realtime.insert / update / delete` call before responding.\n\nAuto-broadcasts carry the table's declared gates: the `realtime.access.roles`\naudience (or the deprecated `requiredRoles` alias) becomes the broadcast's\n`targetRoles` (with role-hierarchy `+` expanded and UPPERCASE pseudo-roles like\n`PUBLIC`/`USER` evaluated at fanout exactly as REST evaluates them), and the\ntable's effective masking config —\ndeclared plus auto-detected sensitive columns — is applied per subscriber\nrole at fanout, matching what the HTTP routes mask. A `type: 'custom'` mask\nfunction can't be replicated by the Broadcaster, so those columns broadcast\nas `[REDACTED]` (fail closed). Tables that declare neither broadcast openly,\nas before.\n\nEverywhere else — action handlers, queue consumers, scheduled jobs, custom Hono routes — you broadcast manually. In action handlers on realtime-enabled projects, Quickback now injects a typed `realtime` helper directly into `execute(...)`; outside actions you still call `createRealtime(env)` yourself.\n\n| Mutation site | Auto-broadcast? | Why |\n|---|---|---|\n| Generated CRUD route (`POST /`, `PATCH /:id`, `DELETE /:id`) | Yes | The compiler emits the call after the write returns. |\n| Generated batch route (`/batch/...`) | Yes | Same pattern, emitted per record. |\n| `scoped.insert/update/delete` inside an action handler | No — manual | Scoped-db is a query-shape wrapper (firewall + soft-delete WHERE injection). It deliberately has no side-effects so explicit handlers can write multiple records, conditionally roll back, etc. without surprise broadcasts. |\n| `unsafeDb` writes in actions (or any custom route) | No — manual | Same reasoning — `unsafeDb` is the un-wrapped escape hatch. |\n| Queue consumers, cron jobs, webhook handlers | No — manual | These run outside the CRUD path entirely. |\n\nThe rule of thumb: if your code calls `db.insert(...)` / `scoped.insert(...)` directly, you also call `realtime.insert(...)` directly on the next line. Otherwise the cross-tab live-update you wired up in the SPA won't fire.\n\n## Generated Helper\n\nAction handlers on realtime-enabled projects receive a typed `realtime` param. The underlying `createRealtime()` factory still powers it and remains the API to use from queues, cron jobs, and other non-action code:\n\n```typescript\nexport const execute: ActionExecutor = async ({ db, ctx, input, realtime }) => {\n // After creating a record\n await realtime.insert('applications', newApplication, ctx.activeOrgId!);\n\n // After updating a record\n await realtime.update('applications', newApplication, oldApplication, ctx.activeOrgId!);\n\n // After deleting a record\n await realtime.delete('applications', { id: applicationId }, ctx.activeOrgId!);\n\n return { success: true };\n};\n```\n\n`env` is also typed in action handlers, so custom bindings like R2, D1, Queues, Durable Objects, and auth env vars no longer need `(env as any)` casts.\n\nFor explicit targeting, pass an object instead of the historical org string:\n\n```typescript\nawait realtime.broadcast(\"event-page-updated\", payload, {\n scopeKey: `events:${input.eventId}`,\n});\n\nawait realtime.broadcast(\"dm\", payload, {\n userId: recipientId,\n});\n```\n\n## Event Format\n\nQuickback broadcasts events in a structured JSON format for easy client-side handling.\n\n### Insert Event\n\n```typescript\nawait realtime.insert('applications', {\n id: 'app_123',\n candidateId: 'cnd_456',\n stage: 'applied'\n}, ctx.activeOrgId!);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"INSERT\",\n \"schema\": \"public\",\n \"new\": {\n \"id\": \"app_123\",\n \"candidateId\": \"cnd_456\",\n \"stage\": \"applied\"\n },\n \"old\": null\n}\n```\n\n### Update Event\n\n```typescript\nawait realtime.update('applications',\n { id: 'app_123', stage: 'interview' }, // new\n { id: 'app_123', stage: 'screening' }, // old\n ctx.activeOrgId!\n);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"UPDATE\",\n \"schema\": \"public\",\n \"new\": { \"id\": \"app_123\", \"stage\": \"interview\" },\n \"old\": { \"id\": \"app_123\", \"stage\": \"screening\" }\n}\n```\n\n### Delete Event\n\n```typescript\nawait realtime.delete('applications',\n { id: 'app_123' },\n ctx.activeOrgId!\n);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"DELETE\",\n \"schema\": \"public\",\n \"new\": null,\n \"old\": { \"id\": \"app_123\" }\n}\n```\n\n## Custom Broadcasts\n\nFor arbitrary events that don't map to CRUD operations:\n\n```typescript\nawait realtime.broadcast('screening-complete', {\n applicationId: 'app_123',\n candidateId: 'cnd_456',\n stage: 'interview'\n}, ctx.activeOrgId!, {\n targetRoles: ['AUTHENTICATED'],\n});\n```\n\n**Every send needs an audience.** Delivery is fail-closed: a broadcast whose\n`targetRoles` is omitted or empty reaches **nobody**. \"Everyone in the room\" is\nspelled explicitly — `targetRoles: ['AUTHENTICATED']` (any authenticated\nsubscriber) or `['PUBLIC']`.\n\nBroadcasts:\n```json\n{\n \"type\": \"broadcast\",\n \"event\": \"screening-complete\",\n \"payload\": {\n \"applicationId\": \"app_123\",\n \"candidateId\": \"cnd_456\",\n \"stage\": \"interview\"\n }\n}\n```\n\n## User-Specific Broadcasts\n\nTarget a specific user instead of the entire organization:\n\n```typescript\n// Only this user receives the notification\nawait realtime.insert('notifications', newNotification, ctx.activeOrgId!, {\n userId: ctx.userId,\n targetRoles: ['AUTHENTICATED'],\n});\n\n// Notify a hiring manager of a new application\nawait realtime.broadcast('application-received', {\n applicationId: 'app_123',\n jobId: 'job_789'\n}, ctx.activeOrgId!, {\n userId: hiringManagerId,\n targetRoles: ['AUTHENTICATED'],\n});\n```\n\n`userId` targeting matches the **socket identity** — the Better Auth user id, or\nthe synthetic `scope:<subjectId>` principal for sessionless scope connections. If\nthe same person can connect through either door, prefer\n[identity-tag targeting](#identity-tag-targeting) — one send reaches both.\n\n## Role-Based Filtering\n\nLimit which roles receive a broadcast using `targetRoles`:\n\n```typescript\n// Only hiring managers and recruiters receive this broadcast\nawait realtime.insert('applications', application, ctx.activeOrgId!, {\n targetRoles: ['hiring-manager', 'recruiter']\n});\n\n// Interviewers only see applications assigned to them\nawait realtime.update('applications', newRecord, oldRecord, ctx.activeOrgId!, {\n targetRoles: ['hiring-manager']\n});\n```\n\n**Fail-closed (v0.48+):** an omitted or empty `targetRoles` delivers to\n**nobody** — there is no implicit \"everyone\" fallback. To reach every\nauthenticated subscriber in the scope, say so explicitly with\n`targetRoles: ['AUTHENTICATED']`. UPPERCASE pseudo-roles (`PUBLIC`,\n`AUTHENTICATED`, `USER`, `SYSADMIN`) are evaluated exactly as the REST access\nevaluator does.\n\n> **Migrating from pre-0.48:** custom `realtime.broadcast(...)` /\n> `realtime.insert(...)` calls that omitted `targetRoles` used to fan out to\n> everyone; they now silently deliver to nobody. Audit every manual send and add\n> an explicit audience.\n\n## Identity-Tag Targeting\n\nEvery connection carries **identity tags**, proven at ticket mint and signed\ninto the ticket (never client-supplied):\n\n- `user:<userId>` — every Better Auth caller\n- `scope:<kind>:<subjectId>` — when a scope subject is proven, on **either**\n door: a sessionless scope principal's verified claim, or a Better Auth caller\n whose matched relationship lane maps to a scope kind with\n `subject: 'supplied' | 'both'`. Both doors stamp the **identical** tag (the\n subject row's id), which is the point.\n\nTarget them with `targetTags`:\n\n```typescript\n// ONE send reaches this guest whether they're connected via their Better Auth\n// session or a sessionless scope link — no per-identity double-send.\nawait realtime.broadcast('chat.frame', payload, { scopeKey }, {\n targetTags: [`scope:guest:${guestId}`],\n targetRoles: ['AUTHENTICATED'],\n});\n\n// Reach a person under either identity explicitly (deduped per socket):\nawait realtime.broadcast('rsvp.updated', payload, { scopeKey }, {\n targetTags: [`scope:guest:${guestId}`, `user:${linkedUserId}`],\n targetRoles: ['AUTHENTICATED'],\n});\n```\n\nSemantics:\n\n- Delivery is the **deduplicated union** of the runtime's indexed tag lookup\n (`getWebSockets(tag)`) — no attachment scan, and a dual-identity socket\n matches once.\n- `targetTags` **replaces the `userId` identity arm** when present; the\n scope/org bind and the `targetRoles` audience still apply on top.\n- **Fail-closed:** `targetTags: []` delivers to nobody.\n- Tags are **immutable** for a socket's lifetime (a Workers hibernation-tag\n constraint) — an identity change requires a reconnect.\n- Limits: at most 10 tags per connection, 256 characters per tag. The mint\n rejects violations; it never truncates.\n\n## Authorization Lease\n\nThe 60-second ws-ticket is verified once, at upgrade — but Durable Object\nhibernation keeps sockets alive indefinitely. Without a lease, a ban, member\nremoval, or subject revocation (say, an organizer cancelling a guest) would\nnever affect an already-connected socket. The lease closes that gap:\n\n- At upgrade, the connection stores `authExpiresAt = ticket.iat + lease`\n (default **15 minutes**).\n- The fan-out **skips expired connections** — they receive nothing — and closes\n them with code **4401** so the client knows to re-ticket rather than blindly\n reconnect. Inbound messages (even pings) are enforced the same way.\n- Renewal happens at mint: `POST /broadcast/v1/ws-ticket` re-runs the full\n authorization gate (session validity, revocation checks, relationship /\n scope-claim probes), so a revoked principal simply can't obtain a renewal\n ticket. Revocation propagates within one lease period with no polling.\n\nConfigure it on the realtime transport:\n\n```typescript\nproviders: {\n database: {\n config: {\n realtime: {\n enabled: true,\n lease: '15m', // default; also '900s', '1h', or a number of seconds\n // lease: false // disable (discouraged — reopens the revocation gap)\n },\n },\n },\n}\n```\n\nThe lease must be at least 60 seconds (the handshake-ticket TTL).\n\n### In-place renewal (`reauth`)\n\nInstead of reconnecting every lease period, a client can renew in place: mint a\nfresh ticket and send it over the open socket.\n\n```typescript\n// On a timer comfortably inside the lease (e.g. every 10 min for a 15m lease):\nconst { wsTicket } = await mintTicket(); // POST /broadcast/v1/ws-ticket\nws.send(JSON.stringify({ type: 'reauth', ticket: wsTicket }));\n\nws.onmessage = (event) => {\n const msg = JSON.parse(event.data);\n if (msg.type === 'reauth_ok') {\n scheduleNextRenewal(msg.authExpiresAt); // lease extended, roles refreshed\n }\n if (msg.type === 'error' && msg.code === 'REAUTH_FAILED') {\n // Ticket invalid/expired — mint a fresh one and retry before the lease lapses.\n }\n};\n\nws.onclose = (event) => {\n if (event.code === 4401) {\n // Lease expired or identity drift: mint a fresh ticket and reconnect.\n reconnectWithFreshTicket();\n }\n};\n```\n\nRenewal is **strict**: the fresh ticket must carry the same `userId`,\n`scopeKey`/`organizationId`, and the **exact same tag set** as the live socket\n(tags are immutable). A renewal that matches extends the lease and refreshes\n`role`/`roles` in place — live permission changes without socket churn. One\nthat doesn't closes the socket with 4401: reconnect fresh.\n\nClients that never send `reauth` still work — their socket is closed with 4401\nonce per lease and normal reconnect logic (with a fresh ticket) re-runs the\nfull gate. The lease is the server-side invariant either way.\n\n## Per-Role Field Masking\n\nApply different field masking based on the subscriber's role using `maskingConfig`:\n\n```typescript\nawait realtime.insert('candidates', newCandidate, ctx.activeOrgId!, {\n maskingConfig: {\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n email: { type: 'email', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n resumeUrl: { type: 'redact', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n },\n});\n```\n\n**How masking works:**\n- Each subscriber receives a payload masked according to their role\n- Roles in the `show.roles` array see unmasked values\n- All other roles see the masked version\n- Masking is pre-computed per-role (O(roles) not O(subscribers))\n\n**Available mask types:**\n| Type | Example Output |\n|------|----------------|\n| `email` | `j***@y*********.com` |\n| `phone` | `******4567` |\n| `ssn` | `*****6789` |\n| `creditCard` | `**** **** **** 1111` |\n| `name` | `J***` |\n| `redact` | `[REDACTED]` |\n\n### Owner-Based Masking\n\nShow unmasked data to the record owner:\n\n```typescript\nmaskingConfig: {\n phone: {\n type: 'phone',\n show: { roles: ['hiring-manager'], or: 'owner' } // Hiring manager OR owner sees unmasked\n },\n}\n```\n\n## Client-Side Subscription\n\n### WebSocket Authentication\n\nQuickback uses **ticket-based authentication** for WebSocket connections. The client first obtains a short-lived ticket from the main API, then connects with it as a URL parameter. The Broadcaster verifies the ticket cryptographically at upgrade time — no HTTP round-trip needed.\n\n```typescript\n// 1. Get a ws-ticket from your API (requires session auth)\nconst response = await fetch('/broadcast/v1/ws-ticket', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${sessionToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ eventId: 'evt_123' }),\n});\nconst { wsTicket } = await response.json();\n\n// 2. Connect with ticket as URL param\nconst ws = new WebSocket(\n `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}`\n);\n\nws.onopen = () => {\n console.log('Connected and authenticated!');\n // No auth message needed — pre-authenticated at upgrade\n};\n```\n\nTickets expire after 60 seconds, so fetch a fresh one before each connection or reconnection.\n\n### Handling Messages\n\n```typescript\nws.onmessage = (event) => {\n const msg = JSON.parse(event.data);\n\n // Handle CRUD events\n if (msg.type === 'postgres_changes') {\n const { table, eventType, new: newRecord, old: oldRecord } = msg;\n\n if (eventType === 'INSERT') {\n addRecord(table, newRecord);\n } else if (eventType === 'UPDATE') {\n updateRecord(table, newRecord);\n } else if (eventType === 'DELETE') {\n removeRecord(table, oldRecord.id);\n }\n }\n\n // Handle custom broadcasts\n if (msg.type === 'broadcast') {\n const { event, payload } = msg;\n\n if (event === 'screening-complete') {\n refreshApplication(payload.applicationId);\n } else if (event === 'interview-scheduled') {\n showInterviewNotification(payload.applicationId);\n }\n }\n};\n```\n\n## Environment\n\nNo additional environment variables are needed for realtime. The Broadcaster DO runs inline in your main worker and uses `BETTER_AUTH_SECRET` (already required for auth) to sign and verify WebSocket tickets.\n\n| Variable | Description |\n|----------|-------------|\n| `BETTER_AUTH_SECRET` | Signs/verifies WebSocket tickets (already set for auth) |\n\nThe `BROADCASTER` binding is a `DurableObjectNamespace` — the compiler generates this in your `wrangler.toml` automatically:\n\n```toml\n[[durable_objects.bindings]]\nname = \"BROADCASTER\"\nclass_name = \"Broadcaster\"\n\n[[migrations]]\ntag = \"v1\"\nnew_classes = [\"Broadcaster\"]\n```\n\n## Architecture\n\n```\n 1. POST /ws-ticket\n┌───────────────────────────────────────────────┐ ┌─────────────────┐\n│ Quickback Worker │ ◄──│ Browser Client │\n│ │ ──►│ │\n│ ┌──────────┐ DO binding ┌────────────────┐ │ └───────┬─────────┘\n│ │ Hono API │ ───────────► │ Broadcaster DO │ │ │\n│ └──────────┘ (in-process)└───────┬────────┘ │ 2. WS ?ws_ticket=...\n│ │ │ │\n└────────────────────────────────────┼──────────┘ │\n │◄──────────────────────┘\n WebSocket (verified at upgrade)\n```\n\n1. **Client gets a ticket** — `POST /broadcast/v1/ws-ticket` on the main API (session-authenticated). Returns a 60-second HMAC-signed ticket.\n2. **Client connects** — Opens WebSocket with `?ws_ticket=<ticket>`. The Durable Object verifies the ticket cryptographically at upgrade and attaches the socket to the ticket's `scopeKey`, `organizationId`, or `userId`.\n3. **API broadcasts** — After CRUD ops, or from custom handlers, the API calls the Broadcaster DO directly via its binding (in-process, no network hop) using the same target model.\n\n## Best Practices\n\n### Broadcast After Commit\n\nAlways broadcast after the database operation succeeds:\n\n```typescript\n// Good - broadcast after successful insert\nconst [newApp] = await db.insert(applications).values(data).returning();\nawait realtime.insert('applications', newApp, ctx.activeOrgId!);\n\n// Bad - don't broadcast before confirming success\nawait realtime.insert('applications', data, ctx.activeOrgId!);\nawait db.insert(applications).values(data); // Could fail!\n```\n\n### Minimal Payloads\n\nOnly include necessary data in broadcasts:\n\n```typescript\n// Good - minimal payload\nawait realtime.update('applications',\n { id: record.id, stage: 'interview' },\n { id: record.id, stage: 'screening' },\n ctx.activeOrgId!\n);\n\n// Avoid - sending entire record with large content\nawait realtime.update('applications', fullRecord, oldRecord, ctx.activeOrgId!);\n```\n\n### Use Broadcasts for Complex Events\n\nFor events that don't map cleanly to CRUD:\n\n```typescript\n// Hiring pipeline stage completed\nawait realtime.broadcast('pipeline-stage-complete', {\n applicationId: application.id,\n stages: ['applied', 'screening', 'interview'],\n currentStage: 'offer',\n candidateId: application.candidateId\n}, ctx.activeOrgId!);\n```\n\n## Custom Event Namespaces\n\nFor complex applications with many custom events, you can define typed event namespaces using `defineRealtime`. This generates strongly-typed helper methods for your custom events.\n\n### Defining Event Namespaces\n\nCreate a file in `services/realtime/`:\n\n```typescript\n// services/realtime/screening.ts\n\nexport default defineRealtime({\n name: 'screening',\n events: ['started', 'progress', 'completed', 'failed'],\n description: 'Candidate screening pipeline events',\n});\n```\n\n### Generated Helper Methods\n\nAfter compilation, the `createRealtime()` helper includes your custom namespace:\n\n```typescript\n\nexport const execute: ActionExecutor = async ({ ctx, input }) => {\n const realtime = createRealtime(ctx.env);\n\n // Type-safe custom event methods\n await realtime.screening.started({\n applicationId: input.applicationId,\n }, ctx.activeOrgId!);\n\n // Progress updates\n await realtime.screening.progress({\n applicationId: input.applicationId,\n percent: 50,\n step: 'background-check',\n }, ctx.activeOrgId!);\n\n // Completion\n await realtime.screening.completed({\n applicationId: input.applicationId,\n result: 'passed',\n duration: 1234,\n }, ctx.activeOrgId!);\n\n return { success: true };\n};\n```\n\n### Event Format\n\nCustom namespace events use the `broadcast` type with namespaced event names:\n\n```json\n{\n \"type\": \"broadcast\",\n \"event\": \"screening:started\",\n \"payload\": {\n \"applicationId\": \"app_123\"\n }\n}\n```\n\n### Multiple Namespaces\n\nDefine multiple namespaces for different parts of your application:\n\n```typescript\n// services/realtime/notifications.ts\nexport default defineRealtime({\n name: 'notifications',\n events: ['interview-reminder', 'offer-update', 'application-received'],\n description: 'Recruitment notification events',\n});\n\n// services/realtime/presence.ts\nexport default defineRealtime({\n name: 'presence',\n events: ['joined', 'left', 'reviewing', 'idle'],\n description: 'Who is reviewing which candidate',\n});\n```\n\nUsage:\n```typescript\nconst realtime = createRealtime(ctx.env);\n\n// Notification events\nawait realtime.notifications['interview-reminder']({ ... }, ctx.activeOrgId!);\n\n// Presence events — who's reviewing which candidate\nawait realtime.presence.reviewing({ userId: ctx.userId, candidateId: 'cnd_456' }, ctx.activeOrgId!);\n```\n\n### Namespace vs Generic Broadcast\n\n| Use Case | Approach |\n|----------|----------|\n| One-off custom event | `realtime.broadcast('event-name', payload, orgId)` |\n| Repeated event patterns | `defineRealtime` namespace |\n| Type-safe events | `defineRealtime` namespace |\n| Event discovery | `defineRealtime` (appears in generated types) |"
438
+ "content": "Quickback can generate realtime notification helpers for broadcasting changes to connected clients. This enables live updates via WebSocket using Cloudflare Durable Objects.\n\nThe targeting model is shared across ws tickets, websocket attachment, and server-side broadcasts:\n\n- string target: historical `organizationId` shorthand\n- object target: `{ scopeKey?, organizationId?, userId? }`\n\nThat means the same mental model drives both `createRealtime()` and the generated Broadcaster filter path.\n\n## Enabling Realtime\n\nAdd `realtime` configuration to individual table definitions:\n\n```typescript\n// features/applications/applications.ts\n\nexport const applications = sqliteTable(\"applications\", {\n id: text(\"id\").primaryKey(),\n candidateId: text(\"candidate_id\").notNull(),\n jobId: text(\"job_id\").notNull(),\n stage: text(\"stage\").notNull(),\n organizationId: text(\"organization_id\").notNull(),\n});\n\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n realtime: {\n enabled: true, // Enable realtime broadcasts for this table\n onInsert: true, // Broadcast on INSERT (default: true)\n onUpdate: true, // Broadcast on UPDATE (default: true)\n onDelete: true, // Broadcast on DELETE (default: true)\n access: { roles: [\"recruiter\", \"hiring-manager\"] }, // Audience — MANDATORY, fail-closed\n fields: [\"id\", \"candidateId\", \"stage\"], // Fields to include (optional)\n },\n // ... guards, crud\n});\n```\n\nWhen any table has realtime enabled, the compiler generates `src/lib/realtime.ts` with helper functions for sending notifications.\n\nAt the project level, `providers.database.config.realtime` can stay boolean or become object-shaped when you need resource-scoped tickets. The mint gate accepts three authorization vocabularies via the discriminated `access` form — pick exactly one arm:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: {\n wsTicket: {\n access: { authzRole: \"attendee\" }, // authz relationship role (legacy shorthand: role: \"attendee\")\n // access: { roles: [\"member+\"] }, // org-membership roles — verifies the org role AND that the\n // // scope row is in the caller's ACTIVE org (org column required)\n // access: { fga: { relation: \"viewer\", object: \"event:{id}\" } }, // FGA relation on the scope row —\n // // same evaluator + object template as read-path access:{ fga }\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n },\n }),\n}\n```\n\nThat tells `/broadcast/v1/ws-ticket` to authenticate with Better Auth, run the declared gate against `body.eventId`, and mint a short-lived ticket scoped to the resolved `events:<id>` lane. See [Realtime → Enabling Realtime](/stack/realtime#enabling-realtime) for the full per-arm semantics; all three forms fail closed at compile time (ambiguous names living in two vocabularies, missing `auth.roleHierarchy` for `+`, missing `authz.fga`, unknown FGA type/relation, missing organization column, non-tenant-scoped `scopeTable`).\n\n### Namespace-backed tickets (per-matched-lane)\n\nThe single-`role` form above authorizes the ticket through **one** relationship.\nWhen the room is gated by an [authz namespace](/compiler/definitions/scopes#mintscope-mint-the-scope-token-from-the-namespace-resolver)\nwith a **multi-lane `via:`** — e.g. an event reachable by attendees, organizers,\ncontractors, *and* org admins — point the ticket at the namespace instead, and it\nauthorizes through the namespace's full `via` (per-matched-lane):\n\n```typescript\nrealtime: {\n wsTicket: {\n namespace: \"eventScope\", // authorize via this namespace's full multi-lane `via`\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n},\n```\n\n`/broadcast/v1/ws-ticket` now runs the **same first-match-wins gate** the\nnamespace uses, and issues the ticket for whichever lane matched:\n\n| Caller matched via | Ticket role |\n|---|---|\n| `attendeeOf` (relationship lane) | `attendee` |\n| `organizerOf` | `organizer` |\n| `contractorOf` | `contractor` |\n| `{ roles: [\"admin\",\"owner\"] }` (bulk lane) | the caller's **org/membership roles** — no scope role |\n\nThis closes the gap where the single-`role` form denied (`403`) an org admin who\ncould legitimately reach the room through the bulk lane but isn't a confirmed\nattendee — their realtime socket now opens.\n\n## When auto-broadcast fires (and when you call it manually)\n\nQuickback emits auto-broadcasts in **only one place**: the generated CRUD route handlers (`POST /` create, `PATCH /:id` update, `DELETE /:id` delete) for resources that **explicitly declare** a `realtime.enabled` block. The project-level `dbConfig.realtime` switch wires the *transport* (Broadcaster DO + ws-ticket route) but does **not** auto-enable broadcasting on any resource — broadcasting is opt-in per resource, like CRUD. Those handlers wrap each successful write with a `realtime.insert / update / delete` call before responding.\n\nAuto-broadcasts carry the table's declared gates: the `realtime.access.roles`\naudience (or the deprecated `requiredRoles` alias) becomes the broadcast's\n`targetRoles` (with role-hierarchy `+` expanded and UPPERCASE pseudo-roles like\n`PUBLIC`/`USER` evaluated at fanout exactly as REST evaluates them), and the\ntable's effective masking config —\ndeclared plus auto-detected sensitive columns — is applied per subscriber\nrole at fanout, matching what the HTTP routes mask. A `type: 'custom'` mask\nfunction can't be replicated by the Broadcaster, so those columns broadcast\nas `[REDACTED]` (fail closed). Tables that declare neither broadcast openly,\nas before.\n\nEverywhere else — action handlers, queue consumers, scheduled jobs, custom Hono routes — you broadcast manually. In action handlers on realtime-enabled projects, Quickback now injects a typed `realtime` helper directly into `execute(...)`; outside actions you still call `createRealtime(env)` yourself.\n\n| Mutation site | Auto-broadcast? | Why |\n|---|---|---|\n| Generated CRUD route (`POST /`, `PATCH /:id`, `DELETE /:id`) | Yes | The compiler emits the call after the write returns. |\n| Generated batch route (`/batch/...`) | Yes | Same pattern, emitted per record. |\n| `scoped.insert/update/delete` inside an action handler | No — manual | Scoped-db is a query-shape wrapper (firewall + soft-delete WHERE injection). It deliberately has no side-effects so explicit handlers can write multiple records, conditionally roll back, etc. without surprise broadcasts. |\n| `unsafeDb` writes in actions (or any custom route) | No — manual | Same reasoning — `unsafeDb` is the un-wrapped escape hatch. |\n| Queue consumers, cron jobs, webhook handlers | No — manual | These run outside the CRUD path entirely. |\n\nThe rule of thumb: if your code calls `db.insert(...)` / `scoped.insert(...)` directly, you also call `realtime.insert(...)` directly on the next line. Otherwise the cross-tab live-update you wired up in the SPA won't fire.\n\n## Generated Helper\n\nAction handlers on realtime-enabled projects receive a typed `realtime` param. The underlying `createRealtime()` factory still powers it and remains the API to use from queues, cron jobs, and other non-action code:\n\n```typescript\nexport const execute: ActionExecutor = async ({ db, ctx, input, realtime }) => {\n // After creating a record\n await realtime.insert('applications', newApplication, ctx.activeOrgId!);\n\n // After updating a record\n await realtime.update('applications', newApplication, oldApplication, ctx.activeOrgId!);\n\n // After deleting a record\n await realtime.delete('applications', { id: applicationId }, ctx.activeOrgId!);\n\n return { success: true };\n};\n```\n\n`env` is also typed in action handlers, so custom bindings like R2, D1, Queues, Durable Objects, and auth env vars no longer need `(env as any)` casts.\n\nFor explicit targeting, pass an object instead of the historical org string:\n\n```typescript\nawait realtime.broadcast(\"event-page-updated\", payload, {\n scopeKey: `events:${input.eventId}`,\n});\n\nawait realtime.broadcast(\"dm\", payload, {\n userId: recipientId,\n});\n```\n\n## Event Format\n\nQuickback broadcasts events in a structured JSON format for easy client-side handling.\n\n### Insert Event\n\n```typescript\nawait realtime.insert('applications', {\n id: 'app_123',\n candidateId: 'cnd_456',\n stage: 'applied'\n}, ctx.activeOrgId!);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"INSERT\",\n \"schema\": \"public\",\n \"new\": {\n \"id\": \"app_123\",\n \"candidateId\": \"cnd_456\",\n \"stage\": \"applied\"\n },\n \"old\": null\n}\n```\n\n### Update Event\n\n```typescript\nawait realtime.update('applications',\n { id: 'app_123', stage: 'interview' }, // new\n { id: 'app_123', stage: 'screening' }, // old\n ctx.activeOrgId!\n);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"UPDATE\",\n \"schema\": \"public\",\n \"new\": { \"id\": \"app_123\", \"stage\": \"interview\" },\n \"old\": { \"id\": \"app_123\", \"stage\": \"screening\" }\n}\n```\n\n### Delete Event\n\n```typescript\nawait realtime.delete('applications',\n { id: 'app_123' },\n ctx.activeOrgId!\n);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"DELETE\",\n \"schema\": \"public\",\n \"new\": null,\n \"old\": { \"id\": \"app_123\" }\n}\n```\n\n## Custom Broadcasts\n\nFor arbitrary events that don't map to CRUD operations:\n\n```typescript\nawait realtime.broadcast('screening-complete', {\n applicationId: 'app_123',\n candidateId: 'cnd_456',\n stage: 'interview'\n}, ctx.activeOrgId!, {\n targetRoles: ['AUTHENTICATED'],\n});\n```\n\n**Every send needs an audience.** Delivery is fail-closed: a broadcast whose\n`targetRoles` is omitted or empty reaches **nobody**. \"Everyone in the room\" is\nspelled explicitly — `targetRoles: ['AUTHENTICATED']` (any authenticated\nsubscriber) or `['PUBLIC']`.\n\nBroadcasts:\n```json\n{\n \"type\": \"broadcast\",\n \"event\": \"screening-complete\",\n \"payload\": {\n \"applicationId\": \"app_123\",\n \"candidateId\": \"cnd_456\",\n \"stage\": \"interview\"\n }\n}\n```\n\n## User-Specific Broadcasts\n\nTarget a specific user instead of the entire organization:\n\n```typescript\n// Only this user receives the notification\nawait realtime.insert('notifications', newNotification, ctx.activeOrgId!, {\n userId: ctx.userId,\n targetRoles: ['AUTHENTICATED'],\n});\n\n// Notify a hiring manager of a new application\nawait realtime.broadcast('application-received', {\n applicationId: 'app_123',\n jobId: 'job_789'\n}, ctx.activeOrgId!, {\n userId: hiringManagerId,\n targetRoles: ['AUTHENTICATED'],\n});\n```\n\n`userId` targeting matches the **socket identity** — the Better Auth user id, or\nthe synthetic `scope:<subjectId>` principal for sessionless scope connections. If\nthe same person can connect through either door, prefer\n[identity-tag targeting](#identity-tag-targeting) — one send reaches both.\n\n## Role-Based Filtering\n\nLimit which roles receive a broadcast using `targetRoles`:\n\n```typescript\n// Only hiring managers and recruiters receive this broadcast\nawait realtime.insert('applications', application, ctx.activeOrgId!, {\n targetRoles: ['hiring-manager', 'recruiter']\n});\n\n// Interviewers only see applications assigned to them\nawait realtime.update('applications', newRecord, oldRecord, ctx.activeOrgId!, {\n targetRoles: ['hiring-manager']\n});\n```\n\n**Fail-closed (v0.48+):** an omitted or empty `targetRoles` delivers to\n**nobody** — there is no implicit \"everyone\" fallback. To reach every\nauthenticated subscriber in the scope, say so explicitly with\n`targetRoles: ['AUTHENTICATED']`. UPPERCASE pseudo-roles (`PUBLIC`,\n`AUTHENTICATED`, `USER`, `SYSADMIN`) are evaluated exactly as the REST access\nevaluator does.\n\n> **Migrating from pre-0.48:** custom `realtime.broadcast(...)` /\n> `realtime.insert(...)` calls that omitted `targetRoles` used to fan out to\n> everyone; they now silently deliver to nobody. Audit every manual send and add\n> an explicit audience.\n\n## Identity-Tag Targeting\n\nEvery connection carries **identity tags**, proven at ticket mint and signed\ninto the ticket (never client-supplied):\n\n- `user:<userId>` — every Better Auth caller\n- `scope:<kind>:<subjectId>` — when a scope subject is proven, on **either**\n door: a sessionless scope principal's verified claim, or a Better Auth caller\n whose matched relationship lane maps to a scope kind with\n `subject: 'supplied' | 'both'`. Both doors stamp the **identical** tag (the\n subject row's id), which is the point.\n\nTarget them with `targetTags`:\n\n```typescript\n// ONE send reaches this guest whether they're connected via their Better Auth\n// session or a sessionless scope link — no per-identity double-send.\nawait realtime.broadcast('chat.frame', payload, { scopeKey }, {\n targetTags: [`scope:guest:${guestId}`],\n targetRoles: ['AUTHENTICATED'],\n});\n\n// Reach a person under either identity explicitly (deduped per socket):\nawait realtime.broadcast('rsvp.updated', payload, { scopeKey }, {\n targetTags: [`scope:guest:${guestId}`, `user:${linkedUserId}`],\n targetRoles: ['AUTHENTICATED'],\n});\n```\n\nSemantics:\n\n- Delivery is the **deduplicated union** of the runtime's indexed tag lookup\n (`getWebSockets(tag)`) — no attachment scan, and a dual-identity socket\n matches once.\n- `targetTags` **replaces the `userId` identity arm** when present; the\n scope/org bind and the `targetRoles` audience still apply on top.\n- **Fail-closed:** `targetTags: []` delivers to nobody.\n- Tags are **immutable** for a socket's lifetime (a Workers hibernation-tag\n constraint) — an identity change requires a reconnect.\n- Limits: at most 10 tags per connection, 256 characters per tag. The mint\n rejects violations; it never truncates.\n\n## Authorization Lease\n\nThe 60-second ws-ticket is verified once, at upgrade — but Durable Object\nhibernation keeps sockets alive indefinitely. Without a lease, a ban, member\nremoval, or subject revocation (say, an organizer cancelling a guest) would\nnever affect an already-connected socket. The lease closes that gap:\n\n- At upgrade, the connection stores `authExpiresAt = ticket.iat + lease`\n (default **15 minutes**).\n- The fan-out **skips expired connections** — they receive nothing — and closes\n them with code **4401** so the client knows to re-ticket rather than blindly\n reconnect. Inbound messages (even pings) are enforced the same way.\n- Renewal happens at mint: `POST /broadcast/v1/ws-ticket` re-runs the full\n authorization gate (session validity, revocation checks, relationship /\n scope-claim probes), so a revoked principal simply can't obtain a renewal\n ticket. Revocation propagates within one lease period with no polling.\n\nConfigure it on the realtime transport:\n\n```typescript\nproviders: {\n database: {\n config: {\n realtime: {\n enabled: true,\n lease: '15m', // default; also '900s', '1h', or a number of seconds\n // lease: false // disable (discouraged — reopens the revocation gap)\n },\n },\n },\n}\n```\n\nThe lease must be at least 60 seconds (the handshake-ticket TTL).\n\n### In-place renewal (`reauth`)\n\nInstead of reconnecting every lease period, a client can renew in place: mint a\nfresh ticket and send it over the open socket.\n\n```typescript\n// On a timer comfortably inside the lease (e.g. every 10 min for a 15m lease):\nconst { wsTicket } = await mintTicket(); // POST /broadcast/v1/ws-ticket\nws.send(JSON.stringify({ type: 'reauth', ticket: wsTicket }));\n\nws.onmessage = (event) => {\n const msg = JSON.parse(event.data);\n if (msg.type === 'reauth_ok') {\n scheduleNextRenewal(msg.authExpiresAt); // lease extended, roles refreshed\n }\n if (msg.type === 'error' && msg.code === 'REAUTH_FAILED') {\n // Ticket invalid/expired — mint a fresh one and retry before the lease lapses.\n }\n};\n\nws.onclose = (event) => {\n if (event.code === 4401) {\n // Lease expired or identity drift: mint a fresh ticket and reconnect.\n reconnectWithFreshTicket();\n }\n};\n```\n\nRenewal is **strict**: the fresh ticket must carry the same `userId`,\n`scopeKey`/`organizationId`, and the **exact same tag set** as the live socket\n(tags are immutable). A renewal that matches extends the lease and refreshes\n`role`/`roles` in place — live permission changes without socket churn. One\nthat doesn't closes the socket with 4401: reconnect fresh.\n\nClients that never send `reauth` still work — their socket is closed with 4401\nonce per lease and normal reconnect logic (with a fresh ticket) re-runs the\nfull gate. The lease is the server-side invariant either way.\n\n## Per-Role Field Masking\n\nApply different field masking based on the subscriber's role using `maskingConfig`:\n\n```typescript\nawait realtime.insert('candidates', newCandidate, ctx.activeOrgId!, {\n maskingConfig: {\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n email: { type: 'email', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n resumeUrl: { type: 'redact', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n },\n});\n```\n\n**How masking works:**\n- Each subscriber receives a payload masked according to their role\n- Roles in the `show.roles` array see unmasked values\n- All other roles see the masked version\n- Masking is pre-computed per-role (O(roles) not O(subscribers))\n\n**Available mask types:**\n| Type | Example Output |\n|------|----------------|\n| `email` | `j***@y*********.com` |\n| `phone` | `******4567` |\n| `ssn` | `*****6789` |\n| `creditCard` | `**** **** **** 1111` |\n| `name` | `J***` |\n| `redact` | `[REDACTED]` |\n\n### Owner-Based Masking\n\nShow unmasked data to the record owner:\n\n```typescript\nmaskingConfig: {\n phone: {\n type: 'phone',\n show: { roles: ['hiring-manager'], or: 'owner' } // Hiring manager OR owner sees unmasked\n },\n}\n```\n\n## Client-Side Subscription\n\n### WebSocket Authentication\n\nQuickback uses **ticket-based authentication** for WebSocket connections. The client first obtains a short-lived ticket from the main API, then connects with it as a URL parameter. The Broadcaster verifies the ticket cryptographically at upgrade time — no HTTP round-trip needed.\n\n```typescript\n// 1. Get a ws-ticket from your API (requires session auth)\nconst response = await fetch('/broadcast/v1/ws-ticket', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${sessionToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ eventId: 'evt_123' }),\n});\nconst { wsTicket } = await response.json();\n\n// 2. Connect with ticket as URL param\nconst ws = new WebSocket(\n `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}`\n);\n\nws.onopen = () => {\n console.log('Connected and authenticated!');\n // No auth message needed — pre-authenticated at upgrade\n};\n```\n\nTickets expire after 60 seconds, so fetch a fresh one before each connection or reconnection.\n\n### Handling Messages\n\n```typescript\nws.onmessage = (event) => {\n const msg = JSON.parse(event.data);\n\n // Handle CRUD events\n if (msg.type === 'postgres_changes') {\n const { table, eventType, new: newRecord, old: oldRecord } = msg;\n\n if (eventType === 'INSERT') {\n addRecord(table, newRecord);\n } else if (eventType === 'UPDATE') {\n updateRecord(table, newRecord);\n } else if (eventType === 'DELETE') {\n removeRecord(table, oldRecord.id);\n }\n }\n\n // Handle custom broadcasts\n if (msg.type === 'broadcast') {\n const { event, payload } = msg;\n\n if (event === 'screening-complete') {\n refreshApplication(payload.applicationId);\n } else if (event === 'interview-scheduled') {\n showInterviewNotification(payload.applicationId);\n }\n }\n};\n```\n\n## Environment\n\nNo additional environment variables are needed for realtime. The Broadcaster DO runs inline in your main worker and uses `BETTER_AUTH_SECRET` (already required for auth) to sign and verify WebSocket tickets.\n\n| Variable | Description |\n|----------|-------------|\n| `BETTER_AUTH_SECRET` | Signs/verifies WebSocket tickets (already set for auth) |\n\nThe `BROADCASTER` binding is a `DurableObjectNamespace` — the compiler generates this in your `wrangler.toml` automatically:\n\n```toml\n[[durable_objects.bindings]]\nname = \"BROADCASTER\"\nclass_name = \"Broadcaster\"\n\n[[migrations]]\ntag = \"v1\"\nnew_classes = [\"Broadcaster\"]\n```\n\n## Architecture\n\n```\n 1. POST /ws-ticket\n┌───────────────────────────────────────────────┐ ┌─────────────────┐\n│ Quickback Worker │ ◄──│ Browser Client │\n│ │ ──►│ │\n│ ┌──────────┐ DO binding ┌────────────────┐ │ └───────┬─────────┘\n│ │ Hono API │ ───────────► │ Broadcaster DO │ │ │\n│ └──────────┘ (in-process)└───────┬────────┘ │ 2. WS ?ws_ticket=...\n│ │ │ │\n└────────────────────────────────────┼──────────┘ │\n │◄──────────────────────┘\n WebSocket (verified at upgrade)\n```\n\n1. **Client gets a ticket** — `POST /broadcast/v1/ws-ticket` on the main API (session-authenticated). Returns a 60-second HMAC-signed ticket.\n2. **Client connects** — Opens WebSocket with `?ws_ticket=<ticket>`. The Durable Object verifies the ticket cryptographically at upgrade and attaches the socket to the ticket's `scopeKey`, `organizationId`, or `userId`.\n3. **API broadcasts** — After CRUD ops, or from custom handlers, the API calls the Broadcaster DO directly via its binding (in-process, no network hop) using the same target model.\n\n## Best Practices\n\n### Broadcast After Commit\n\nAlways broadcast after the database operation succeeds:\n\n```typescript\n// Good - broadcast after successful insert\nconst [newApp] = await db.insert(applications).values(data).returning();\nawait realtime.insert('applications', newApp, ctx.activeOrgId!);\n\n// Bad - don't broadcast before confirming success\nawait realtime.insert('applications', data, ctx.activeOrgId!);\nawait db.insert(applications).values(data); // Could fail!\n```\n\n### Minimal Payloads\n\nOnly include necessary data in broadcasts:\n\n```typescript\n// Good - minimal payload\nawait realtime.update('applications',\n { id: record.id, stage: 'interview' },\n { id: record.id, stage: 'screening' },\n ctx.activeOrgId!\n);\n\n// Avoid - sending entire record with large content\nawait realtime.update('applications', fullRecord, oldRecord, ctx.activeOrgId!);\n```\n\n### Use Broadcasts for Complex Events\n\nFor events that don't map cleanly to CRUD:\n\n```typescript\n// Hiring pipeline stage completed\nawait realtime.broadcast('pipeline-stage-complete', {\n applicationId: application.id,\n stages: ['applied', 'screening', 'interview'],\n currentStage: 'offer',\n candidateId: application.candidateId\n}, ctx.activeOrgId!);\n```\n\n## Custom Event Namespaces\n\nFor complex applications with many custom events, you can define typed event namespaces using `defineRealtime`. This generates strongly-typed helper methods for your custom events.\n\n### Defining Event Namespaces\n\nCreate a file in `services/realtime/`:\n\n```typescript\n// services/realtime/screening.ts\n\nexport default defineRealtime({\n name: 'screening',\n events: ['started', 'progress', 'completed', 'failed'],\n description: 'Candidate screening pipeline events',\n});\n```\n\n### Generated Helper Methods\n\nAfter compilation, the `createRealtime()` helper includes your custom namespace:\n\n```typescript\n\nexport const execute: ActionExecutor = async ({ ctx, input }) => {\n const realtime = createRealtime(ctx.env);\n\n // Type-safe custom event methods\n await realtime.screening.started({\n applicationId: input.applicationId,\n }, ctx.activeOrgId!);\n\n // Progress updates\n await realtime.screening.progress({\n applicationId: input.applicationId,\n percent: 50,\n step: 'background-check',\n }, ctx.activeOrgId!);\n\n // Completion\n await realtime.screening.completed({\n applicationId: input.applicationId,\n result: 'passed',\n duration: 1234,\n }, ctx.activeOrgId!);\n\n return { success: true };\n};\n```\n\n### Event Format\n\nCustom namespace events use the `broadcast` type with namespaced event names:\n\n```json\n{\n \"type\": \"broadcast\",\n \"event\": \"screening:started\",\n \"payload\": {\n \"applicationId\": \"app_123\"\n }\n}\n```\n\n### Multiple Namespaces\n\nDefine multiple namespaces for different parts of your application:\n\n```typescript\n// services/realtime/notifications.ts\nexport default defineRealtime({\n name: 'notifications',\n events: ['interview-reminder', 'offer-update', 'application-received'],\n description: 'Recruitment notification events',\n});\n\n// services/realtime/presence.ts\nexport default defineRealtime({\n name: 'presence',\n events: ['joined', 'left', 'reviewing', 'idle'],\n description: 'Who is reviewing which candidate',\n});\n```\n\nUsage:\n```typescript\nconst realtime = createRealtime(ctx.env);\n\n// Notification events\nawait realtime.notifications['interview-reminder']({ ... }, ctx.activeOrgId!);\n\n// Presence events — who's reviewing which candidate\nawait realtime.presence.reviewing({ userId: ctx.userId, candidateId: 'cnd_456' }, ctx.activeOrgId!);\n```\n\n### Namespace vs Generic Broadcast\n\n| Use Case | Approach |\n|----------|----------|\n| One-off custom event | `realtime.broadcast('event-name', payload, orgId)` |\n| Repeated event patterns | `defineRealtime` namespace |\n| Type-safe events | `defineRealtime` namespace |\n| Event discovery | `defineRealtime` (appears in generated types) |"
439
439
  },
440
440
  "stack/realtime": {
441
441
  "title": "Realtime",
442
- "content": "Quickback ships **two parallel realtime primitives**, both backed by Cloudflare Durable Objects:\n\n- **`/broadcast/v1/*` — server fan-out.** One DO instance per subscription scope. Postgres-changes events from CRUD routes plus custom broadcast events flow out to every subscriber, with role filtering and per-role field masking applied. Best for \"tell every client in this shared scope that something changed.\" The scope can be an organization, a specific user, or a compiler-resolved resource key like `events:evt_123`. Documented on this page.\n- **`/realtime/<binding>/<room-id>` — bidirectional rooms.** One DO instance per room (per document, per interview, per game). Client↔client messages, presence, and CRDT-friendly state. Use these for collaborative editing. See [PartyServer rooms](/stack/realtime/partyserver-rooms).\n\nBoth share the same auth model and ride on the same compiled worker; they solve different problems.\n\n## Architecture\n\n```\n┌──────────────────────────────────────────┐\n│ Quickback Worker │\n│ │\n│ ┌──────────┐ DO binding ┌────────────────────┐\n│ │ Hono API │ ──────────────► │ Broadcaster (DO) │\n│ │ │ │ WebSocket manager │\n│ └──────────┘ └─────────┬──────────┘\n│ │\n└─────────────────────────────────────────┼┘\n │ WebSocket\n │\n ┌────────▼─────────┐\n │ Browser Clients │\n │ (CMS, Account, │\n │ Admin, Custom) │\n └──────────────────┘\n```\n\nThe Broadcaster Durable Object runs **inline** in your main Quickback worker — no separate worker deployment needed. The API calls the DO directly via its binding (in-process, no network hop).\n\n1. **Quickback Worker** — Your compiled API with the Broadcaster DO class exported from the same worker.\n2. **Broadcaster (Durable Object)** — Manages WebSocket connections per subscription scope. One instance per `scopeKey`, organization, or user lane.\n3. **Browser Clients** — CMS, Account, Admin, and custom frontends connect via WebSocket on the same origin.\n\n## Key Features\n\n| Feature | Description |\n|---------|-------------|\n| Scope-aware fan-out | Routes by `scopeKey`, `organizationId`, or `userId` |\n| Role-based filtering | Only send events to users with matching roles |\n| Per-role masking | Different users see different field values based on their role |\n| User-specific targeting | Send events to a specific user within an org |\n| Resource-scoped tickets | Reuse authz relationship roles to mint scope-bound ws tickets |\n| Custom broadcasts | Arbitrary events beyond CRUD |\n| Custom namespaces | `defineRealtime()` for type-safe event helpers |\n| Ticket-based auth | HMAC-signed tickets verified at WebSocket upgrade — no HTTP round-trip |\n\n## Enabling Realtime\n\nBroadcasting is **opt-in per resource**, exactly like CRUD — a table broadcasts\nonly if it declares its own `realtime` block. Add `realtime` to individual table\ndefinitions:\n\n```typescript\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n realtime: {\n enabled: true,\n onInsert: true,\n onUpdate: true,\n onDelete: true,\n // Audience — WHO may receive these live rows. Same { roles } shape as\n // read.access / crud.*.access. MANDATORY and fail-closed: a broadcast\n // reaches every subscriber in the room, so the audience is not optional.\n // Omit it (or leave it empty) and compilation fails. Roles may be concrete\n // membership/scope roles or UPPERCASE pseudo-roles.\n access: { roles: [\"recruiter\", \"hiring-manager\"] },\n fields: [\"id\", \"candidateId\", \"stage\"],\n },\n});\n```\n\nAnd enable the realtime **transport** in your database config. This is a\nproject-level switch that stands up the Broadcaster Durable Object + the\nconnection route; it does **not** by itself make any resource broadcast\n(that's the per-resource `realtime` block above). The compiler generates the\nDurable Object class, helper functions, and wrangler bindings — all within\nyour main worker.\n\nFor most apps — including org-scoped apps like chat, feeds, and dashboards —\nthe boolean form is all you need. Session-authenticated members subscribe\ndirectly; audiences come from each resource's `realtime.access.roles`:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: true,\n }),\n}\n```\n\nThe object form is the **advanced** variant, only needed when you mint\nresource-scoped tickets for relationship-authorized subscribers (e.g. an\nexternal attendee who may join one event's channel). `wsTicket.role` must be\nan `authz.roles` relationship role — NOT an org-membership role like\n`member`/`admin`/`owner` (those names are reserved and will not compile here):\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: {\n wsTicket: {\n role: \"attendee\", // authz relationship role, not an org role\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n },\n }),\n}\n```\n\nWith that config, `/broadcast/v1/ws-ticket` can authenticate the caller, verify the declared authz relationship role against `body.eventId`, and mint a short-lived ticket scoped to the resolved `events:<id>` channel.\n\n## Pages\n\n- **[Durable Objects Setup](/stack/realtime/durable-objects)** — Broadcaster configuration, wrangler bindings, event formats, masking, and custom namespaces\n- **[Using Realtime](/stack/realtime/using-realtime)** — Subscribing to `/broadcast/v1/*`: WebSocket connection, ticket auth, client-side handling\n- **[PartyServer Rooms](/stack/realtime/partyserver-rooms)** — Per-room collab via `/realtime/<binding>/<room-id>`: presence, live notes, room IDs"
442
+ "content": "Quickback ships **two parallel realtime primitives**, both backed by Cloudflare Durable Objects:\n\n- **`/broadcast/v1/*` — server fan-out.** One DO instance per subscription scope. Postgres-changes events from CRUD routes plus custom broadcast events flow out to every subscriber, with role filtering and per-role field masking applied. Best for \"tell every client in this shared scope that something changed.\" The scope can be an organization, a specific user, or a compiler-resolved resource key like `events:evt_123`. Documented on this page.\n- **`/realtime/<binding>/<room-id>` — bidirectional rooms.** One DO instance per room (per document, per interview, per game). Client↔client messages, presence, and CRDT-friendly state. Use these for collaborative editing. See [PartyServer rooms](/stack/realtime/partyserver-rooms).\n\nBoth share the same auth model and ride on the same compiled worker; they solve different problems.\n\n## Architecture\n\n```\n┌──────────────────────────────────────────┐\n│ Quickback Worker │\n│ │\n│ ┌──────────┐ DO binding ┌────────────────────┐\n│ │ Hono API │ ──────────────► │ Broadcaster (DO) │\n│ │ │ │ WebSocket manager │\n│ └──────────┘ └─────────┬──────────┘\n│ │\n└─────────────────────────────────────────┼┘\n │ WebSocket\n │\n ┌────────▼─────────┐\n │ Browser Clients │\n │ (CMS, Account, │\n │ Admin, Custom) │\n └──────────────────┘\n```\n\nThe Broadcaster Durable Object runs **inline** in your main Quickback worker — no separate worker deployment needed. The API calls the DO directly via its binding (in-process, no network hop).\n\n1. **Quickback Worker** — Your compiled API with the Broadcaster DO class exported from the same worker.\n2. **Broadcaster (Durable Object)** — Manages WebSocket connections per subscription scope. One instance per `scopeKey`, organization, or user lane.\n3. **Browser Clients** — CMS, Account, Admin, and custom frontends connect via WebSocket on the same origin.\n\n## Key Features\n\n| Feature | Description |\n|---------|-------------|\n| Scope-aware fan-out | Routes by `scopeKey`, `organizationId`, or `userId` |\n| Role-based filtering | Only send events to users with matching roles |\n| Per-role masking | Different users see different field values based on their role |\n| User-specific targeting | Send events to a specific user within an org |\n| Resource-scoped tickets | Mint scope-bound ws tickets gated by org-membership roles, authz relationship roles, or FGA relations |\n| Custom broadcasts | Arbitrary events beyond CRUD |\n| Custom namespaces | `defineRealtime()` for type-safe event helpers |\n| Ticket-based auth | HMAC-signed tickets verified at WebSocket upgrade — no HTTP round-trip |\n\n## Enabling Realtime\n\nBroadcasting is **opt-in per resource**, exactly like CRUD — a table broadcasts\nonly if it declares its own `realtime` block. Add `realtime` to individual table\ndefinitions:\n\n```typescript\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n realtime: {\n enabled: true,\n onInsert: true,\n onUpdate: true,\n onDelete: true,\n // Audience — WHO may receive these live rows. Same { roles } shape as\n // read.access / crud.*.access. MANDATORY and fail-closed: a broadcast\n // reaches every subscriber in the room, so the audience is not optional.\n // Omit it (or leave it empty) and compilation fails. Roles may be concrete\n // membership/scope roles or UPPERCASE pseudo-roles.\n access: { roles: [\"recruiter\", \"hiring-manager\"] },\n fields: [\"id\", \"candidateId\", \"stage\"],\n },\n});\n```\n\nAnd enable the realtime **transport** in your database config. This is a\nproject-level switch that stands up the Broadcaster Durable Object + the\nconnection route; it does **not** by itself make any resource broadcast\n(that's the per-resource `realtime` block above). The compiler generates the\nDurable Object class, helper functions, and wrangler bindings — all within\nyour main worker.\n\nFor most apps — including org-scoped apps like chat, feeds, and dashboards —\nthe boolean form is all you need. Session-authenticated members subscribe\ndirectly; audiences come from each resource's `realtime.access.roles`:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: true,\n }),\n}\n```\n\nThe object form is the **advanced** variant, only needed when you mint\nresource-scoped tickets (e.g. an external attendee who may join one event's\nchannel, or an org member who may join one project's room). The mint gate is\ndeclared with `wsTicket.access`, a discriminated union — the arm names the\nauthorization vocabulary, so a bare name can never silently mean two things:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: {\n wsTicket: {\n // Pick EXACTLY ONE arm:\n access: { roles: [\"member+\"] }, // org-membership roles (hierarchy expands)\n // access: { authzRole: \"attendee\" }, // authz relationship role\n // access: { fga: { relation: \"viewer\", object: \"event:{id}\" } }, // FGA relation on the scope row\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n },\n }),\n}\n```\n\n- **`{ roles }` — org-membership roles.** `\"member+\"` expands via\n `auth.roleHierarchy` (compile error without it). Firewall-consistent: the\n route verifies the caller's org role **and** that the requested `scopeTable`\n row belongs to the caller's *active* organization — an org-A member cannot\n mint a ticket to org B's room. The scope table must therefore carry an\n organization column (compile error otherwise). UPPERCASE pseudo-roles are\n rejected here: a `PUBLIC`/`AUTHENTICATED` ticket factory would hand signed\n room credentials to callers with no org standing.\n- **`{ authzRole }` — a declared `authz.roles` relationship role** (`{ via }`).\n The route probes the relationship table against `body.eventId`; the ticket\n carries the relationship role (e.g. `attendee`). The legacy\n `role: \"attendee\"` string is the back-compat shorthand for this arm and\n compiles identically. Org-membership names (`member`/`admin`/`owner`) are\n still rejected in this arm — spell those `access: { roles: [...] }`.\n- **`{ fga }` — an FGA relation.** The route loads the `scopeTable` row through\n its own firewall (tenant bind), derives the object from the template\n (`\"event:{id}\"` — `{field}` tokens read from the row, the same template\n language as the read path's `access: { fga }`), and requires the caller to\n hold `relation` on it via the same org-scoped check evaluator the read path\n uses. Requires `authz.fga`; the object type and relation are validated\n against the model at compile time.\n\nWhichever arm you pick, `/broadcast/v1/ws-ticket` authenticates the caller,\nruns that gate against `body.eventId`, and mints a short-lived ticket scoped to\nthe resolved `events:<id>` channel. Everything fails closed at compile time:\na bare name that exists in more than one vocabulary is an ambiguity error\ndemanding the explicit arm, and a missing hierarchy, missing FGA model, or\nmissing organization column fails the build with an actionable message.\n\n## Pages\n\n- **[Durable Objects Setup](/stack/realtime/durable-objects)** — Broadcaster configuration, wrangler bindings, event formats, masking, and custom namespaces\n- **[Using Realtime](/stack/realtime/using-realtime)** — Subscribing to `/broadcast/v1/*`: WebSocket connection, ticket auth, client-side handling\n- **[PartyServer Rooms](/stack/realtime/partyserver-rooms)** — Per-room collab via `/realtime/<binding>/<room-id>`: presence, live notes, room IDs"
443
443
  },
444
444
  "stack/realtime/live-views": {
445
445
  "title": "Live Views",