@quickback-dev/cli 0.50.3 → 0.50.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/dist/commands/deploy.d.ts +29 -0
  2. package/dist/commands/deploy.d.ts.map +1 -0
  3. package/dist/commands/deploy.js +324 -0
  4. package/dist/commands/deploy.js.map +1 -0
  5. package/dist/docs/content.d.ts.map +1 -1
  6. package/dist/docs/content.js +22 -17
  7. package/dist/docs/content.js.map +1 -1
  8. package/dist/index.js +10 -1
  9. package/dist/index.js.map +1 -1
  10. package/dist/lib/config-id-splice.d.ts +68 -0
  11. package/dist/lib/config-id-splice.d.ts.map +1 -0
  12. package/dist/lib/config-id-splice.js +364 -0
  13. package/dist/lib/config-id-splice.js.map +1 -0
  14. package/dist/lib/config-id-splice.test.d.ts +2 -0
  15. package/dist/lib/config-id-splice.test.d.ts.map +1 -0
  16. package/dist/lib/config-id-splice.test.js +246 -0
  17. package/dist/lib/config-id-splice.test.js.map +1 -0
  18. package/dist/lib/shell.d.ts +14 -0
  19. package/dist/lib/shell.d.ts.map +1 -1
  20. package/dist/lib/shell.js +27 -0
  21. package/dist/lib/shell.js.map +1 -1
  22. package/dist/lib/wrangler-resources.d.ts +131 -0
  23. package/dist/lib/wrangler-resources.d.ts.map +1 -0
  24. package/dist/lib/wrangler-resources.js +355 -0
  25. package/dist/lib/wrangler-resources.js.map +1 -0
  26. package/dist/lib/wrangler-resources.test.d.ts +2 -0
  27. package/dist/lib/wrangler-resources.test.d.ts.map +1 -0
  28. package/dist/lib/wrangler-resources.test.js +321 -0
  29. package/dist/lib/wrangler-resources.test.js.map +1 -0
  30. package/dist/skill/docs/changelog.md +6 -0
  31. package/dist/skill/docs/compiler/cloud-compiler/deploy.md +82 -0
  32. package/dist/skill/docs/compiler/cloud-compiler/endpoints.md +23 -0
  33. package/dist/skill/docs/compiler/cloud-compiler/local-compiler.md +2 -0
  34. package/dist/skill/docs/compiler/config/index.md +5 -0
  35. package/dist/skill/docs/compiler/config/security.md +1 -0
  36. package/dist/skill/docs/compiler/definitions/access.md +1 -0
  37. package/dist/skill/docs/compiler/definitions/actions.md +27 -1
  38. package/dist/skill/docs/compiler/definitions/encryption.md +1 -0
  39. package/dist/skill/docs/compiler/definitions/feature.md +2 -0
  40. package/dist/skill/docs/compiler/definitions/masking.md +1 -0
  41. package/dist/skill/docs/compiler/getting-started/hand-crafted.md +8 -1
  42. package/dist/skill/docs/compiler/getting-started/patterns.md +1 -1
  43. package/dist/skill/docs/compiler/targets/hono-api/database/neon.md +11 -4
  44. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/errors.md +1 -0
  45. package/dist/skill/docs/stack/account-ui/environment-variables.md +11 -0
  46. package/dist/skill/docs/stack/account-ui/with-quickback.md +2 -0
  47. package/dist/skill/docs/stack/auth/jwt-optimization.md +9 -0
  48. package/dist/skill/docs/stack/cms/connecting.md +5 -0
  49. package/dist/skill/docs/stack/realtime/index.md +23 -5
  50. package/package.json +1 -1
  51. package/src/skill/docs/changelog.md +6 -0
  52. package/src/skill/docs/compiler/cloud-compiler/deploy.md +82 -0
  53. package/src/skill/docs/compiler/cloud-compiler/endpoints.md +23 -0
  54. package/src/skill/docs/compiler/cloud-compiler/local-compiler.md +2 -0
  55. package/src/skill/docs/compiler/config/index.md +5 -0
  56. package/src/skill/docs/compiler/config/security.md +1 -0
  57. package/src/skill/docs/compiler/definitions/access.md +1 -0
  58. package/src/skill/docs/compiler/definitions/actions.md +27 -1
  59. package/src/skill/docs/compiler/definitions/encryption.md +1 -0
  60. package/src/skill/docs/compiler/definitions/feature.md +2 -0
  61. package/src/skill/docs/compiler/definitions/masking.md +1 -0
  62. package/src/skill/docs/compiler/getting-started/hand-crafted.md +8 -1
  63. package/src/skill/docs/compiler/getting-started/patterns.md +1 -1
  64. package/src/skill/docs/compiler/targets/hono-api/database/neon.md +11 -4
  65. package/src/skill/docs/compiler/targets/hono-api/using-the-api/errors.md +1 -0
  66. package/src/skill/docs/stack/account-ui/environment-variables.md +11 -0
  67. package/src/skill/docs/stack/account-ui/with-quickback.md +2 -0
  68. package/src/skill/docs/stack/auth/jwt-optimization.md +9 -0
  69. package/src/skill/docs/stack/cms/connecting.md +5 -0
  70. package/src/skill/docs/stack/realtime/index.md +23 -5
@@ -3,7 +3,7 @@
3
3
  export const DOCS = {
4
4
  "changelog": {
5
5
  "title": "Changelog",
6
- "content": "## Unreleased\n\n### Neon reads through user-anchored relationships\n\nResources readable via a multi-hop chain anchored on the caller's user id (e.g. a\nconference attendee reaching their own registrations through\n`person_account_links → people → event_people → registrations`) now work on Neon.\nDeclare the chain once with the `hops` form on an `authz.relationships` entry and\nreference it from a resource `firewall` via `{ field, via }`. Because the\ncorrelated multi-hop join reaches across intermediate tables that each `FORCE ROW\nLEVEL SECURITY`, caller-claims RLS would deny such a read to zero rows — so the\ncompiler routes **only that resource's read handlers** (collection `GET /`,\n`GET /:id`, and views) through the service-role handle (`createServiceDb`), with\nthe compiled app-layer reachability WHERE as the sole row filter. Org/owner/team\nreads are untouched (caller claims + RLS backstop); writes are unchanged. The\nswap is fail-closed — a service-handle read with no firewall WHERE is a compile\nerror. The anchor table is required to be caller-read-own on the subject column\nand service-role-write-only (a forgeable link would mint reachability to a\nvictim's data); this link-integrity check is target-independent and fails the\ncompile on **both** Neon and D1. The same config compiles identically on D1,\nwhere the app-layer WHERE was already the whole firewall. See\n[Reads through a user-anchored relationship](/compiler/targets/hono-api/database/neon#reads-through-a-user-anchored-relationship).\n\n### Neon interactive transactions via Hyperdrive\n\nA Neon project can now opt into `connectionMode: 'hyperdrive'` to run its feature\ndatabase over a Cloudflare Hyperdrive binding (`postgres.js` /\n`drizzle-orm/postgres-js`), unlocking **real interactive transactions** in\ngenerated actions: read current state, lock it (`for update`), decide in\nTypeScript, then write dependent rows — committed atomically, rolled back on\nthrow. `tx` is fully schema-typed (invalid columns fail `tsc`), the verified RLS\nclaims run as the first transaction-local statement inside the transaction (no\nleak across the connection pool), and Hyperdrive query caching is force-disabled\n(ETags cache at the correct post-auth layer). `http` mode stays the lightweight\nbatch-only default and is byte-identical; requesting `db.transaction()` outside\nhyperdrive mode is a fail-closed compile error. WebSocket mode is deprecated —\nHyperdrive supersedes it as the full-capability path. See\n[Interactive transactions](/compiler/targets/hono-api/database/neon#interactive-transactions).\n\n### Neon migration & environment tooling\n\n`environments` config maps dev/staging/prod to Neon branches + Cloudflare envs;\n`quickback canary <env>` branches the target DB, applies pending migrations to\nthe branch, diffs, and (with `--apply`) promotes — verifying schema changes\nagainst real state before they touch a live environment. Record-condition\nfirewall predicates now lower to Postgres RLS policy arms (enforced twice — app\nlayer and database). Opt-in API `contract.version` scaffolding landed (`v1`\ndefault; `v2` fail-closed pending completion).\n\n### Neon PostgreSQL reaches deploy parity with D1 (v0.50)\n\nA Neon-backed service now compiles, typechecks, migrates, and deploys with the\nsame capability surface as a D1 service — over HTTP (`@neondatabase/serverless`),\nthe Cloudflare default. There is no Hyperdrive binding and no Neon Authorize /\nJWKS configuration: the Worker verifies each caller, then writes the trusted\nuser/org/team context into transaction-local Postgres settings\n(`set_config('request.jwt.claim.sub' | 'org_id' | 'team_id', …, true)`) as the\nfirst statement of every query batch. RLS reads them through a compiler-defined\n`auth.user_id()` shim and the `get_active_org_id()` helper — **not** a persisted\n`user_sessions` mirror (which never shipped).\n\n- **Background contexts run under a service-role handle.** Queue consumers, cron\n schedules, and cross-tenant `unsafe` actions acquire `createServiceDb(env)`,\n which sets `quickback.service_role = 'true'` (all request claims cleared);\n every feature table carries a `<table>_service_role` RLS policy admitting\n exactly that context. Unsafe-action audit events are unchanged.\n- **Webhooks port to a `webhooks` Postgres schema** in the same database (no\n `WEBHOOKS_DB` binding). `webhooksBinding` is a pure enable flag on Neon; the\n D1-only `webhooksDatabaseId` / `webhooksDatabaseName` keys are rejected. The\n store is service-role-only.\n- **`.encrypted()` / `.sealed()` columns are supported** on Neon over HTTP: the\n key/vault tables fold into the journaled migration set with org-scoped and\n service-role-only RLS.\n- **Batch transactions advertise the truth.** Neon HTTP is fail-fast and\n non-transactional (`meta.transactional: false`, like D1) because\n `drizzle-orm/neon-http` has no interactive transactions; Neon WebSocket\n (Node/Bun) gets real rollback (`meta.transactional: true`).\n- **Deploy glue matches D1:** a generated `deploy` script\n (`npm run db:migrate && wrangler deploy`), a boot check asserting\n `DATABASE_URL`, `.dev.vars.example` (wrangler dev reads `.dev.vars`, not\n `.env`) gitignored, and `drizzle.config.ts` preferring\n `DATABASE_MIGRATION_URL ?? DATABASE_URL` for the privileged migration role.\n- **Fail-closed capability gates:** managed file storage (use presign-only R2),\n the Better Auth `subscriptions` plugin, raw `sqliteTable` interop sources on a\n Postgres target, and — under WebSocket mode — webhooks / unsafe actions /\n encrypted columns are all compile-time errors rather than silently-broken\n output. Mixed database providers remain unsupported.\n- **Docs corrected:** the [Neon page](/compiler/targets/hono-api/database/neon)\n no longer describes Neon Authorize, a `user_sessions` table, or Hyperdrive —\n none of which the compiler emits.\n- **Migration-journal hardening.** The role bootstrap now grants\n `quickback_admin` everything the pinned Drizzle runner's journal needs —\n database-level `CREATE` (so `CREATE SCHEMA IF NOT EXISTS drizzle` passes even\n as a no-op) plus ownership of the `drizzle` schema and\n `drizzle.__drizzle_migrations` — so routine migrates after the owner-run\n bootstrap need no owner credential. Generated Postgres migrations are also\n post-processed so a referenced composite `UNIQUE` / `PRIMARY KEY` constraint\n always precedes the foreign keys that consume it (an upgrade delta applies\n unedited instead of failing with \"no unique constraint matching given keys\").\n\n### Realtime identity tags — one send reaches a person on either auth door (v0.49)\n\nWebSocket connections now carry **identity tags**, proven at ticket mint and\nsigned into the ws-ticket (never client-supplied): `user:<userId>` for every\nBetter Auth caller, plus `scope:<kind>:<subjectId>` whenever a scope subject is\nproven — on **either** door. A sessionless scope principal's claim and a Better\nAuth caller's matched relationship lane stamp the **identical** subject-keyed\ntag (both derive from the same relationship row), so senders no longer\ndouble-send per recipient to cover `subject: 'both'` roles.\n\n- **`targetTags` on every send** (`realtime.broadcast`, `realtime.insert`, …):\n delivery is the deduplicated union of the runtime's indexed\n `getWebSockets(tag)` lookup — no per-frame attachment scan. Replaces the\n `userId` identity arm when present; the scope/org bind and `targetRoles`\n audience still apply.\n- **Fail-closed:** `targetTags: []` delivers to nobody, consistent with the\n empty-audience rule.\n- Tags are immutable for a socket's lifetime (hibernation-tag semantics);\n limits (10/socket, 256 chars) are validated at mint — rejected, never\n truncated.\n\n### Realtime authorization lease — hibernated sockets no longer outlive revocation (v0.49)\n\nA ws-ticket was verified once at upgrade, and DO hibernation kept the socket\nauthorized forever — bans, member removal, and subject revocation never touched\na live connection. Connections now carry a delivery-time **authorization\nlease** (default **15 minutes**, from ticket `iat`):\n\n- The fan-out skips expired connections (they receive nothing) and closes them\n with code **4401**; inbound messages — even pings — are enforced the same way.\n- **In-place renewal:** `{ type: \"reauth\", ticket: \"<fresh ws-ticket>\" }`\n extends the lease and refreshes roles without socket churn. Renewal is\n strict — same `userId`, same scope/org, exact same tag set (tags are\n immutable); identity drift closes with 4401 → reconnect fresh.\n- Renewal tickets come from `POST /broadcast/v1/ws-ticket`, which re-runs the\n **full** authorization gate (session, KV revocation, relationship/scope-claim\n probes) — so revocation propagates within one lease period, with no KV reads\n in the Durable Object.\n- Configure via `realtime: { lease: '15m' | seconds | false }` (min 60s;\n `false` disables — discouraged). Clients that never reauth degrade gracefully\n to one forced reconnect per lease.\n\n### Realtime broadcasts are fail-closed — explicit per-resource audience (BREAKING)\n\nRealtime broadcasting is now opt-in **per resource** with a **mandatory audience**,\nmirroring how CRUD is explicit. This closes a fanout footgun where a resource that\nnever mentioned realtime could still broadcast its rows to an entire room.\n\n- **`realtime.access: { roles: [...] }`** is the audience — same `{ roles }` shape\n as `read.access` / `crud.*.access`. A subscriber receives a live row iff that\n role bucket would admit them at REST. Roles may be concrete membership/scope\n roles or UPPERCASE pseudo-roles (`PUBLIC`, `AUTHENTICATED`, `USER`, `SYSADMIN`).\n- **Fail-closed, at compile time** — a broadcasting resource with no/empty audience\n is a **compile error** naming the resource. There is no implicit fanout. To\n broadcast to everyone in the room, say so deliberately with `access: { roles: ['PUBLIC'] }`.\n- **Fail-closed, at runtime** — the Broadcaster now treats an **empty audience as\n nobody** (previously: everybody) and evaluates the uppercase pseudo-roles exactly\n as the REST access evaluator does (`userRole` is threaded through the ws-ticket\n for `USER`/`SYSADMIN`).\n- **No project-wide auto-broadcast** — `providers.database.config.realtime` now\n only wires the transport (Broadcaster DO + ws-ticket route); it no longer\n enables broadcasts on any resource.\n- **Migration** — a project that relied on the project-wide auto-broadcast must add\n an explicit `realtime: { enabled: true, access: { roles: [...] } }` block to each\n resource that should broadcast. `requiredRoles` is the deprecated spelling of\n `access.roles` (still compiles, normalized internally). `q-events` `guests`\n demonstrates the staff-lane pattern (`access: { roles: ['admin','member'] }`,\n event-scoped, masked).\n\n### Deterministic codegen output\n\nThe compiler now sorts every filesystem-discovered collection (features, and each\n`services.*` group) by a stable key before generating, so recompiles produce\nbyte-identical output regardless of the CLI's directory-scan order. Eliminates the\nchurny, behavior-neutral diffs (queue-consumer case order, auth blocks, schema\nimports) that appeared across machines/CLI versions.\n\n### `acceptScope`: one namespaced handler for the user AND the sessionless principal\n\nA project-level namespace can now **accept an already-minted scope claim as\nproof of entry** — the inverse of `mintScope`. Set\n**`authz.namespaces.<ns>.acceptScope: '<kind>'`** and the hoisted resolver gains\na fast-path: a scope-only principal (`ctx.scopePrincipal`, no `ctx.userId`)\ncarrying a verified `ctx.scope.<kind>` claim proves entry by that claim, without\na DB relationship probe. One `/event/:eventId/*` handler then serves **both** the\nBetter-Auth user and the sessionless invite-principal — retiring the parallel\nPUBLIC `/attendee/*` twin.\n\n- **Named-string only** — the kind is always explicit; a bare `true` is a type\n error. Default absent → the resolver never admits a scope principal (fail-closed).\n- **Two locks, compile-enforced** — `acceptScope` opts the namespace in, **and**\n at least one relationship lane must confer a `<kind>` role declared\n `subject: 'supplied' \\| 'both'`. A `subject: 'user'` role emits no accept arm;\n a kind whose every conferring lane is user-only is a **compile error**, not a\n dead fast-path. The kind must be declared and its `requestField` must equal the\n prefix's first `:param`.\n- **Forging-safe** — the claim is verified (never caller-asserted), the kind is\n read by name (not an any-key loop), the instance is pinned twice\n (`entry.id === :param` in the gate + `eq(loads.pk, :param)` in hydration), and\n each accept arm is one exact `(role, lane)` pair. New proof source, zero new\n enforcement surface — firewall, masking, `access`, and scoped-db read the same\n `ctx.scope` they read for a userId caller.\n- **Composes with `mintScope`** — a userId caller still gets a rolling re-mint;\n a scope principal's verified claim is preserved (not re-stamped) so its\n `subjectId` / sub-keys survive.\n- **Realtime shares the same acceptance** — the `ws-ticket` route now proves a\n scope principal through the *same* emitter as the REST gate\n (`emitScopeAcceptance`), so the two surfaces can't drift. Bringing the ws-ticket\n path onto it tightened it to the named-kind read + supplied-reachable role\n filter, closing an any-kind cross-kind match. `q-events` ships a `vendor` scope\n role (`subject: 'both'`) + logistics-only view demonstrating the sessionless\n supplier end-to-end.\n- **Writes work too** — the scoped-db audit wrapper no longer throws when the\n caller is a verified scope principal (`ctx.scopePrincipal`, no `ctx.userId`).\n Instead of failing on the missing user, it stamps the synthetic, audit-only\n principal id (`scope:<kind>:<subjectId>`, the token's `sub`) into\n `created_by` / `modified_by`. So the SAME `/event/:eventId/*` handler body\n serves both a Better-Auth user and the sessionless principal on **reads AND\n writes** — no parallel raw-`db` write path. Still fail-closed: a genuine\n no-user write (no scope principal) throws exactly as before. `q-events` adds a\n `vendorCheckin` write under the acceptScope namespace exercising it end-to-end.\n\nSee [Scopes → `acceptScope`](/compiler/definitions/scopes#acceptscope--accept-an-incoming-scope-claim-as-proof-of-entry).\n\n### Sessionless scope mint: `ctx.mintScope` + `subject: 'supplied' \\| 'both'`\n\nA scope can now be minted for a principal who has **no Better Auth account** — an\nevent attendee arriving by email + invite code, a kiosk/handout code, a partner\ntoken. The action proves the relationship its own way and asks Quickback to mint\na disciplined scope token from the row it proved.\n\n- **`authz.scopes.<kind>.roles.<role>.subject: 'user' \\| 'supplied' \\| 'both'`** (default `'user'`).\n `'both'` makes the *same* `scope:event:attendee` reachable by a logged-in user\n (via `/scope/v1/enter`) and a sessionless invite-holder (via `ctx.mintScope`) —\n one firewall arm, one masking rule, both principals.\n- **`ctx.mintScope({ via, subject })`** — hydrated on `ctx` in any action (including\n PUBLIC) when a `supplied`/`both` role is declared. The action supplies only the\n conferring row's **primary key**; Quickback reads the role, resource id,\n sub-keys, and subject id **off that row** — never caller-asserted, so the role\n can't be forged. Returns a **scope-only** JWT (no user identity): `ctx.userId`\n stays undefined, so user/org/owner gates and the `AUTHENTICATED`/`USER`\n pseudo-roles all fail closed; only `scope:<kind>:<role>` gates admit it.\n- **`ctx.scope.<kind>.subjectId`** — a reserved claim carrying the proven subject\n row's PK, populated on **both** proof paths. Scope an attendee's self-data\n (travel, dietary, todos) with a single firewall arm\n (`{ field: 'guestId', equals: 'ctx.scope.event.subjectId' }`) that serves both a\n user-attendee and a sessionless one.\n- **Realtime** — the ws-ticket authorizes a scope-only principal directly off its\n proven `ctx.scope` claim, so accountless attendees join the same rooms with the\n same scope role. The `where:` filter runs on the mint probe, so a cancelled row\n confers nothing (revocation within one ≤180s mint cycle).\n\nSee [Scopes → Sessionless scope mint](/compiler/definitions/scopes#sessionless-scope-mint--ctxmintscope).\n\n### MCP OAuth: split authorization-server / resource-server (multi-app SSO)\n\nYou can now run one canonical authorization server with many resource servers (each\nhosting its own `/mcp`) over a shared auth DB:\n\n- A resource server that sets `agents.mcp.requireAuth` now emits the full OAuth\n access-token **verification** path on its own — previously the JWKS-verify block\n only emitted when the separate `auth.config.oauth.enabled` flag was set, so a\n requireAuth-only resource server fell back to HMAC + session and 401'd every valid\n externally-issued bearer.\n- Point a resource server at an external AS with `auth.config.oauth.issuerUrl`; the\n middleware verifies incoming bearers against the shared JWKS (`iss`/`aud`/`exp` +\n live-session binding).\n- `auth.config.oauth.audiences` (an array) registers federated resource-server\n audiences on the AS (RFC 8707). It now **unions** with the AS's own origin instead\n of replacing it, so listing federated servers never drops the AS's own `/mcp`\n audience. Also exposed on the plugin-form `oauthProvider.validAudiences`.\n\nSee [Agents → Split authorization server](/compiler/config/agents#split-authorization-server--resource-server-multi-app-sso).\n\n### MCP tools: callable path params + typed input schemas\n\nAn action mounted under a path that carries a parameter — a namespace prefix like\n`/scope/:scopeId/...`, or any `path:` with `:params` — now produces a fully\ncallable MCP tool:\n\n- The mounted route's path params are extracted into the tool's `inputSchema`\n (and `_pathParams`), so the model has a field to supply each one. Previously\n only record-based actions emitted a param (the hard-coded `id`); a standalone\n or namespace path param was absent from the schema, the URL resolved with an\n empty segment, and the action was uncallable over MCP.\n- Standalone routes are stored in Hono colon form (`:scopeId`); the OpenAPI spec\n key (and therefore the tool's `_path`) is now normalized to brace form\n (`{scopeId}`) so the runtime's brace-only path interpolation can fill it.\n\nAction `input` schemas also lower to richer JSON Schema instead of a phantom\nempty `{}`: `z.coerce.*`, `z.literal`, unions of literals, and **nested\n`z.object`** (child keys stay nested) now emit their real types, so the model —\nand the OpenAPI spec — see the actual field shapes. See\n[Agents → MCP tools](/compiler/config/agents).\n\n### Scaffold surfaces MCP/OAuth + secrets opt-ins\n\n`quickback create` now seeds the generated `quickback.config.ts` with curated,\ncommented-out hints for the authenticated MCP server (`agents.mcp.requireAuth`), the\nsplit-AS `oauth.issuerUrl`/`audiences`, and `bindings.secrets` — so these opt-ins are\ndiscoverable in the config itself, not only in the docs.\n\n### Custom secrets via `bindings.secrets`\n\nDeclare a custom secret your feature/action code reads off `env` — name and\ncontract only, never the value:\n\n```ts\nbindings: {\n secrets: [\n { name: \"WEBHOOK_SIGNING_SECRET\", description: \"HMAC for webhook callbacks\", required: true },\n ],\n}\n```\n\nIt's emitted into the generated `env.d.ts` `Env` interface so `env.\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### Security: three fail-closed fixes in the generated runtime\n\n- **Scoped `db` blocks Drizzle's relational query API.** `db.query.<table>.findFirst()` / `findMany()` build their SQL outside the scoped wrapper's reach, so they read across organizations. The scoped `db` handed to actions now **throws** on any `db.query.<table>` access (and the Neon hyperdrive typed `db`/`tx` fails `tsc` on it) with directions to `db.select()` (auto-scoped) or an `unsafe: true` action's `unsafeDb.query` with an explicit scope predicate. Handlers that relied on the unscoped pass-through were reading other tenants' rows and must be updated. See [Relational queries are blocked](/compiler/definitions/actions#relational-queries-are-blocked-fail-closed).\n- **`POST /api/v1/token` requires session authentication.** The auth middleware now stamps `ctx.authMethod` (`'session' | 'jwt' | 'api-key' | 'oauth'`), and the token endpoint rejects anything but `'session'` with `401 AUTH_SESSION_REQUIRED`. Pre-fix, a JWT could mint its own replacement — a stolen or revoked token (banned user, removed member, demoted role) could roll a 180s-TTL token forever without re-validating the session.\n- **Broadcaster DO no longer trusts the `X-Internal-Call` header alone.** Inline-mode `checkAuth` now requires `X-Internal-Secret` to match `BETTER_AUTH_SECRET` (already provisioned; the secret never leaves the worker/DO boundary on a stub call), separate mode compares `ACCESS_TOKEN` constant-time, and every generated internal caller (`lib/realtime.ts` senders, the live-view seq reader, the Better Auth role-change hook) sends the secret. A spoofed header can no longer reach broadcast injection or webhook repointing through any forwarded route.\n\n### Neon reads through user-anchored relationships\n\nResources readable via a multi-hop chain anchored on the caller's user id (e.g. a\nconference attendee reaching their own registrations through\n`person_account_links → people → event_people → registrations`) now work on Neon.\nDeclare the chain once with the `hops` form on an `authz.relationships` entry and\nreference it from a resource `firewall` via `{ field, via }`. Because the\ncorrelated multi-hop join reaches across intermediate tables that each `FORCE ROW\nLEVEL SECURITY`, caller-claims RLS would deny such a read to zero rows — so the\ncompiler routes **only that resource's read handlers** (collection `GET /`,\n`GET /:id`, and views) through the service-role handle (`createServiceDb`), with\nthe compiled app-layer reachability WHERE as the sole row filter. Org/owner/team\nreads are untouched (caller claims + RLS backstop); writes are unchanged. The\nswap is fail-closed — a service-handle read with no firewall WHERE is a compile\nerror. The anchor table is required to be caller-read-own on the subject column\nand service-role-write-only (a forgeable link would mint reachability to a\nvictim's data); this link-integrity check is target-independent and fails the\ncompile on **both** Neon and D1. The same config compiles identically on D1,\nwhere the app-layer WHERE was already the whole firewall. See\n[Reads through a user-anchored relationship](/compiler/targets/hono-api/database/neon#reads-through-a-user-anchored-relationship).\n\n### Neon interactive transactions via Hyperdrive\n\nA Neon project can now opt into `connectionMode: 'hyperdrive'` to run its feature\ndatabase over a Cloudflare Hyperdrive binding (`postgres.js` /\n`drizzle-orm/postgres-js`), unlocking **real interactive transactions** in\ngenerated actions: read current state, lock it (`for update`), decide in\nTypeScript, then write dependent rows — committed atomically, rolled back on\nthrow. `tx` is fully schema-typed (invalid columns fail `tsc`), the verified RLS\nclaims run as the first transaction-local statement inside the transaction (no\nleak across the connection pool), and Hyperdrive query caching is force-disabled\n(ETags cache at the correct post-auth layer). `http` mode stays the lightweight\nbatch-only default and is byte-identical; requesting `db.transaction()` outside\nhyperdrive mode is a fail-closed compile error. WebSocket mode is deprecated —\nHyperdrive supersedes it as the full-capability path. See\n[Interactive transactions](/compiler/targets/hono-api/database/neon#interactive-transactions).\n\n### Neon migration & environment tooling\n\n`environments` config maps dev/staging/prod to Neon branches + Cloudflare envs;\n`quickback canary <env>` branches the target DB, applies pending migrations to\nthe branch, diffs, and (with `--apply`) promotes — verifying schema changes\nagainst real state before they touch a live environment. Record-condition\nfirewall predicates now lower to Postgres RLS policy arms (enforced twice — app\nlayer and database). Opt-in API `contract.version` scaffolding landed (`v1`\ndefault; `v2` fail-closed pending completion).\n\n### Neon PostgreSQL reaches deploy parity with D1 (v0.50)\n\nA Neon-backed service now compiles, typechecks, migrates, and deploys with the\nsame capability surface as a D1 service — over HTTP (`@neondatabase/serverless`),\nthe Cloudflare default. There is no Hyperdrive binding and no Neon Authorize /\nJWKS configuration: the Worker verifies each caller, then writes the trusted\nuser/org/team context into transaction-local Postgres settings\n(`set_config('request.jwt.claim.sub' | 'org_id' | 'team_id', …, true)`) as the\nfirst statement of every query batch. RLS reads them through a compiler-defined\n`auth.user_id()` shim and the `get_active_org_id()` helper — **not** a persisted\n`user_sessions` mirror (which never shipped).\n\n- **Background contexts run under a service-role handle.** Queue consumers, cron\n schedules, and cross-tenant `unsafe` actions acquire `createServiceDb(env)`,\n which sets `quickback.service_role = 'true'` (all request claims cleared);\n every feature table carries a `<table>_service_role` RLS policy admitting\n exactly that context. Unsafe-action audit events are unchanged.\n- **Webhooks port to a `webhooks` Postgres schema** in the same database (no\n `WEBHOOKS_DB` binding). `webhooksBinding` is a pure enable flag on Neon; the\n D1-only `webhooksDatabaseId` / `webhooksDatabaseName` keys are rejected. The\n store is service-role-only.\n- **`.encrypted()` / `.sealed()` columns are supported** on Neon over HTTP: the\n key/vault tables fold into the journaled migration set with org-scoped and\n service-role-only RLS.\n- **Batch transactions advertise the truth.** Neon HTTP is fail-fast and\n non-transactional (`meta.transactional: false`, like D1) because\n `drizzle-orm/neon-http` has no interactive transactions; Neon WebSocket\n (Node/Bun) gets real rollback (`meta.transactional: true`).\n- **Deploy glue matches D1:** a generated `deploy` script\n (`npm run db:migrate && wrangler deploy`), a boot check asserting\n `DATABASE_URL`, `.dev.vars.example` (wrangler dev reads `.dev.vars`, not\n `.env`) gitignored, and `drizzle.config.ts` preferring\n `DATABASE_MIGRATION_URL ?? DATABASE_URL` for the privileged migration role.\n- **Fail-closed capability gates:** managed file storage (use presign-only R2),\n the Better Auth `subscriptions` plugin, raw `sqliteTable` interop sources on a\n Postgres target, and — under WebSocket mode — webhooks / unsafe actions /\n encrypted columns are all compile-time errors rather than silently-broken\n output. Mixed database providers remain unsupported.\n- **Docs corrected:** the [Neon page](/compiler/targets/hono-api/database/neon)\n no longer describes Neon Authorize, a `user_sessions` table, or Hyperdrive —\n none of which the compiler emits.\n- **Migration-journal hardening.** The role bootstrap now grants\n `quickback_admin` everything the pinned Drizzle runner's journal needs —\n database-level `CREATE` (so `CREATE SCHEMA IF NOT EXISTS drizzle` passes even\n as a no-op) plus ownership of the `drizzle` schema and\n `drizzle.__drizzle_migrations` — so routine migrates after the owner-run\n bootstrap need no owner credential. Generated Postgres migrations are also\n post-processed so a referenced composite `UNIQUE` / `PRIMARY KEY` constraint\n always precedes the foreign keys that consume it (an upgrade delta applies\n unedited instead of failing with \"no unique constraint matching given keys\").\n\n### Realtime identity tags — one send reaches a person on either auth door (v0.49)\n\nWebSocket connections now carry **identity tags**, proven at ticket mint and\nsigned into the ws-ticket (never client-supplied): `user:<userId>` for every\nBetter Auth caller, plus `scope:<kind>:<subjectId>` whenever a scope subject is\nproven — on **either** door. A sessionless scope principal's claim and a Better\nAuth caller's matched relationship lane stamp the **identical** subject-keyed\ntag (both derive from the same relationship row), so senders no longer\ndouble-send per recipient to cover `subject: 'both'` roles.\n\n- **`targetTags` on every send** (`realtime.broadcast`, `realtime.insert`, …):\n delivery is the deduplicated union of the runtime's indexed\n `getWebSockets(tag)` lookup — no per-frame attachment scan. Replaces the\n `userId` identity arm when present; the scope/org bind and `targetRoles`\n audience still apply.\n- **Fail-closed:** `targetTags: []` delivers to nobody, consistent with the\n empty-audience rule.\n- Tags are immutable for a socket's lifetime (hibernation-tag semantics);\n limits (10/socket, 256 chars) are validated at mint — rejected, never\n truncated.\n\n### Realtime authorization lease — hibernated sockets no longer outlive revocation (v0.49)\n\nA ws-ticket was verified once at upgrade, and DO hibernation kept the socket\nauthorized forever — bans, member removal, and subject revocation never touched\na live connection. Connections now carry a delivery-time **authorization\nlease** (default **15 minutes**, from ticket `iat`):\n\n- The fan-out skips expired connections (they receive nothing) and closes them\n with code **4401**; inbound messages — even pings — are enforced the same way.\n- **In-place renewal:** `{ type: \"reauth\", ticket: \"<fresh ws-ticket>\" }`\n extends the lease and refreshes roles without socket churn. Renewal is\n strict — same `userId`, same scope/org, exact same tag set (tags are\n immutable); identity drift closes with 4401 → reconnect fresh.\n- Renewal tickets come from `POST /broadcast/v1/ws-ticket`, which re-runs the\n **full** authorization gate (session, KV revocation, relationship/scope-claim\n probes) — so revocation propagates within one lease period, with no KV reads\n in the Durable Object.\n- Configure via `realtime: { lease: '15m' | seconds | false }` (min 60s;\n `false` disables — discouraged). Clients that never reauth degrade gracefully\n to one forced reconnect per lease.\n\n### Realtime broadcasts are fail-closed — explicit per-resource audience (BREAKING)\n\nRealtime broadcasting is now opt-in **per resource** with a **mandatory audience**,\nmirroring how CRUD is explicit. This closes a fanout footgun where a resource that\nnever mentioned realtime could still broadcast its rows to an entire room.\n\n- **`realtime.access: { roles: [...] }`** is the audience — same `{ roles }` shape\n as `read.access` / `crud.*.access`. A subscriber receives a live row iff that\n role bucket would admit them at REST. Roles may be concrete membership/scope\n roles or UPPERCASE pseudo-roles (`PUBLIC`, `AUTHENTICATED`, `USER`, `SYSADMIN`).\n- **Fail-closed, at compile time** — a broadcasting resource with no/empty audience\n is a **compile error** naming the resource. There is no implicit fanout. To\n broadcast to everyone in the room, say so deliberately with `access: { roles: ['PUBLIC'] }`.\n- **Fail-closed, at runtime** — the Broadcaster now treats an **empty audience as\n nobody** (previously: everybody) and evaluates the uppercase pseudo-roles exactly\n as the REST access evaluator does (`userRole` is threaded through the ws-ticket\n for `USER`/`SYSADMIN`).\n- **No project-wide auto-broadcast** — `providers.database.config.realtime` now\n only wires the transport (Broadcaster DO + ws-ticket route); it no longer\n enables broadcasts on any resource.\n- **Migration** — a project that relied on the project-wide auto-broadcast must add\n an explicit `realtime: { enabled: true, access: { roles: [...] } }` block to each\n resource that should broadcast. `requiredRoles` is the deprecated spelling of\n `access.roles` (still compiles, normalized internally). `q-events` `guests`\n demonstrates the staff-lane pattern (`access: { roles: ['admin','member'] }`,\n event-scoped, masked).\n\n### Deterministic codegen output\n\nThe compiler now sorts every filesystem-discovered collection (features, and each\n`services.*` group) by a stable key before generating, so recompiles produce\nbyte-identical output regardless of the CLI's directory-scan order. Eliminates the\nchurny, behavior-neutral diffs (queue-consumer case order, auth blocks, schema\nimports) that appeared across machines/CLI versions.\n\n### `acceptScope`: one namespaced handler for the user AND the sessionless principal\n\nA project-level namespace can now **accept an already-minted scope claim as\nproof of entry** — the inverse of `mintScope`. Set\n**`authz.namespaces.<ns>.acceptScope: '<kind>'`** and the hoisted resolver gains\na fast-path: a scope-only principal (`ctx.scopePrincipal`, no `ctx.userId`)\ncarrying a verified `ctx.scope.<kind>` claim proves entry by that claim, without\na DB relationship probe. One `/event/:eventId/*` handler then serves **both** the\nBetter-Auth user and the sessionless invite-principal — retiring the parallel\nPUBLIC `/attendee/*` twin.\n\n- **Named-string only** — the kind is always explicit; a bare `true` is a type\n error. Default absent → the resolver never admits a scope principal (fail-closed).\n- **Two locks, compile-enforced** — `acceptScope` opts the namespace in, **and**\n at least one relationship lane must confer a `<kind>` role declared\n `subject: 'supplied' \\| 'both'`. A `subject: 'user'` role emits no accept arm;\n a kind whose every conferring lane is user-only is a **compile error**, not a\n dead fast-path. The kind must be declared and its `requestField` must equal the\n prefix's first `:param`.\n- **Forging-safe** — the claim is verified (never caller-asserted), the kind is\n read by name (not an any-key loop), the instance is pinned twice\n (`entry.id === :param` in the gate + `eq(loads.pk, :param)` in hydration), and\n each accept arm is one exact `(role, lane)` pair. New proof source, zero new\n enforcement surface — firewall, masking, `access`, and scoped-db read the same\n `ctx.scope` they read for a userId caller.\n- **Composes with `mintScope`** — a userId caller still gets a rolling re-mint;\n a scope principal's verified claim is preserved (not re-stamped) so its\n `subjectId` / sub-keys survive.\n- **Realtime shares the same acceptance** — the `ws-ticket` route now proves a\n scope principal through the *same* emitter as the REST gate\n (`emitScopeAcceptance`), so the two surfaces can't drift. Bringing the ws-ticket\n path onto it tightened it to the named-kind read + supplied-reachable role\n filter, closing an any-kind cross-kind match. `q-events` ships a `vendor` scope\n role (`subject: 'both'`) + logistics-only view demonstrating the sessionless\n supplier end-to-end.\n- **Writes work too** — the scoped-db audit wrapper no longer throws when the\n caller is a verified scope principal (`ctx.scopePrincipal`, no `ctx.userId`).\n Instead of failing on the missing user, it stamps the synthetic, audit-only\n principal id (`scope:<kind>:<subjectId>`, the token's `sub`) into\n `created_by` / `modified_by`. So the SAME `/event/:eventId/*` handler body\n serves both a Better-Auth user and the sessionless principal on **reads AND\n writes** — no parallel raw-`db` write path. Still fail-closed: a genuine\n no-user write (no scope principal) throws exactly as before. `q-events` adds a\n `vendorCheckin` write under the acceptScope namespace exercising it end-to-end.\n\nSee [Scopes → `acceptScope`](/compiler/definitions/scopes#acceptscope--accept-an-incoming-scope-claim-as-proof-of-entry).\n\n### Sessionless scope mint: `ctx.mintScope` + `subject: 'supplied' \\| 'both'`\n\nA scope can now be minted for a principal who has **no Better Auth account** — an\nevent attendee arriving by email + invite code, a kiosk/handout code, a partner\ntoken. The action proves the relationship its own way and asks Quickback to mint\na disciplined scope token from the row it proved.\n\n- **`authz.scopes.<kind>.roles.<role>.subject: 'user' \\| 'supplied' \\| 'both'`** (default `'user'`).\n `'both'` makes the *same* `scope:event:attendee` reachable by a logged-in user\n (via `/scope/v1/enter`) and a sessionless invite-holder (via `ctx.mintScope`) —\n one firewall arm, one masking rule, both principals.\n- **`ctx.mintScope({ via, subject })`** — hydrated on `ctx` in any action (including\n PUBLIC) when a `supplied`/`both` role is declared. The action supplies only the\n conferring row's **primary key**; Quickback reads the role, resource id,\n sub-keys, and subject id **off that row** — never caller-asserted, so the role\n can't be forged. Returns a **scope-only** JWT (no user identity): `ctx.userId`\n stays undefined, so user/org/owner gates and the `AUTHENTICATED`/`USER`\n pseudo-roles all fail closed; only `scope:<kind>:<role>` gates admit it.\n- **`ctx.scope.<kind>.subjectId`** — a reserved claim carrying the proven subject\n row's PK, populated on **both** proof paths. Scope an attendee's self-data\n (travel, dietary, todos) with a single firewall arm\n (`{ field: 'guestId', equals: 'ctx.scope.event.subjectId' }`) that serves both a\n user-attendee and a sessionless one.\n- **Realtime** — the ws-ticket authorizes a scope-only principal directly off its\n proven `ctx.scope` claim, so accountless attendees join the same rooms with the\n same scope role. The `where:` filter runs on the mint probe, so a cancelled row\n confers nothing (revocation within one ≤180s mint cycle).\n\nSee [Scopes → Sessionless scope mint](/compiler/definitions/scopes#sessionless-scope-mint--ctxmintscope).\n\n### MCP OAuth: split authorization-server / resource-server (multi-app SSO)\n\nYou can now run one canonical authorization server with many resource servers (each\nhosting its own `/mcp`) over a shared auth DB:\n\n- A resource server that sets `agents.mcp.requireAuth` now emits the full OAuth\n access-token **verification** path on its own — previously the JWKS-verify block\n only emitted when the separate `auth.config.oauth.enabled` flag was set, so a\n requireAuth-only resource server fell back to HMAC + session and 401'd every valid\n externally-issued bearer.\n- Point a resource server at an external AS with `auth.config.oauth.issuerUrl`; the\n middleware verifies incoming bearers against the shared JWKS (`iss`/`aud`/`exp` +\n live-session binding).\n- `auth.config.oauth.audiences` (an array) registers federated resource-server\n audiences on the AS (RFC 8707). It now **unions** with the AS's own origin instead\n of replacing it, so listing federated servers never drops the AS's own `/mcp`\n audience. Also exposed on the plugin-form `oauthProvider.validAudiences`.\n\nSee [Agents → Split authorization server](/compiler/config/agents#split-authorization-server--resource-server-multi-app-sso).\n\n### MCP tools: callable path params + typed input schemas\n\nAn action mounted under a path that carries a parameter — a namespace prefix like\n`/scope/:scopeId/...`, or any `path:` with `:params` — now produces a fully\ncallable MCP tool:\n\n- The mounted route's path params are extracted into the tool's `inputSchema`\n (and `_pathParams`), so the model has a field to supply each one. Previously\n only record-based actions emitted a param (the hard-coded `id`); a standalone\n or namespace path param was absent from the schema, the URL resolved with an\n empty segment, and the action was uncallable over MCP.\n- Standalone routes are stored in Hono colon form (`:scopeId`); the OpenAPI spec\n key (and therefore the tool's `_path`) is now normalized to brace form\n (`{scopeId}`) so the runtime's brace-only path interpolation can fill it.\n\nAction `input` schemas also lower to richer JSON Schema instead of a phantom\nempty `{}`: `z.coerce.*`, `z.literal`, unions of literals, and **nested\n`z.object`** (child keys stay nested) now emit their real types, so the model —\nand the OpenAPI spec — see the actual field shapes. See\n[Agents → MCP tools](/compiler/config/agents).\n\n### Scaffold surfaces MCP/OAuth + secrets opt-ins\n\n`quickback create` now seeds the generated `quickback.config.ts` with curated,\ncommented-out hints for the authenticated MCP server (`agents.mcp.requireAuth`), the\nsplit-AS `oauth.issuerUrl`/`audiences`, and `bindings.secrets` — so these opt-ins are\ndiscoverable in the config itself, not only in the docs.\n\n### Custom secrets via `bindings.secrets`\n\nDeclare a custom secret your feature/action code reads off `env` — name and\ncontract only, never the value:\n\n```ts\nbindings: {\n secrets: [\n { name: \"WEBHOOK_SIGNING_SECRET\", description: \"HMAC for webhook callbacks\", required: true },\n ],\n}\n```\n\nIt's emitted into the generated `env.d.ts` `Env` interface so `env.\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",
@@ -17,9 +17,13 @@ export const DOCS = {
17
17
  "title": "CLI Reference",
18
18
  "content": "The Quickback CLI is the fastest way to create, compile, and manage your backend projects.\n\n## Installation\n\n```bash\n# One-shot via npx — recommended for first run\nnpx @quickback-dev/cli start\n\n# Or install globally for repeat use\nnpm install -g @quickback-dev/cli\n```\n\n## Commands\n\n### Start a Project (interactive)\n\n```bash\nquickback start\n```\n\nInteractive onboarding designed for new users. No flags required.\n\n- Prompts for a template (`cloudflare`, `todos`, `blog`, `empty`)\n- Prompts for a project name (defaults to the current directory's name if empty)\n- Auto-detects whether to scaffold in-place or create a `./<name>/` subdirectory\n- Defers login until just before the compile step — cancel at the auth prompt and the scaffold stays on disk, ready for `quickback compile` later\n\n**Example:**\n```bash\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n```\n\n### Create a Project (scriptable)\n\n```bash\nquickback create <template> <name>\n```\n\n**Templates:**\n- `cloudflare` — Cloudflare Workers + D1 + Better Auth, bare scaffold\n- `todos` — Working todos example with masking + actions + a named view\n- `blog` — Single-tenant blog, PUBLIC reads, admin writes\n- `empty` — Cloudflare scaffold, no example features\n- `saas` — Full B2B SaaS: orgs, R2 file storage, webhooks, split databases, realtime\n\n**Example:**\n```bash\nquickback create todos my-app\n```\n\nThis scaffolds a complete project with:\n- `quickback.config.ts` — Project configuration\n- `quickback/features/` — Your table definitions\n- Example feature with full security configuration (for `todos` / `blog` / `saas`)\n\nSee the [Templates](/compiler/getting-started/templates) page for a deeper guide on choosing between them.\n\n### Compile Definitions\n\n```bash\nquickback compile\n```\n\nUse `quickback compile --verbose` when a remote compile fails and you need the\nunderlying command, exit code, stderr/stdout tail, and compiler-suggested fixes.\n\nReads your definitions and generates:\n- Database migrations (Drizzle)\n- API route handlers (Hono)\n- TypeScript client SDK\n- OpenAPI specification\n\nRun this after making changes to your definitions.\n\n#### Generated `src/` is hermetic\n\nEvery file under `src/` carries a `Generated by quickback.dev` header and is owned by the compiler. Before each compile writes its output, the CLI:\n\n1. Snapshots the existing `src/` tree to `quickback/.archives/src-<ISO-timestamp>/` (a plain recursive copy — `cp -R` semantics, no compression).\n2. Wipes `src/` entirely.\n3. Writes the fresh manifest from the compiler.\n\nThis prevents stale output: removed features stop leaving orphan folders, deleted SPA assets with old content hashes get cleared, and `.DS_Store` files don't keep retired directories alive.\n\nThe most recent **3** archives are retained (older ones are pruned automatically). If a compile produces unexpected output, your last-known-good tree is sitting in `quickback/.archives/` ready to grep or copy back:\n\n```bash\nls quickback/.archives/\n# src-2026-04-27T16-31-02-014/\n# src-2026-04-27T16-29-44-882/\n# src-2026-04-27T16-12-19-301/\n```\n\nAs a safety net, the wipe is **skipped** when the manifest contains zero files for the target directory — that's almost always an upstream compile bug, and we'd rather keep your last working tree than overwrite it with nothing.\n\n### View Documentation\n\n```bash\nquickback docs # List available topics\nquickback docs <topic> # Show documentation for a topic\n```\n\n**Available topics:**\n- `firewall` - Data isolation layer\n- `access` - Role-based permissions\n- `guards` - Field protection\n- `masking` - PII redaction\n- `actions` - Custom business logic\n- `api` - CRUD endpoints reference\n- `config` - Configuration reference\n- `features` - Schema definitions\n\nDocumentation is bundled with the CLI and works offline.\n\n### Manage Claude Code Skill\n\n```bash\nquickback claude install # Interactive install\nquickback claude install --global # Install to ~/.claude/skills/\nquickback claude install --local # Install to ./.claude/\nquickback claude update # Update to latest version\nquickback claude remove # Remove installed skill\nquickback claude status # Check installation status\n```\n\nThe Quickback skill for Claude Code provides AI assistance for:\n- Creating resource definitions with proper security layers\n- Configuring Firewall, Access, Guards, and Masking\n- Debugging configuration issues\n- Understanding security patterns\n\n## Authentication\n\n### Login\n\n```bash\nquickback login\n```\n\nUses the [OAuth 2.0 Device Authorization Grant](https://datatracker.ietf.org/doc/html/rfc8628) (RFC 8628) to authenticate securely without exposing tokens in URLs.\n\n**How it works:**\n\n1. The CLI requests a one-time device code from the Quickback API.\n2. A code is displayed in your terminal (e.g., `AUL8-H93S`).\n3. Your browser opens to the Quickback account page where you approve the code.\n4. The CLI detects approval and exchanges it for a session token.\n5. If you belong to one organization, it's auto-selected. If you have multiple, you choose one.\n6. Credentials are stored locally.\n\n```\n$ quickback login\n\n🔐 Quickback Login\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n Your code: AUL8-H93S\n\n Visit: https://account.quickback.dev/cli/authorize\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n✓ Login successful!\nWelcome, Paul Stenhouse!\n\nUsing organization: Acme\n✓ Active organization: Acme\n```\n\nThis flow works in headless environments (SSH, containers, WSL) since it doesn't require a localhost callback.\n\n### Logout\n\n```bash\nquickback logout\n```\n\nClears stored credentials from `~/.quickback/credentials.json`.\n\n### Check Auth Status\n\n```bash\nquickback whoami\n```\n\nShows the currently authenticated user, organization, and token expiration.\n\n### Credential Storage\n\nCredentials are stored at `~/.quickback/credentials.json`:\n\n```json\n{\n \"token\": \"...\",\n \"user\": {\n \"id\": \"...\",\n \"email\": \"paul@example.com\",\n \"name\": \"Paul Stenhouse\"\n },\n \"expiresAt\": \"2026-02-16T01:42:21.519Z\",\n \"organization\": {\n \"id\": \"...\",\n \"name\": \"Acme\",\n \"slug\": \"acme\"\n }\n}\n```\n\nSessions expire after 7 days. Run `quickback login` again to re-authenticate.\n\n### Organizations\n\nAfter login, the CLI auto-selects your organization:\n- **One organization** - automatically set as active.\n- **Multiple organizations** - you're prompted to choose one.\n\nThe active organization is stored in your credentials and sent with compile requests, so the compiler knows which org context to use.\n\n## Quick Start\n\n```bash\n# 1. Start a new project (interactive — picks template, scaffolds,\n# prompts for login only when needed)\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n\n# 2. Run locally\nnpm run dev\n```\n\nOr the scriptable form:\n\n```bash\n# 1. Create the project (scaffolds + compiles + installs)\nquickback create todos my-app # prompts for login on first compile\ncd my-app\n\n# 2. Run\nnpm run dev\n\n# 3. Recompile after editing definitions\nquickback compile\n```\n\n## Options\n\n| Flag | Description |\n|------|-------------|\n| `-v, --version` | Show version number |\n| `-h, --help` | Show help message |\n\n## Environment Variables\n\n| Variable | Description |\n|----------|-------------|\n| `QUICKBACK_API_KEY` | API key for authentication (alternative to `quickback login`) |\n| `QUICKBACK_API_URL` | Override compiler API URL |\n\n### API Key Authentication\n\nUse an API key instead of interactive login. Useful for CI/CD pipelines and automated workflows:\n\n```bash\n# Pass API key for a single command\nQUICKBACK_API_KEY=your_api_key quickback compile\n\n# Or export for the session\nexport QUICKBACK_API_KEY=your_api_key\nquickback compile\n```\n\nThe API key takes precedence over stored credentials from `quickback login`.\n\nYou can create API keys from your [Quickback account](https://account.quickback.dev/profile). Each key is scoped to your organization.\n\n### Custom Compiler URL\n\nPoint the CLI to a different compiler (local or custom):\n\n```bash\n# Use a local compiler\nQUICKBACK_API_URL=http://localhost:3020 quickback compile\n\n# Or export for the session\nexport QUICKBACK_API_URL=http://localhost:3020\nquickback compile\n```\n\nSee [Local Compiler](/compiler/cloud-compiler/local-compiler) for running the compiler locally with Docker.\n\n## Troubleshooting\n\n### \"Command not found: quickback\"\n\nMake sure the CLI is installed globally:\n```bash\nnpm install -g @quickback-dev/cli\n```\n\nOr use npx (no global install needed):\n```bash\nnpx @quickback-dev/cli start\n```\n\n### Compile errors\n\n1. Check your `quickback.config.ts` exists and is valid\n2. Ensure all tables in `quickback/features/` have valid exports\n3. Run `quickback compile` with `--verbose` for detailed output\n4. For rename-related Drizzle failures in CI/headless runs, configure `compiler.migrations.renames` in `quickback.config.ts`\n\n### Authentication issues\n\nClear credentials and re-authenticate:\n```bash\nquickback logout\nquickback login\n```\n\n### \"Could not load organizations\"\n\nThis can happen if your session token expired or if the API is temporarily unavailable. Re-login:\n```bash\nquickback logout\nquickback login\n```"
19
19
  },
20
+ "compiler/cloud-compiler/deploy": {
21
+ "title": "Deploying",
22
+ "content": "A freshly compiled project's `wrangler.toml` contains **placeholder resource ids** — the compiler can't know your D1 database ids or KV namespace id until those resources exist in your Cloudflare account. Historically that meant a manual dance: `wrangler d1 create`, copy the id, paste it into `quickback.config.ts`, repeat for every database, recompile, deploy.\n\n`quickback deploy` does the whole dance for you:\n\n```bash\ncd my-app && quickback deploy\n```\n\n## What it does\n\n1. **Preflight** — verifies `wrangler` is runnable (via `npx`) and authenticated with Cloudflare (`wrangler whoami`). Log in with `npx wrangler login` or set `CLOUDFLARE_API_TOKEN`.\n2. **Compiles first if needed** — if the project has never compiled (no `wrangler.toml`), it runs the same flow as `quickback compile` before planning anything.\n3. **Plans from wrangler.toml** — reads the generated `wrangler.toml` and finds every resource whose id is still a placeholder:\n - **D1 databases** — auth, features, files, and webhooks databases (whichever your project's features pull in; split-database projects get one entry each)\n - **KV namespace** — the `KV` binding used for rate limiting and session overflow\n - **R2 buckets** — file-storage buckets (R2 is referenced by name, so buckets are simply ensured to exist)\n4. **Creates what's missing** — `wrangler d1 create <name>`, `wrangler kv namespace create <BINDING>`, `wrangler r2 bucket create <name>`. Resources are named from your project name exactly the way the compiler names them (`my-app-auth`, `my-app-features`, `my-app-files`, `my-app-KV`, …). If a resource with the expected name already exists in your account, its id is reused instead of creating a duplicate.\n5. **Writes ids back into quickback.config.ts** — a surgical, formatting-preserving edit of your `providers.database.config` (and `providers.storage.config` for the KV id when you declare a `cloudflare-kv` storage provider). Comments, indentation, and every other key are left untouched. Works with both authoring styles:\n\n ```ts\n // defineDatabase(...) wrapper\n database: defineDatabase(\"cloudflare-d1\", {\n splitDatabases: true,\n authDatabaseId: \"…\", // ← inserted/updated here\n featuresDatabaseId: \"…\",\n }),\n\n // plain object form\n database: {\n name: \"cloudflare-d1\",\n config: {\n authDatabaseId: \"…\", // ← or here\n },\n },\n ```\n\n6. **Recompiles** — so `wrangler.toml` regenerates with the real ids.\n7. **Applies D1 migrations remotely** — `wrangler d1 migrations apply <db> --remote` for each database that has pending migration files (each database's `migrations_dir` comes straight from `wrangler.toml`).\n8. **Deploys** — `wrangler deploy`, streaming wrangler's output.\n\n## Idempotent by design\n\nRun it again any time. When every id is real, there's nothing to create — the command goes straight to compile → migrations → deploy. It's a perfectly good everyday \"ship it\" command, not just a first-deploy tool.\n\n## Flags\n\n| Flag | Effect |\n|------|--------|\n| `--dry-run` | Print the provisioning plan (what would be created vs. what's already set) and exit. Creates nothing. |\n| `--skip-deploy` | Provision resources + sync ids + recompile, but skip migrations and the deploy itself. |\n| `--force` | Overwrite a config id that differs from what Cloudflare reports. Without it, a mismatch prints both values and aborts — never silently overwritten. |\n| `--verbose` | Detailed remote compile failure output (same as `quickback compile --verbose`). |\n\n```bash\n# See the plan without touching your account\nquickback deploy --dry-run\n\n# Provision + write ids only; deploy later\nquickback deploy --skip-deploy\n```\n\n## Conflicting ids\n\nIf `quickback.config.ts` already carries a real id for a resource and Cloudflare reports a different one for the same-named resource, `quickback deploy` prints both and stops:\n\n```\n✖ Config ids differ from what Cloudflare reports:\n providers.database.config.authDatabaseId\n in quickback.config.ts: 13b688c8-…\n from Cloudflare: f6b8f9a0-…\n```\n\nRe-run with `--force` to take Cloudflare's value, or fix the config by hand.\n\n## Notes\n\n- **Security-audit database** — projects using unsafe cross-tenant actions require an audit D1 database, and the compiler fails closed at compile time until `auditDatabaseId` is set. Follow the compile error's instructions (create the database, set the id), then re-run `quickback deploy`.\n- **Neon projects** — `quickback deploy` does not apply Postgres migrations. Run `npm run db:migrate` (needs `DATABASE_MIGRATION_URL`) before traffic hits the worker, or use the generated project's `npm run deploy` script which chains both.\n- **Hyperdrive** — a Hyperdrive binding can't be auto-created (it needs your database connection string). Create it with `wrangler hyperdrive create <name> --connection-string=… --caching-disabled` and set `providers.database.config.hyperdrive.id`.\n- **Two logins** — the compile step uses your Quickback account (`quickback login`); resource creation and deploy use your wrangler credentials."
23
+ },
20
24
  "compiler/cloud-compiler/endpoints": {
21
25
  "title": "Endpoints",
22
- "content": "The cloud compiler API is hosted at `https://compiler.quickback.dev`.\n\n## Public (No Auth)\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `/health` | GET | Health check |\n| `/templates` | GET | List available templates |\n\n## Authenticated\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `/compile` | POST | Compile definitions into backend files |\n\nThe `/compile` endpoint requires either a session token (from `quickback login`) or an API key (via `QUICKBACK_API_KEY` header). See [Authentication](/compiler/cloud-compiler/authentication) for details.\n\n## Environment Variables\n\n| Variable | Description |\n|----------|-------------|\n| `QUICKBACK_API_KEY` | API key for authentication (alternative to `quickback login`) |\n| `QUICKBACK_API_URL` | Override compiler API URL (default: `https://compiler.quickback.dev`) |\n\n### Custom Compiler URL\n\nPoint the CLI to a different compiler (local or custom):\n\n```bash\nQUICKBACK_API_URL=http://localhost:3020 quickback compile\n```\n\nSee [Local Compiler](/compiler/cloud-compiler/local-compiler) for running the compiler locally with Docker.\n\n## Streaming Protocol (`POST /compile`)\n\nBy default `/compile` returns a single JSON response. If the request includes `Accept: text/event-stream`, the compiler upgrades to Server-Sent Events so the CLI can render progress while the build runs.\n\nThere are two stream protocol versions, negotiated via the `X-Quickback-Stream` request header:\n\n| Header | Protocol | Behavior |\n|--------|----------|----------|\n| _(absent)_ | **v1** | Sends `progress` events during the build, then a single `result` event with the entire compilation payload (config, generated files, drizzle output, SPA bundles, etc.) JSON-encoded as one frame. |\n| `X-Quickback-Stream: v2` | **v2 (chunked)** | Sends `progress` events during the build, then a `meta` event with the file count, then one `file` event per generated file, then a final `done` event with metadata, commands, and warnings. |\n\nThe server echoes the chosen version back as the response `X-Quickback-Stream` header so the CLI knows which framing to parse.\n\n### Why v2\n\nMulti-megabyte SPA bundles (CMS + Account, with sourcemaps) take long enough to `JSON.stringify` that the v1 single-frame `result` event blocks Cloudflare's container event loop. Two things break: Docker's `HEALTHCHECK` fails, and the CLI's 120-second connection timeout fires before the body flushes. v2 emits files one at a time and yields back to the event loop every 10 files (`setImmediate`), keeping `/health` responsive and TCP backpressure alive.\n\nThe `@quickback-dev/cli` v0.10.x and later send `X-Quickback-Stream: v2` automatically. v1 is preserved for older clients.\n\n### Event shapes (v2)\n\n```\nevent: progress\ndata: { \"stage\": \"vite-cms\", \"message\": \"...\" }\n\nevent: meta\ndata: { \"fileCount\": 412, \"version\": \"0.10.3\" }\n\nevent: file\ndata: { \"path\": \"src/...\", \"content\": \"...\", ... }\n…\n\nevent: done\ndata: { \"meta\": {...}, \"commands\": [...], \"warnings\": [...] }\n```\n\nOn failure, an `error` event is emitted in either protocol:\n\n```\nevent: error\ndata: { \"error\": \"Compilation failed\", \"code\": \"...\", \"message\": \"...\" }\n```"
26
+ "content": "The cloud compiler API is hosted at `https://compiler.quickback.dev`.\n\n## Public (No Auth)\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `/health` | GET | Health check |\n| `/templates` | GET | List available templates |\n\n## Authenticated\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `/compile` | POST | Compile definitions into backend files |\n\nThe `/compile` endpoint requires either a session token (from `quickback login`) or an API key (via `QUICKBACK_API_KEY` header). See [Authentication](/compiler/cloud-compiler/authentication) for details.\n\n## Raw-files mode (`POST /compile`)\n\n`/compile` normally expects the parsed `CompilerInput` the CLI assembles client-side. Thin clients (agents, web builders, CI without the CLI) can instead send the project sources verbatim and let the compiler organize them server-side:\n\n```json\n{\n \"rawFiles\": {\n \"quickback/quickback.config.ts\": \"import { defineConfig } from …\",\n \"quickback/features/todos/todos.ts\": \"import { feature, q } from …\",\n \"quickback/features/todos/actions/complete.ts\": \"…\"\n }\n}\n```\n\nThe map uses project-root-relative paths and follows the same layout `quickback compile` reads from disk: `quickback/quickback.config.ts`, `quickback/features/**`, `quickback/services/**`, `quickback/{lib,hooks,plugins,middlewares,email-templates}/**`, plus `quickback/drizzle/**/meta/**` and `wrangler.toml` for incremental builds.\n\nTwo constraints, both fail-closed:\n\n- **The config must be fully static.** The compiler parses `quickback.config.ts` with a literals-only evaluator — it never executes user code. Object/array/string/number/boolean literals, substitution-free template literals, and the `define*` helper calls all work; variables, computed values, and imports-as-values are rejected with a 400 that names the offending construct and line.\n- **Action input schemas are optional.** The CLI harvests `z.toJSONSchema` on your machine; raw-files requests may pass `actionInputSchemas` alongside `rawFiles`, otherwise the compiler's static parser supplies lower-fidelity input schemas.\n\nWorks with both `?complete=true` and `?complete=false` (validation-only) compiles.\n\n## Environment Variables\n\n| Variable | Description |\n|----------|-------------|\n| `QUICKBACK_API_KEY` | API key for authentication (alternative to `quickback login`) |\n| `QUICKBACK_API_URL` | Override compiler API URL (default: `https://compiler.quickback.dev`) |\n\n### Custom Compiler URL\n\nPoint the CLI to a different compiler (local or custom):\n\n```bash\nQUICKBACK_API_URL=http://localhost:3020 quickback compile\n```\n\nSee [Local Compiler](/compiler/cloud-compiler/local-compiler) for running the compiler locally with Docker.\n\n## Streaming Protocol (`POST /compile`)\n\nBy default `/compile` returns a single JSON response. If the request includes `Accept: text/event-stream`, the compiler upgrades to Server-Sent Events so the CLI can render progress while the build runs.\n\nThere are two stream protocol versions, negotiated via the `X-Quickback-Stream` request header:\n\n| Header | Protocol | Behavior |\n|--------|----------|----------|\n| _(absent)_ | **v1** | Sends `progress` events during the build, then a single `result` event with the entire compilation payload (config, generated files, drizzle output, SPA bundles, etc.) JSON-encoded as one frame. |\n| `X-Quickback-Stream: v2` | **v2 (chunked)** | Sends `progress` events during the build, then a `meta` event with the file count, then one `file` event per generated file, then a final `done` event with metadata, commands, and warnings. |\n\nThe server echoes the chosen version back as the response `X-Quickback-Stream` header so the CLI knows which framing to parse.\n\n### Why v2\n\nMulti-megabyte SPA bundles (CMS + Account, with sourcemaps) take long enough to `JSON.stringify` that the v1 single-frame `result` event blocks Cloudflare's container event loop. Two things break: Docker's `HEALTHCHECK` fails, and the CLI's 120-second connection timeout fires before the body flushes. v2 emits files one at a time and yields back to the event loop every 10 files (`setImmediate`), keeping `/health` responsive and TCP backpressure alive.\n\nThe `@quickback-dev/cli` v0.10.x and later send `X-Quickback-Stream: v2` automatically. v1 is preserved for older clients.\n\n### Event shapes (v2)\n\n```\nevent: progress\ndata: { \"stage\": \"vite-cms\", \"message\": \"...\" }\n\nevent: meta\ndata: { \"fileCount\": 412, \"version\": \"0.10.3\" }\n\nevent: file\ndata: { \"path\": \"src/...\", \"content\": \"...\", ... }\n…\n\nevent: done\ndata: { \"meta\": {...}, \"commands\": [...], \"warnings\": [...] }\n```\n\nOn failure, an `error` event is emitted in either protocol:\n\n```\nevent: error\ndata: { \"error\": \"Compilation failed\", \"code\": \"...\", \"message\": \"...\" }\n```"
23
27
  },
24
28
  "compiler/cloud-compiler": {
25
29
  "title": "Cloud Compiler",
@@ -27,7 +31,7 @@ export const DOCS = {
27
31
  },
28
32
  "compiler/cloud-compiler/local-compiler": {
29
33
  "title": "Local Compiler",
30
- "content": "Run the Quickback compiler locally using Docker. The local compiler uses the exact same Docker image as the cloud compiler, ensuring identical behavior — including SPA builds with correct environment variables.\n\n## Prerequisites\n\n- Docker Desktop installed and running\n- Quickback monorepo cloned locally\n- Authenticated via `quickback login`\n\n## Quick Start\n\nFrom the monorepo root:\n\n```bash\ncd apps/compiler-local && bash dev.sh\n```\n\nThis will:\n1. Ensure Docker Desktop is running\n2. Stop any existing compiler container\n3. Build the Docker image from `apps/compiler/Dockerfile`\n4. Run it on port 3000\n\n### Custom Port\n\n```bash\nbash dev.sh 3001\n```\n\n## Compiling a Project\n\nPoint the CLI to your local compiler:\n\n```bash\nQUICKBACK_API_URL=http://localhost:3000 quickback compile\n```\n\nOr export it for the session:\n\n```bash\nexport QUICKBACK_API_URL=http://localhost:3000\nquickback compile\n```\n\nAuthentication is always required. Run `quickback login` first if you haven't already.\n\n## Manual Build & Run\n\nYou can also build and run the Docker image directly from the monorepo root:\n\n```bash\n# Build\ndocker build -t quickback-compiler -f apps/compiler/Dockerfile .\n\n# Run\ndocker run --rm -p 3000:3000 quickback-compiler\n```\n\n## Verify\n\nCheck the compiler is running:\n\n```bash\ncurl http://localhost:3000/health\n```\n\n## How It Works\n\nThe Docker image includes:\n- Pre-installed dependencies for compiled projects (`/deps/node_modules`)\n- CMS and Account SPA source code (`/spa/cms/`, `/spa/account/`)\n- Pre-installed SPA dependencies (`/spa-deps/cms/`, `/spa-deps/account/`)\n\nWhen compiling a project with `cms: true` or `account: true`, the compiler builds the SPAs from source inside the container with the correct Vite environment variables (e.g., `VITE_QUICKBACK_API_URL`, `VITE_QUICKBACK_ACCOUNT_URL`). This ensures each project gets properly configured SPA assets without manual intervention.\n\n## Deploying to Cloud\n\nAfter making changes to the compiler, deploy to `compiler.quickback.dev`:\n\n```bash\ncd apps/compiler-cloud && bash deploy.sh\n```\n\n## Troubleshooting\n\n### Container not starting\n\n```bash\ndocker logs quickback-compiler-local\n```\n\n### Port already in use\n\n```bash\n# Find what's using the port\nlsof -i :3000\n\n# Use a different port\nbash dev.sh 3001\n```\n\n### Docker out of disk space\n\n```bash\ndocker system prune -af\n```\n\n### SPA build warnings\n\nIf you see SPA build warnings during compilation, ensure the SPA dependency files are up to date:\n- `apps/compiler/deps-spa-cms-package.json`\n- `apps/compiler/deps-spa-account-package.json`\n\nThese must include all dependencies from `packages/cms/package.json` and `packages/account/package.json` respectively."
34
+ "content": "Run the Quickback compiler locally using Docker. The local compiler uses the exact same Docker image as the cloud compiler, ensuring identical behavior — including SPA builds with correct environment variables.\n\n## Prerequisites\n\n- Docker Desktop installed and running\n- Quickback monorepo cloned locally\n- Authenticated via `quickback login`\n\n## Quick Start\n\nFrom the monorepo root:\n\n```bash\ncd apps/compiler-local && bash dev.sh\n```\n\nThis will:\n1. Ensure Docker Desktop is running\n2. Stop any existing compiler container\n3. Build the Docker image from `apps/compiler/Dockerfile`\n4. Run it on port 3000\n\n### Custom Port\n\n```bash\nbash dev.sh 3001\n```\n\n## Compiling a Project\n\nPoint the CLI to your local compiler:\n\n```bash\nQUICKBACK_API_URL=http://localhost:3000 quickback compile\n```\n\nOr export it for the session:\n\n```bash\nexport QUICKBACK_API_URL=http://localhost:3000\nquickback compile\n```\n\nAuthentication is always required. Run `quickback login` first if you haven't already.\n\n## Manual Build & Run\n\nYou can also build and run the Docker image directly from the monorepo root:\n\n```bash\n# Build\ndocker build -t quickback-compiler -f apps/compiler/Dockerfile .\n\n# Run\ndocker run --rm -p 3000:3000 quickback-compiler\n```\n\n## Verify\n\nCheck the compiler is running:\n\n```bash\ncurl http://localhost:3000/health\n```\n\n## How It Works\n\nThe Docker image includes:\n- Pre-installed dependencies for compiled projects (`/deps/node_modules`)\n- CMS and Account SPA source code (`/spa/cms/`, `/spa/account/`)\n- Pre-installed SPA dependencies (`/spa-deps/cms/`, `/spa-deps/account/`)\n\nWhen compiling a project with `cms: true` or `account: true`, the compiler builds the SPAs from source inside the container with the correct Vite environment variables (e.g., `VITE_QUICKBACK_API_URL`, `VITE_QUICKBACK_ACCOUNT_URL`). This ensures each project gets properly configured SPA assets without manual intervention.\n\nThe generated worker additionally injects the same per-project values into every served SPA shell as `window.__QUICKBACK_RUNTIME`, and the SPAs prefer that runtime blob over the baked env — so the served behavior is identical even with a generic (no-`.env`) SPA build.\n\n## Deploying to Cloud\n\nAfter making changes to the compiler, deploy to `compiler.quickback.dev`:\n\n```bash\ncd apps/compiler-cloud && bash deploy.sh\n```\n\n## Troubleshooting\n\n### Container not starting\n\n```bash\ndocker logs quickback-compiler-local\n```\n\n### Port already in use\n\n```bash\n# Find what's using the port\nlsof -i :3000\n\n# Use a different port\nbash dev.sh 3001\n```\n\n### Docker out of disk space\n\n```bash\ndocker system prune -af\n```\n\n### SPA build warnings\n\nIf you see SPA build warnings during compilation, ensure the SPA dependency files are up to date:\n- `apps/compiler/deps-spa-cms-package.json`\n- `apps/compiler/deps-spa-account-package.json`\n\nThese must include all dependencies from `packages/cms/package.json` and `packages/account/package.json` respectively."
31
35
  },
32
36
  "compiler/cloud-compiler/troubleshooting": {
33
37
  "title": "Troubleshooting",
@@ -51,7 +55,7 @@ export const DOCS = {
51
55
  },
52
56
  "compiler/config": {
53
57
  "title": "Configuration",
54
- "content": "The `quickback.config.ts` file configures your Quickback project. It defines which providers to use, which features to enable, and how the compiler generates code.\n\n```typescript\n\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## Discoverable options block\n\nAfter your first `quickback compile`, the file gets a managed block bracketed by sentinel comments:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: cloudflare({}),\n\n // [quickback:options-start]\n // ── Project ──\n //\n // Primary custom domain (auto-inferred from cms/account/api domains if unset).\n // domain: \"example.com\",\n //\n // ── Embedded UIs (CMS / Account) ──\n //\n // Login/signup/profile/orgs SPA. Set `true` for default, or object to customize.\n // account: {\n // fileUploads: false, // show the avatar upload UI on the profile page\n // auth: { passkey: false, emailOTP: false, ... },\n // ...\n // },\n //\n // ... every other option Quickback supports\n // [quickback:options-end]\n});\n```\n\nThis block is **regenerated on every compile** — the compiler is the source of truth, so newly added options surface automatically when you upgrade Quickback (no CLI bump needed).\n\n**To enable an option**, copy the line you care about *above* the `[quickback:options-start]` sentinel and uncomment it:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: cloudflare({}),\n\n account: {\n fileUploads: true, // ← lifted out of the managed block\n },\n\n // [quickback:options-start]\n // ... account is now omitted from this block on next compile\n // [quickback:options-end]\n});\n```\n\nQuickback notices that `account` is set above the marker and drops it from the managed block on the next compile to avoid duplicate definitions. Anything outside the marker block is yours and never touched.\n\nIf you ever want to opt out of the auto-managed block, run:\n\n```bash\nquickback compile --no-sync-config\n```\n\n## Required Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `name` | `string` | Project name |\n| `template` | `\"hono\"` | Application template (`\"nextjs\"` is experimental) |\n| `providers` | `object` | Runtime, database, and auth provider configuration |\n\n## Optional Fields\n\nEvery optional top-level key the config accepts is listed below. You never have to memorize them — after your first compile, the [discoverable options block](#discoverable-options-block) lists each one (minus the ones you've set) right inside your `quickback.config.ts`. This table is the human reference; follow the links for detailed pages.\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `domain` | `string` | Primary custom domain (auto-inferred from `cms`/`account`/`api` domains if unset) — see [Domains](/compiler/config/domains) |\n| `api` | `object` | Dedicated hostname for the feature API surface (`/api/v1/*`); additive alias — see [Domains](/compiler/config/domains) |\n| `auth` | `object` | App-level auth settings (`roleHierarchy`, `jwt`, `loginUrl`/`profileUrl`, `domain`) — see [Access](/compiler/definitions/access#role-hierarchy) |\n| `authz` | `object` | Relationship-based authorization (`relationships`, `roles`, `permissions`, `arrows`) — see [Permissions](/compiler/definitions/permissions) |\n| `trustedOrigins` | `string[]` | CORS trusted origins for cross-domain auth |\n| `features` | `object` | Feature flags such as `organizations` / `pinnedOrganizationId` — see [Pinned Organization Mode](/compiler/config/single-tenant) |\n| `cms` | `boolean \\| object` | Embed CMS in compiled Worker (`domain`, `access`, `sysadmin`) — see [CMS](/stack/cms) |\n| `account` | `boolean \\| object` | Embed Account UI in compiled Worker (`domain`, `name`, `auth.*`, branding) — see [Account UI](/stack/account-ui) |\n| `apps` | `object` | Mount hand-authored SPAs on their own hostname or path prefix — see [Domains](/compiler/config/domains) |\n| `agents` | `boolean \\| object` | AI/agent discovery surface (`robots.txt`, `llms.txt`, MCP, OAuth discovery) — see [Agents](/compiler/config/agents) |\n| `security` | `object \\| false` | HTTP response security headers (CSP, HSTS, COOP/COEP, Referrer/Permissions-Policy) — see [Security Headers](/compiler/config/security) |\n| `openapi` | `object` | OpenAPI spec generation (`generate`, `publish`, `docs: 'scalar' \\| 'swagger'`, `types`) — see [OpenAPI](/compiler/targets/hono-api/using-the-api/openapi) |\n| `schemaRegistry` | `object` | Schema registry generation for the CMS (`{ generate: false }` to disable) — see [Schema Registry](/stack/cms/schema-registry) |\n| `etag` | `object` | ETag caching for GET responses (`{ enabled: false }` to disable) — see [Caching & ETags](/compiler/targets/hono-api/using-the-api/caching) |\n| `email` | `object` | Email delivery config (`provider`, `from`, `fromName`, `region`) — see [Email Configuration](#email-configuration) |\n| `bindings` | `object` | Extra Cloudflare bindings (durable objects, queues, R2, services, `vars`, AI) — see [Bindings](/compiler/config/bindings) |\n| `compiler` | `object` | Compiler internals — `features.auditFields: false`, `migrations.renames` (headless CI), `securityContracts`, `injectId`, `routes` |\n| `build` | `object` | Build options (`outputDir`, `packageManager`, `dependencies`) — see [Custom Dependencies](#custom-dependencies) |\n| `dev` | `object` | Local development settings (`port`, `api`, `cms`, `account`, `hostnames`) — see [Variables](/compiler/config/variables) |\n| `preset` | `string` | Inherit defaults from a named preset |\n\n## Custom Dependencies\n\nAdd third-party npm packages to the generated `package.json` using `build.dependencies`. This is useful when your action handlers import external libraries.\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n build: {\n dependencies: {\n \"fast-xml-parser\": \"^4.5.0\",\n \"lodash-es\": \"^4.17.21\",\n },\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\nThese are merged into the generated `package.json` alongside Quickback's own dependencies. Run `npm install` after compiling to install them.\n\n## Headless Migration Rename Hints\n\nWhen `drizzle-kit generate` detects a potential rename, it normally prompts for confirmation. Cloud/CI compiles are non-interactive, so you must provide explicit rename hints.\n\nAdd hints in `compiler.migrations.renames`:\n\n```typescript\nexport default defineConfig({\n // ...\n compiler: {\n migrations: {\n renames: {\n // Keys are NEW names, values are OLD names\n tables: {\n events_v2: \"events\",\n },\n columns: {\n events: {\n summary_text: \"summary\",\n },\n },\n },\n },\n },\n});\n```\n\nRules:\n- `tables`: `new_table_name -> old_table_name`\n- `columns.<table>`: `new_column_name -> old_column_name`\n- Keys must match the names in your current schema (the new names)\n- Validation fails fast for malformed rename config, unsupported keys, or conflicting legacy/new rename paths.\n\n## Disable Audit Field Injection\n\nBy default, Quickback auto-injects four **audit fields** (`createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`) into every feature table, plus two **soft-delete fields** (`deletedAt`, `deletedBy`) into tables that use soft delete (the default delete mode). The audit fields drive record-provenance queries and the CMS audit panel; the soft-delete pair drives soft-delete filtering.\n\nTo opt out project-wide:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n compiler: {\n features: {\n auditFields: false, // skip audit-field injection globally\n },\n },\n providers: { /* ... */ },\n});\n```\n\nWhen disabled, you're responsible for supplying these columns yourself if you want soft delete, audit trails, or modifiedAt-based optimistic concurrency. See the [Schema → Audit Fields](/compiler/definitions/schema#audit-fields) section for the full list and what each field drives.\n\n## Security Contract Reports and Signing\n\nAfter generation, Quickback verifies machine-checkable security contracts for Hono routes and RLS SQL.\n\nIt also emits a report artifact and signature artifact by default:\n\n- `reports/security-contracts.report.json`\n- `reports/security-contracts.report.sig.json`\n\nYou can configure output paths and signing behavior:\n\n```typescript\nexport default defineConfig({\n // ...\n compiler: {\n securityContracts: {\n failMode: \"error\", // or \"warn\"\n report: {\n path: \"reports/security-contracts.report.json\",\n signature: {\n enabled: true,\n required: true,\n keyEnv: \"QUICKBACK_SECURITY_REPORT_SIGNING_KEY\",\n keyId: \"prod-k1\",\n path: \"reports/security-contracts.report.sig.json\",\n },\n },\n },\n },\n});\n```\n\nIf `signature.required: true` and no key is available, compilation fails with a clear error message (or warning in `failMode: \"warn\"`).\n\n## Hostname architecture (v0.33+)\n\nA modern Quickback project runs on **one Cloudflare Worker** that serves multiple URL surfaces. By default, everything lives under a single unified backend hostname (auto-inferred as `quickback.{baseDomain}` from your other configured subdomains, or overridable via `config.domain`). For larger deployments, you can opt-in to **dedicated hostnames** for specific surfaces — they're additive aliases, never replacements.\n\n### The unified backend contract\n\nWhen any subdomain is configured (`account.domain`, `cms.domain`, `auth.domain`, `api.domain`, `apps.<n>.domain`), the compiler always emits a unified backend host where **every compiler-emitted backend route** is reachable:\n\n- `/api/v1/*` — feature routes\n- `/auth/v1/*` — Better Auth\n- `/storage/*` — R2 file storage\n- `/health`, `/openapi.json` — monitoring/discovery\n- `/account/*`, `/cms/*` — bundled SPAs (when enabled)\n- `/broadcast/v1/*` (realtime), `/mcp` (MCP), etc.\n\nThe unified hostname is `quickback.{baseDomain}` by default (where baseDomain is extracted from your first configured subdomain). Override with `config.domain` if you prefer a different name.\n\nThis contract is forward-pointing: it gives a stable URL pattern for future management tooling — `https://quickback.{baseDomain}/...` will always reach a Quickback backend regardless of how the operator splits their surfaces.\n\n### Dedicated hostnames (optional, additive)\n\nFor branding or operational separation, you can opt specific surfaces onto their own hostnames:\n\n```ts\n{\n // Bundled SPAs on their own hosts (already-shipped pattern):\n cms: { domain: 'cms.example.com' },\n account: { domain: 'account.example.com' },\n\n // v0.33+ — backend surfaces on their own hosts:\n auth: { domain: 'auth.example.com' },\n api: { domain: 'api.example.com' },\n\n // User SPAs (existing pattern):\n apps: {\n www: { domain: 'app.example.com' },\n },\n}\n```\n\nOn a dedicated hostname, **the hostname IS the namespace** — the path drops the prefix that matches the hostname:\n\n| URL on dedicated host | Internally rewritten to | Notes |\n|---|---|---|\n| `https://api.example.com/v1/users` | `/api/v1/users` | Worker-entry rewriter prepends `/api` |\n| `https://auth.example.com/v1/sign-in/email` | `/auth/v1/sign-in/email` | Same shape with `/auth` |\n| `https://api.example.com/api/v1/users` | (unchanged) | Long form also accepted |\n| `https://api.example.com/auth/v1/sign-in` | **404** | Auth doesn't live on the API hostname |\n| `https://api.example.com/health` | (unchanged) | Explicit exception — monitoring agents expect `/health` everywhere |\n\nDual-reach is preserved on the unified host:\n\n| URL on unified host | Handler | Notes |\n|---|---|---|\n| `https://quickback.example.com/api/v1/users` | feature route | Works whether `api.domain` is set or not |\n| `https://quickback.example.com/auth/v1/sign-in/email` | Better Auth | Works whether `auth.domain` is set or not |\n| `https://quickback.example.com/v1/users` | **404** | Shortcut only applies on dedicated hostnames |\n\nEach dedicated hostname also:\n\n- Gets a `{ pattern, custom_domain: true }` route in `wrangler.toml` automatically\n- Joins `trustedOrigins` for CORS\n- Joins the cross-subdomain cookie inference (auto-enables `crossSubDomainCookies` when ≥2 same-parent subdomains are configured, so `auth.example.com` and `app.example.com` can share session cookies)\n- Joins CSP `connect-src` so SPAs can fetch from it\n\n### Why two URL shapes (Shape 1 vs Shape 2)\n\nIf you only want Better Auth to **advertise** itself on a different URL (e.g. so verification emails link to `auth.example.com` instead of the unified host), set the `BETTER_AUTH_URL` env var on the Worker — no code change required. BA generates outgoing URLs against that value. This is sufficient when the goal is branding email/OAuth callback URLs without changing where requests actually land.\n\n`auth.domain` (Shape 1, above) is the heavier option: it binds an actual hostname to the Worker, configures CORS/cookies/CSP for it, and adds the path-shortcut rewriter. Use it when you want the dedicated hostname as a real ingress, not just a label.\n\n## CMS Configuration\n\nEmbed the [Quickback CMS](/stack/cms) in your compiled Worker. The CMS reads your schema registry and renders a complete admin interface — zero UI code per table.\n\n```typescript\n// Simple — embed CMS at root\ncms: true,\n\n// With custom domain\ncms: { domain: \"cms.example.com\" },\n\n// With access control (only admins can access CMS)\ncms: { domain: \"cms.example.com\", access: \"admin\" },\n\n// Cross-tenant DB-admin tier — sysadmins see every tenant's data\ncms: { domain: \"cms.example.com\", sysadmin: true },\n```\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `domain` | `string` | — | Custom domain for CMS. Adds a `custom_domain` route to `wrangler.toml`. |\n| `access` | `\"user\" \\| \"admin\"` | `\"admin\"` | Controls who can access the CMS. When `\"admin\"`, platform control-plane users (`user.role === \"appmanager\"`) can enter; when `sysadmin` mode is also on, `user.role === \"sysadmin\"` is admitted too. The gate is enforced at the Worker level (SPA shell, `/api/v1/schema`, and `custom_view` CRUD all return 403 to callers outside those roles) and in the SPA. Also hides the CMS link in Account UI. See [CMS Connecting](/stack/cms/connecting) for the full enforcement model. |\n| `sysadmin` | `boolean` | `false` | Cross-tenant DB-admin tier. When `true`, opts into the `SYSADMIN` pseudo-role (`user.role === \"sysadmin\"`), the firewall escape hatch (sysadmins bypass tenant scopes, soft-delete still enforced), the cross-tenant `/auth/v1/admin/list-organizations` endpoint (sibling of Better Auth's `/auth/v1/admin/list-users`, gated to sysadmin only), and the SPA's \"All organizations\" sentinel. The CMS HTML gate admits `userRole === \"sysadmin\"` alongside `\"appmanager\"`. Off by default. See [`SYSADMIN` pseudo-role](/compiler/definitions/access#sysadmin--cross-tenant-db-admin-tier). |\n\n### Sysadmin tier (`cms.sysadmin: true`)\n\nQuickback's default model assumes every CMS user belongs to at least one organization (`member` row in the auth DB). For platforms that need a Supabase-style cross-tenant DB-admin tool — debugging a tenant's data, running cross-tenant queries, supporting a customer — that's a poor fit: a sysadmin without `member` rows would dead-end, and auto-filling their active org from \"first membership\" silently scopes them to a tenant they have no relationship with.\n\n`cms: { sysadmin: true }` introduces a separate role tier:\n\n- **Role**: `user.role === \"sysadmin\"` (set on the Better Auth user table). Distinct from `\"appmanager\"` — appmanagers keep platform control-plane access (CMS shell, Better Auth admin surfaces, support tooling), while sysadmins get true cross-tenant data access. `ADMIN` is now a rejected legacy pseudo-role; use `userRole: [\"appmanager\"]` for control-plane gates and `roles: [\"SYSADMIN\"]` for cross-tenant access.\n- **Firewall**: every `buildFirewallConditions()` emits an `if (ctx.userRole === \"sysadmin\") return undefined` (or just the soft-delete predicate when present) at the top, so sysadmins see every tenant's rows. See [Firewall escape hatch](/compiler/definitions/firewall#sysadmin-escape-hatch).\n- **Org listing**: a `GET /auth/v1/admin/list-organizations` endpoint selects directly from the auth-schema `organization` table — every row, every tenant. Sits under Better Auth's admin URL namespace (sibling of `/auth/v1/admin/list-users`) so the URL shape matches BA convention; the handler is Quickback-emitted and gated to `user.role === \"sysadmin\"` only. For the membership-bound caller's-orgs listing, use BA's own `/auth/v1/organization/list`.\n- **CMS SPA**: when the user is a sysadmin, the header switcher loads from the cross-tenant endpoint, defaults to \"All organizations\" (which omits `?organizationId=` and reaches the firewall escape), and pins selected tenants via `?organizationId=` on every API call. Org admins keep the existing membership-based switcher.\n- **CMS HTML gate**: admits `userRole === \"sysadmin\"` alongside `\"appmanager\"`. Org admins are not locked out when you set `cms.access: \"user\"`; `cms.access: \"admin\"` is specifically the platform control-plane gate.\n\nOff by default. Projects that don't enable it get zero behavior change; setting `cms.sysadmin: true` and granting a user `user.role = \"sysadmin\"` is the only way to unlock the cross-tenant view.\n\n## Account UI Configuration\n\nEmbed the [Account UI](/stack/account-ui) in your compiled Worker. Provides login, signup, profile management, organization management, and admin — all built from your config at compile time.\n\nFor post-signup logic — auto-provisioning a workspace, gating signup, setting an active organization — drop a file in `quickback/hooks/`. See [Auth Hooks](/stack/account-ui/hooks).\n\n```typescript\n// Simple — embed Account UI with defaults\naccount: true,\n\n// Full configuration\naccount: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n companyName: \"My Company\",\n auth: {\n password: true,\n emailOTP: false,\n passkey: true,\n organizations: true,\n admin: true,\n },\n},\n```\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `domain` | `string` | Custom domain for Account UI (e.g., `auth.example.com`) |\n| `adminDomain` | `string` | Custom domain for admin-only access (e.g., `admin.example.com`). Serves the same Account SPA — the client-side router handles admin routing. |\n| `appUrl` | `string` | URL of the tenant's main application — where users are redirected after login. Baked into the Account SPA as `VITE_QUICKBACK_APP_URL`. Independent from `domain`. |\n| `name` | `string` | App display name shown on login, profile, and email templates |\n| `companyName` | `string` | Company name for branding |\n| `tagline` | `string` | App tagline shown on login page |\n| `description` | `string` | App description |\n\n### Auth Feature Flags\n\nControl which authentication features are exposed. Disabled features are excluded from the Account UI bundle at compile time (routes removed before the Vite build, keeping bundle sizes minimal) **and** enforced on the server side via the Better Auth config — so \"signup off\" actually closes `POST /auth/v1/sign-up/email`, not just the SPA's signup screen.\n\n`account.auth.*` is a shorthand for `providers.auth.config` — the compiler maps each flag onto the Better Auth server config before any code is generated. You can write either side directly; setting both incompatibly (e.g. `account.auth.signup: false` and `emailAndPassword.disableSignUp: false`) fails the compile with a precise error rather than picking a silent winner.\n\n| Flag | Type | Default | Maps to (server) | Description |\n|------|------|---------|------------------|-------------|\n| `auth.password` | `boolean` | `true` | `emailAndPassword.enabled` | Email/password authentication — both server endpoint and UI |\n| `auth.emailOTP` | `boolean` | `false` | adds `emailOtp` plugin | Email one-time password login — adds plugin server-side, surfaces UI |\n| `auth.passkey` | `boolean` | `false` | adds `passkey` plugin | WebAuthn/FIDO2 passkey authentication — adds plugin server-side, surfaces UI |\n| `auth.signup` | `boolean` | `true` | `emailAndPassword.disableSignUp` (inverted) | Self-service account registration — false hides the UI **and** rejects the server endpoint with 403 |\n| `auth.organizations` | `boolean` | `true` | UI surface only | Organization management UI (dashboard, invitations, roles). Server-side organization support stays on regardless; set `features.pinnedOrganizationId` when you want one fixed org with no switching UI |\n| `auth.admin` | `boolean` | `false` | UI surface only | Admin panel for user management in the Account SPA. The Better Auth admin plugin is compiler-managed separately from this UI toggle |\n| `auth.emailVerification` | `boolean` | `false` | `emailAndPassword.requireEmailVerification` | Require email verification before sessions are issued. False = sessions usable immediately after signup |\n\n## Trusted Origins\n\nList of origins allowed to make cross-origin requests to your API. Required when your CMS, Account UI, or frontend app run on different domains.\n\n```typescript\ntrustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n \"https://cms.example.com\",\n \"https://app.example.com\",\n],\n```\n\n## Local Development\n\nConfigure local development URLs. These are automatically added to the trusted origins list for CORS and Better Auth, so authentication works out of the box during local development.\n\n```typescript\ndev: {\n port: 8787, // wrangler dev port (default: 8787)\n api: \"http://localhost:8787\", // API backend URL\n cms: \"http://localhost:8787/cms\", // CMS URL (path on same worker)\n account: \"http://localhost:8787/account\", // Account URL (path on same worker)\n},\n```\n\nIf you run a SPA standalone on its own Vite dev server, set its URL here so CORS allows it:\n\n```typescript\ndev: {\n port: 8787,\n api: \"http://localhost:8787\",\n account: \"http://localhost:5173\", // standalone Account dev server\n},\n```\n\n| Field | Type | Default | Description |\n|-------|------|---------|-------------|\n| `port` | `number` | `8787` | Local dev server port (sets `[dev].port` in wrangler.toml) |\n| `api` | `string` | `http://localhost:{port}` | API backend URL |\n| `cms` | `string` | — | CMS dev URL (added to trusted origins if set) |\n| `account` | `string` | — | Account dev URL (added to trusted origins if set) |\n\n## Email Configuration\n\nConfigure email delivery for authentication emails (verification, password reset, invitations).\n\n> **Cloudflare Email Sending is now in public beta** and is Quickback's default transport for Cloudflare deploys. The Workers `send_email` binding is zero-config — no API keys, no third-party accounts. AWS SES remains supported as an explicit opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes or existing SES setups.\n\n```typescript\n// Cloudflare Email Service (default) — uses send_email binding, no API keys needed\nemail: {\n from: \"noreply@example.com\",\n fromName: \"My App\",\n},\n\n// AWS SES — requires AWS credentials set as Wrangler secrets\nemail: {\n provider: \"aws-ses\",\n region: \"us-east-2\",\n from: \"noreply@example.com\",\n fromName: \"My App\",\n},\n```\n\n| Field | Type | Default | Description |\n|-------|------|---------|-------------|\n| `provider` | `\"cloudflare\" \\| \"aws-ses\"` | `\"cloudflare\"` | Email transport |\n| `from` | `string` | `\"noreply@example.com\"` | Sender email address |\n| `fromName` | `string` | `\"{name} \\| Account Services\"` | Sender display name |\n| `region` | `string` | `\"us-east-2\"` | AWS SES region (aws-ses only) |\n\n### Auto-wiring\n\nFor the Cloudflare provider (the default), the compiler automatically:\n- Emits `[[send_email]] EMAIL` into `wrangler.toml`\n- Generates `src/lib/cloudflare-email.ts`\n- Wires `sendResetPassword`, `sendVerificationEmail`, `sendInvitationEmail`, etc. into Better Auth\n\n…whenever any auth surface needs to send mail — `emailAndPassword.enabled`, the `emailOtp` / `magicLink` / `organization` plugins — or you set the top-level `email: {…}` config. You don't need to add `bindings.sendEmail` by hand for the standard cases.\n\n> **Cloudflare Email Routing setup is required.** The binding alone does not deliver mail. Enable Email Routing on the sending zone and add at least one verified destination address ([Cloudflare docs](https://developers.cloudflare.com/email-routing/get-started/)). Otherwise sends fail at runtime even with the binding present and the `/auth/v1/ses/status` check passing locally.\n\n## Multi-Domain Example\n\nA complete config with CMS, Account UI, and Admin on separate subdomains:\n\n```typescript\nexport default {\n name: \"my-app\",\n template: \"hono\",\n cms: { domain: \"cms.example.com\", access: \"admin\" },\n account: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n companyName: \"Example Inc.\",\n auth: {\n password: true,\n emailOTP: false,\n passkey: true,\n organizations: false,\n admin: true,\n },\n },\n email: {\n from: \"noreply@example.com\",\n fromName: \"My App\",\n },\n trustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n \"https://cms.example.com\",\n \"https://example.com\",\n ],\n providers: {\n runtime: { name: \"cloudflare\", config: {\n routes: [{ pattern: \"api.example.com\", custom_domain: true }],\n }},\n database: { name: \"cloudflare-d1\", config: { binding: \"DB\" } },\n auth: { name: \"better-auth\", config: { plugins: [\"admin\"] } },\n },\n};\n```\n\nThis produces a single Cloudflare Worker serving five domains. See [Multi-Domain Architecture](/compiler/config/domains) for details on hostname routing, cross-subdomain cookies, and the unified fallback domain.\n\n---\n\nSee the sub-pages for detailed reference on each section:\n- [Providers](/compiler/config/providers) — Runtime, database, and auth options\n- [Variables](/compiler/config/variables) — Environment variables and flags\n- [Output](/compiler/config/output) — Generated file structure\n- [Pinned Organization Mode](/compiler/config/single-tenant) — Fixed-org deployments without org switching UI\n- [Multi-Domain Architecture](/compiler/config/domains) — Custom domains, hostname routing, and cross-subdomain auth"
58
+ "content": "The `quickback.config.ts` file configures your Quickback project. It defines which providers to use, which features to enable, and how the compiler generates code.\n\n```typescript\n\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n auth: {\n // Required for \"+\" role expansion in access rules (e.g. roles: [\"member+\"]).\n // Lowest → highest. Omit if you always list roles explicitly.\n roleHierarchy: [\"member\", \"admin\", \"owner\"],\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## Discoverable options block\n\nAfter your first `quickback compile`, the file gets a managed block bracketed by sentinel comments:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: cloudflare({}),\n\n // [quickback:options-start]\n // ── Project ──\n //\n // Primary custom domain (auto-inferred from cms/account/api domains if unset).\n // domain: \"example.com\",\n //\n // ── Embedded UIs (CMS / Account) ──\n //\n // Login/signup/profile/orgs SPA. Set `true` for default, or object to customize.\n // account: {\n // fileUploads: false, // show the avatar upload UI on the profile page\n // auth: { passkey: false, emailOTP: false, ... },\n // ...\n // },\n //\n // ... every other option Quickback supports\n // [quickback:options-end]\n});\n```\n\nThis block is **regenerated on every compile** — the compiler is the source of truth, so newly added options surface automatically when you upgrade Quickback (no CLI bump needed).\n\n**To enable an option**, copy the line you care about *above* the `[quickback:options-start]` sentinel and uncomment it:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: cloudflare({}),\n\n account: {\n fileUploads: true, // ← lifted out of the managed block\n },\n\n // [quickback:options-start]\n // ... account is now omitted from this block on next compile\n // [quickback:options-end]\n});\n```\n\nQuickback notices that `account` is set above the marker and drops it from the managed block on the next compile to avoid duplicate definitions. Anything outside the marker block is yours and never touched.\n\nIf you ever want to opt out of the auto-managed block, run:\n\n```bash\nquickback compile --no-sync-config\n```\n\n## Required Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `name` | `string` | Project name |\n| `template` | `\"hono\"` | Application template (`\"nextjs\"` is experimental) |\n| `providers` | `object` | Runtime, database, and auth provider configuration |\n\n## Optional Fields\n\nEvery optional top-level key the config accepts is listed below. You never have to memorize them — after your first compile, the [discoverable options block](#discoverable-options-block) lists each one (minus the ones you've set) right inside your `quickback.config.ts`. This table is the human reference; follow the links for detailed pages.\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `domain` | `string` | Primary custom domain (auto-inferred from `cms`/`account`/`api` domains if unset) — see [Domains](/compiler/config/domains) |\n| `api` | `object` | Dedicated hostname for the feature API surface (`/api/v1/*`); additive alias — see [Domains](/compiler/config/domains) |\n| `auth` | `object` | App-level auth settings (`roleHierarchy`, `jwt`, `loginUrl`/`profileUrl`, `domain`) — see [Access](/compiler/definitions/access#role-hierarchy) |\n| `authz` | `object` | Relationship-based authorization (`relationships`, `roles`, `permissions`, `arrows`) — see [Permissions](/compiler/definitions/permissions) |\n| `trustedOrigins` | `string[]` | CORS trusted origins for cross-domain auth |\n| `features` | `object` | Feature flags such as `organizations` / `pinnedOrganizationId` — see [Pinned Organization Mode](/compiler/config/single-tenant) |\n| `cms` | `boolean \\| object` | Embed CMS in compiled Worker (`domain`, `access`, `sysadmin`) — see [CMS](/stack/cms) |\n| `account` | `boolean \\| object` | Embed Account UI in compiled Worker (`domain`, `name`, `auth.*`, branding) — see [Account UI](/stack/account-ui) |\n| `apps` | `object` | Mount hand-authored SPAs on their own hostname or path prefix — see [Domains](/compiler/config/domains) |\n| `agents` | `boolean \\| object` | AI/agent discovery surface (`robots.txt`, `llms.txt`, MCP, OAuth discovery) — see [Agents](/compiler/config/agents) |\n| `security` | `object \\| false` | HTTP response security headers (CSP, HSTS, COOP/COEP, Referrer/Permissions-Policy) — see [Security Headers](/compiler/config/security) |\n| `openapi` | `object` | OpenAPI spec generation (`generate`, `publish`, `docs: 'scalar' \\| 'swagger'`, `types`) — see [OpenAPI](/compiler/targets/hono-api/using-the-api/openapi) |\n| `schemaRegistry` | `object` | Schema registry generation for the CMS (`{ generate: false }` to disable) — see [Schema Registry](/stack/cms/schema-registry) |\n| `etag` | `object` | ETag caching for GET responses (`{ enabled: false }` to disable) — see [Caching & ETags](/compiler/targets/hono-api/using-the-api/caching) |\n| `email` | `object` | Email delivery config (`provider`, `from`, `fromName`, `region`) — see [Email Configuration](#email-configuration) |\n| `bindings` | `object` | Extra Cloudflare bindings (durable objects, queues, R2, services, `vars`, AI) — see [Bindings](/compiler/config/bindings) |\n| `compiler` | `object` | Compiler internals — `features.auditFields: false`, `migrations.renames` (headless CI), `securityContracts`, `injectId`, `routes` |\n| `build` | `object` | Build options (`outputDir`, `packageManager`, `dependencies`) — see [Custom Dependencies](#custom-dependencies) |\n| `dev` | `object` | Local development settings (`port`, `api`, `cms`, `account`, `hostnames`) — see [Variables](/compiler/config/variables) |\n| `preset` | `string` | Inherit defaults from a named preset |\n\n## Custom Dependencies\n\nAdd third-party npm packages to the generated `package.json` using `build.dependencies`. This is useful when your action handlers import external libraries.\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n build: {\n dependencies: {\n \"fast-xml-parser\": \"^4.5.0\",\n \"lodash-es\": \"^4.17.21\",\n },\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\nThese are merged into the generated `package.json` alongside Quickback's own dependencies. Run `npm install` after compiling to install them.\n\n## Headless Migration Rename Hints\n\nWhen `drizzle-kit generate` detects a potential rename, it normally prompts for confirmation. Cloud/CI compiles are non-interactive, so you must provide explicit rename hints.\n\nAdd hints in `compiler.migrations.renames`:\n\n```typescript\nexport default defineConfig({\n // ...\n compiler: {\n migrations: {\n renames: {\n // Keys are NEW names, values are OLD names\n tables: {\n events_v2: \"events\",\n },\n columns: {\n events: {\n summary_text: \"summary\",\n },\n },\n },\n },\n },\n});\n```\n\nRules:\n- `tables`: `new_table_name -> old_table_name`\n- `columns.<table>`: `new_column_name -> old_column_name`\n- Keys must match the names in your current schema (the new names)\n- Validation fails fast for malformed rename config, unsupported keys, or conflicting legacy/new rename paths.\n\n## Disable Audit Field Injection\n\nBy default, Quickback auto-injects four **audit fields** (`createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`) into every feature table, plus two **soft-delete fields** (`deletedAt`, `deletedBy`) into tables that use soft delete (the default delete mode). The audit fields drive record-provenance queries and the CMS audit panel; the soft-delete pair drives soft-delete filtering.\n\nTo opt out project-wide:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n compiler: {\n features: {\n auditFields: false, // skip audit-field injection globally\n },\n },\n providers: { /* ... */ },\n});\n```\n\nWhen disabled, you're responsible for supplying these columns yourself if you want soft delete, audit trails, or modifiedAt-based optimistic concurrency. See the [Schema → Audit Fields](/compiler/definitions/schema#audit-fields) section for the full list and what each field drives.\n\n## Security Contract Reports and Signing\n\nAfter generation, Quickback verifies machine-checkable security contracts for Hono routes and RLS SQL.\n\nIt also emits a report artifact and signature artifact by default:\n\n- `reports/security-contracts.report.json`\n- `reports/security-contracts.report.sig.json`\n\nYou can configure output paths and signing behavior:\n\n```typescript\nexport default defineConfig({\n // ...\n compiler: {\n securityContracts: {\n failMode: \"error\", // or \"warn\"\n report: {\n path: \"reports/security-contracts.report.json\",\n signature: {\n enabled: true,\n required: true,\n keyEnv: \"QUICKBACK_SECURITY_REPORT_SIGNING_KEY\",\n keyId: \"prod-k1\",\n path: \"reports/security-contracts.report.sig.json\",\n },\n },\n },\n },\n});\n```\n\nIf `signature.required: true` and no key is available, compilation fails with a clear error message (or warning in `failMode: \"warn\"`).\n\n## Hostname architecture (v0.33+)\n\nA modern Quickback project runs on **one Cloudflare Worker** that serves multiple URL surfaces. By default, everything lives under a single unified backend hostname (auto-inferred as `quickback.{baseDomain}` from your other configured subdomains, or overridable via `config.domain`). For larger deployments, you can opt-in to **dedicated hostnames** for specific surfaces — they're additive aliases, never replacements.\n\n### The unified backend contract\n\nWhen any subdomain is configured (`account.domain`, `cms.domain`, `auth.domain`, `api.domain`, `apps.<n>.domain`), the compiler always emits a unified backend host where **every compiler-emitted backend route** is reachable:\n\n- `/api/v1/*` — feature routes\n- `/auth/v1/*` — Better Auth\n- `/storage/*` — R2 file storage\n- `/health`, `/openapi.json` — monitoring/discovery\n- `/account/*`, `/cms/*` — bundled SPAs (when enabled)\n- `/broadcast/v1/*` (realtime), `/mcp` (MCP), etc.\n\nThe unified hostname is `quickback.{baseDomain}` by default (where baseDomain is extracted from your first configured subdomain). Override with `config.domain` if you prefer a different name.\n\nThis contract is forward-pointing: it gives a stable URL pattern for future management tooling — `https://quickback.{baseDomain}/...` will always reach a Quickback backend regardless of how the operator splits their surfaces.\n\n### Dedicated hostnames (optional, additive)\n\nFor branding or operational separation, you can opt specific surfaces onto their own hostnames:\n\n```ts\n{\n // Bundled SPAs on their own hosts (already-shipped pattern):\n cms: { domain: 'cms.example.com' },\n account: { domain: 'account.example.com' },\n\n // v0.33+ — backend surfaces on their own hosts:\n auth: { domain: 'auth.example.com' },\n api: { domain: 'api.example.com' },\n\n // User SPAs (existing pattern):\n apps: {\n www: { domain: 'app.example.com' },\n },\n}\n```\n\nOn a dedicated hostname, **the hostname IS the namespace** — the path drops the prefix that matches the hostname:\n\n| URL on dedicated host | Internally rewritten to | Notes |\n|---|---|---|\n| `https://api.example.com/v1/users` | `/api/v1/users` | Worker-entry rewriter prepends `/api` |\n| `https://auth.example.com/v1/sign-in/email` | `/auth/v1/sign-in/email` | Same shape with `/auth` |\n| `https://api.example.com/api/v1/users` | (unchanged) | Long form also accepted |\n| `https://api.example.com/auth/v1/sign-in` | **404** | Auth doesn't live on the API hostname |\n| `https://api.example.com/health` | (unchanged) | Explicit exception — monitoring agents expect `/health` everywhere |\n\nDual-reach is preserved on the unified host:\n\n| URL on unified host | Handler | Notes |\n|---|---|---|\n| `https://quickback.example.com/api/v1/users` | feature route | Works whether `api.domain` is set or not |\n| `https://quickback.example.com/auth/v1/sign-in/email` | Better Auth | Works whether `auth.domain` is set or not |\n| `https://quickback.example.com/v1/users` | **404** | Shortcut only applies on dedicated hostnames |\n\nEach dedicated hostname also:\n\n- Gets a `{ pattern, custom_domain: true }` route in `wrangler.toml` automatically\n- Joins `trustedOrigins` for CORS\n- Joins the cross-subdomain cookie inference (auto-enables `crossSubDomainCookies` when ≥2 same-parent subdomains are configured, so `auth.example.com` and `app.example.com` can share session cookies)\n- Joins CSP `connect-src` so SPAs can fetch from it\n\n### Why two URL shapes (Shape 1 vs Shape 2)\n\nIf you only want Better Auth to **advertise** itself on a different URL (e.g. so verification emails link to `auth.example.com` instead of the unified host), set the `BETTER_AUTH_URL` env var on the Worker — no code change required. BA generates outgoing URLs against that value. This is sufficient when the goal is branding email/OAuth callback URLs without changing where requests actually land.\n\n`auth.domain` (Shape 1, above) is the heavier option: it binds an actual hostname to the Worker, configures CORS/cookies/CSP for it, and adds the path-shortcut rewriter. Use it when you want the dedicated hostname as a real ingress, not just a label.\n\n## CMS Configuration\n\nEmbed the [Quickback CMS](/stack/cms) in your compiled Worker. The CMS reads your schema registry and renders a complete admin interface — zero UI code per table.\n\n```typescript\n// Simple — embed CMS at root\ncms: true,\n\n// With custom domain\ncms: { domain: \"cms.example.com\" },\n\n// With access control (only admins can access CMS)\ncms: { domain: \"cms.example.com\", access: \"admin\" },\n\n// Cross-tenant DB-admin tier — sysadmins see every tenant's data\ncms: { domain: \"cms.example.com\", sysadmin: true },\n```\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `domain` | `string` | — | Custom domain for CMS. Adds a `custom_domain` route to `wrangler.toml`. |\n| `access` | `\"user\" \\| \"admin\"` | `\"admin\"` | Controls who can access the CMS. When `\"admin\"`, platform control-plane users (`user.role === \"appmanager\"`) can enter; when `sysadmin` mode is also on, `user.role === \"sysadmin\"` is admitted too. The gate is enforced at the Worker level (SPA shell, `/api/v1/schema`, and `custom_view` CRUD all return 403 to callers outside those roles) and in the SPA. Also hides the CMS link in Account UI. See [CMS Connecting](/stack/cms/connecting) for the full enforcement model. |\n| `sysadmin` | `boolean` | `false` | Cross-tenant DB-admin tier. When `true`, opts into the `SYSADMIN` pseudo-role (`user.role === \"sysadmin\"`), the firewall escape hatch (sysadmins bypass tenant scopes, soft-delete still enforced), the cross-tenant `/auth/v1/admin/list-organizations` endpoint (sibling of Better Auth's `/auth/v1/admin/list-users`, gated to sysadmin only), and the SPA's \"All organizations\" sentinel. The CMS HTML gate admits `userRole === \"sysadmin\"` alongside `\"appmanager\"`. Off by default. See [`SYSADMIN` pseudo-role](/compiler/definitions/access#sysadmin--cross-tenant-db-admin-tier). |\n\n### Sysadmin tier (`cms.sysadmin: true`)\n\nQuickback's default model assumes every CMS user belongs to at least one organization (`member` row in the auth DB). For platforms that need a Supabase-style cross-tenant DB-admin tool — debugging a tenant's data, running cross-tenant queries, supporting a customer — that's a poor fit: a sysadmin without `member` rows would dead-end, and auto-filling their active org from \"first membership\" silently scopes them to a tenant they have no relationship with.\n\n`cms: { sysadmin: true }` introduces a separate role tier:\n\n- **Role**: `user.role === \"sysadmin\"` (set on the Better Auth user table). Distinct from `\"appmanager\"` — appmanagers keep platform control-plane access (CMS shell, Better Auth admin surfaces, support tooling), while sysadmins get true cross-tenant data access. `ADMIN` is now a rejected legacy pseudo-role; use `userRole: [\"appmanager\"]` for control-plane gates and `roles: [\"SYSADMIN\"]` for cross-tenant access.\n- **Firewall**: every `buildFirewallConditions()` emits an `if (ctx.userRole === \"sysadmin\") return undefined` (or just the soft-delete predicate when present) at the top, so sysadmins see every tenant's rows. See [Firewall escape hatch](/compiler/definitions/firewall#sysadmin-escape-hatch).\n- **Org listing**: a `GET /auth/v1/admin/list-organizations` endpoint selects directly from the auth-schema `organization` table — every row, every tenant. Sits under Better Auth's admin URL namespace (sibling of `/auth/v1/admin/list-users`) so the URL shape matches BA convention; the handler is Quickback-emitted and gated to `user.role === \"sysadmin\"` only. For the membership-bound caller's-orgs listing, use BA's own `/auth/v1/organization/list`.\n- **CMS SPA**: when the user is a sysadmin, the header switcher loads from the cross-tenant endpoint, defaults to \"All organizations\" (which omits `?organizationId=` and reaches the firewall escape), and pins selected tenants via `?organizationId=` on every API call. Org admins keep the existing membership-based switcher.\n- **CMS HTML gate**: admits `userRole === \"sysadmin\"` alongside `\"appmanager\"`. Org admins are not locked out when you set `cms.access: \"user\"`; `cms.access: \"admin\"` is specifically the platform control-plane gate.\n\nOff by default. Projects that don't enable it get zero behavior change; setting `cms.sysadmin: true` and granting a user `user.role = \"sysadmin\"` is the only way to unlock the cross-tenant view.\n\n## Account UI Configuration\n\nEmbed the [Account UI](/stack/account-ui) in your compiled Worker. Provides login, signup, profile management, organization management, and admin — all built from your config at compile time.\n\nFor post-signup logic — auto-provisioning a workspace, gating signup, setting an active organization — drop a file in `quickback/hooks/`. See [Auth Hooks](/stack/account-ui/hooks).\n\n```typescript\n// Simple — embed Account UI with defaults\naccount: true,\n\n// Full configuration\naccount: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n companyName: \"My Company\",\n auth: {\n password: true,\n emailOTP: false,\n passkey: true,\n organizations: true,\n admin: true,\n },\n},\n```\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `domain` | `string` | Custom domain for Account UI (e.g., `auth.example.com`) |\n| `adminDomain` | `string` | Custom domain for admin-only access (e.g., `admin.example.com`). Serves the same Account SPA — the client-side router handles admin routing. |\n| `appUrl` | `string` | URL of the tenant's main application — where users are redirected after login. Baked into the Account SPA as `VITE_QUICKBACK_APP_URL`. Independent from `domain`. |\n| `name` | `string` | App display name shown on login, profile, and email templates |\n| `companyName` | `string` | Company name for branding |\n| `tagline` | `string` | App tagline shown on login page |\n| `description` | `string` | App description |\n\n### Auth Feature Flags\n\nControl which authentication features are exposed. Disabled features are excluded from the Account UI bundle at compile time (routes removed before the Vite build, keeping bundle sizes minimal) **and** enforced on the server side via the Better Auth config — so \"signup off\" actually closes `POST /auth/v1/sign-up/email`, not just the SPA's signup screen.\n\n`account.auth.*` is a shorthand for `providers.auth.config` — the compiler maps each flag onto the Better Auth server config before any code is generated. You can write either side directly; setting both incompatibly (e.g. `account.auth.signup: false` and `emailAndPassword.disableSignUp: false`) fails the compile with a precise error rather than picking a silent winner.\n\n| Flag | Type | Default | Maps to (server) | Description |\n|------|------|---------|------------------|-------------|\n| `auth.password` | `boolean` | `true` | `emailAndPassword.enabled` | Email/password authentication — both server endpoint and UI |\n| `auth.emailOTP` | `boolean` | `false` | adds `emailOtp` plugin | Email one-time password login — adds plugin server-side, surfaces UI |\n| `auth.passkey` | `boolean` | `false` | adds `passkey` plugin | WebAuthn/FIDO2 passkey authentication — adds plugin server-side, surfaces UI |\n| `auth.signup` | `boolean` | `true` | `emailAndPassword.disableSignUp` (inverted) | Self-service account registration — false hides the UI **and** rejects the server endpoint with 403 |\n| `auth.organizations` | `boolean` | `true` | UI surface only | Organization management UI (dashboard, invitations, roles). Server-side organization support stays on regardless; set `features.pinnedOrganizationId` when you want one fixed org with no switching UI |\n| `auth.admin` | `boolean` | `false` | UI surface only | Admin panel for user management in the Account SPA. The Better Auth admin plugin is compiler-managed separately from this UI toggle |\n| `auth.emailVerification` | `boolean` | `false` | `emailAndPassword.requireEmailVerification` | Require email verification before sessions are issued. False = sessions usable immediately after signup |\n\n## Trusted Origins\n\nList of origins allowed to make cross-origin requests to your API. Required when your CMS, Account UI, or frontend app run on different domains.\n\n```typescript\ntrustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n \"https://cms.example.com\",\n \"https://app.example.com\",\n],\n```\n\n## Local Development\n\nConfigure local development URLs. These are automatically added to the trusted origins list for CORS and Better Auth, so authentication works out of the box during local development.\n\n```typescript\ndev: {\n port: 8787, // wrangler dev port (default: 8787)\n api: \"http://localhost:8787\", // API backend URL\n cms: \"http://localhost:8787/cms\", // CMS URL (path on same worker)\n account: \"http://localhost:8787/account\", // Account URL (path on same worker)\n},\n```\n\nIf you run a SPA standalone on its own Vite dev server, set its URL here so CORS allows it:\n\n```typescript\ndev: {\n port: 8787,\n api: \"http://localhost:8787\",\n account: \"http://localhost:5173\", // standalone Account dev server\n},\n```\n\n| Field | Type | Default | Description |\n|-------|------|---------|-------------|\n| `port` | `number` | `8787` | Local dev server port (sets `[dev].port` in wrangler.toml) |\n| `api` | `string` | `http://localhost:{port}` | API backend URL |\n| `cms` | `string` | — | CMS dev URL (added to trusted origins if set) |\n| `account` | `string` | — | Account dev URL (added to trusted origins if set) |\n\n## Email Configuration\n\nConfigure email delivery for authentication emails (verification, password reset, invitations).\n\n> **Cloudflare Email Sending is now in public beta** and is Quickback's default transport for Cloudflare deploys. The Workers `send_email` binding is zero-config — no API keys, no third-party accounts. AWS SES remains supported as an explicit opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes or existing SES setups.\n\n```typescript\n// Cloudflare Email Service (default) — uses send_email binding, no API keys needed\nemail: {\n from: \"noreply@example.com\",\n fromName: \"My App\",\n},\n\n// AWS SES — requires AWS credentials set as Wrangler secrets\nemail: {\n provider: \"aws-ses\",\n region: \"us-east-2\",\n from: \"noreply@example.com\",\n fromName: \"My App\",\n},\n```\n\n| Field | Type | Default | Description |\n|-------|------|---------|-------------|\n| `provider` | `\"cloudflare\" \\| \"aws-ses\"` | `\"cloudflare\"` | Email transport |\n| `from` | `string` | `\"noreply@example.com\"` | Sender email address |\n| `fromName` | `string` | `\"{name} \\| Account Services\"` | Sender display name |\n| `region` | `string` | `\"us-east-2\"` | AWS SES region (aws-ses only) |\n\n### Auto-wiring\n\nFor the Cloudflare provider (the default), the compiler automatically:\n- Emits `[[send_email]] EMAIL` into `wrangler.toml`\n- Generates `src/lib/cloudflare-email.ts`\n- Wires `sendResetPassword`, `sendVerificationEmail`, `sendInvitationEmail`, etc. into Better Auth\n\n…whenever any auth surface needs to send mail — `emailAndPassword.enabled`, the `emailOtp` / `magicLink` / `organization` plugins — or you set the top-level `email: {…}` config. You don't need to add `bindings.sendEmail` by hand for the standard cases.\n\n> **Cloudflare Email Routing setup is required.** The binding alone does not deliver mail. Enable Email Routing on the sending zone and add at least one verified destination address ([Cloudflare docs](https://developers.cloudflare.com/email-routing/get-started/)). Otherwise sends fail at runtime even with the binding present and the `/auth/v1/ses/status` check passing locally.\n\n## Multi-Domain Example\n\nA complete config with CMS, Account UI, and Admin on separate subdomains:\n\n```typescript\nexport default {\n name: \"my-app\",\n template: \"hono\",\n cms: { domain: \"cms.example.com\", access: \"admin\" },\n account: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n companyName: \"Example Inc.\",\n auth: {\n password: true,\n emailOTP: false,\n passkey: true,\n organizations: false,\n admin: true,\n },\n },\n email: {\n from: \"noreply@example.com\",\n fromName: \"My App\",\n },\n trustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n \"https://cms.example.com\",\n \"https://example.com\",\n ],\n providers: {\n runtime: { name: \"cloudflare\", config: {\n routes: [{ pattern: \"api.example.com\", custom_domain: true }],\n }},\n database: { name: \"cloudflare-d1\", config: { binding: \"DB\" } },\n auth: { name: \"better-auth\", config: { plugins: [\"admin\"] } },\n },\n};\n```\n\nThis produces a single Cloudflare Worker serving five domains. See [Multi-Domain Architecture](/compiler/config/domains) for details on hostname routing, cross-subdomain cookies, and the unified fallback domain.\n\n---\n\nSee the sub-pages for detailed reference on each section:\n- [Providers](/compiler/config/providers) — Runtime, database, and auth options\n- [Variables](/compiler/config/variables) — Environment variables and flags\n- [Output](/compiler/config/output) — Generated file structure\n- [Pinned Organization Mode](/compiler/config/single-tenant) — Fixed-org deployments without org switching UI\n- [Multi-Domain Architecture](/compiler/config/domains) — Custom domains, hostname routing, and cross-subdomain auth"
55
59
  },
56
60
  "compiler/config/output": {
57
61
  "title": "Output Structure",
@@ -63,7 +67,7 @@ export const DOCS = {
63
67
  },
64
68
  "compiler/config/security": {
65
69
  "title": "Security Headers",
66
- "content": "Every compiled Quickback Worker sets a baseline of security response-headers on every response: HSTS, `X-Content-Type-Options: nosniff`, a clickjacking CSP (`frame-ancestors 'self' …TRUSTED_ORIGINS`), `X-Frame-Options: SAMEORIGIN`, `Referrer-Policy`, and `Permissions-Policy`. Adding the `security` block lets you override individual headers, ship a fuller Content-Security-Policy, or suppress them all if an upstream gateway handles headers.\n\n## Default behavior\n\nOmit `security` entirely → the baseline above. No config change needed for clickjacking + HSTS protection.\n\n```ts title=\"quickback.config.ts\"\n\nexport default defineConfig({\n name: 'my-api',\n // ...\n // security defaults are applied automatically.\n});\n```\n\n## Suppress every security header\n\nFor Workers fronted by a gateway that owns headers:\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // ...\n security: false,\n});\n```\n\nThe compiler emits a no-op middleware comment so the route table still lines up with the rest of the generated code, but no `c.header(...)` calls fire.\n\n## Per-header overrides\n\nEach field on the `security` block accepts either a typed value or `false` to suppress that specific header. Defaults still apply for fields you don't set.\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // ...\n security: {\n // Suppress just CSP — keeps HSTS, referrer, permissions, etc.\n csp: false,\n\n // Or override individual fields:\n coop: 'same-origin',\n coep: 'credentialless',\n referrerPolicy: 'no-referrer',\n permissionsPolicy: { geolocation: [], microphone: [], camera: [], payment: [] },\n hsts: { maxAge: 63072000, includeSubDomains: true, preload: true },\n },\n});\n```\n\n## Content Security Policy\n\n`security.csp` accepts a typed object. Each `*Src` field is an array of source expressions. The compiler accepts both the `@`-prefixed sentinels (idiomatic, type-safe) and CSP wire-form keywords (`\"'self'\"`, `\"'unsafe-inline'\"`); both normalize to the same output.\n\n### Sentinels\n\n| Sentinel | Wire form | Notes |\n|---|---|---|\n| `@self` | `'self'` | Same-origin. |\n| `@none` | `'none'` | Empty-set keyword. |\n| `@unsafe-inline` | `'unsafe-inline'` | Allows inline scripts/styles — defeats most XSS mitigation when used in `script-src`. |\n| `@unsafe-eval` | `'unsafe-eval'` | Allows `eval()` and friends. |\n| `@trustedOrigins` | The `…TRUSTED_ORIGINS` constant at runtime | Resolves to `auth.trustedOrigins` as configured in `quickback.config.ts`. |\n| `@nonce` | `'nonce-…'` per request | Reserved for the per-request nonce middleware shipping in 0.10.15. Using this in 0.10.14 is a compile-time error. |\n\nUnknown `@…` tokens are rejected at compile rather than silently stringified into the wire CSP.\n\n### Example: paste-in CSP for a Quickback SPA project\n\nThe bundled CMS and Account SPAs load Google Fonts cross-origin, so the strict `'self'`-only CSP would white-screen them on load. This config is a known-working starting point for Quickback projects with the bundled SPAs:\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // ...\n security: {\n csp: {\n defaultSrc: ['@self'],\n // Tailwind dynamic styles + bundled Google Fonts CSS need\n // unsafe-inline + the gstatic / googleapis hosts. Tightening\n // styles to nonces ships in 0.10.15.\n styleSrc: ['@self', '@unsafe-inline', 'https://fonts.googleapis.com'],\n scriptSrc: ['@self'],\n fontSrc: ['@self', 'data:', 'https://fonts.gstatic.com'],\n imgSrc: ['@self', 'data:', 'blob:', 'https:'],\n connectSrc: ['@self', '@trustedOrigins'],\n frameAncestors: ['@self', '@trustedOrigins'],\n formAction: ['@self'],\n baseUri: ['@self'],\n objectSrc: ['@none'],\n upgradeInsecureRequests: true,\n },\n },\n});\n```\n\n### Troubleshooting CSP violations\n\nIf the browser console shows CSP errors after enabling `security.csp`, match the directive named in the error against this table — it maps the failure mode back to the directive that needs widening.\n\n| Console error | Directive | Why it happens | Fix |\n|---|---|---|---|\n| `Loading the stylesheet 'https://fonts.googleapis.com/...' violates 'style-src ...'` | `styleSrc` | Bundled CMS/Account SPAs `<link>` to Google Fonts CSS. | Add `'https://fonts.googleapis.com'` to `styleSrc`. |\n| `Refused to load the font 'https://fonts.gstatic.com/...' because it violates 'font-src ...'` | `fontSrc` | The CSS file from googleapis loads `.woff2` files from gstatic. | Add `'https://fonts.gstatic.com'` to `fontSrc`. |\n| `Connecting to 'https://api.your-domain/...' violates 'connect-src 'self''` | `connectSrc` | API on a sibling subdomain (e.g. SPA on `app.example.com`, API on `api.example.com`) — `'self'` only covers exact origin. | Use `connectSrc: ['@self', '@trustedOrigins']` so the same allowlist `cors()` enforces gets reused. |\n| `Refused to apply inline style because it violates 'style-src ...'` | `styleSrc` | TanStack Router / Tailwind's `style=\"...\"` attributes are inline. | Add `'@unsafe-inline'` to `styleSrc` until 0.10.15 ships per-request nonces. |\n| `Refused to load the image '...' because it violates 'img-src ...'` | `imgSrc` | User-uploaded avatars / R2-hosted assets / `data:` URIs from blob previews. | Widen `imgSrc` to `['@self', 'data:', 'blob:', 'https:']` (or list specific hosts). |\n| `Refused to connect to 'wss://...' because it violates 'connect-src ...'` | `connectSrc` | Realtime / Durable Object WebSockets. | The `@trustedOrigins` sentinel covers HTTPS only — add the explicit `wss://` origin if your DO lives elsewhere. |\n\nThe general rule: `'self'` means *exact origin* (scheme + host + port). Anything cross-origin needs an explicit host or the `@trustedOrigins` sentinel. The [paste-in recipe above](#example-paste-in-csp-for-a-quickback-spa-project) is a known-good baseline for a stock Quickback project — start there and tighten, rather than starting from `'self'`-only and chasing console errors.\n\n### Auto-derivations\n\nThe compiler applies these so config stays minimal:\n\n- **`csp.frameAncestors` defaults to `['@self', '@trustedOrigins']`** when `csp` is set but `frameAncestors` is omitted. Same allowlist as CORS.\n- **`X-Frame-Options` derives from `csp.frameAncestors`** (`['@none']` → `DENY`, contains `@self` → `SAMEORIGIN`, otherwise omitted — XFO can't represent arbitrary origins so CSP becomes the truth there). Override with `security.frameOptions`.\n- **`corp: 'same-origin'` is auto-emitted when `coep` is set.** `require-corp` without CORP breaks the ASSETS binding fetches on Cloudflare; the compiler couples them so users don't have to remember.\n\n### CSP auto-config (0.10.15+)\n\nWhen you opt into a `csp` object, the compiler additively widens directives based on which Quickback features your project has enabled. **Additive** means anything you already wrote stays; we only push values that aren't already present.\n\n| Trigger | Auto-added | To directive | Why |\n|---|---|---|---|\n| `cms: true` OR `account: true` | `'unsafe-inline'` | `styleSrc` | Tailwind / TanStack Router emit inline `style=` attributes |\n| `cms: true` OR `account: true` | `https://fonts.googleapis.com` | `styleSrc` | Bundled SPAs `<link>` to Google Fonts CSS |\n| `cms: true` OR `account: true` | `https://fonts.gstatic.com` | `fontSrc` | The googleapis CSS loads `.woff2` from gstatic |\n| `csp` set (always) | `@trustedOrigins` | `connectSrc` | XHR/fetch must reach the same allowlist `cors()` permits — covers cross-subdomain APIs without re-listing them |\n| `cms: true` OR `account: true` | `https://${domain}` for each `cms.domain` / `account.domain` / `domain` / inferred unified domain | `connectSrc` | The Vite bundle hardcodes `VITE_QUICKBACK_API_URL` at compile time, so the SPA fetches that exact URL even when the page is served from a different origin (e.g. localhost dev hitting prod-baked SPA). Emitted with the host's first letter capitalised (`https://Api.example.com`) so `wrangler dev`'s response-header rewrite can't mangle it — see [the `wrangler dev` note below](#why-the-spa-baked-origin-shows-up-capitalised-in-csp). |\n\n**Scaffold rule:** if you set `defaultSrc` but omit the target directive (e.g. you wrote `defaultSrc: ['@self']` and nothing for `connectSrc`), auto-config creates the new directive seeded with your `defaultSrc` values plus the addition. `defaultSrc` itself stays clean. So `defaultSrc: ['@self']` + auto-config produces:\n\n```\ndefault-src 'self'\nstyle-src 'self' 'unsafe-inline' https://fonts.googleapis.com\nfont-src 'self' https://fonts.gstatic.com\nconnect-src 'self' @trustedOrigins https://api.your-app.com\n```\n\nEach directive is scoped to exactly what it needs. `defaultSrc` is *not* widened with style-only or connect-only hosts — that would let those hosts also reach `script-src` / `img-src` / `media-src` via fall-back, which is wider than the bundled SPA actually needs. (This rule changed in 0.10.17 — earlier versions incorrectly pushed additions into defaultSrc.)\n\n**Visibility:** every applied addition prints to stderr at compile time — one line per addition with the directive, value, and reason. No silent magic. Loop's compile output now looks like:\n\n```\n[security] auto-added 'unsafe-inline' to csp.styleSrc — account: true → bundled Account SPA → inline style attributes from Tailwind / TanStack Router\n[security] auto-added https://fonts.googleapis.com to csp.styleSrc — account: true → bundled Account SPA → loads Google Fonts CSS cross-origin\n[security] auto-added https://fonts.gstatic.com to csp.fontSrc — account: true → bundled Account SPA → woff2 font files served from gstatic.com\n[security] auto-added @trustedOrigins to csp.connectSrc — CORS-trusted origins must be reachable from XHR/fetch (matches cors() allowlist)\n```\n\n**Opt-out:** `security: { cspAutoConfig: false, csp: { ... } }` for projects fronted by a CDN that injects its own CSP, or teams that want strict from-scratch control. With auto-config off, every value above must be authored by hand.\n\n#### Why the SPA-baked origin shows up capitalised in CSP\n\nProjects with `domain: \"...\"` + bundled CMS / Account SPAs will see `connect-src 'self' https://Api.example.com …` in their served CSP — note the capital `A`. That's deliberate (added in 0.10.19) and works around a `wrangler dev` quirk, not a typo on our end.\n\n`wrangler dev` rewrites the configured `custom_domain` host string in **every** response header value (Location, Content-Security-Policy, X-…) to the local hostname, with a case-sensitive substring matcher. Without the case-shift, the served CSP becomes `connect-src 'self' https://localhost:8787 …` and the bundled SPA's hardcoded `VITE_QUICKBACK_API_URL` fetches get blocked because the prod URL no longer appears in the allowlist.\n\nCSP host-source matching is ASCII case-insensitive per CSP3 (`Matching Source Expressions`), so browsers treat `https://Api.example.com` as identical to `https://api.example.com` for the purpose of CSP checks. Wrangler's matcher is case-sensitive, so the capitalised form slips past the rewrite and survives into the served header. End result: the SPA's lowercase fetch target matches the capitalised CSP entry, auth round-trips work in dev, and prod CSP behaviour is unchanged (browsers don't care).\n\nIf wrangler ever fixes the response-header rewrite, the capitalised form remains a valid CSP entry — no follow-up needed.\n\nWith auto-config on, the [paste-in recipe above](#example-paste-in-csp-for-a-quickback-spa-project) becomes much shorter — most users only need:\n\n```ts\nsecurity: {\n csp: {\n defaultSrc: ['@self'],\n scriptSrc: ['@self'],\n imgSrc: ['@self', 'data:', 'blob:', 'https:'],\n objectSrc: ['@none'],\n upgradeInsecureRequests: true,\n },\n}\n```\n\nThe compiler fills in the SPA-specific font hosts, inline-style allowance, and trusted-origin connect rules from the project's own feature flags.\n\n## Cross-origin window/embedder isolation\n\n```ts title=\"quickback.config.ts\"\nsecurity: {\n coop: 'same-origin', // Defends against window.opener back-references from popups.\n coep: 'credentialless', // Required for SharedArrayBuffer / cross-origin isolation.\n // corp auto-emits as 'same-origin' here.\n}\n```\n\n## HSTS\n\nDefault: `max-age=31536000; includeSubDomains; preload` (HSTS preload-list eligible).\n\n```ts title=\"quickback.config.ts\"\nsecurity: {\n hsts: { maxAge: 63072000, includeSubDomains: true, preload: true },\n}\n```\n\nThe generated middleware automatically suppresses HSTS on `localhost`, `127.0.0.1`, and `*.localhost` regardless of this config. Without that gate, `wrangler dev` would pin the developer's browser to HTTPS for `maxAge` seconds, which is observable across every project on that machine.\n\nTo submit to the [HSTS preload list](https://hstspreload.org), you need:\n\n- `maxAge` ≥ 31536000 (one year)\n- `includeSubDomains: true`\n- `preload: true`\n\nThe compiler warns at compile time if `preload: true` without the other two — the preload list rejects either anyway.\n\n## Permissions Policy\n\nMap of feature name → list of allowed origins.\n\n```ts title=\"quickback.config.ts\"\nsecurity: {\n permissionsPolicy: {\n geolocation: [], // disabled for everyone\n microphone: ['self'], // allowed only on own origin\n camera: ['self', 'https://meet.example.com'],\n payment: [],\n },\n}\n```\n\nThe compiler encodes the wire syntax (which differs from CSP — values use `()`, not space-separated tokens, with bareword `self` and quoted URLs).\n\n## Custom response headers\n\n`security.headers` sets arbitrary response headers on every response, alongside the managed security headers. Keys are header names; values are static strings or templates that interpolate per-deploy Worker env vars via the `{{env.VAR_NAME}}` token.\n\n```ts title=\"quickback.config.ts\"\nsecurity: {\n headers: {\n // Stamp the deployed build identity. Read from Worker vars at runtime,\n // so the value tracks whatever you inject at deploy time.\n 'X-Server-Version': '{{env.SERVER_VERSION}}+{{env.SERVER_BUILD}}',\n\n // Static value — always emitted.\n 'X-Powered-By': 'Quickback',\n },\n}\n```\n\nThe canonical use case is exposing a build/version identity on every response so clients (`curl -I`, mobile apps, dashboards) can read the running build without a body request — and so you can detect drift between what's deployed and what git/CF report.\n\n### Omit-if-unset\n\nA header whose value references env vars is emitted **only when every referenced var is set** (non-`undefined`, non-empty string) at runtime. A version header on a Worker that forgot to inject the var simply doesn't appear — never `X-Server-Version: undefined`. Static headers (no `{{env…}}`) are always emitted.\n\nThe value is read from `c.env` per request, so you don't declare these vars at compile time — inject them as Worker vars (`[vars]` in `wrangler.toml`, or `--var` at deploy) and the header picks them up.\n\n### Generated middleware\n\nFor the config above, the compiler appends this to the security-headers middleware — no post-compile patching:\n\n```ts\n// Custom response headers (security.headers).\n{\n const v0 = (c.env as unknown as Record<string, string | undefined>)[\"SERVER_VERSION\"];\n const v1 = (c.env as unknown as Record<string, string | undefined>)[\"SERVER_BUILD\"];\n if (v0 != null && v0 !== '' && v1 != null && v1 !== '') {\n c.header(\"X-Server-Version\", `${v0}+${v1}`);\n }\n}\nc.header(\"X-Powered-By\", \"Quickback\");\n```\n\n### Rules\n\n- **Header names** must be valid HTTP field tokens. Names already managed by a dedicated `security` field — `Content-Security-Policy`, `Strict-Transport-Security`, `X-Frame-Options`, `X-Content-Type-Options`, `Cross-Origin-Opener-Policy`/`-Embedder-Policy`/`-Resource-Policy`, `Referrer-Policy`, `Permissions-Policy` — are rejected; use that field instead so the two emitters don't race.\n- **Only `{{env.VAR_NAME}}`** interpolation is supported (`VAR_NAME` is a valid env-var identifier). A malformed token (`{{env.FOO}`, `{{ENV.FOO}}`) is a compile-time error rather than leaking literal braces into the wire header.\n\n## Compile-time lint rules\n\nThe compiler walks the resolved config and emits warnings (or errors) for known footguns. Errors block compile; warnings print to stderr.\n\n| Code | Severity | Trigger |\n|---|---|---|\n| `csp/nonce-not-yet-supported` | error | `@nonce` sentinel used in 0.10.14. Per-request nonce middleware ships in 0.10.15. |\n| `csp/unsafe-inline-with-nonce` | error | `@unsafe-inline` and `@nonce` in the same directive (CSP3 silently ignores `unsafe-inline` when nonce is present). |\n| `csp/empty-resolved-directive` | error | `*Src` array contains only `@trustedOrigins` and `auth.trustedOrigins` is empty — would emit a directive Chrome reads as `'none'`. |\n| `csp/unsafe-inline-script` | warn | `@unsafe-inline` in `scriptSrc` defeats most XSS mitigations. |\n| `csp/open-source` | warn | Wildcard `*` or scheme-only `https:` / `http:` in any `*-src`. |\n| `csp/unsafe-eval-with-data` | warn | `@unsafe-eval` combined with any `data:` source — trivial bypass. |\n| `csp/missing-default-src` | warn | Other `*-src` set without `defaultSrc`. |\n| `csp/upgrade-with-http` | warn | `upgradeInsecureRequests: true` plus an `http://` source elsewhere. |\n| `csp/report-uri-only` | warn | `reportUri` set without `reportTo` (deprecated CSP2 path). |\n| `hsts/preload-needs-long-max-age` | warn | `preload: true` with `maxAge < 31536000`. |\n| `hsts/preload-needs-include-subdomains` | warn | `preload: true` without `includeSubDomains`. |\n\n## Verification\n\nSpin up the deployed Worker (or `wrangler dev`) and check the response headers:\n\n```bash\ncurl -sI https://my-api.example.com/health \\\n | grep -E '^(content-security-policy|x-frame-options|strict-transport-security|cross-origin-opener-policy|cross-origin-embedder-policy|cross-origin-resource-policy|referrer-policy|permissions-policy):'\n```\n\nUse [securityheaders.com](https://securityheaders.com) for an external grade — Quickback's defaults are A on the baseline and A+ once a fuller `csp` is configured."
70
+ "content": "Every compiled Quickback Worker sets a baseline of security response-headers on every response: HSTS, `X-Content-Type-Options: nosniff`, a clickjacking CSP (`frame-ancestors 'self' …TRUSTED_ORIGINS`), `X-Frame-Options: SAMEORIGIN`, `Referrer-Policy`, and `Permissions-Policy`. Adding the `security` block lets you override individual headers, ship a fuller Content-Security-Policy, or suppress them all if an upstream gateway handles headers.\n\n## Default behavior\n\nOmit `security` entirely → the baseline above. No config change needed for clickjacking + HSTS protection.\n\n```ts title=\"quickback.config.ts\"\n\nexport default defineConfig({\n name: 'my-api',\n // ...\n // security defaults are applied automatically.\n});\n```\n\n## Suppress every security header\n\nFor Workers fronted by a gateway that owns headers:\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // ...\n security: false,\n});\n```\n\nThe compiler emits a no-op middleware comment so the route table still lines up with the rest of the generated code, but no `c.header(...)` calls fire.\n\n## Per-header overrides\n\nEach field on the `security` block accepts either a typed value or `false` to suppress that specific header. Defaults still apply for fields you don't set.\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // ...\n security: {\n // Suppress just CSP — keeps HSTS, referrer, permissions, etc.\n csp: false,\n\n // Or override individual fields:\n coop: 'same-origin',\n coep: 'credentialless',\n referrerPolicy: 'no-referrer',\n permissionsPolicy: { geolocation: [], microphone: [], camera: [], payment: [] },\n hsts: { maxAge: 63072000, includeSubDomains: true, preload: true },\n },\n});\n```\n\n## Content Security Policy\n\n`security.csp` accepts a typed object. Each `*Src` field is an array of source expressions. The compiler accepts both the `@`-prefixed sentinels (idiomatic, type-safe) and CSP wire-form keywords (`\"'self'\"`, `\"'unsafe-inline'\"`); both normalize to the same output.\n\n### Sentinels\n\n| Sentinel | Wire form | Notes |\n|---|---|---|\n| `@self` | `'self'` | Same-origin. |\n| `@none` | `'none'` | Empty-set keyword. |\n| `@unsafe-inline` | `'unsafe-inline'` | Allows inline scripts/styles — defeats most XSS mitigation when used in `script-src`. |\n| `@unsafe-eval` | `'unsafe-eval'` | Allows `eval()` and friends. |\n| `@trustedOrigins` | The `…TRUSTED_ORIGINS` constant at runtime | Resolves to `auth.trustedOrigins` as configured in `quickback.config.ts`. |\n| `@nonce` | `'nonce-…'` per request | Reserved for the per-request nonce middleware shipping in 0.10.15. Using this in 0.10.14 is a compile-time error. |\n\nUnknown `@…` tokens are rejected at compile rather than silently stringified into the wire CSP.\n\n### Example: paste-in CSP for a Quickback SPA project\n\nThe bundled CMS and Account SPAs load Google Fonts cross-origin, so the strict `'self'`-only CSP would white-screen them on load. This config is a known-working starting point for Quickback projects with the bundled SPAs:\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // ...\n security: {\n csp: {\n defaultSrc: ['@self'],\n // Tailwind dynamic styles + bundled Google Fonts CSS need\n // unsafe-inline + the gstatic / googleapis hosts. Tightening\n // styles to nonces ships in 0.10.15.\n styleSrc: ['@self', '@unsafe-inline', 'https://fonts.googleapis.com'],\n scriptSrc: ['@self'],\n fontSrc: ['@self', 'data:', 'https://fonts.gstatic.com'],\n imgSrc: ['@self', 'data:', 'blob:', 'https:'],\n connectSrc: ['@self', '@trustedOrigins'],\n frameAncestors: ['@self', '@trustedOrigins'],\n formAction: ['@self'],\n baseUri: ['@self'],\n objectSrc: ['@none'],\n upgradeInsecureRequests: true,\n },\n },\n});\n```\n\n### Troubleshooting CSP violations\n\nIf the browser console shows CSP errors after enabling `security.csp`, match the directive named in the error against this table — it maps the failure mode back to the directive that needs widening.\n\n| Console error | Directive | Why it happens | Fix |\n|---|---|---|---|\n| `Loading the stylesheet 'https://fonts.googleapis.com/...' violates 'style-src ...'` | `styleSrc` | Bundled CMS/Account SPAs `<link>` to Google Fonts CSS. | Add `'https://fonts.googleapis.com'` to `styleSrc`. |\n| `Refused to load the font 'https://fonts.gstatic.com/...' because it violates 'font-src ...'` | `fontSrc` | The CSS file from googleapis loads `.woff2` files from gstatic. | Add `'https://fonts.gstatic.com'` to `fontSrc`. |\n| `Connecting to 'https://api.your-domain/...' violates 'connect-src 'self''` | `connectSrc` | API on a sibling subdomain (e.g. SPA on `app.example.com`, API on `api.example.com`) — `'self'` only covers exact origin. | Use `connectSrc: ['@self', '@trustedOrigins']` so the same allowlist `cors()` enforces gets reused. |\n| `Refused to apply inline style because it violates 'style-src ...'` | `styleSrc` | TanStack Router / Tailwind's `style=\"...\"` attributes are inline. | Add `'@unsafe-inline'` to `styleSrc` until 0.10.15 ships per-request nonces. |\n| `Refused to load the image '...' because it violates 'img-src ...'` | `imgSrc` | User-uploaded avatars / R2-hosted assets / `data:` URIs from blob previews. | Widen `imgSrc` to `['@self', 'data:', 'blob:', 'https:']` (or list specific hosts). |\n| `Refused to connect to 'wss://...' because it violates 'connect-src ...'` | `connectSrc` | Realtime / Durable Object WebSockets. | The `@trustedOrigins` sentinel covers HTTPS only — add the explicit `wss://` origin if your DO lives elsewhere. |\n\nThe general rule: `'self'` means *exact origin* (scheme + host + port). Anything cross-origin needs an explicit host or the `@trustedOrigins` sentinel. The [paste-in recipe above](#example-paste-in-csp-for-a-quickback-spa-project) is a known-good baseline for a stock Quickback project — start there and tighten, rather than starting from `'self'`-only and chasing console errors.\n\n### Auto-derivations\n\nThe compiler applies these so config stays minimal:\n\n- **`csp.frameAncestors` defaults to `['@self', '@trustedOrigins']`** when `csp` is set but `frameAncestors` is omitted. Same allowlist as CORS.\n- **`X-Frame-Options` derives from `csp.frameAncestors`** (`['@none']` → `DENY`, contains `@self` → `SAMEORIGIN`, otherwise omitted — XFO can't represent arbitrary origins so CSP becomes the truth there). Override with `security.frameOptions`.\n- **`corp: 'same-origin'` is auto-emitted when `coep` is set.** `require-corp` without CORP breaks the ASSETS binding fetches on Cloudflare; the compiler couples them so users don't have to remember.\n\n### CSP auto-config (0.10.15+)\n\nWhen you opt into a `csp` object, the compiler additively widens directives based on which Quickback features your project has enabled. **Additive** means anything you already wrote stays; we only push values that aren't already present.\n\n| Trigger | Auto-added | To directive | Why |\n|---|---|---|---|\n| `cms: true` OR `account: true` | `'unsafe-inline'` | `styleSrc` | Tailwind / TanStack Router emit inline `style=` attributes |\n| `cms: true` OR `account: true` | `https://fonts.googleapis.com` | `styleSrc` | Bundled SPAs `<link>` to Google Fonts CSS |\n| `cms: true` OR `account: true` | `https://fonts.gstatic.com` | `fontSrc` | The googleapis CSS loads `.woff2` from gstatic |\n| `csp` set (always) | `@trustedOrigins` | `connectSrc` | XHR/fetch must reach the same allowlist `cors()` permits — covers cross-subdomain APIs without re-listing them |\n| `cms: true` OR `account: true` | `https://${domain}` for each `cms.domain` / `account.domain` / `domain` / inferred unified domain | `connectSrc` | The Vite bundle hardcodes `VITE_QUICKBACK_API_URL` at compile time, so the SPA fetches that exact URL even when the page is served from a different origin (e.g. localhost dev hitting prod-baked SPA). Emitted with the host's first letter capitalised (`https://Api.example.com`) so `wrangler dev`'s response-header rewrite can't mangle it — see [the `wrangler dev` note below](#why-the-spa-baked-origin-shows-up-capitalised-in-csp). |\n| `cms: true` OR `account: true` | `'sha256-…'` (one exact hash per bundled SPA) | `scriptSrc` | The worker injects `<script>window.__QUICKBACK_RUNTIME={...}</script>` into every served SPA shell (runtime-configured SPAs). The blob is fixed at compile time, so an exact script hash keeps strict `script-src` policies intact — no `'unsafe-inline'`. |\n\n**Scaffold rule:** if you set `defaultSrc` but omit the target directive (e.g. you wrote `defaultSrc: ['@self']` and nothing for `connectSrc`), auto-config creates the new directive seeded with your `defaultSrc` values plus the addition. `defaultSrc` itself stays clean. So `defaultSrc: ['@self']` + auto-config produces:\n\n```\ndefault-src 'self'\nstyle-src 'self' 'unsafe-inline' https://fonts.googleapis.com\nfont-src 'self' https://fonts.gstatic.com\nconnect-src 'self' @trustedOrigins https://api.your-app.com\n```\n\nEach directive is scoped to exactly what it needs. `defaultSrc` is *not* widened with style-only or connect-only hosts — that would let those hosts also reach `script-src` / `img-src` / `media-src` via fall-back, which is wider than the bundled SPA actually needs. (This rule changed in 0.10.17 — earlier versions incorrectly pushed additions into defaultSrc.)\n\n**Visibility:** every applied addition prints to stderr at compile time — one line per addition with the directive, value, and reason. No silent magic. Loop's compile output now looks like:\n\n```\n[security] auto-added 'unsafe-inline' to csp.styleSrc — account: true → bundled Account SPA → inline style attributes from Tailwind / TanStack Router\n[security] auto-added https://fonts.googleapis.com to csp.styleSrc — account: true → bundled Account SPA → loads Google Fonts CSS cross-origin\n[security] auto-added https://fonts.gstatic.com to csp.fontSrc — account: true → bundled Account SPA → woff2 font files served from gstatic.com\n[security] auto-added @trustedOrigins to csp.connectSrc — CORS-trusted origins must be reachable from XHR/fetch (matches cors() allowlist)\n```\n\n**Opt-out:** `security: { cspAutoConfig: false, csp: { ... } }` for projects fronted by a CDN that injects its own CSP, or teams that want strict from-scratch control. With auto-config off, every value above must be authored by hand.\n\n#### Why the SPA-baked origin shows up capitalised in CSP\n\nProjects with `domain: \"...\"` + bundled CMS / Account SPAs will see `connect-src 'self' https://Api.example.com …` in their served CSP — note the capital `A`. That's deliberate (added in 0.10.19) and works around a `wrangler dev` quirk, not a typo on our end.\n\n`wrangler dev` rewrites the configured `custom_domain` host string in **every** response header value (Location, Content-Security-Policy, X-…) to the local hostname, with a case-sensitive substring matcher. Without the case-shift, the served CSP becomes `connect-src 'self' https://localhost:8787 …` and the bundled SPA's hardcoded `VITE_QUICKBACK_API_URL` fetches get blocked because the prod URL no longer appears in the allowlist.\n\nCSP host-source matching is ASCII case-insensitive per CSP3 (`Matching Source Expressions`), so browsers treat `https://Api.example.com` as identical to `https://api.example.com` for the purpose of CSP checks. Wrangler's matcher is case-sensitive, so the capitalised form slips past the rewrite and survives into the served header. End result: the SPA's lowercase fetch target matches the capitalised CSP entry, auth round-trips work in dev, and prod CSP behaviour is unchanged (browsers don't care).\n\nIf wrangler ever fixes the response-header rewrite, the capitalised form remains a valid CSP entry — no follow-up needed.\n\nWith auto-config on, the [paste-in recipe above](#example-paste-in-csp-for-a-quickback-spa-project) becomes much shorter — most users only need:\n\n```ts\nsecurity: {\n csp: {\n defaultSrc: ['@self'],\n scriptSrc: ['@self'],\n imgSrc: ['@self', 'data:', 'blob:', 'https:'],\n objectSrc: ['@none'],\n upgradeInsecureRequests: true,\n },\n}\n```\n\nThe compiler fills in the SPA-specific font hosts, inline-style allowance, and trusted-origin connect rules from the project's own feature flags.\n\n## Cross-origin window/embedder isolation\n\n```ts title=\"quickback.config.ts\"\nsecurity: {\n coop: 'same-origin', // Defends against window.opener back-references from popups.\n coep: 'credentialless', // Required for SharedArrayBuffer / cross-origin isolation.\n // corp auto-emits as 'same-origin' here.\n}\n```\n\n## HSTS\n\nDefault: `max-age=31536000; includeSubDomains; preload` (HSTS preload-list eligible).\n\n```ts title=\"quickback.config.ts\"\nsecurity: {\n hsts: { maxAge: 63072000, includeSubDomains: true, preload: true },\n}\n```\n\nThe generated middleware automatically suppresses HSTS on `localhost`, `127.0.0.1`, and `*.localhost` regardless of this config. Without that gate, `wrangler dev` would pin the developer's browser to HTTPS for `maxAge` seconds, which is observable across every project on that machine.\n\nTo submit to the [HSTS preload list](https://hstspreload.org), you need:\n\n- `maxAge` ≥ 31536000 (one year)\n- `includeSubDomains: true`\n- `preload: true`\n\nThe compiler warns at compile time if `preload: true` without the other two — the preload list rejects either anyway.\n\n## Permissions Policy\n\nMap of feature name → list of allowed origins.\n\n```ts title=\"quickback.config.ts\"\nsecurity: {\n permissionsPolicy: {\n geolocation: [], // disabled for everyone\n microphone: ['self'], // allowed only on own origin\n camera: ['self', 'https://meet.example.com'],\n payment: [],\n },\n}\n```\n\nThe compiler encodes the wire syntax (which differs from CSP — values use `()`, not space-separated tokens, with bareword `self` and quoted URLs).\n\n## Custom response headers\n\n`security.headers` sets arbitrary response headers on every response, alongside the managed security headers. Keys are header names; values are static strings or templates that interpolate per-deploy Worker env vars via the `{{env.VAR_NAME}}` token.\n\n```ts title=\"quickback.config.ts\"\nsecurity: {\n headers: {\n // Stamp the deployed build identity. Read from Worker vars at runtime,\n // so the value tracks whatever you inject at deploy time.\n 'X-Server-Version': '{{env.SERVER_VERSION}}+{{env.SERVER_BUILD}}',\n\n // Static value — always emitted.\n 'X-Powered-By': 'Quickback',\n },\n}\n```\n\nThe canonical use case is exposing a build/version identity on every response so clients (`curl -I`, mobile apps, dashboards) can read the running build without a body request — and so you can detect drift between what's deployed and what git/CF report.\n\n### Omit-if-unset\n\nA header whose value references env vars is emitted **only when every referenced var is set** (non-`undefined`, non-empty string) at runtime. A version header on a Worker that forgot to inject the var simply doesn't appear — never `X-Server-Version: undefined`. Static headers (no `{{env…}}`) are always emitted.\n\nThe value is read from `c.env` per request, so you don't declare these vars at compile time — inject them as Worker vars (`[vars]` in `wrangler.toml`, or `--var` at deploy) and the header picks them up.\n\n### Generated middleware\n\nFor the config above, the compiler appends this to the security-headers middleware — no post-compile patching:\n\n```ts\n// Custom response headers (security.headers).\n{\n const v0 = (c.env as unknown as Record<string, string | undefined>)[\"SERVER_VERSION\"];\n const v1 = (c.env as unknown as Record<string, string | undefined>)[\"SERVER_BUILD\"];\n if (v0 != null && v0 !== '' && v1 != null && v1 !== '') {\n c.header(\"X-Server-Version\", `${v0}+${v1}`);\n }\n}\nc.header(\"X-Powered-By\", \"Quickback\");\n```\n\n### Rules\n\n- **Header names** must be valid HTTP field tokens. Names already managed by a dedicated `security` field — `Content-Security-Policy`, `Strict-Transport-Security`, `X-Frame-Options`, `X-Content-Type-Options`, `Cross-Origin-Opener-Policy`/`-Embedder-Policy`/`-Resource-Policy`, `Referrer-Policy`, `Permissions-Policy` — are rejected; use that field instead so the two emitters don't race.\n- **Only `{{env.VAR_NAME}}`** interpolation is supported (`VAR_NAME` is a valid env-var identifier). A malformed token (`{{env.FOO}`, `{{ENV.FOO}}`) is a compile-time error rather than leaking literal braces into the wire header.\n\n## Compile-time lint rules\n\nThe compiler walks the resolved config and emits warnings (or errors) for known footguns. Errors block compile; warnings print to stderr.\n\n| Code | Severity | Trigger |\n|---|---|---|\n| `csp/nonce-not-yet-supported` | error | `@nonce` sentinel used in 0.10.14. Per-request nonce middleware ships in 0.10.15. |\n| `csp/unsafe-inline-with-nonce` | error | `@unsafe-inline` and `@nonce` in the same directive (CSP3 silently ignores `unsafe-inline` when nonce is present). |\n| `csp/empty-resolved-directive` | error | `*Src` array contains only `@trustedOrigins` and `auth.trustedOrigins` is empty — would emit a directive Chrome reads as `'none'`. |\n| `csp/unsafe-inline-script` | warn | `@unsafe-inline` in `scriptSrc` defeats most XSS mitigations. |\n| `csp/open-source` | warn | Wildcard `*` or scheme-only `https:` / `http:` in any `*-src`. |\n| `csp/unsafe-eval-with-data` | warn | `@unsafe-eval` combined with any `data:` source — trivial bypass. |\n| `csp/missing-default-src` | warn | Other `*-src` set without `defaultSrc`. |\n| `csp/upgrade-with-http` | warn | `upgradeInsecureRequests: true` plus an `http://` source elsewhere. |\n| `csp/report-uri-only` | warn | `reportUri` set without `reportTo` (deprecated CSP2 path). |\n| `hsts/preload-needs-long-max-age` | warn | `preload: true` with `maxAge < 31536000`. |\n| `hsts/preload-needs-include-subdomains` | warn | `preload: true` without `includeSubDomains`. |\n\n## Verification\n\nSpin up the deployed Worker (or `wrangler dev`) and check the response headers:\n\n```bash\ncurl -sI https://my-api.example.com/health \\\n | grep -E '^(content-security-policy|x-frame-options|strict-transport-security|cross-origin-opener-policy|cross-origin-embedder-policy|cross-origin-resource-policy|referrer-policy|permissions-policy):'\n```\n\nUse [securityheaders.com](https://securityheaders.com) for an external grade — Quickback's defaults are A on the baseline and A+ once a fuller `csp` is configured."
67
71
  },
68
72
  "compiler/config/single-tenant": {
69
73
  "title": "Pinned Organization Mode",
@@ -75,11 +79,11 @@ export const DOCS = {
75
79
  },
76
80
  "compiler/definitions/access": {
77
81
  "title": "Access - Role & Condition-Based Access Control",
78
- "content": "Define who can perform read and write operations and under what conditions.\n\n## Basic Usage\n\n```typescript\n// features/applications/applications.ts\n\nexport const applications = sqliteTable('applications', {\n id: text('id').primaryKey(),\n candidateId: text('candidate_id').notNull(),\n jobId: text('job_id').notNull(),\n stage: text('stage').notNull(),\n notes: text('notes'),\n organizationId: text('organization_id').notNull(),\n});\n\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: { createable: [\"candidateId\", \"jobId\", \"notes\"], updatable: [\"notes\"] },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n});\n```\n\n## Role Hierarchy\n\nIf your project uses a tiered role system (e.g., `member` < `admin` < `owner`), you can define a hierarchy in your config and use the `+` suffix to mean \"this role and above\":\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n name: \"my-app\",\n auth: {\n roleHierarchy: ['member', 'admin', 'owner'], // lowest → highest\n },\n // ...\n});\n```\n\nThen in your resource definitions:\n\n```typescript\nread: { access: { roles: [\"member+\"] } }, // member, admin, owner\ncreate: { access: { roles: [\"admin+\"] } }, // admin, owner\ndelete: { access: { roles: [\"owner\"] } }, // owner only (no +)\n```\n\nThe `+` suffix expands at compile time — `\"member+\"` becomes `[\"member\", \"admin\", \"owner\"]` in the generated code. You can mix hierarchical and exact roles: `roles: [\"member+\", \"finance\"]` expands to `[\"member\", \"admin\", \"owner\", \"finance\"]`.\n\n- Roles without `+` are exact matches (no expansion)\n- Pseudo-roles / reserved markers (`PUBLIC`, `AUTHENTICATED`, `USER`, `ADMIN`, `SYSADMIN`) cannot use the `+` suffix — they're terminal markers\n- Using `+` with a role not in the hierarchy throws a compile error\n- Using `+` without configuring `auth.roleHierarchy` throws a compile error\n\n## Custom org roles\n\nYou're not limited to Better Auth's built-in `owner` / `admin` / `member` —\nany lowercase role name you reference in an access tree (`\"recruiter\"`,\n`\"hiring-manager\"`, `\"support\"`, …) is a custom org-membership role, matched\nagainst `ctx.roles` like the built-ins.\n\nAs of v0.46, custom roles declared in access trees are **auto-registered\nwith the Better Auth organization plugin**, so members can actually be\nprovisioned into them: `invite-member` and `update-member-role` accept them\n(previously they rejected custom roles with `400 ROLE_NOT_FOUND`).\nAuto-registered roles carry member-equivalent Better Auth permissions —\nregistration is about assignability; your access trees remain the\nauthorization model. If you pass your own `roles` / `ac` to the organization\nplugin options, those win and auto-registration is skipped.\n\n## Configuration Options\n\n```typescript\ninterface Access {\n // Org-membership roles (OR logic — user needs at least one)\n // Matched against ctx.roles. Use \"role+\" suffix for hierarchy expansion.\n roles?: string[];\n\n // User-table role (OR logic). Matched against ctx.userRole from the\n // user.role column — independent of org membership. See userRole below.\n userRole?: string[];\n\n // Record-level conditions\n record?: {\n [field: string]: FieldCondition;\n };\n\n // Combinators\n or?: Access[];\n and?: Access[];\n}\n```\n\n## `userRole` vs `roles`\n\n`roles` and `userRole` check **two different fields** and are often confused — get this wrong and you'll grant access too broadly.\n\n| Primitive | Checks | Source | Example values |\n|-----------|--------|--------|----------------|\n| `roles` | `ctx.roles` | Org membership roles | `\"owner\"`, `\"admin\"`, `\"member\"` |\n| `userRole` | `ctx.userRole` | The `user.role` column (Better Auth / platform control-plane roles) | `\"user\"`, `\"appmanager\"`, `\"sysadmin\"` |\n\nIn multi-tenant mode, **`roles: [\"admin\"]` means \"org admin\" — not a platform-wide role.** An org-admin of Acme Corp has no elevated rights across other orgs. If you want platform control-plane operators through regardless of org membership (CMS, Better Auth admin surfaces, support tooling), use `userRole: [\"appmanager\"]`. If you need true cross-tenant data-plane access, use `roles: [\"SYSADMIN\"]` (with `cms: { sysadmin: true }`).\n\nPinned organization mode does not change this split. `roles` still come from organization membership in the pinned org, while `userRole` still comes from Better Auth's `user.role` column.\n\n### When to use `userRole`\n\n```typescript\n// Platform control-plane users can see SSNs on every customer record, regardless of org\nmasking: {\n ssn: { type: 'ssn', show: { userRole: ['appmanager'] } },\n}\n\n// Platform ops (user.role === 'appmanager') OR the org owner can refund\naccess: {\n or: [\n { userRole: ['appmanager'] },\n { roles: ['owner'] },\n ],\n}\n\n// CMS-internal resource: only platform control-plane users\nread: { access: { userRole: ['appmanager'] } },\ncreate: { access: { userRole: ['appmanager'] } },\nupdate: { access: { userRole: ['appmanager'] } },\ndelete: { access: { userRole: ['appmanager'] } },\n```\n\nWhen `roles` and `userRole` both appear in a single `Access` node, they're combined with AND — the user must satisfy both. Use `or:` to express \"one or the other\".\n\n`userRole` doesn't expand with the `+` hierarchy suffix — user-table roles are flat (typically just `\"user\"`, `\"appmanager\"`, and `\"sysadmin\"`). If you've added custom user-table roles via Better Auth, list them explicitly.\n\n### Pseudo-roles\n\nQuickback ships five reserved UPPERCASE markers. Four are real pseudo-roles handled directly by the compiler; `ADMIN` is retained only as a reserved legacy marker so the compiler can fail loudly with migration guidance. The casing carries the boundary: UPPERCASE = compiler-owned marker, lowercase = real role from a plugin's table (e.g. `members.role` from the org plugin).\n\n| Role | Auth gate | Compile-time requirement | Runtime check |\n|------|-----------|-------------------------|---------------|\n| `PUBLIC` | bypassed | none — explicit opt-in for unauthenticated access | always passes (auth skipped) |\n| `AUTHENTICATED` | required | none | `ctx.authenticated === true` |\n| `USER` | required | resource firewall **must** scope by `userId` | `ctx.authenticated` AND (`ctx.userRole` is unset OR `ctx.userRole === \"user\"`) |\n| `ADMIN` | required | reserved legacy marker — compiler rejects it | `false` |\n| `SYSADMIN` | required | `cms: { sysadmin: true }` **must** be set on the project | `ctx.authenticated && ctx.userRole === \"sysadmin\"` |\n\nYou can mix pseudo-roles with real roles in the same list — they're OR'd together.\n\n#### `PUBLIC` — unauthenticated access\n\nUse `roles: [\"PUBLIC\"]` for public-facing endpoints like contact forms, public listings, or webhooks. Skips both the auth gate and the role check.\n\n```typescript\naccess: { roles: [\"PUBLIC\"] }\n```\n\n**Important:**\n- `PUBLIC` skips authentication and role checks — anyone can call the endpoint\n- **`PUBLIC` is the explicit, uppercase opt-in for unauthenticated access.** It works on every access node — reads, top-level writes (`create`/`update`/`delete`/`upsert`), views, and actions. The compiler trusts the marker; row-level safety comes from the firewall, masking, and (for token-gated endpoints like RSVP confirm, magic-link redemption, List-Unsubscribe-Post, webhook ingest) your handler's own validation. Anonymous write endpoints typically pair `roles: [\"PUBLIC\"]` with `firewall: { exception: true }` on the resource so the row predicate doesn't reject every unauthenticated caller.\n- **Firewall still applies** — data is scoped by the firewall (organization, owner, team)\n- **Tree semantics:** `PUBLIC` admits anonymous callers from anywhere in the access tree, not just a flat `roles` list. An `or:` arm containing `PUBLIC` admits anonymous callers past the authentication gate; an `and:` group admits them only when *every* arm does. The access, org, and firewall layers still evaluate the full tree afterwards. (Before v0.46 the emitted auth gate only honored `PUBLIC` in a flat `roles` list — a nested `PUBLIC` arm incorrectly answered `401`.)\n- Every `PUBLIC` action invocation is **mandatory audit logged** to the security audit table (IP address, input, result, timing)\n- The wildcard `\"*\"` is **not supported** — using it throws a compile-time error\n- Tables with no isolation columns and any `PUBLIC` route do not require `firewall: [{ exception: true }]`\n\nFor org-scoped tables, `PUBLIC` routes still filter by organization. Since the user isn't authenticated, the organization ID must be passed as a query parameter:\n\n```\nGET /api/v1/listings?organizationId=org_abc123\n```\n\nThe firewall WHERE clause is always enforced. If no `organizationId` is provided, the API returns a `403` with code `ORG_REQUIRED`.\n\n```typescript\n// Public listing page — anyone can browse, but scoped to an org\nexport default defineTable(listings, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: { access: { roles: [\"PUBLIC\"] } }, // Public browsing + detail\n create: { access: { roles: [\"admin\", \"member\"] } }, // Auth required to create\n});\n```\n\n#### `AUTHENTICATED` — any signed-in user\n\nUse `roles: [\"AUTHENTICATED\"]` for endpoints that any logged-in user can hit, regardless of role or org membership. No plugin context required.\n\n```typescript\n// Public events feed — any signed-in user can list/read; anonymous gets 401\nread: { access: { roles: [\"AUTHENTICATED\"] } }\n```\n\n#### `USER` — per-user records\n\nUse `roles: [\"USER\"]` for resources where each user only sees their own records. **Requires the firewall to scope by `userId`** — the role marker is the access half of the pair, the firewall is the row-filter half.\n\n```typescript\n// \"My todos\" — each caller sees only their own rows\nexport default defineTable(todos, {\n firewall: [{ field: 'userId', equals: 'ctx.userId' }],\n read: { access: { roles: [\"USER\"] } },\n create: { access: { roles: [\"USER\"] } },\n update: { access: { roles: [\"USER\"] } },\n delete: { access: { roles: [\"USER\"] } },\n});\n```\n\nIf you forget the `userId` firewall predicate, the compiler throws:\n\n> `roles: [\"USER\"]` requires the resource to be scoped per-user. Add a `userId` column (auto-scoped) or an explicit owner predicate. If you want any signed-in user to read all records, use `roles: [\"AUTHENTICATED\"]` instead.\n\nWhen the Better Auth admin plugin is enabled, `USER` matches `user.role === \"user\"` specifically — appmanagers and sysadmins are excluded. If the same route should serve both, express it explicitly with `or: [{ roles: [\"USER\"] }, { userRole: [\"appmanager\"] }]`.\n\n#### `ADMIN` — legacy reserved marker (compile-time error)\n\n`roles: [\"ADMIN\"]` is no longer supported. The compiler fails hard on any use of `ADMIN` so platform and tenant roles can't be confused.\n\n```typescript\n// Platform control-plane audit log\nread: { access: { userRole: [\"appmanager\"] } }\n```\n\nUse one of these instead:\n\n- `userRole: [\"appmanager\"]` for platform control-plane access\n- `roles: [\"admin\"]` for org-membership admin access\n- `roles: [\"SYSADMIN\"]` for true cross-tenant access\n\n#### `SYSADMIN` — cross-tenant DB-admin tier\n\nUse `roles: [\"SYSADMIN\"]` for endpoints that should only be reachable by platform sysadmins — the cross-tenant DB-admin tier introduced in v0.15.0. Compiles to `ctx.userRole === \"sysadmin\"`. **Requires `cms: { sysadmin: true }` on the project config**; without that flag, using `SYSADMIN` fails the compile so the role can't sit as dead code.\n\n```typescript\n// Cross-tenant audit dashboard, sysadmin-only\nread: { access: { roles: [\"SYSADMIN\"] } }\n```\n\n`SYSADMIN` is distinct from `userRole: [\"appmanager\"]`. Appmanager is the platform control-plane tier (CMS shell, Better Auth admin surfaces, support tooling); sysadmin is the cross-tenant data-plane tier. The one place sysadmin gets implicit extra powers is **the firewall escape hatch**: when `cms.sysadmin: true`, every `buildFirewallConditions` emits an `if (ctx.userRole === 'sysadmin') return undefined;` (or just the soft-delete predicate when present) at the top — so sysadmins see every tenant's rows, not just their own org's. That escape hatch does NOT fire for `userRole === 'appmanager'`; appmanagers still go through the firewall like everyone else.\n\nThis separation exists so Better Auth admin-plugin powers (user management, impersonation, org creation) and DB-admin powers (cross-tenant data inspection) stay decoupled. A user can have `user.role === 'appmanager'` without DB-level cross-tenant access; a user can have `user.role === 'sysadmin'` without org-membership context. See [CMS Configuration](/compiler/config#cms-configuration) for the `cms.sysadmin` flag, the cross-tenant `/auth/v1/admin/list-organizations` endpoint, and the SPA's \"All organizations\" sentinel.\n\n#### Mixing pseudo-roles with real roles\n\nPseudo-roles and lowercase real roles compose with OR:\n\n```typescript\n// Record owner OR a platform control-plane user can read\nread: { access: { or: [{ roles: [\"USER\"] }, { userRole: [\"appmanager\"] }] } }\n\n// Org owner OR sysadmin\ndelete: { access: { or: [{ roles: [\"owner\"] }, { roles: [\"SYSADMIN\"] }] } }\n```\n\n> Note: `userRole: [\"appmanager\"]` never bypasses a `userId` firewall scope. If you need cross-user visibility, expose a separate route with `firewall: { exception: true }` or a `SYSADMIN`-gated cross-tenant surface.\n\n#### Quick reference\n\n```typescript\n// Unauthenticated public\naccess: { roles: [\"PUBLIC\"] }\n\n// Any signed-in user, no scoping\naccess: { roles: [\"AUTHENTICATED\"] }\n\n// Per-user records (requires userId firewall scope)\naccess: { roles: [\"USER\"] }\n\n// Platform control-plane\naccess: { userRole: [\"appmanager\"] }\n\n// Cross-tenant DB-admin tier\naccess: { roles: [\"SYSADMIN\"] }\n\n// Org-membership roles with hierarchy expansion\naccess: { roles: [\"member+\"] } // expands to [\"member\", \"admin\", \"owner\"]\naccess: { roles: [\"admin+\"] } // expands to [\"admin\", \"owner\"]\naccess: { roles: [\"admin\"] } // exact match (no expansion)\n```\n\n```typescript\n// Field conditions - value can be string | number | boolean\ntype FieldCondition =\n | { equals: value | '$ctx.userId' | '$ctx.activeOrgId' }\n | { notEquals: value }\n | { in: value[] }\n | { notIn: value[] }\n | { lessThan: number }\n | { greaterThan: number }\n | { lessThanOrEqual: number }\n | { greaterThanOrEqual: number };\n```\n\n## Relationship-based authorization\n\nBeyond Better Auth roles (org membership, user-table role) and pseudo-roles, Quickback supports **relationship-based authorization roles** — names that bind to a declared relationship between the caller and a resource. Use these when access should follow a domain-table membership (\"user is a confirmed guest of this event\") rather than an org/admin gate.\n\n### `authz.relationships`\n\nDeclare relationships once in `quickback.config.ts`:\n\n```typescript\n// quickback.config.ts\n\nexport default defineConfig({\n // ...providers...\n authz: {\n relationships: {\n guestOf: {\n from: 'event_guests', // table name string\n subject: { column: 'userId', equals: 'ctx.userId' }, // caller side\n resource: { column: 'eventId' }, // resource side\n where: { status: 'confirmed' }, // optional filter\n },\n },\n roles: {\n guest: { via: 'guestOf' },\n // Composite: any guest OR an org owner/admin\n eventStaff: {\n or: [\n { via: 'guestOf' },\n { roles: ['admin', 'owner'] },\n ],\n },\n },\n },\n});\n```\n\n### Using relationship-roles in resources\n\nResource definitions reference declared roles by name in `roles: [...]` arrays exactly like BA roles or pseudo-roles. The compiler rewrites the access tree at build time so the runtime route does an inline relationship lookup against the declared table.\n\n**Today (v1) this works on:**\n\n| Surface | Status | Notes |\n|---|---|---|\n| `firewall:` `via:` predicate | ✓ Supported | Subquery composes as outermost AND |\n| `crud.*.access` `roles: ['guest']` | ✓ Supported | Inline async lookup per request |\n| `read.access` / `read.views.*.access` `roles: ['guest']` | ✓ Supported | Same inline path |\n| `masking.<field>.show` `roles: ['guest']` | ⚠ Refused at compile | v1 limitation — async/batched mask functions deferred |\n| **Standalone** `actions.<name>.access` `roles: ['guest']` | ✓ Supported (v0.19+) | Inline gate; surface must expose `resource.column` as path param or input field |\n| **Record-based** `actions.<name>.access` `roles: ['guest']` | ⚠ Fail-closed at runtime | Runtime helper denies; inline emission is a planned follow-up. Use `firewall: { exception: true }` or move the check into `execute()` until then |\n\nFor the surfaces that are not yet supported, the compiler refuses at build time with a clear error pointing to a workaround. The runtime evaluator fails closed on relationship arms regardless, so silent grants are impossible.\n\n### Standalone actions: surface keys and `loads` / `exposeAs` (v0.19+)\n\nWhen a standalone action's `access.roles` references a relationship-role, the compiler emits a runtime gate between input validation and `execute()`. The gate reads the relationship's `resource.column` value from the action surface — either a path parameter (`:eventId`) or an input field (`input.eventId`). If neither is present, the compiler:\n\n- **v0.19** — emits a `[quickback:authz]` warning and skips resolver emission. The action's own hand-rolled gate (if any) keeps the route working at runtime.\n- **v0.20** — hard compile error. Set `firewall: { exception: true }` to opt out (cross-tenant/admin routes only).\n\nPair the relationship with `loads` + `exposeAs` to hydrate the loaded resource onto `ctx`:\n\n```typescript\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events', // ← v0.19+: load matching event row\n exposeAs: 'event', // ← onto ctx.event for the action body\n },\n },\n roles: {\n attendee: { via: 'attendeeOf' },\n },\n}\n```\n\nThe resolver (v0.20):\n\n1. **Cheap in-memory role check** first — `ctx.roles?.includes('admin')` and friends. If the caller has a qualifying role, this short-circuits and no DB queries fire for the access gate.\n2. **Firewall-gated relationship match** if the role check failed — `SELECT { organizationId, teamId } FROM guests WHERE userId=ctx.userId AND eventId=input.eventId AND status='confirmed'` with the `guests` table's full firewall AND-applied. If neither role nor relationship qualifies → 403.\n3. **Tenant stamping from the matched row** — for any tenant column the `from` table carries (`organizationId`, `teamId`), the resolver stamps `ctx.activeOrgId ??= matchedRow.organizationId` (and similar for team). This is **in-memory mutation of the request-scoped ctx only** — no JWT remint, no session-record write, no persistent grant.\n4. **Firewall-gated load of the loaded resource** — `SELECT * FROM events WHERE id = :eventId AND buildEventsFirewallConditions(ctx, db)`. The events firewall is applied as normal; it succeeds for attendees because tenant was just stamped from the relationship row.\n5. Assigns the loaded row to `ctx.event` for the action body.\n\n**No firewall bypass anywhere.** Both queries run with their respective tables' full firewalls. The relationship row's existence is the proof that the caller is authorized; its tenant columns are the source of the stamped claim.\n\n### Conditional tenant preconditions (v0.20+)\n\nStandalone actions in features with org/team-scoped tables previously emitted unconditional preconditions:\n\n```ts\nif (!ctx.activeOrgId) return c.json(AccessErrors.noOrg(), 403);\nif (!ctx.activeTeamId) return c.json(AccessErrors.noTeam(), 403);\n```\n\nThese ran **before** the relationship resolver, which 403'd attendees whose sessions don't carry an active tenant claim (the canonical event-attendee shape).\n\nv0.20 makes these preconditions **conditional on relationship supply**. If the access tree contains a relationship arm whose `from` table carries the matching tenant column, the precondition is skipped — the resolver runs first and stamps the value. Pseudo-role short-circuits (PUBLIC / AUTHENTICATED / USER / SYSADMIN) and `firewall: { exception: true }` still bypass the preconditions as before. `ADMIN` is now rejected at compile time.\n\nTypical event-attendee setup (`guests` table carries `organizationId`): the org precondition is dropped on every action whose access references `attendee` or `eventStaff`. Org admins still get `ctx.activeOrgId` from their session as today; attendees get it from the relationship row, mid-request. Both paths converge on a valid tenant claim before `execute()` runs.\n\n### Requirement on the relationship's `from` table\n\nFor the v0.20 tenant-stamping to work, the relationship's `from` table must carry tenant columns:\n\n- For org stamping: an `organizationId` column (or whatever spelling the project's auth-provider defaults pick).\n- For team stamping: a `teamId` column.\n\nWhen the `from` table has **neither**, the compiler emits a `[quickback:authz]` warning at compile time:\n\n```\nRelationship \"X\" at authz.relationships.X has no organization or team columns\non its `from` table (\"guests\"). Action \"Y\" will compile, but downstream\nscoped-db queries inside execute() may 403 because ctx.activeOrgId /\nactiveTeamId cannot be stamped from the match row. Either add the tenant\ncolumn to \"guests\", or set firewall: { exception: true } on the action.\n```\n\nThe relationship match still works (existence check), but no tenant gets stamped — so the conventional precondition still fires and the action still 403s for callers without a session-resident tenant claim. Add the tenant column (or denormalize it onto the relationship table during writes) to enable the stamping path.\n\nThe body can then trust `ctx.event` and drop the hand-rolled `SELECT … FROM guests WHERE …` boilerplate:\n\n```ts\n// features/chat/actions/getInbox.ts\nexport default defineAction({\n path: '/chat/get-inbox',\n input: z.object({ eventId: z.number().int().positive() }),\n access: { roles: ['admin', 'member', 'attendee'] }, // attendee is a relationship-role\n execute: async ({ db, ctx, input }) => {\n // No hand-rolled attendance check needed — the resolver already ran.\n // ctx.event is the loaded events row. Typed as `any` here because the\n // hand-rolled `roles: ['attendee']` action gates per-action, not per-\n // namespace — see \"Narrow ctx.<exposeAs> typing\" below for the typed\n // import flip available when the same hydration runs through a\n // namespace mount.\n const event = ctx.event as typeof events.$inferSelect;\n // … domain logic only.\n },\n});\n```\n\n`loads` and `exposeAs` are co-required (set both or neither). `exposeAs` must be a valid JS identifier and must not collide with built-in `ctx` fields (`userId`, `activeOrgId`, `activeTeamId`, `db`, etc.).\n\n### Action firewall escape hatch (v0.19+)\n\n`defineAction({ firewall: { exception: true } })` opts the action out of the inherited session-key preconditions (`ctx.activeOrgId` / `ctx.activeTeamId` requirements) AND the relationship resolver. The handler receives `unsafeDb` for raw Drizzle access. Use for cross-tenant or admin routes whose surface intentionally doesn't name a session/relationship key:\n\n```ts\ndefineAction({\n path: '/admin/cross-tenant-report',\n firewall: { exception: true },\n unsafe: { reason: 'cross-tenant audit', adminOnly: true, targetScope: 'all' },\n access: { roles: ['ADMIN'] },\n execute: async ({ unsafeDb, ctx }) => { /* cross-org query */ },\n});\n```\n\n`firewall: { exception: true }` is the declarative twin of `unsafe: true` — they're conceptually distinct: `firewall.exception` opts out of the gate-emission pillars; `unsafe` signals audit/cross-tenant intent (and still applies for logging). Most cross-tenant actions set both.\n\n### Recommended pattern: gate at the firewall layer\n\nMost of the time, relationship-based row visibility is what you want, and putting it at the **firewall** layer is the cleanest expression. The firewall is row-filter; the access layer is route/role-filter; let each do its job:\n\n```typescript\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' }, // ← row visibility\n],\nread: {\n access: { roles: ['admin', 'member'] }, // ← who can hit the route\n views: {\n cms: { access: { roles: ['admin', 'member'] }, fields: [...] },\n guest: { access: { roles: ['member', 'admin'] }, fields: [...] },\n },\n},\n```\n\nA guest who's in your org as `member` can hit the endpoint and the firewall filters them down to events they're guests of. Cross-tenant access is impossible because the org filter is the outermost AND.\n\n### Cross-tenant \"my events\" dashboards are NOT this\n\nA common adjacent pattern — \"logged-in user wants `GET /my-events` returning events they're a guest of *across all tenants*\" — is **not** solved by relationship-roles. The tenant firewall is enforced at the outermost AND, so a guest of an event in another tenant remains correctly blocked.\n\nFor cross-tenant aggregation, use one of:\n\n- **User-scoped firewall**: `firewall: { owner: { column: 'userId' } }` — a flat per-user table.\n- **A standalone action that walks the relationship table itself** — see worked example below.\n\nDon't reach for relationship-roles first and then get confused when the tenant firewall blocks. The two patterns serve different problems.\n\n#### Worked example: `GET /my-events` standalone action\n\nThe cleanest expression of the cross-tenant attendee dashboard is a standalone action with a custom path that does its own join against the relationship table. The action is gated by `roles: ['AUTHENTICATED']` (any signed-in user can hit it; per-row scoping is the query itself), and the SQL filters by `ctx.userId` so each caller sees exactly the events they're a guest of:\n\n```ts\n// features/dashboard/actions/myEvents.ts\n\nexport default defineAction({\n description: \"List events the caller is a confirmed guest of, across all tenants.\",\n path: '/my-events',\n method: 'GET',\n input: z.object({}),\n // Any signed-in user. Row visibility comes from the query, not the role.\n access: { roles: ['AUTHENTICATED'] },\n async execute({ db, ctx }) {\n // 1. Find every event the caller has a confirmed guest row for.\n const guestRows = await db\n .select({ eventId: guests.eventId })\n .from(guests)\n .where(\n and(\n eq(guests.userId, ctx.userId!),\n eq(guests.status, 'confirmed'),\n // guests.organizationId is NOT filtered here — that's the whole\n // point of the cross-tenant lane. The relationship row's org is\n // ambient information that this action explicitly traverses.\n )\n );\n\n if (guestRows.length === 0) return { events: [] };\n\n // 2. Pull the matching events. NOTE: this query also bypasses\n // `events.organizationId` scope — by design — so explicitly filter\n // out soft-deleted rows yourself if your `events` table uses them.\n const eventIds = guestRows.map((r) => r.eventId);\n const rows = await db\n .select()\n .from(events)\n .where(inArray(events.id, eventIds));\n\n return { events: rows };\n },\n});\n```\n\nWhy this is a standalone action and not a CRUD route:\n\n- **Tenant firewall would block it.** The default `firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }]` on `events` is correct for every other read — only the cross-tenant dashboard wants to step outside it, and that's a deliberate, explicit step taken in handler code.\n- **The join is the access control.** A relationship-role at the firewall layer can't express \"filter by this user's relationships, ignoring the org context.\" The handler does that join directly.\n- **Audit-logged automatically.** Standalone actions are mandatorily audit-logged in the runtime — the cross-tenant traversal is recorded with `ctx.userId`, IP, and timing.\n\nTwo important guardrails when you write one of these:\n\n1. **Always filter by `ctx.userId` in the relationship lookup.** If you accept a `userId` from the request body and trust it, you've built an IDOR. The example above uses `ctx.userId!` directly so the only events returned are the caller's.\n2. **You take responsibility for soft-delete and other invariants the firewall would otherwise apply.** Add the `deletedAt` filter, status checks, and any other row-level predicates by hand. The action is OUTSIDE the firewall pipeline by design — the cost is that you can't lean on the auto-applied predicates.\n\nIf you find yourself writing more than one of these per project, that's usually a signal to revisit the schema (could a user-owned `userEvents` materialized view replace the join?) rather than a sign Quickback should ship a higher-level abstraction. Cross-tenant lanes are intentionally explicit.\n\n### Compile-time refusals (consolidated)\n\nThe validator and resolver reject:\n\n- Unknown key in `authz` block (typo guard — `realtionships` would otherwise silently produce a permanently-denied role).\n- Reserved role-name (auth-provider-derived). Names like `guest`, `speaker`, `attendee` are free; `admin`/`owner`/`member` are reserved when the BA org plugin is on.\n- Cycle in role composition (`a → b → a`).\n- Relationship `from` references unknown table.\n- Relationship-role used on a resource missing the `resource.column`.\n- Relationship table with `firewall: { exception: true }` (would let cross-tenant grants slip through).\n- `lowering: 'session'` (reserved for v2 — staleness/invalidation ergonomics not yet shipped).\n- `+` hierarchy suffix on a relationship-role name (terminal, like pseudo-roles).\n- Relationship-roles in `masking.show` / `actions.access` (deferred surfaces — see the table above).\n\n## Namespace mounts (hoisted relationship middleware)\n\nWhen several standalone actions share a path prefix and the same relationship gate — `/event/:eventId/announce`, `/event/:eventId/cancel`, `/event/:eventId/respond` — declaring the gate per-action means writing the same `roles: ['attendee']` over and over AND paying the relationship-resolver cost N times per request (one subquery + one row-load, multiplied by the number of actions).\n\nNamespace mounts hoist the resolver into one Hono middleware that runs once per request. Every action under the prefix skips the inline gate; `ctx.<exposeAs>` is hydrated by the middleware before the action's `execute()` runs. With the per-namespace helper (v0.27+, [below](#narrow-ctxexposeas-typing-v027)), that field is also statically typed as the loaded row.\n\n### When to use roles vs. relationships\n\nA user is authorized for a row when **any** of the following is true:\n\n- they have a **per-row relationship** to it (e.g. an attendee row, a named organizer row), or\n- they have a **role on the row's tenant** (org admin/owner of the row's `organizationId`), or\n- they have **team membership** matching the row's `teamId`.\n\nUse **relationships** when membership is specific to *this row* — external collaborators who aren't in your org, attendees, anyone connected to the resource by virtue of data rather than payroll. Use **roles / team** when staff at your org/team should see everything in their scope by default.\n\nThe two compose at the action level (`access.or` accepts both relationship-roles and tenant roles) and — as of v0.25 — at the namespace level too: `namespace.via` accepts an array of lanes, first match wins.\n\n> **Rule of thumb.** If the answer is *\"yes if you work here,\"* reach for org/team roles. If the answer is *\"yes if you have something to do with **this** row,\"* reach for a per-row relationship. Reach for both together — at the namespace or via `access.or` — when an action should let either side in.\n\nTwo declaration sites depending on whether the participating actions live in one feature or many:\n\n### Single feature: `defineTable({ namespace })` (v0.23+)\n\nUse when every action under the prefix lives in the same feature directory. The namespace travels with the table that owns it — no addition to `quickback.config.ts` needed.\n\n```typescript\n// features/events/events.ts\nexport default defineTable(events, {\n firewall: [...],\n crud: { ... },\n namespace: {\n prefix: '/event/:eventId', // absolute URL path\n via: 'attendeeOf', // relationship gate (must exist in authz.relationships)\n },\n});\n\n// features/events/actions/post-announcement.ts\nexport default defineAction({\n path: '/event/:eventId/announcements',\n method: 'POST',\n // No gate boilerplate. ctx.event is typed inside execute().\n});\n```\n\nThe compiler emits one `app.use(...)` on the events feature's Hono app. Every standalone action in `features/events/actions/` whose path starts with `/event/:eventId/` joins the namespace automatically.\n\nMulti-lane via (v0.25+) and bulk-grant lanes (v0.26+) work identically on the table-level declaration — `via:` accepts the same shapes documented below for the project-level form.\n\n### Cross-feature: `authz.namespaces` (v0.24+)\n\nUse when the namespace spans multiple features. The declaration sits next to your other authz config in `quickback.config.ts`.\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n namespaces: {\n eventScope: { prefix: '/event/:eventId', via: 'attendeeOf' },\n },\n}\n```\n\nWith the namespace declared, any standalone action whose `path:` matches the prefix joins the gate — regardless of which feature owns it:\n\n```typescript\n// features/feeds/actions/feed-moments.ts (in one feature)\nexport default defineAction({\n path: '/event/:eventId/feed-moments',\n method: 'POST',\n});\n\n// features/rsvp/actions/respond.ts (in a different feature)\nexport default defineAction({\n path: '/event/:eventId/respond',\n method: 'POST',\n});\n```\n\nThe compiler emits one synthetic `src/routes/__namespace-event-scope.routes.ts` that imports each contributing feature's `actions` map under a distinct alias, mounts the resolver middleware once, and dispatches to the matching action. Worker-root mount order ensures the middleware fires before any per-feature route handler under the prefix.\n\n### Multi-lane via (v0.25+) — first match wins\n\nWhen more than one relationship can authorize a caller for the namespaced resource, pass `via:` as an array. The middleware tries each lane in declaration order and stops at the first match — `ctx.<exposeAs>` is hydrated from whichever lane fired.\n\n```typescript\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'linkedUserId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events',\n exposeAs: 'event',\n },\n // Named per-event organizers (potentially EXTERNAL — these users may\n // not be a member of the event's org. That's the point: lets you grant\n // event-level access to freelancers / partner staff without adding\n // them to the org's member list.)\n organizerOf: {\n from: 'eventOrganizers',\n subject: { column: 'linkedUserId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n namespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: ['attendeeOf', 'organizerOf'],\n },\n },\n}\n```\n\nAll relationship lanes in a namespace **must agree on `loads:` + `exposeAs:`** — that's what guarantees `ctx.event` has the same shape regardless of which lane matched. The compiler rejects heterogeneous lanes at parse time.\n\n### Bulk-grant lanes (v0.26+)\n\nRelationship lanes cover \"specifically connected to this row.\" Bulk-grant lanes cover \"anyone with this role / team membership in the row's tenant\" — the case where an org admin or a team member should see every event in their scope without writing per-event relationship rows.\n\n```typescript\nnamespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: [\n 'attendeeOf',\n 'organizerOf',\n { roles: ['admin', 'owner'] }, // org-role bulk grant\n { team: true }, // active-team-membership bulk grant\n ],\n },\n}\n```\n\nEach bulk-grant lane:\n\n- **`{ roles: [...] }`** — passes when the caller's BA org-role for the loaded resource's tenant includes any listed role. Short-circuits the relationship loop entirely; the role check is in-memory and cheap. Use for the \"company admin sees everything\" case.\n- **`{ team: true }`** — passes when `ctx.activeTeamId` is set. The loads-table firewall does the actual `events.teamId === ctx.activeTeamId` check during hydration. Use when the resource is team-scoped and you want active-team membership to grant access.\n\nBoth bulk-grant lanes piggyback on the namespace's relationship lane(s) for hydration — they don't fetch a separate per-row subject; they just gate access and let the loads-table firewall handle the tenant scoping. **At least one relationship lane is required** alongside bulk-grant lanes in v0.26 (to anchor `loads:` + `exposeAs:`).\n\nWhen a request misses every lane, the 403 deny payload lists every authorization path the caller could have taken — relationship names, role names, and `\"team-membership\"` for `{ team: true }` lanes — so a developer debugging an unexpected 403 sees the full surface they need to satisfy.\n\nA namespace can also fold the scope machinery into this same gate: `mintScope: true` **mints** a scope token on a matched userId lane, and `acceptScope: '<kind>'` **accepts** an already-minted scope claim as proof of entry — one handler under the prefix serves both a Better-Auth user and a sessionless scope principal. See [Scopes → `acceptScope`](/compiler/definitions/scopes#acceptscope--accept-an-incoming-scope-claim-as-proof-of-entry).\n\n### Discovery is path-prefix-only\n\nActions opt in by matching `path:` against a declared namespace prefix. There's no `namespace: 'foo'` field on `defineAction` — the path string is the discoverable surface, consistent with how `path:` already determines an action's URL.\n\n### Requirements (enforced at compile time)\n\nBoth forms share the same shape checks:\n\n- **`via:` accepts one of three shapes.** A single relationship name (v0.23+), an array of relationship names (v0.25+, first match wins), or — as of v0.26 — an array mixing relationship names with bulk-grant guards (`{ roles: [...] }`, `{ team: true }`).\n- **Every relationship lane must declare `loads + exposeAs`.** Without `loads` there's nothing for the middleware to hydrate; the namespace gate would be indistinguishable from a per-action access rule.\n- **All relationship lanes in one namespace must agree on `loads:` + `exposeAs:`.** Otherwise `ctx.<exposeAs>` would change shape depending on which lane matched.\n- **Bulk-grant lanes inherit `loads:` + `exposeAs:` from sibling relationship lanes.** Pure bulk-grant namespaces (no relationship lane at all) are also accepted — set `loads:` + `exposeAs:` directly on the namespace declaration so hydration has somewhere to anchor.\n- **`prefix:` must contain at least one `:param` segment** (e.g. `/event/:eventId`). The middleware reads the relationship key from `c.req.param()` because no request body has been parsed at middleware time.\n- **One declaration per namespace name.** The same name in both `defineTable({ namespace })` and `authz.namespaces` is rejected. The project-level form is canonical for cross-feature; the table-level form is the single-feature shorthand.\n\nProject-level only:\n\n- **Ambiguous prefixes** like `/a/:x` and `/a/:y` (same shape, different `:param` names) are rejected. Strict super/sub-set relationships (`/event/:e` vs `/event/:e/admin`) are fine — the harvester routes each action to the longest matching prefix.\n- **Unused namespace** emits a `[quickback:authz]` warning when no action's path matches the declared prefix. Not a hard error — the namespace may be staged ahead of the actions.\n\n### What namespace actions get for free\n\nInside a namespace action's `execute()`:\n\n- `ctx.<exposeAs>` is populated by the middleware with the loaded resource row. Statically `any` by default — narrowed to `typeof <loadsTable>.$inferSelect` when the action's import points at the per-namespace helper (see [below](#narrow-ctxexposeas-typing-v027)).\n- Tenant context (`ctx.activeOrgId` / `ctx.activeTeamId`) is stamped from the matched relationship row when its `from` table carries those columns. Downstream scoped queries work without further setup.\n- The action's own `access:` block (additional roles, userRole, record predicates, OTHER relationship arms) still runs after the namespace gate — namespace handles entry, per-action gates further.\n\n### Narrow `ctx.<exposeAs>` typing (v0.27+)\n\nThe namespace middleware hydrates `ctx.<exposeAs>` at runtime — that's been true since v0.23. The static type of that field, though, is `any` via the `AppContext` index signature: useful for not blocking access, but a missed opportunity for autocomplete and typo-catching.\n\nv0.27 emits one **per-namespace `defineAction` helper** alongside the standard `<feature>/.quickback/define-action.ts`. Importing from the narrowed helper retypes `ctx.<exposeAs>` inside `execute({ ctx })` to the loaded row's `$inferSelect` shape. Nothing else changes — runtime behavior, action discovery, and the `path:` namespace match are identical.\n\n```ts title=\"features/feeds/actions/feed-moments.ts\"\n// One-line flip per namespace-scoped action:\n\n// └──────┬──────┘\n// kebab(namespaceName)\n\nexport default defineAction({\n path: '/event/:eventId/feed-moments',\n method: 'POST',\n input: z.object({ body: z.string() }),\n access: { roles: ['attendee'] },\n async execute({ ctx, input }) {\n ctx.event.id // ✓ string\n ctx.event.startsAt // ✓ Date — autocomplete works\n ctx.event.organizerId // ✓ narrows on the field's declared type\n\n ctx.event.idd // ✗ TS2339 — typo caught at compile time\n },\n});\n```\n\nThe compiler emits one helper per `(feature, namespace)` pair where the feature owns at least one action whose `path:` falls under the namespace prefix. Filename is `define-action.<kebab(namespaceName)>.ts` — `eventScope` becomes `define-action.event-scope.ts`. Helpers live next to the standard `define-action.ts` in `<feature>/.quickback/`, so the relative import is the same shape as every other action file in your project.\n\n#### Opt-in, not breaking\n\nActions that keep their existing `import { defineAction } from '../.quickback/define-action'` continue to compile unchanged — `ctx.<exposeAs>` is `any` via the `AppContext` index signature, which is exactly the v0.23–v0.26 behavior. You flip imports per action at your own pace.\n\n#### Compile-time advisory\n\nWhen `quickback compile` sees a namespace-scoped action still importing the generic helper, it emits a one-line advisory pointing at the narrowed path:\n\n```text\n[quickback:typing] action \"feedMoments\" in feature \"feeds\" lives under\n namespace \"eventScope\" — switch its import to\n `../.quickback/define-action.event-scope` for narrow ctx.<exposeAs> typing.\n (Runtime behavior is unchanged; the narrowed helper only refines TS types.)\n```\n\nNon-blocking — same `[quickback:typing]` family as `[quickback:authz]`. The advisory only mentions actions the compiler can be confident about (namespace-claimed actions whose source still imports the generic helper).\n\n#### Multi-namespace features\n\nA single feature can contribute actions to several namespaces — say, an `interviews` feature with actions under both `interviewScope` and `eventScope`. The compiler emits one narrowed helper per namespace the feature participates in, and each action picks the import that matches its path.\n\n```text\nsrc/features/interviews/.quickback/\n├── define-action.ts # generic — standard fallback\n├── define-action.interview-scope.ts # ctx.interview typed\n└── define-action.event-scope.ts # ctx.event typed\n```\n\n#### Why per-namespace and not per-action\n\nA `defineAction` helper that's narrow to *one* exposed key (the namespace's `exposeAs`) is enough — every action under a namespace sees the same hydrated key. The alternative (per-action emit) duplicates the same prelude N times for the same shape; per-namespace keeps emission proportional to the number of distinct hydration shapes in the project.\n\n## Read & Write Configuration\n\nReads (`GET /` and `GET /:id`) live under `read:`; mutations live under top-level `create:`, `update:`, `delete:`, and `upsert:`. See [Read](/compiler/definitions/read) for the full read pipeline reference.\n\n```typescript\nread: {\n // LIST + GET - GET /resource and GET /resource/:id\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n pageSize: 25, // Default page size\n maxPageSize: 100, // Client can't exceed this\n views: { // Per-view field projections\n summary: {\n fields: ['id', 'candidateId', 'jobId', 'stage'],\n access: { roles: [\"interviewer\"] },\n },\n },\n}\n\ncreate: {\n // CREATE - POST /resource\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] },\n defaults: { // Default values for new records\n stage: 'applied',\n },\n},\n\nupdate: {\n // UPDATE - PATCH /resource/:id\n access: {\n or: [\n { roles: [\"hiring-manager\", \"recruiter\"] },\n { roles: [\"interviewer\"], record: { stage: { equals: \"interview\" } } }\n ]\n },\n},\n\ndelete: {\n // DELETE - DELETE /resource/:id\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"soft\", // 'soft' (default) or 'hard'\n},\n\nupsert: {\n // PUT - PUT /resource/:id (only when generateId: false + guards: false)\n access: { roles: [\"hiring-manager\", \"sync-service\"] },\n}\n```\n\n## Evaluation Order\n\nGenerated `/:id` and batch handlers evaluate access in this fixed order:\n\n1. **Auth gate** — 401 if unauthenticated\n2. **Pre-record access** — role-only check (skips `access.record` predicates)\n3. **Firewall query** — `WHERE` clause filters by ownership\n4. **Post-record access** — full check including record-level predicates\n5. **Masking** — applied to the response\n\nStep 2 closes the 404-vs-403 ID-probe channel: an unauthorized caller without\na matching role gets 403 before the database is touched, so they can't tell\napart \"row exists out-of-scope\" from \"row doesn't exist.\" A caller with the\nright role but the wrong tenant gets 403 by default (firewall reveals via\nthe access layer); set\n[`firewallErrorMode: 'hide'`](/compiler/definitions/firewall) to return an\nopaque 404 instead.\n\nFunction-form access (`access: async (ctx, record) => ...`) is opaque to\nthe pre-record phase and always passes there; it's fully evaluated post-record.\n\n## List Filtering (Query Parameters)\n\nThe LIST endpoint automatically supports filtering via query params:\n\n```\nGET /jobs?status=open # Exact match\nGET /jobs?salaryMin.gt=50000 # Greater than\nGET /jobs?salaryMin.gte=50000 # Greater than or equal\nGET /jobs?salaryMax.lt=200000 # Less than\nGET /jobs?salaryMax.lte=200000 # Less than or equal\nGET /jobs?status.ne=closed # Not equal\nGET /jobs?title.like=Engineer # Pattern match (LIKE %value%)\nGET /jobs?status.in=open,draft # IN clause\n```\n\n| Operator | Query Param | SQL Equivalent |\n|----------|-------------|----------------|\n| Equals | `?field=value` | `WHERE field = value` |\n| Not equals | `?field.ne=value` | `WHERE field != value` |\n| Greater than | `?field.gt=value` | `WHERE field > value` |\n| Greater or equal | `?field.gte=value` | `WHERE field >= value` |\n| Less than | `?field.lt=value` | `WHERE field < value` |\n| Less or equal | `?field.lte=value` | `WHERE field <= value` |\n| Pattern match | `?field.like=value` | `WHERE field LIKE '%value%'` |\n| In list | `?field.in=a,b,c` | `WHERE field IN ('a','b','c')` |\n\n## Sorting & Pagination\n\n```\nGET /jobs?sort=createdAt&order=desc # Sort by field\nGET /jobs?limit=25&offset=50 # Pagination\n```\n\n- **Default limit**: 50\n- **Max limit**: 100 (or `maxPageSize` if configured)\n- **Default order**: `asc`\n\n## Delete Modes\n\n```typescript\ndelete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"soft\", // Sets deletedAt/deletedBy, record stays in DB\n}\n\ndelete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"hard\", // Permanent deletion from database\n}\n```\n\n## Context Variables\n\nUse `$ctx.` prefix to reference context values in conditions:\n\n```typescript\n// User can only view their own records\naccess: {\n record: { userId: { equals: \"$ctx.userId\" } }\n}\n\n// Nested path support for complex context objects\naccess: {\n record: { ownerId: { equals: \"$ctx.user.id\" } }\n}\n```\n\n### AppContext Reference\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `$ctx.userId` | `string` | Current authenticated user's ID |\n| `$ctx.activeOrgId` | `string` | User's active organization ID |\n| `$ctx.activeTeamId` | `string \\| null` | User's active team ID (if applicable) |\n| `$ctx.roles` | `string[]` | User's roles in current context |\n| `$ctx.isAnonymous` | `boolean` | Whether user is anonymous |\n| `$ctx.user` | `object` | Full user object from auth provider |\n| `$ctx.user.id` | `string` | User ID (nested path example) |\n| `$ctx.user.email` | `string` | User's email address |\n| `$ctx.{property}` | `any` | Any custom context property |\n\n## Function-Based Access\n\nFor complex access logic that can't be expressed declaratively, use a function:\n\n```typescript\nupdate: {\n access: async (ctx, record) => {\n // Custom logic - return true to allow, false to deny\n if (ctx.roles.includes('admin')) return true;\n if (record.ownerId === ctx.userId) return true;\n\n // Check custom business logic\n const membership = await checkTeamMembership(ctx.userId, record.teamId);\n return membership.canEdit;\n }\n}\n```\n\nFunction access receives:\n- `ctx`: The full AppContext object\n- `record`: The record being accessed (for get/update/delete operations)"
82
+ "content": "Define who can perform read and write operations and under what conditions.\n\n## Basic Usage\n\n```typescript\n// features/applications/applications.ts\n\nexport const applications = sqliteTable('applications', {\n id: text('id').primaryKey(),\n candidateId: text('candidate_id').notNull(),\n jobId: text('job_id').notNull(),\n stage: text('stage').notNull(),\n notes: text('notes'),\n organizationId: text('organization_id').notNull(),\n});\n\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: { createable: [\"candidateId\", \"jobId\", \"notes\"], updatable: [\"notes\"] },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n});\n```\n\n## Role Hierarchy\n\nIf your project uses a tiered role system (e.g., `member` < `admin` < `owner`), you can define a hierarchy in your config and use the `+` suffix to mean \"this role and above\":\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n name: \"my-app\",\n auth: {\n roleHierarchy: ['member', 'admin', 'owner'], // lowest → highest\n },\n // ...\n});\n```\n\nThen in your resource definitions:\n\n```typescript\nread: { access: { roles: [\"member+\"] } }, // member, admin, owner\ncreate: { access: { roles: [\"admin+\"] } }, // admin, owner\ndelete: { access: { roles: [\"owner\"] } }, // owner only (no +)\n```\n\nThe `+` suffix expands at compile time — `\"member+\"` becomes `[\"member\", \"admin\", \"owner\"]` in the generated code. You can mix hierarchical and exact roles: `roles: [\"member+\", \"finance\"]` expands to `[\"member\", \"admin\", \"owner\", \"finance\"]`.\n\n- Roles without `+` are exact matches (no expansion)\n- Pseudo-roles / reserved markers (`PUBLIC`, `AUTHENTICATED`, `USER`, `ADMIN`, `SYSADMIN`) cannot use the `+` suffix — they're terminal markers\n- Using `+` with a role not in the hierarchy throws a compile error\n- Using `+` without configuring `auth.roleHierarchy` throws a compile error\n\n## Custom org roles\n\nYou're not limited to Better Auth's built-in `owner` / `admin` / `member` —\nany lowercase role name you reference in an access tree (`\"recruiter\"`,\n`\"hiring-manager\"`, `\"support\"`, …) is a custom org-membership role, matched\nagainst `ctx.roles` like the built-ins.\n\nAs of v0.46, custom roles declared in access trees are **auto-registered\nwith the Better Auth organization plugin**, so members can actually be\nprovisioned into them: `invite-member` and `update-member-role` accept them\n(previously they rejected custom roles with `400 ROLE_NOT_FOUND`).\nAuto-registered roles carry member-equivalent Better Auth permissions —\nregistration is about assignability; your access trees remain the\nauthorization model. If you pass your own `roles` / `ac` to the organization\nplugin options, those win and auto-registration is skipped.\n\n## Configuration Options\n\n```typescript\ninterface Access {\n // Org-membership roles (OR logic — user needs at least one)\n // Matched against ctx.roles. Use \"role+\" suffix for hierarchy expansion.\n roles?: string[];\n\n // User-table role (OR logic). Matched against ctx.userRole from the\n // user.role column — independent of org membership. See userRole below.\n userRole?: string[];\n\n // Record-level conditions\n record?: {\n [field: string]: FieldCondition;\n };\n\n // Combinators\n or?: Access[];\n and?: Access[];\n}\n```\n\n## `userRole` vs `roles`\n\n`roles` and `userRole` check **two different fields** and are often confused — get this wrong and you'll grant access too broadly.\n\n| Primitive | Checks | Source | Example values |\n|-----------|--------|--------|----------------|\n| `roles` | `ctx.roles` | Org membership roles | `\"owner\"`, `\"admin\"`, `\"member\"` |\n| `userRole` | `ctx.userRole` | The `user.role` column (Better Auth / platform control-plane roles) | `\"user\"`, `\"appmanager\"`, `\"sysadmin\"` |\n\nIn multi-tenant mode, **`roles: [\"admin\"]` means \"org admin\" — not a platform-wide role.** An org-admin of Acme Corp has no elevated rights across other orgs. If you want platform control-plane operators through regardless of org membership (CMS, Better Auth admin surfaces, support tooling), use `userRole: [\"appmanager\"]`. If you need true cross-tenant data-plane access, use `roles: [\"SYSADMIN\"]` (with `cms: { sysadmin: true }`).\n\nPinned organization mode does not change this split. `roles` still come from organization membership in the pinned org, while `userRole` still comes from Better Auth's `user.role` column.\n\n### When to use `userRole`\n\n```typescript\n// Platform control-plane users can see SSNs on every customer record, regardless of org\nmasking: {\n ssn: { type: 'ssn', show: { userRole: ['appmanager'] } },\n}\n\n// Platform ops (user.role === 'appmanager') OR the org owner can refund\naccess: {\n or: [\n { userRole: ['appmanager'] },\n { roles: ['owner'] },\n ],\n}\n\n// CMS-internal resource: only platform control-plane users\nread: { access: { userRole: ['appmanager'] } },\ncreate: { access: { userRole: ['appmanager'] } },\nupdate: { access: { userRole: ['appmanager'] } },\ndelete: { access: { userRole: ['appmanager'] } },\n```\n\nWhen `roles` and `userRole` both appear in a single `Access` node, they're combined with AND — the user must satisfy both. Use `or:` to express \"one or the other\".\n\n`userRole` doesn't expand with the `+` hierarchy suffix — user-table roles are flat (typically just `\"user\"`, `\"appmanager\"`, and `\"sysadmin\"`). If you've added custom user-table roles via Better Auth, list them explicitly.\n\n### Pseudo-roles\n\nQuickback ships five reserved UPPERCASE markers. Four are real pseudo-roles handled directly by the compiler; `ADMIN` is retained only as a reserved legacy marker so the compiler can fail loudly with migration guidance. The casing carries the boundary: UPPERCASE = compiler-owned marker, lowercase = real role from a plugin's table (e.g. `members.role` from the org plugin).\n\n| Role | Auth gate | Compile-time requirement | Runtime check |\n|------|-----------|-------------------------|---------------|\n| `PUBLIC` | bypassed | none — explicit opt-in for unauthenticated access | always passes (auth skipped) |\n| `AUTHENTICATED` | required | none | `ctx.authenticated === true` |\n| `USER` | required | resource firewall **must** scope by `userId` | `ctx.authenticated` AND (`ctx.userRole` is unset OR `ctx.userRole === \"user\"`) |\n| `ADMIN` | required | reserved legacy marker — compiler rejects it | `false` |\n| `SYSADMIN` | required | `cms: { sysadmin: true }` **must** be set on the project | `ctx.authenticated && ctx.userRole === \"sysadmin\"` |\n\nYou can mix pseudo-roles with real roles in the same list — they're OR'd together.\n\n#### `PUBLIC` — unauthenticated access\n\nUse `roles: [\"PUBLIC\"]` for public-facing endpoints like contact forms, public listings, or webhooks. Skips both the auth gate and the role check.\n\n```typescript\naccess: { roles: [\"PUBLIC\"] }\n```\n\n**Important:**\n- `PUBLIC` skips authentication and role checks — anyone can call the endpoint\n- **`PUBLIC` is the explicit, uppercase opt-in for unauthenticated access.** It works on every access node — reads, top-level writes (`create`/`update`/`delete`/`upsert`), views, and actions. The compiler trusts the marker; row-level safety comes from the firewall, masking, and (for token-gated endpoints like RSVP confirm, magic-link redemption, List-Unsubscribe-Post, webhook ingest) your handler's own validation. Anonymous write endpoints typically pair `roles: [\"PUBLIC\"]` with `firewall: { exception: true }` on the resource so the row predicate doesn't reject every unauthenticated caller.\n- **Firewall still applies** — data is scoped by the firewall (organization, owner, team)\n- **Tree semantics:** `PUBLIC` admits anonymous callers from anywhere in the access tree, not just a flat `roles` list. An `or:` arm containing `PUBLIC` admits anonymous callers past the authentication gate; an `and:` group admits them only when *every* arm does. The access, org, and firewall layers still evaluate the full tree afterwards. (Before v0.46 the emitted auth gate only honored `PUBLIC` in a flat `roles` list — a nested `PUBLIC` arm incorrectly answered `401`.)\n- Every `PUBLIC` action invocation is **mandatory audit logged** to the security audit table (IP address, input, result, timing)\n- The wildcard `\"*\"` is **not supported** — using it throws a compile-time error\n- Tables with no isolation columns and any `PUBLIC` route do not require `firewall: [{ exception: true }]`\n\nFor org-scoped tables, `PUBLIC` routes still filter by organization. Since the user isn't authenticated, the organization ID must be passed as a query parameter:\n\n```\nGET /api/v1/listings?organizationId=org_abc123\n```\n\nThe firewall WHERE clause is always enforced. If no `organizationId` is provided, the API returns a `403` with code `ORG_REQUIRED`.\n\n```typescript\n// Public listing page — anyone can browse, but scoped to an org\nexport default defineTable(listings, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: { access: { roles: [\"PUBLIC\"] } }, // Public browsing + detail\n create: { access: { roles: [\"admin\", \"member\"] } }, // Auth required to create\n});\n```\n\n#### `AUTHENTICATED` — any signed-in user\n\nUse `roles: [\"AUTHENTICATED\"]` for endpoints that any logged-in user can hit, regardless of role or org membership. No plugin context required.\n\n```typescript\n// Public events feed — any signed-in user can list/read; anonymous gets 401\nread: { access: { roles: [\"AUTHENTICATED\"] } }\n```\n\n#### `USER` — per-user records\n\nUse `roles: [\"USER\"]` for resources where each user only sees their own records. **Requires the firewall to scope by `userId`** — the role marker is the access half of the pair, the firewall is the row-filter half.\n\n```typescript\n// \"My todos\" — each caller sees only their own rows\nexport default defineTable(todos, {\n firewall: [{ field: 'userId', equals: 'ctx.userId' }],\n read: { access: { roles: [\"USER\"] } },\n create: { access: { roles: [\"USER\"] } },\n update: { access: { roles: [\"USER\"] } },\n delete: { access: { roles: [\"USER\"] } },\n});\n```\n\nIf you forget the `userId` firewall predicate, the compiler throws:\n\n> `roles: [\"USER\"]` requires the resource to be scoped per-user. Add a `userId` column (auto-scoped) or an explicit owner predicate. If you want any signed-in user to read all records, use `roles: [\"AUTHENTICATED\"]` instead.\n\nWhen the Better Auth admin plugin is enabled, `USER` matches `user.role === \"user\"` specifically — appmanagers and sysadmins are excluded. If the same route should serve both, express it explicitly with `or: [{ roles: [\"USER\"] }, { userRole: [\"appmanager\"] }]`.\n\n#### `ADMIN` — legacy reserved marker (compile-time error)\n\n`roles: [\"ADMIN\"]` is no longer supported. The compiler fails hard on any use of `ADMIN` so platform and tenant roles can't be confused.\n\n```typescript\n// Platform control-plane audit log\nread: { access: { userRole: [\"appmanager\"] } }\n```\n\nUse one of these instead:\n\n- `userRole: [\"appmanager\"]` for platform control-plane access\n- `roles: [\"admin\"]` for org-membership admin access\n- `roles: [\"SYSADMIN\"]` for true cross-tenant access\n\n#### `SYSADMIN` — cross-tenant DB-admin tier\n\nUse `roles: [\"SYSADMIN\"]` for endpoints that should only be reachable by platform sysadmins — the cross-tenant DB-admin tier introduced in v0.15.0. Compiles to `ctx.userRole === \"sysadmin\"`. **Requires `cms: { sysadmin: true }` on the project config**; without that flag, using `SYSADMIN` fails the compile so the role can't sit as dead code.\n\n```typescript\n// Cross-tenant audit dashboard, sysadmin-only\nread: { access: { roles: [\"SYSADMIN\"] } }\n```\n\n`SYSADMIN` is distinct from `userRole: [\"appmanager\"]`. Appmanager is the platform control-plane tier (CMS shell, Better Auth admin surfaces, support tooling); sysadmin is the cross-tenant data-plane tier. The one place sysadmin gets implicit extra powers is **the firewall escape hatch**: when `cms.sysadmin: true`, every `buildFirewallConditions` emits an `if (ctx.userRole === 'sysadmin') return undefined;` (or just the soft-delete predicate when present) at the top — so sysadmins see every tenant's rows, not just their own org's. That escape hatch does NOT fire for `userRole === 'appmanager'`; appmanagers still go through the firewall like everyone else.\n\nThis separation exists so Better Auth admin-plugin powers (user management, impersonation, org creation) and DB-admin powers (cross-tenant data inspection) stay decoupled. A user can have `user.role === 'appmanager'` without DB-level cross-tenant access; a user can have `user.role === 'sysadmin'` without org-membership context. See [CMS Configuration](/compiler/config#cms-configuration) for the `cms.sysadmin` flag, the cross-tenant `/auth/v1/admin/list-organizations` endpoint, and the SPA's \"All organizations\" sentinel.\n\n#### Mixing pseudo-roles with real roles\n\nPseudo-roles and lowercase real roles compose with OR:\n\n```typescript\n// Record owner OR a platform control-plane user can read\nread: { access: { or: [{ roles: [\"USER\"] }, { userRole: [\"appmanager\"] }] } }\n\n// Org owner OR sysadmin\ndelete: { access: { or: [{ roles: [\"owner\"] }, { roles: [\"SYSADMIN\"] }] } }\n```\n\n> Note: `userRole: [\"appmanager\"]` never bypasses a `userId` firewall scope. If you need cross-user visibility, expose a separate route with `firewall: { exception: true }` or a `SYSADMIN`-gated cross-tenant surface.\n\n#### Quick reference\n\n```typescript\n// Unauthenticated public\naccess: { roles: [\"PUBLIC\"] }\n\n// Any signed-in user, no scoping\naccess: { roles: [\"AUTHENTICATED\"] }\n\n// Per-user records (requires userId firewall scope)\naccess: { roles: [\"USER\"] }\n\n// Platform control-plane\naccess: { userRole: [\"appmanager\"] }\n\n// Cross-tenant DB-admin tier\naccess: { roles: [\"SYSADMIN\"] }\n\n// Org-membership roles with hierarchy expansion\n// (\"+\" requires auth.roleHierarchy in quickback.config.ts — see Role Hierarchy above)\naccess: { roles: [\"member+\"] } // expands to [\"member\", \"admin\", \"owner\"]\naccess: { roles: [\"admin+\"] } // expands to [\"admin\", \"owner\"]\naccess: { roles: [\"admin\"] } // exact match (no expansion)\n```\n\n```typescript\n// Field conditions - value can be string | number | boolean\ntype FieldCondition =\n | { equals: value | '$ctx.userId' | '$ctx.activeOrgId' }\n | { notEquals: value }\n | { in: value[] }\n | { notIn: value[] }\n | { lessThan: number }\n | { greaterThan: number }\n | { lessThanOrEqual: number }\n | { greaterThanOrEqual: number };\n```\n\n## Relationship-based authorization\n\nBeyond Better Auth roles (org membership, user-table role) and pseudo-roles, Quickback supports **relationship-based authorization roles** — names that bind to a declared relationship between the caller and a resource. Use these when access should follow a domain-table membership (\"user is a confirmed guest of this event\") rather than an org/admin gate.\n\n### `authz.relationships`\n\nDeclare relationships once in `quickback.config.ts`:\n\n```typescript\n// quickback.config.ts\n\nexport default defineConfig({\n // ...providers...\n authz: {\n relationships: {\n guestOf: {\n from: 'event_guests', // table name string\n subject: { column: 'userId', equals: 'ctx.userId' }, // caller side\n resource: { column: 'eventId' }, // resource side\n where: { status: 'confirmed' }, // optional filter\n },\n },\n roles: {\n guest: { via: 'guestOf' },\n // Composite: any guest OR an org owner/admin\n eventStaff: {\n or: [\n { via: 'guestOf' },\n { roles: ['admin', 'owner'] },\n ],\n },\n },\n },\n});\n```\n\n### Using relationship-roles in resources\n\nResource definitions reference declared roles by name in `roles: [...]` arrays exactly like BA roles or pseudo-roles. The compiler rewrites the access tree at build time so the runtime route does an inline relationship lookup against the declared table.\n\n**Today (v1) this works on:**\n\n| Surface | Status | Notes |\n|---|---|---|\n| `firewall:` `via:` predicate | ✓ Supported | Subquery composes as outermost AND |\n| `crud.*.access` `roles: ['guest']` | ✓ Supported | Inline async lookup per request |\n| `read.access` / `read.views.*.access` `roles: ['guest']` | ✓ Supported | Same inline path |\n| `masking.<field>.show` `roles: ['guest']` | ⚠ Refused at compile | v1 limitation — async/batched mask functions deferred |\n| **Standalone** `actions.<name>.access` `roles: ['guest']` | ✓ Supported (v0.19+) | Inline gate; surface must expose `resource.column` as path param or input field |\n| **Record-based** `actions.<name>.access` `roles: ['guest']` | ⚠ Fail-closed at runtime | Runtime helper denies; inline emission is a planned follow-up. Use `firewall: { exception: true }` or move the check into `execute()` until then |\n\nFor the surfaces that are not yet supported, the compiler refuses at build time with a clear error pointing to a workaround. The runtime evaluator fails closed on relationship arms regardless, so silent grants are impossible.\n\n### Standalone actions: surface keys and `loads` / `exposeAs` (v0.19+)\n\nWhen a standalone action's `access.roles` references a relationship-role, the compiler emits a runtime gate between input validation and `execute()`. The gate reads the relationship's `resource.column` value from the action surface — either a path parameter (`:eventId`) or an input field (`input.eventId`). If neither is present, the compiler:\n\n- **v0.19** — emits a `[quickback:authz]` warning and skips resolver emission. The action's own hand-rolled gate (if any) keeps the route working at runtime.\n- **v0.20** — hard compile error. Set `firewall: { exception: true }` to opt out (cross-tenant/admin routes only).\n\nPair the relationship with `loads` + `exposeAs` to hydrate the loaded resource onto `ctx`:\n\n```typescript\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events', // ← v0.19+: load matching event row\n exposeAs: 'event', // ← onto ctx.event for the action body\n },\n },\n roles: {\n attendee: { via: 'attendeeOf' },\n },\n}\n```\n\nThe resolver (v0.20):\n\n1. **Cheap in-memory role check** first — `ctx.roles?.includes('admin')` and friends. If the caller has a qualifying role, this short-circuits and no DB queries fire for the access gate.\n2. **Firewall-gated relationship match** if the role check failed — `SELECT { organizationId, teamId } FROM guests WHERE userId=ctx.userId AND eventId=input.eventId AND status='confirmed'` with the `guests` table's full firewall AND-applied. If neither role nor relationship qualifies → 403.\n3. **Tenant stamping from the matched row** — for any tenant column the `from` table carries (`organizationId`, `teamId`), the resolver stamps `ctx.activeOrgId ??= matchedRow.organizationId` (and similar for team). This is **in-memory mutation of the request-scoped ctx only** — no JWT remint, no session-record write, no persistent grant.\n4. **Firewall-gated load of the loaded resource** — `SELECT * FROM events WHERE id = :eventId AND buildEventsFirewallConditions(ctx, db)`. The events firewall is applied as normal; it succeeds for attendees because tenant was just stamped from the relationship row.\n5. Assigns the loaded row to `ctx.event` for the action body.\n\n**No firewall bypass anywhere.** Both queries run with their respective tables' full firewalls. The relationship row's existence is the proof that the caller is authorized; its tenant columns are the source of the stamped claim.\n\n### Conditional tenant preconditions (v0.20+)\n\nStandalone actions in features with org/team-scoped tables previously emitted unconditional preconditions:\n\n```ts\nif (!ctx.activeOrgId) return c.json(AccessErrors.noOrg(), 403);\nif (!ctx.activeTeamId) return c.json(AccessErrors.noTeam(), 403);\n```\n\nThese ran **before** the relationship resolver, which 403'd attendees whose sessions don't carry an active tenant claim (the canonical event-attendee shape).\n\nv0.20 makes these preconditions **conditional on relationship supply**. If the access tree contains a relationship arm whose `from` table carries the matching tenant column, the precondition is skipped — the resolver runs first and stamps the value. Pseudo-role short-circuits (PUBLIC / AUTHENTICATED / USER / SYSADMIN) and `firewall: { exception: true }` still bypass the preconditions as before. `ADMIN` is now rejected at compile time.\n\nTypical event-attendee setup (`guests` table carries `organizationId`): the org precondition is dropped on every action whose access references `attendee` or `eventStaff`. Org admins still get `ctx.activeOrgId` from their session as today; attendees get it from the relationship row, mid-request. Both paths converge on a valid tenant claim before `execute()` runs.\n\n### Requirement on the relationship's `from` table\n\nFor the v0.20 tenant-stamping to work, the relationship's `from` table must carry tenant columns:\n\n- For org stamping: an `organizationId` column (or whatever spelling the project's auth-provider defaults pick).\n- For team stamping: a `teamId` column.\n\nWhen the `from` table has **neither**, the compiler emits a `[quickback:authz]` warning at compile time:\n\n```\nRelationship \"X\" at authz.relationships.X has no organization or team columns\non its `from` table (\"guests\"). Action \"Y\" will compile, but downstream\nscoped-db queries inside execute() may 403 because ctx.activeOrgId /\nactiveTeamId cannot be stamped from the match row. Either add the tenant\ncolumn to \"guests\", or set firewall: { exception: true } on the action.\n```\n\nThe relationship match still works (existence check), but no tenant gets stamped — so the conventional precondition still fires and the action still 403s for callers without a session-resident tenant claim. Add the tenant column (or denormalize it onto the relationship table during writes) to enable the stamping path.\n\nThe body can then trust `ctx.event` and drop the hand-rolled `SELECT … FROM guests WHERE …` boilerplate:\n\n```ts\n// features/chat/actions/getInbox.ts\nexport default defineAction({\n path: '/chat/get-inbox',\n input: z.object({ eventId: z.number().int().positive() }),\n access: { roles: ['admin', 'member', 'attendee'] }, // attendee is a relationship-role\n execute: async ({ db, ctx, input }) => {\n // No hand-rolled attendance check needed — the resolver already ran.\n // ctx.event is the loaded events row. Typed as `any` here because the\n // hand-rolled `roles: ['attendee']` action gates per-action, not per-\n // namespace — see \"Narrow ctx.<exposeAs> typing\" below for the typed\n // import flip available when the same hydration runs through a\n // namespace mount.\n const event = ctx.event as typeof events.$inferSelect;\n // … domain logic only.\n },\n});\n```\n\n`loads` and `exposeAs` are co-required (set both or neither). `exposeAs` must be a valid JS identifier and must not collide with built-in `ctx` fields (`userId`, `activeOrgId`, `activeTeamId`, `db`, etc.).\n\n### Action firewall escape hatch (v0.19+)\n\n`defineAction({ firewall: { exception: true } })` opts the action out of the inherited session-key preconditions (`ctx.activeOrgId` / `ctx.activeTeamId` requirements) AND the relationship resolver. The handler receives `unsafeDb` for raw Drizzle access. Use for cross-tenant or admin routes whose surface intentionally doesn't name a session/relationship key:\n\n```ts\ndefineAction({\n path: '/admin/cross-tenant-report',\n firewall: { exception: true },\n unsafe: { reason: 'cross-tenant audit', adminOnly: true, targetScope: 'all' },\n access: { roles: ['ADMIN'] },\n execute: async ({ unsafeDb, ctx }) => { /* cross-org query */ },\n});\n```\n\n`firewall: { exception: true }` is the declarative twin of `unsafe: true` — they're conceptually distinct: `firewall.exception` opts out of the gate-emission pillars; `unsafe` signals audit/cross-tenant intent (and still applies for logging). Most cross-tenant actions set both.\n\n### Recommended pattern: gate at the firewall layer\n\nMost of the time, relationship-based row visibility is what you want, and putting it at the **firewall** layer is the cleanest expression. The firewall is row-filter; the access layer is route/role-filter; let each do its job:\n\n```typescript\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' }, // ← row visibility\n],\nread: {\n access: { roles: ['admin', 'member'] }, // ← who can hit the route\n views: {\n cms: { access: { roles: ['admin', 'member'] }, fields: [...] },\n guest: { access: { roles: ['member', 'admin'] }, fields: [...] },\n },\n},\n```\n\nA guest who's in your org as `member` can hit the endpoint and the firewall filters them down to events they're guests of. Cross-tenant access is impossible because the org filter is the outermost AND.\n\n### Cross-tenant \"my events\" dashboards are NOT this\n\nA common adjacent pattern — \"logged-in user wants `GET /my-events` returning events they're a guest of *across all tenants*\" — is **not** solved by relationship-roles. The tenant firewall is enforced at the outermost AND, so a guest of an event in another tenant remains correctly blocked.\n\nFor cross-tenant aggregation, use one of:\n\n- **User-scoped firewall**: `firewall: { owner: { column: 'userId' } }` — a flat per-user table.\n- **A standalone action that walks the relationship table itself** — see worked example below.\n\nDon't reach for relationship-roles first and then get confused when the tenant firewall blocks. The two patterns serve different problems.\n\n#### Worked example: `GET /my-events` standalone action\n\nThe cleanest expression of the cross-tenant attendee dashboard is a standalone action with a custom path that does its own join against the relationship table. The action is gated by `roles: ['AUTHENTICATED']` (any signed-in user can hit it; per-row scoping is the query itself), and the SQL filters by `ctx.userId` so each caller sees exactly the events they're a guest of:\n\n```ts\n// features/dashboard/actions/myEvents.ts\n\nexport default defineAction({\n description: \"List events the caller is a confirmed guest of, across all tenants.\",\n path: '/my-events',\n method: 'GET',\n input: z.object({}),\n // Any signed-in user. Row visibility comes from the query, not the role.\n access: { roles: ['AUTHENTICATED'] },\n async execute({ db, ctx }) {\n // 1. Find every event the caller has a confirmed guest row for.\n const guestRows = await db\n .select({ eventId: guests.eventId })\n .from(guests)\n .where(\n and(\n eq(guests.userId, ctx.userId!),\n eq(guests.status, 'confirmed'),\n // guests.organizationId is NOT filtered here — that's the whole\n // point of the cross-tenant lane. The relationship row's org is\n // ambient information that this action explicitly traverses.\n )\n );\n\n if (guestRows.length === 0) return { events: [] };\n\n // 2. Pull the matching events. NOTE: this query also bypasses\n // `events.organizationId` scope — by design — so explicitly filter\n // out soft-deleted rows yourself if your `events` table uses them.\n const eventIds = guestRows.map((r) => r.eventId);\n const rows = await db\n .select()\n .from(events)\n .where(inArray(events.id, eventIds));\n\n return { events: rows };\n },\n});\n```\n\nWhy this is a standalone action and not a CRUD route:\n\n- **Tenant firewall would block it.** The default `firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }]` on `events` is correct for every other read — only the cross-tenant dashboard wants to step outside it, and that's a deliberate, explicit step taken in handler code.\n- **The join is the access control.** A relationship-role at the firewall layer can't express \"filter by this user's relationships, ignoring the org context.\" The handler does that join directly.\n- **Audit-logged automatically.** Standalone actions are mandatorily audit-logged in the runtime — the cross-tenant traversal is recorded with `ctx.userId`, IP, and timing.\n\nTwo important guardrails when you write one of these:\n\n1. **Always filter by `ctx.userId` in the relationship lookup.** If you accept a `userId` from the request body and trust it, you've built an IDOR. The example above uses `ctx.userId!` directly so the only events returned are the caller's.\n2. **You take responsibility for soft-delete and other invariants the firewall would otherwise apply.** Add the `deletedAt` filter, status checks, and any other row-level predicates by hand. The action is OUTSIDE the firewall pipeline by design — the cost is that you can't lean on the auto-applied predicates.\n\nIf you find yourself writing more than one of these per project, that's usually a signal to revisit the schema (could a user-owned `userEvents` materialized view replace the join?) rather than a sign Quickback should ship a higher-level abstraction. Cross-tenant lanes are intentionally explicit.\n\n### Compile-time refusals (consolidated)\n\nThe validator and resolver reject:\n\n- Unknown key in `authz` block (typo guard — `realtionships` would otherwise silently produce a permanently-denied role).\n- Reserved role-name (auth-provider-derived). Names like `guest`, `speaker`, `attendee` are free; `admin`/`owner`/`member` are reserved when the BA org plugin is on.\n- Cycle in role composition (`a → b → a`).\n- Relationship `from` references unknown table.\n- Relationship-role used on a resource missing the `resource.column`.\n- Relationship table with `firewall: { exception: true }` (would let cross-tenant grants slip through).\n- `lowering: 'session'` (reserved for v2 — staleness/invalidation ergonomics not yet shipped).\n- `+` hierarchy suffix on a relationship-role name (terminal, like pseudo-roles).\n- Relationship-roles in `masking.show` / `actions.access` (deferred surfaces — see the table above).\n\n## Namespace mounts (hoisted relationship middleware)\n\nWhen several standalone actions share a path prefix and the same relationship gate — `/event/:eventId/announce`, `/event/:eventId/cancel`, `/event/:eventId/respond` — declaring the gate per-action means writing the same `roles: ['attendee']` over and over AND paying the relationship-resolver cost N times per request (one subquery + one row-load, multiplied by the number of actions).\n\nNamespace mounts hoist the resolver into one Hono middleware that runs once per request. Every action under the prefix skips the inline gate; `ctx.<exposeAs>` is hydrated by the middleware before the action's `execute()` runs. With the per-namespace helper (v0.27+, [below](#narrow-ctxexposeas-typing-v027)), that field is also statically typed as the loaded row.\n\n### When to use roles vs. relationships\n\nA user is authorized for a row when **any** of the following is true:\n\n- they have a **per-row relationship** to it (e.g. an attendee row, a named organizer row), or\n- they have a **role on the row's tenant** (org admin/owner of the row's `organizationId`), or\n- they have **team membership** matching the row's `teamId`.\n\nUse **relationships** when membership is specific to *this row* — external collaborators who aren't in your org, attendees, anyone connected to the resource by virtue of data rather than payroll. Use **roles / team** when staff at your org/team should see everything in their scope by default.\n\nThe two compose at the action level (`access.or` accepts both relationship-roles and tenant roles) and — as of v0.25 — at the namespace level too: `namespace.via` accepts an array of lanes, first match wins.\n\n> **Rule of thumb.** If the answer is *\"yes if you work here,\"* reach for org/team roles. If the answer is *\"yes if you have something to do with **this** row,\"* reach for a per-row relationship. Reach for both together — at the namespace or via `access.or` — when an action should let either side in.\n\nTwo declaration sites depending on whether the participating actions live in one feature or many:\n\n### Single feature: `defineTable({ namespace })` (v0.23+)\n\nUse when every action under the prefix lives in the same feature directory. The namespace travels with the table that owns it — no addition to `quickback.config.ts` needed.\n\n```typescript\n// features/events/events.ts\nexport default defineTable(events, {\n firewall: [...],\n crud: { ... },\n namespace: {\n prefix: '/event/:eventId', // absolute URL path\n via: 'attendeeOf', // relationship gate (must exist in authz.relationships)\n },\n});\n\n// features/events/actions/post-announcement.ts\nexport default defineAction({\n path: '/event/:eventId/announcements',\n method: 'POST',\n // No gate boilerplate. ctx.event is typed inside execute().\n});\n```\n\nThe compiler emits one `app.use(...)` on the events feature's Hono app. Every standalone action in `features/events/actions/` whose path starts with `/event/:eventId/` joins the namespace automatically.\n\nMulti-lane via (v0.25+) and bulk-grant lanes (v0.26+) work identically on the table-level declaration — `via:` accepts the same shapes documented below for the project-level form.\n\n### Cross-feature: `authz.namespaces` (v0.24+)\n\nUse when the namespace spans multiple features. The declaration sits next to your other authz config in `quickback.config.ts`.\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n namespaces: {\n eventScope: { prefix: '/event/:eventId', via: 'attendeeOf' },\n },\n}\n```\n\nWith the namespace declared, any standalone action whose `path:` matches the prefix joins the gate — regardless of which feature owns it:\n\n```typescript\n// features/feeds/actions/feed-moments.ts (in one feature)\nexport default defineAction({\n path: '/event/:eventId/feed-moments',\n method: 'POST',\n});\n\n// features/rsvp/actions/respond.ts (in a different feature)\nexport default defineAction({\n path: '/event/:eventId/respond',\n method: 'POST',\n});\n```\n\nThe compiler emits one synthetic `src/routes/__namespace-event-scope.routes.ts` that imports each contributing feature's `actions` map under a distinct alias, mounts the resolver middleware once, and dispatches to the matching action. Worker-root mount order ensures the middleware fires before any per-feature route handler under the prefix.\n\n### Multi-lane via (v0.25+) — first match wins\n\nWhen more than one relationship can authorize a caller for the namespaced resource, pass `via:` as an array. The middleware tries each lane in declaration order and stops at the first match — `ctx.<exposeAs>` is hydrated from whichever lane fired.\n\n```typescript\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'linkedUserId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events',\n exposeAs: 'event',\n },\n // Named per-event organizers (potentially EXTERNAL — these users may\n // not be a member of the event's org. That's the point: lets you grant\n // event-level access to freelancers / partner staff without adding\n // them to the org's member list.)\n organizerOf: {\n from: 'eventOrganizers',\n subject: { column: 'linkedUserId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n namespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: ['attendeeOf', 'organizerOf'],\n },\n },\n}\n```\n\nAll relationship lanes in a namespace **must agree on `loads:` + `exposeAs:`** — that's what guarantees `ctx.event` has the same shape regardless of which lane matched. The compiler rejects heterogeneous lanes at parse time.\n\n### Bulk-grant lanes (v0.26+)\n\nRelationship lanes cover \"specifically connected to this row.\" Bulk-grant lanes cover \"anyone with this role / team membership in the row's tenant\" — the case where an org admin or a team member should see every event in their scope without writing per-event relationship rows.\n\n```typescript\nnamespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: [\n 'attendeeOf',\n 'organizerOf',\n { roles: ['admin', 'owner'] }, // org-role bulk grant\n { team: true }, // active-team-membership bulk grant\n ],\n },\n}\n```\n\nEach bulk-grant lane:\n\n- **`{ roles: [...] }`** — passes when the caller's BA org-role for the loaded resource's tenant includes any listed role. Short-circuits the relationship loop entirely; the role check is in-memory and cheap. Use for the \"company admin sees everything\" case.\n- **`{ team: true }`** — passes when `ctx.activeTeamId` is set. The loads-table firewall does the actual `events.teamId === ctx.activeTeamId` check during hydration. Use when the resource is team-scoped and you want active-team membership to grant access.\n\nBoth bulk-grant lanes piggyback on the namespace's relationship lane(s) for hydration — they don't fetch a separate per-row subject; they just gate access and let the loads-table firewall handle the tenant scoping. **At least one relationship lane is required** alongside bulk-grant lanes in v0.26 (to anchor `loads:` + `exposeAs:`).\n\nWhen a request misses every lane, the 403 deny payload lists every authorization path the caller could have taken — relationship names, role names, and `\"team-membership\"` for `{ team: true }` lanes — so a developer debugging an unexpected 403 sees the full surface they need to satisfy.\n\nA namespace can also fold the scope machinery into this same gate: `mintScope: true` **mints** a scope token on a matched userId lane, and `acceptScope: '<kind>'` **accepts** an already-minted scope claim as proof of entry — one handler under the prefix serves both a Better-Auth user and a sessionless scope principal. See [Scopes → `acceptScope`](/compiler/definitions/scopes#acceptscope--accept-an-incoming-scope-claim-as-proof-of-entry).\n\n### Discovery is path-prefix-only\n\nActions opt in by matching `path:` against a declared namespace prefix. There's no `namespace: 'foo'` field on `defineAction` — the path string is the discoverable surface, consistent with how `path:` already determines an action's URL.\n\n### Requirements (enforced at compile time)\n\nBoth forms share the same shape checks:\n\n- **`via:` accepts one of three shapes.** A single relationship name (v0.23+), an array of relationship names (v0.25+, first match wins), or — as of v0.26 — an array mixing relationship names with bulk-grant guards (`{ roles: [...] }`, `{ team: true }`).\n- **Every relationship lane must declare `loads + exposeAs`.** Without `loads` there's nothing for the middleware to hydrate; the namespace gate would be indistinguishable from a per-action access rule.\n- **All relationship lanes in one namespace must agree on `loads:` + `exposeAs:`.** Otherwise `ctx.<exposeAs>` would change shape depending on which lane matched.\n- **Bulk-grant lanes inherit `loads:` + `exposeAs:` from sibling relationship lanes.** Pure bulk-grant namespaces (no relationship lane at all) are also accepted — set `loads:` + `exposeAs:` directly on the namespace declaration so hydration has somewhere to anchor.\n- **`prefix:` must contain at least one `:param` segment** (e.g. `/event/:eventId`). The middleware reads the relationship key from `c.req.param()` because no request body has been parsed at middleware time.\n- **One declaration per namespace name.** The same name in both `defineTable({ namespace })` and `authz.namespaces` is rejected. The project-level form is canonical for cross-feature; the table-level form is the single-feature shorthand.\n\nProject-level only:\n\n- **Ambiguous prefixes** like `/a/:x` and `/a/:y` (same shape, different `:param` names) are rejected. Strict super/sub-set relationships (`/event/:e` vs `/event/:e/admin`) are fine — the harvester routes each action to the longest matching prefix.\n- **Unused namespace** emits a `[quickback:authz]` warning when no action's path matches the declared prefix. Not a hard error — the namespace may be staged ahead of the actions.\n\n### What namespace actions get for free\n\nInside a namespace action's `execute()`:\n\n- `ctx.<exposeAs>` is populated by the middleware with the loaded resource row. Statically `any` by default — narrowed to `typeof <loadsTable>.$inferSelect` when the action's import points at the per-namespace helper (see [below](#narrow-ctxexposeas-typing-v027)).\n- Tenant context (`ctx.activeOrgId` / `ctx.activeTeamId`) is stamped from the matched relationship row when its `from` table carries those columns. Downstream scoped queries work without further setup.\n- The action's own `access:` block (additional roles, userRole, record predicates, OTHER relationship arms) still runs after the namespace gate — namespace handles entry, per-action gates further.\n\n### Narrow `ctx.<exposeAs>` typing (v0.27+)\n\nThe namespace middleware hydrates `ctx.<exposeAs>` at runtime — that's been true since v0.23. The static type of that field, though, is `any` via the `AppContext` index signature: useful for not blocking access, but a missed opportunity for autocomplete and typo-catching.\n\nv0.27 emits one **per-namespace `defineAction` helper** alongside the standard `<feature>/.quickback/define-action.ts`. Importing from the narrowed helper retypes `ctx.<exposeAs>` inside `execute({ ctx })` to the loaded row's `$inferSelect` shape. Nothing else changes — runtime behavior, action discovery, and the `path:` namespace match are identical.\n\n```ts title=\"features/feeds/actions/feed-moments.ts\"\n// One-line flip per namespace-scoped action:\n\n// └──────┬──────┘\n// kebab(namespaceName)\n\nexport default defineAction({\n path: '/event/:eventId/feed-moments',\n method: 'POST',\n input: z.object({ body: z.string() }),\n access: { roles: ['attendee'] },\n async execute({ ctx, input }) {\n ctx.event.id // ✓ string\n ctx.event.startsAt // ✓ Date — autocomplete works\n ctx.event.organizerId // ✓ narrows on the field's declared type\n\n ctx.event.idd // ✗ TS2339 — typo caught at compile time\n },\n});\n```\n\nThe compiler emits one helper per `(feature, namespace)` pair where the feature owns at least one action whose `path:` falls under the namespace prefix. Filename is `define-action.<kebab(namespaceName)>.ts` — `eventScope` becomes `define-action.event-scope.ts`. Helpers live next to the standard `define-action.ts` in `<feature>/.quickback/`, so the relative import is the same shape as every other action file in your project.\n\n#### Opt-in, not breaking\n\nActions that keep their existing `import { defineAction } from '../.quickback/define-action'` continue to compile unchanged — `ctx.<exposeAs>` is `any` via the `AppContext` index signature, which is exactly the v0.23–v0.26 behavior. You flip imports per action at your own pace.\n\n#### Compile-time advisory\n\nWhen `quickback compile` sees a namespace-scoped action still importing the generic helper, it emits a one-line advisory pointing at the narrowed path:\n\n```text\n[quickback:typing] action \"feedMoments\" in feature \"feeds\" lives under\n namespace \"eventScope\" — switch its import to\n `../.quickback/define-action.event-scope` for narrow ctx.<exposeAs> typing.\n (Runtime behavior is unchanged; the narrowed helper only refines TS types.)\n```\n\nNon-blocking — same `[quickback:typing]` family as `[quickback:authz]`. The advisory only mentions actions the compiler can be confident about (namespace-claimed actions whose source still imports the generic helper).\n\n#### Multi-namespace features\n\nA single feature can contribute actions to several namespaces — say, an `interviews` feature with actions under both `interviewScope` and `eventScope`. The compiler emits one narrowed helper per namespace the feature participates in, and each action picks the import that matches its path.\n\n```text\nsrc/features/interviews/.quickback/\n├── define-action.ts # generic — standard fallback\n├── define-action.interview-scope.ts # ctx.interview typed\n└── define-action.event-scope.ts # ctx.event typed\n```\n\n#### Why per-namespace and not per-action\n\nA `defineAction` helper that's narrow to *one* exposed key (the namespace's `exposeAs`) is enough — every action under a namespace sees the same hydrated key. The alternative (per-action emit) duplicates the same prelude N times for the same shape; per-namespace keeps emission proportional to the number of distinct hydration shapes in the project.\n\n## Read & Write Configuration\n\nReads (`GET /` and `GET /:id`) live under `read:`; mutations live under top-level `create:`, `update:`, `delete:`, and `upsert:`. See [Read](/compiler/definitions/read) for the full read pipeline reference.\n\n```typescript\nread: {\n // LIST + GET - GET /resource and GET /resource/:id\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n pageSize: 25, // Default page size\n maxPageSize: 100, // Client can't exceed this\n views: { // Per-view field projections\n summary: {\n fields: ['id', 'candidateId', 'jobId', 'stage'],\n access: { roles: [\"interviewer\"] },\n },\n },\n}\n\ncreate: {\n // CREATE - POST /resource\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] },\n defaults: { // Default values for new records\n stage: 'applied',\n },\n},\n\nupdate: {\n // UPDATE - PATCH /resource/:id\n access: {\n or: [\n { roles: [\"hiring-manager\", \"recruiter\"] },\n { roles: [\"interviewer\"], record: { stage: { equals: \"interview\" } } }\n ]\n },\n},\n\ndelete: {\n // DELETE - DELETE /resource/:id\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"soft\", // 'soft' (default) or 'hard'\n},\n\nupsert: {\n // PUT - PUT /resource/:id (only when generateId: false + guards: false)\n access: { roles: [\"hiring-manager\", \"sync-service\"] },\n}\n```\n\n## Evaluation Order\n\nGenerated `/:id` and batch handlers evaluate access in this fixed order:\n\n1. **Auth gate** — 401 if unauthenticated\n2. **Pre-record access** — role-only check (skips `access.record` predicates)\n3. **Firewall query** — `WHERE` clause filters by ownership\n4. **Post-record access** — full check including record-level predicates\n5. **Masking** — applied to the response\n\nStep 2 closes the 404-vs-403 ID-probe channel: an unauthorized caller without\na matching role gets 403 before the database is touched, so they can't tell\napart \"row exists out-of-scope\" from \"row doesn't exist.\" A caller with the\nright role but the wrong tenant gets 403 by default (firewall reveals via\nthe access layer); set\n[`firewallErrorMode: 'hide'`](/compiler/definitions/firewall) to return an\nopaque 404 instead.\n\nFunction-form access (`access: async (ctx, record) => ...`) is opaque to\nthe pre-record phase and always passes there; it's fully evaluated post-record.\n\n## List Filtering (Query Parameters)\n\nThe LIST endpoint automatically supports filtering via query params:\n\n```\nGET /jobs?status=open # Exact match\nGET /jobs?salaryMin.gt=50000 # Greater than\nGET /jobs?salaryMin.gte=50000 # Greater than or equal\nGET /jobs?salaryMax.lt=200000 # Less than\nGET /jobs?salaryMax.lte=200000 # Less than or equal\nGET /jobs?status.ne=closed # Not equal\nGET /jobs?title.like=Engineer # Pattern match (LIKE %value%)\nGET /jobs?status.in=open,draft # IN clause\n```\n\n| Operator | Query Param | SQL Equivalent |\n|----------|-------------|----------------|\n| Equals | `?field=value` | `WHERE field = value` |\n| Not equals | `?field.ne=value` | `WHERE field != value` |\n| Greater than | `?field.gt=value` | `WHERE field > value` |\n| Greater or equal | `?field.gte=value` | `WHERE field >= value` |\n| Less than | `?field.lt=value` | `WHERE field < value` |\n| Less or equal | `?field.lte=value` | `WHERE field <= value` |\n| Pattern match | `?field.like=value` | `WHERE field LIKE '%value%'` |\n| In list | `?field.in=a,b,c` | `WHERE field IN ('a','b','c')` |\n\n## Sorting & Pagination\n\n```\nGET /jobs?sort=createdAt&order=desc # Sort by field\nGET /jobs?limit=25&offset=50 # Pagination\n```\n\n- **Default limit**: 50\n- **Max limit**: 100 (or `maxPageSize` if configured)\n- **Default order**: `asc`\n\n## Delete Modes\n\n```typescript\ndelete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"soft\", // Sets deletedAt/deletedBy, record stays in DB\n}\n\ndelete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"hard\", // Permanent deletion from database\n}\n```\n\n## Context Variables\n\nUse `$ctx.` prefix to reference context values in conditions:\n\n```typescript\n// User can only view their own records\naccess: {\n record: { userId: { equals: \"$ctx.userId\" } }\n}\n\n// Nested path support for complex context objects\naccess: {\n record: { ownerId: { equals: \"$ctx.user.id\" } }\n}\n```\n\n### AppContext Reference\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `$ctx.userId` | `string` | Current authenticated user's ID |\n| `$ctx.activeOrgId` | `string` | User's active organization ID |\n| `$ctx.activeTeamId` | `string \\| null` | User's active team ID (if applicable) |\n| `$ctx.roles` | `string[]` | User's roles in current context |\n| `$ctx.isAnonymous` | `boolean` | Whether user is anonymous |\n| `$ctx.user` | `object` | Full user object from auth provider |\n| `$ctx.user.id` | `string` | User ID (nested path example) |\n| `$ctx.user.email` | `string` | User's email address |\n| `$ctx.{property}` | `any` | Any custom context property |\n\n## Function-Based Access\n\nFor complex access logic that can't be expressed declaratively, use a function:\n\n```typescript\nupdate: {\n access: async (ctx, record) => {\n // Custom logic - return true to allow, false to deny\n if (ctx.roles.includes('admin')) return true;\n if (record.ownerId === ctx.userId) return true;\n\n // Check custom business logic\n const membership = await checkTeamMembership(ctx.userId, record.teamId);\n return membership.canEdit;\n }\n}\n```\n\nFunction access receives:\n- `ctx`: The full AppContext object\n- `record`: The record being accessed (for get/update/delete operations)"
79
83
  },
80
84
  "compiler/definitions/actions": {
81
85
  "title": "Actions",
82
- "content": "Actions are custom API endpoints for business logic beyond CRUD operations. They enable workflows, integrations, and complex operations.\n\n## Overview\n\nQuickback supports two types of actions:\n\n| Aspect | Record-Based | Standalone |\n|--------|--------------|------------|\n| Route | `{METHOD} /:id/{actionName}` | Custom `path` (required) |\n| Record fetching | Automatic | None (`record` is `undefined`) |\n| Firewall applied | Yes | No |\n| Preconditions | Supported via `access.record` | Not applicable |\n| Response types | JSON only | JSON, stream, file |\n| Use case | Advance application, reject candidate | AI chat, bulk import from job board, webhooks |\n\nStandalone actions are signalled by the presence of a `path:` field in the action config. Record-based actions omit `path` and bind to the feature's primary table.\n\n## Where do actions live?\n\n**One file per action.** Each action is its own module under the feature's\n`actions/` directory:\n\n```\nfeatures/applications/\n├── applications.ts ← defineTable (primary table)\n├── candidates.ts ← defineTable (sibling table)\n├── actions/\n│ ├── advance.ts ← defineAction, binds to applications\n│ ├── reject.ts ← defineAction, binds to applications\n│ ├── stats.ts ← defineAction, standalone (has `path:`)\n│ └── candidates/\n│ └── disqualify.ts ← defineAction, binds to candidates\n└── lib/\n └── inputs.ts ← shared schemas (optional, copied verbatim)\n```\n\n| Layout | Binds to |\n|--------|----------|\n| `actions/<name>.ts` | The feature's primary table (table file matching the feature name), or standalone if `path:` is set. |\n| `actions/<table>/<name>.ts` | The sibling table file `<table>.ts` at the feature root. Standalone actions inside a subdir ignore the binding. |\n\nThe action's filename (sans `.ts`) is the action name and the URL segment.\nUniqueness is enforced per `(bound table, name)` pair — sibling-bound\nactions on **different** tables may share a verb (`actions/episodes/publish.ts`\nand `actions/shows/publish.ts` mount at `/episodes/:id/publish` and\n`/shows/:id/publish` and compile cleanly). The compiler errors only when\ntwo action files would mount at the same URL — for example, a flat\n`actions/foo.ts` (binds to primary) plus `actions/<primary>/foo.ts`, or\ntwo standalones with the same `(method, path)`. Standalone actions are\nunique per `(method, path)`.\n\nTableless features have no top-level `*.ts` files; every action under\n`actions/` must be standalone (have `path:`). Use this for utility endpoints\nlike webhooks, reports, or integrations that don't operate on a specific\nrecord.\n\n### Retired layouts\n\nThese are rejected at load time with migration guidance:\n\n- **`actions.ts`** (bundled multi-action file)\n- **`_feature.ts`** (shared schemas + non-table-bound actions)\n- **`handlers/`** (separate handler-file directory)\n- **`defineActions(table, {...})`** (the multi-action factory)\n- **`defineActions(null, {...})`** (tableless variant)\n- **`*-actions.ts` / `*.actions.ts`** filename patterns\n\nFor shared Zod schemas or helpers, put them under `<feature>/lib/` and import\nfrom each action file. Files under `lib/` are copied verbatim into the\ngenerated output.\n\n## Defining Actions\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n notes: z.string().max(2000).optional(),\n }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: {\n applied: [\"screening\"],\n screening: [\"interview\"],\n interview: [\"offer\"],\n },\n },\n async execute({ db, record, input, whereTransition }) {\n const [updated] = await db\n .update(applications)\n .set({\n status: input.nextStatus,\n notes: input.notes ?? record.notes,\n })\n .where(whereTransition!(applications))\n .returning();\n return updated;\n },\n});\n```\n\n> **`defineAction` import.** Import from `\"../.quickback/define-action\"` —\n> the `.quickback/` directory is generated alongside your feature with a\n> typed helper that infers `record` and `input` types from the rest of the\n> action config. Audit fields (`createdAt`, `createdBy`, `modifiedAt`,\n> `modifiedBy`) are hard-stamped by the audit DB wrapper on every\n> `db.insert().values()` and `db.update().set()` — handlers don't pass\n> them and can't override them.\n\n### Configuration Options\n\n| Option | Required | Description |\n|--------|----------|-------------|\n| `description` | Yes | Human-readable description of the action |\n| `input` | Yes | Zod schema for request validation |\n| `access` | Yes | Access control (roles, record conditions, or function) |\n| `execute` | Yes | Inline async arrow function (`async (ctx) => { … }`) |\n| `path` | Standalone only | Custom route path. Presence of `path` makes the action standalone. |\n| `method` | No | HTTP method: GET, POST, PUT, PATCH, DELETE (default: POST). GET actions parse `input` from query params; all other methods parse from the JSON body. See [GET vs POST for input](#get-vs-post-for-input). |\n| `responseType` | No | Response format: json, stream, file (default: json) |\n| `sideEffects` | No | Hint for AI tools: `'sync'`, `'async'`, or `'fire-and-forget'` |\n| `allowRawSql` | No | Explicit compile-time opt-in for raw SQL in execute code |\n| `unsafe` | No | Unsafe raw DB mode. Object config (`reason`, `adminOnly`, `crossTenant`, `targetScope`). |\n| `transition` | No | State-machine policy enforcing the from/to pair (record-based actions). See [Transitions](#transition-state-machine-policy) |\n| `bulkVariant` | No | Auto-generate a `POST /:resource/batch/{action}` route alongside the per-record route (record-based actions). See [Bulk Variant](#bulk-variant) |\n| `cms` | No | Pass-through metadata blob for CMS surfaces |\n\n`execute` must be an `async (ctx) => { … }` arrow function. `async function`\ndeclarations and non-async forms are rejected at parse time.\n\n## Record-Based Actions\n\nRecord-based actions operate on an existing record. The record is automatically loaded and validated before your action executes.\n\n**Route pattern:** `{METHOD} /:id/{actionName}`\n\n```\nPOST /applications/:id/advance\nPOST /applications/:id/reject\nPOST /applications/:id/schedule-interview\n```\n\n### Runtime Flow\n\n1. **Authentication** - User token is validated\n2. **Input Validation** - Request body validated against Zod schema\n3. **Role Gate** - The access roles are checked *before* the record is\n fetched (v0.46+), so a wrong-role caller gets a uniform\n `403 ACCESS_ROLE_REQUIRED` whether or not the record exists — the\n response can't be used to probe for record ids\n4. **Record Loading** - The record is fetched by ID **through the firewall**\n (a cross-tenant or missing id is a standard firewall miss)\n5. **Access Check** - Record preconditions (`access.record`) and transition\n policy are validated against the loaded record\n6. **Execution** - Your action handler runs\n7. **Response** - Result is returned to client\n\n### Example: Advance Application Stage\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move application to the next pipeline stage\",\n input: z.object({\n stage: z.enum([\"screening\", \"interview\", \"offer\", \"hired\"]),\n notes: z.string().optional(),\n }),\n access: {\n roles: [\"owner\", \"hiring-manager\"],\n record: { stage: { notEquals: \"rejected\" } },\n },\n async execute({ db, record, input }) {\n const [updated] = await db\n .update(applications)\n .set({\n stage: input.stage,\n notes: input.notes ?? record.notes,\n })\n .where(eq(applications.id, record.id))\n .returning();\n return updated;\n },\n});\n```\n\n### Request Example\n\n```\nPOST /applications/app_123/advance\nContent-Type: application/json\n\n{\n \"stage\": \"interview\",\n \"notes\": \"Strong technical background, moving to interview\"\n}\n```\n\n### Response Example\n\n```json\n{\n \"data\": {\n \"id\": \"app_123\",\n \"stage\": \"interview\",\n \"notes\": \"Strong technical background, moving to interview\"\n }\n}\n```\n\n### Bulk variant\n\nSet `bulkVariant: true` to auto-generate a bulk version of the action at\n`POST /:resource/batch/{action}`. The compiler emits a second route alongside\nthe per-record one, looping the same access + transition + execute pipeline\nover an array of ids. This is the answer to \"I need to advance 50\napplications at once\" — you don't have to hand-roll a parallel standalone\naction that duplicates the per-record logic.\n\n```typescript\n// features/applications/actions/advance.ts\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n bulkVariant: true,\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: { applied: [\"screening\"], screening: [\"interview\"], interview: [\"offer\"] },\n },\n async execute({ db, record, input, whereTransition }) {\n const [updated] = await db\n .update(applications)\n .set({ status: input.nextStatus })\n .where(whereTransition!(applications))\n .returning();\n if (!updated) throw new TransitionLostError(\"status\", record.status, input.nextStatus);\n return updated;\n },\n});\n```\n\n**Request shape:**\n\n```http\nPOST /applications/batch/advance\nContent-Type: application/json\n\n{\n \"ids\": [\"app_001\", \"app_002\", \"app_003\"],\n \"input\": { \"nextStatus\": \"interview\" },\n \"failFast\": false\n}\n```\n\nThe `input` is shared across the batch — the action's Zod schema is\nvalidated once, not per id. For per-record input variation, use the\nsingle-record endpoint (`POST /:id/{action}`) or write a standalone action.\n\n**Response (207 Multi-Status when any record fails, 200 when clean):**\n\n```json\n{\n \"success\": [{ \"id\": \"app_001\", \"status\": \"interview\" }],\n \"errors\": [\n {\n \"index\": 1,\n \"id\": \"app_002\",\n \"error\": {\n \"error\": \"Action not allowed for current state\",\n \"code\": \"ACCESS_ACTION_NOT_ALLOWED_FOR_STATE\",\n \"details\": { \"field\": \"status\", \"currentValue\": \"rejected\" }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"failFast\": false,\n \"transactional\": false\n }\n}\n```\n\n**Per-record pipeline** mirrors the single-record route exactly — the same\nfirewall fetch, access reason split (403 vs 409), transition pre-check,\n`whereTransition` factory, and `TransitionLostError` handling. Per-record\nfailures land in `errors[]` with their original index; successful records\nland in `success[]` masked the same way the single-record response is.\n\n**Transactional matrix** (same as `PATCH /batch`):\n\n| Provider | failFast | transactional | Behavior |\n|---|---|---|---|\n| tx-supporting (postgres, neon over websocket) | `true` | `true` | `db.transaction()` wraps the loop; any throw rolls back all writes |\n| (any) | `false` | `false` | Independent per-record outcomes, partial success |\n| cloudflare-d1, neon over http (Cloudflare default) | `true` | `false` | Fail-fast loop without rollback — earlier records stay committed (the driver has no `db.transaction`; `drizzle-orm/neon-http` throws at runtime) |\n\n**Constraints:**\n\n- Record-based actions only. Standalone actions reject `bulkVariant: true`\n at compile time (no record context to loop over).\n- `unsafe` actions reject `bulkVariant: true` in v1 — the cross-tenant\n per-record audit story is not yet wired through.\n- Method is forced to POST regardless of the action's `method` setting. The\n semantic asymmetry (one row → many rows) makes inheriting GET/DELETE\n confusing.\n- Max batch size is 100 ids per request.\n\n## Standalone Actions\n\nStandalone actions are independent endpoints that don't require a record context. Set a `path:` to declare the action standalone.\n\n**Route pattern:** Custom `path`\n\n```\nPOST /chat\nGET /reports/summary\nPOST /webhooks/stripe\n```\n\n### Example: AI Chat with Streaming\n\n```typescript\n// features/sessions/actions/chat.ts\n\nexport default defineAction({\n description: \"Send a message to AI\",\n path: \"/chat\",\n method: \"POST\",\n responseType: \"stream\",\n input: z.object({\n message: z.string().min(1).max(2000),\n }),\n access: { roles: [\"recruiter\", \"hiring-manager\"] },\n async execute({ input, c }) {\n // Stream response back to client...\n return c.newResponse(/* ReadableStream */);\n },\n});\n```\n\n### Streaming Response Example\n\nFor actions with `responseType: 'stream'`:\n\n```\nContent-Type: text/event-stream\n\ndata: {\"type\": \"start\"}\ndata: {\"type\": \"chunk\", \"content\": \"Hello\"}\ndata: {\"type\": \"chunk\", \"content\": \"! I'm\"}\ndata: {\"type\": \"chunk\", \"content\": \" here to help.\"}\ndata: {\"type\": \"done\"}\n```\n\n### Tableless Features\n\nA feature directory with no top-level `*.ts` files is \"tableless\" — every\naction under `actions/` must be standalone. Use this for utility endpoints\nlike reports, integrations, or webhooks that don't map to a specific\nresource.\n\n```\nquickback/features/\n└── reports/\n └── actions/\n ├── trial-balance.ts ← standalone (has path:)\n └── profit-loss.ts ← standalone (has path:)\n```\n\n```typescript\n// features/reports/actions/trial-balance.ts\n\nexport default defineAction({\n description: \"Generate trial balance report\",\n path: \"/reports/trial-balance\",\n method: \"GET\",\n input: z.object({\n startDate: z.string(),\n endDate: z.string(),\n }),\n access: { roles: [\"admin\", \"accountant\"] },\n async execute({ db, input }) {\n // ... build report\n return { rows: [] };\n },\n});\n```\n\n### GET vs POST for input\n\nGET actions read `input` from URL query parameters; every other method (POST,\nPUT, PATCH, DELETE) reads from the JSON body. The Zod schema is the same in\nboth cases — the compiler picks the right parser based on `method`.\n\n```typescript\n// GET — input populated from ?q=…&limit=…\ndefineAction({\n method: \"GET\",\n path: \"/search\",\n input: z.object({\n q: z.string(),\n limit: z.coerce.number().int().positive().max(100).default(20),\n }),\n access: { roles: [\"AUTHENTICATED\"] },\n async execute({ input }) {\n // input is { q: string, limit: number } — fully typed.\n },\n});\n```\n\nRepeated query keys (`?tag=a&tag=b`) come through as arrays automatically;\nsingle values stay as strings. Use Zod's `.coerce.number()` /\n`.coerce.boolean()` when you want typed primitives from the parsed strings.\n\n**Use POST when input is structured.** GET requests cannot carry a JSON body\nin any of the surfaces Quickback APIs are commonly called from:\n\n- Browsers throw on `fetch(url, { method: 'GET', body })`.\n- CDNs and caches key on URL+method; a GET with a body either gets the body\n stripped at the edge or cache-collides with semantically different requests.\n- OpenAPI client generators (axios, openapi-fetch, openapi-typescript-codegen)\n refuse to emit GET-with-body, so the generated SDKs break.\n- The MCP agent surface treats GET as parameter-only — agents calling a GET\n action will only see what the URL exposes.\n\nIf your action takes nested objects, arrays of objects, or large inputs that\ndon't serialize cleanly to a query string, set `method: \"POST\"`. POST doesn't\nimply \"this writes data\" — it's the right method whenever the request body is\nload-bearing. Use the response shape (`responseType: \"json\"`, or just the data\nyour handler returns) to convey read semantics; HTTP method choice is about\ninput transport, not action intent.\n\n## Access Configuration\n\nAccess controls who can execute an action and under what conditions.\n\n### Role-Based Access\n\n```typescript\naccess: {\n roles: [\"hiring-manager\", \"recruiter\"] // OR logic: user needs any of these roles\n}\n```\n\n### Public Access\n\nUse `roles: [\"PUBLIC\"]` for unauthenticated endpoints (contact forms, webhooks, public APIs). Every invocation is **mandatory audit logged** with IP address, input, result, and timing.\n\n```typescript\n// features/contact/actions/submit.ts\n\nexport default defineAction({\n description: \"Public contact form submission\",\n path: \"/submit\",\n input: z.object({\n name: z.string().min(1),\n email: z.string().email(),\n message: z.string().min(10),\n }),\n access: { roles: [\"PUBLIC\"] },\n async execute({ db, input }) {\n // ... persist submission\n return { ok: true };\n },\n});\n```\n\nThe wildcard `\"*\"` is not supported and will throw a compile-time error. Use `\"PUBLIC\"` explicitly.\n\n### Record Conditions\n\nFor record-based actions, you can require the record to be in a specific state:\n\n```typescript\naccess: {\n roles: [\"hiring-manager\"],\n record: {\n stage: { equals: \"screening\" } // Precondition\n }\n}\n```\n\n**Supported operators:**\n\n| Operator | Description |\n|----------|-------------|\n| `equals` | Field must equal value |\n| `notEquals` | Field must not equal value |\n| `in` | Field must be one of the values |\n| `notIn` | Field must not be one of the values |\n\n### Context Substitution\n\nUse `$ctx` to reference the current user's context:\n\n```typescript\naccess: {\n record: {\n ownerId: { equals: \"$ctx.userId\" },\n organizationId: { equals: \"$ctx.activeOrgId\" }\n }\n}\n```\n\n### OR/AND Combinations\n\n```typescript\naccess: {\n or: [\n { roles: [\"hiring-manager\"] },\n {\n roles: [\"recruiter\"],\n record: { ownerId: { equals: \"$ctx.userId\" } }\n }\n ]\n}\n```\n\n### Function Access\n\nFor complex logic, use an access function:\n\n```typescript\naccess: async (ctx, record) => {\n return ctx.roles.includes('admin') || record.ownerId === ctx.userId;\n}\n```\n\n### Relationship-roles in actions\n\n**v0.19+** — standalone actions now support relationship-roles in `access.roles` directly. Declare the relationship under `authz.relationships` with optional `loads` / `exposeAs` for ctx hydration, and reference the role by name on the action:\n\n```ts\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n roles: { attendee: { via: 'attendeeOf' } },\n}\n\n// features/chat/actions/getInbox.ts\nexport default defineAction({\n path: '/chat/get-inbox',\n input: z.object({ eventId: z.number().int().positive() }),\n access: { roles: ['admin', 'member', 'attendee'] },\n execute: async ({ db, ctx, input }) => {\n // The resolver already verified attendance and loaded ctx.event.\n // No hand-rolled `SELECT … FROM guests WHERE …` needed.\n },\n});\n```\n\nThe action's surface (path params + input fields) must expose the relationship's `resource.column`. At v0.19 a missing key emits a `[quickback:authz]` warning and skips resolver emission; at v0.20 it becomes a compile error. See [Access — standalone actions](/compiler/definitions/access#standalone-actions-surface-keys-and-loads--exposeas-v019) for the full mechanism.\n\n**Record-based actions** are NOT yet supported — the runtime evaluator fail-closes (403) on relationship arms reached without an inline gate. Until inline emission for record-based actions lands, either:\n\n- Set `firewall: { exception: true }` on the action and gate manually in `execute()`, OR\n- Apply the relationship at the resource's firewall layer (worked example below).\n\n**Resource-layer workaround for record-based actions**: gate the action on BA roles only and apply the relationship at the resource layer via a firewall `via:` predicate:\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n },\n },\n}\n\n// features/sessions/sessions.ts — firewall scopes rows; action gates on BA role\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' }, // ← row-level relationship check\n],\nactions: {\n comment: defineAction({\n access: { roles: ['member', 'admin'] }, // ← BA role only on the action\n input: z.object({ text: z.string() }),\n execute: async (input, ctx, db, record) => {\n // record is already filtered by the firewall — guest membership\n // is enforced before this handler runs.\n return db.insert(comments).values({ ... });\n },\n }),\n}\n```\n\nThis pattern composes cleanly: the firewall guarantees the caller has the relationship to the record being acted on; the action's access list keeps the role surface obvious.\n\nSee [Access — relationship authorization](/compiler/definitions/access#relationship-based-authorization) for the full picture, including `loads` / `exposeAs` and the `firewall: { exception: true }` escape hatch.\n\n## Scoped Database\n\nAll actions receive a **scoped `db`** instance that automatically enforces security:\n\n| Operation | Org Scoping | Owner Scoping | Soft Delete Filter | Auto-inject on INSERT |\n|-----------|-------------|---------------|--------------------|-----------------------|\n| `SELECT` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n| `INSERT` | n/a | n/a | n/a | `organizationId`, `ownerId` from ctx |\n| `UPDATE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n| `DELETE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n\nScoping is duck-typed at runtime — tables with an `organizationId` column get org scoping, tables with `ownerId` get owner scoping, tables with `deletedAt` get soft delete filtering.\n\n```typescript\nasync execute({ db, ctx, input }) {\n // This query automatically includes WHERE organizationId = ? AND deletedAt IS NULL\n const items = await db.select().from(applications).where(eq(applications.stage, 'interview'));\n\n // Inserts automatically include organizationId\n await db.insert(applications).values({ candidateId: input.candidateId, jobId: input.jobId, stage: 'applied' });\n\n return items;\n}\n```\n\n**Not enforced** in scoped DB (by design):\n- **Guards** — actions ARE the authorized way to modify guarded fields\n- **Masking** — actions are backend code that may need raw data\n- **Access** — already checked before action execution\n\n### Unsafe Mode\n\nActions that need to bypass scoped DB filters (for example, platform-level support operations) can enable unsafe mode.\n\nUse object form for explicit policy and mandatory audit metadata:\n\n```typescript\n// features/admin/actions/cross-tenant-report.ts\n\nexport default defineAction({\n description: \"Generate cross-org hiring report\",\n path: \"/admin/cross-tenant-report\",\n input: z.object({ startDate: z.string() }),\n access: { roles: [\"owner\"] },\n unsafe: {\n reason: \"Support investigation for enterprise customer\",\n adminOnly: true, // default true\n crossTenant: true, // default true\n targetScope: \"all\", // \"all\" | \"organization\"\n },\n async execute({ unsafeDb, input }) {\n // unsafeDb bypasses scoped filters\n const allOrgs = await unsafeDb.select().from(applications);\n return allOrgs;\n },\n});\n```\n\nUnsafe cross-tenant actions are generated with:\n\n- Better Auth authentication required (no unauthenticated path)\n- sysadmin gate (`ctx.userRole === \"sysadmin\"`)\n- mandatory audit logging on deny/success/error\n\n**Provider note (Neon):** on Neon the request-scoped db enforces Row Level\nSecurity with the *caller's* org claims, which would filter out exactly the\ncross-tenant rows unsafe actions exist to reach. Unsafe handlers therefore\nacquire a dedicated service-role handle (`createServiceDb`) that sets the\n`quickback.service_role` transaction marker instead of caller claims; the\ngenerated RLS grants that context an explicit per-table bypass policy. The\naudit-logging contract is identical to D1. Neon with\n`connectionMode: 'websocket'` does not support unsafe actions yet and fails\nthe compile with a descriptive error.\n\n`PUBLIC` actions also receive mandatory audit logging (same audit table), since unauthenticated endpoints are high-risk by nature.\n\nWithout unsafe mode, `unsafeDb` is `undefined` in the executor params.\n\n### Raw SQL Policy\n\nBy default, the compiler rejects raw SQL in action code. Use Drizzle query-builder syntax whenever possible.\n\nIf a specific action must use raw SQL, opt in explicitly:\n\n```typescript\n// features/ledgers/actions/reconcile.ts\n\nexport default defineAction({\n description: \"Run custom reconciliation query\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n allowRawSql: true,\n async execute({ db }) {\n return db.execute(sql`select 1`);\n },\n});\n```\n\nWithout `allowRawSql: true`, compilation fails with a loud error pointing to the action and snippet.\n\nThe detector checks for SQL keywords in string arguments, so non-SQL method calls like `headers.get(\"X-Forwarded-For\")` or `map.get(\"key\")` will not trigger false positives.\n\n## Sharing Code Between Actions\n\nFor Zod schemas, helpers, or constants used across multiple actions in a\nfeature, put them under `<feature>/lib/` and import from each action file.\nFiles under `lib/` are copied verbatim into the generated output.\n\n```\nfeatures/applications/\n├── applications.ts\n├── actions/\n│ ├── advance.ts\n│ └── reject.ts\n└── lib/\n ├── inputs.ts ← shared Zod schemas\n └── transitions.ts ← state-machine helpers\n```\n\n```typescript\n// features/applications/lib/inputs.ts\n\nexport const advanceInput = z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n notes: z.string().max(2000).optional(),\n});\n```\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move forward\",\n input: advanceInput,\n access: { roles: [\"owner\"] },\n async execute({ db, record, input }) { /* … */ },\n});\n```\n\n### Importing Tables\n\nAction files import tables from their own feature or other features. The compiler generates alias files for each table, so you import by the table's file name:\n\n```typescript\n// features/applications/actions/advance.ts\n\n// Same feature — import from parent directory using the table's file name\n\n// Cross-feature — go up to the features directory, then into the other feature\n\n```\n\n**Path pattern from `features/{name}/actions/`:**\n- Same feature table: `../{table-file-name}` (e.g., `../applications`)\n- Other feature table: `../../{other-feature}/{table-file-name}` (e.g., `../../candidates/candidates`)\n- Generated lib files: `../../../lib/{module}` (e.g., `../../../lib/realtime`, `../../../lib/webhooks`)\n\n### Executor Parameters\n\n```typescript\n\ninterface ActionExecutorParams {\n db: DrizzleDB; // Scoped database (auto-applies org/owner/soft-delete filters)\n unsafeDb?: DrizzleDB; // Unscoped database (only available when unsafe mode is enabled)\n ctx: AppContext; // User context (userId, roles, activeOrgId, activeTeamId, userRole)\n record?: TRecord; // The record (record-based only, undefined for standalone)\n input: TInput; // Validated input from Zod schema\n services: TServices; // Configured integrations (billing, notifications, etc.)\n c: HonoContext; // Raw Hono context for advanced use\n env: Env; // Runtime bindings (Cloudflare env / process env). Alias for c.env.\n auth: Auth; // Better Auth instance — call auth.api.getSession(...) etc. Lazy on Cloudflare.\n whereRecord?: (table) => SQL; // Pre-built WHERE: firewall + soft-delete + eq(table.id, record.id). Record-based actions only.\n whereTransition?: (table) => SQL; // whereRecord plus the transition's \"from\" precondition. Transition actions only.\n}\n```\n\n#### `auth` — Better Auth instance\n\n`auth` is the Better Auth instance, ready to call from inside an action\nhandler. Use it for things like minting an OAuth access token, fetching the\ncurrent session in a custom way, or invoking a Better Auth plugin method\nthat isn't already exposed by the generated middleware.\n\n```typescript\n// features/integrations/actions/connect-google-drive.ts\n\nexport default defineAction({\n description: \"Get a fresh Google Drive access token for the signed-in user\",\n input: z.object({}),\n access: { roles: [\"AUTHENTICATED\"] },\n async execute({ auth, ctx, c }) {\n // genericOAuth plugin method — needs a cast since the default-generic\n // `Auth` type doesn't carry plugin-specific API surface.\n const token = await (auth.api as any).getAccessToken({\n headers: c.req.raw.headers,\n body: { providerId: \"google\", userId: ctx.userId },\n });\n return { accessToken: token.accessToken };\n },\n});\n```\n\n**Lazy on Cloudflare**: the generated handler emits a `Proxy` so\n`createAuth(c.env, c.req.raw.cf)` only runs the first time you read a\nproperty on `auth`. Actions that never touch `auth` pay zero construction\ncost. On Bun/Node `auth` is the imported singleton (an IIFE that lazy-loads\nthe database adapter) wrapped in the same proxy shape — call sites are\nidentical across runtimes.\n\n**Typing**: `auth` is typed as `Auth` from `better-auth`. The base API\n(`getSession`, `signOut`, `signInEmail`, etc.) is fully typed. Plugin-only\nmethods (`getAccessToken` from `genericOAuth`, admin-plugin methods, etc.)\nneed a cast at the call site — the default-generic `Auth` doesn't infer\nthe project's specific plugin set.\n\n#### `whereRecord` — explicit, scope-safe WHERE\n\nFor protected-field writes inside record-based actions, prefer\n`whereRecord(table)` over `eq(table.id, record.id)`. It returns a Drizzle\nexpression that AND-merges the resource's firewall and soft-delete predicates\nwith the record id, so the WHERE is explicit even if a future refactor swaps\n`db` back to an unscoped client:\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Advance\",\n input: /* … */,\n access: { roles: [\"owner\"] },\n async execute({ db, record, input, whereRecord }) {\n const [updated] = await db\n .update(applications)\n .set({\n status: input.nextStatus,\n notes: input.notes ?? record.notes,\n })\n .where(whereRecord!(applications)) // firewall + soft-delete + id, all in one\n .returning();\n return updated;\n },\n});\n```\n\nThe audit DB wrapper hard-stamps `modifiedAt`/`modifiedBy` on every\n`.set()` call, so handlers don't write them. The same wrapper hard-stamps\n`createdAt`/`createdBy`/`modifiedAt`/`modifiedBy` on every `.values()`.\nCaller-supplied audit fields are dropped on the floor — the audit log\nalways reflects the real actor and the real moment.\n\n`whereRecord` is undefined for standalone actions (they have no record), so\nthe parameter is typed as optional. `whereTransition` extends `whereRecord`\nwith the transition's \"from\" precondition for transition actions.\n\n#### Reaching Better Auth tables (`authDb`)\n\nThe scoped `db` only sees your feature tables. To read Better Auth tables —\nusers, organizations, members — use the auth database connection from the\nHono context plus the generated `lib/org-access.ts` helper:\n\n```typescript\n// features/projects/actions/assign.ts — validate a userId is an org member\n\nexport default defineAction({\n description: \"Assign a project to an org member\",\n input: z.object({ assigneeId: z.string() }),\n access: { roles: [\"member\", \"admin\"] },\n async execute({ db, record, input, ctx, c, whereRecord }) {\n // getOrgMemberRole(authDb, userId, organizationId) → role string | null\n const role = await getOrgMemberRole(c.get(\"authDb\"), input.assigneeId, ctx.activeOrgId!);\n if (!role) {\n throw new ActionError(\"Assignee is not a member of this organization\", \"NOT_A_MEMBER\", 400);\n }\n const [updated] = await db\n .update(projects)\n .set({ assigneeId: input.assigneeId })\n .where(whereRecord!(projects))\n .returning();\n return updated;\n },\n});\n```\n\n`c.get(\"authDb\")` is the Drizzle connection to the auth database (in dual-DB\nmode it's a separate D1 from your features). For richer queries, import the\nauth schema tables from `../../../auth/schema` and query `authDb` directly.\n\n## HTTP API Reference\n\n### Request Format\n\n| Method | Input Source | Use Case |\n|--------|--------------|----------|\n| `GET` | Query parameters | Read-only operations, fetching data |\n| `POST` | JSON body | Default, state-changing operations |\n| `PUT` | JSON body | Full replacement operations |\n| `PATCH` | JSON body | Partial updates |\n| `DELETE` | JSON body | Deletion with optional payload |\n\n### Response Formats\n\n| Type | Content-Type | Use Case |\n|------|--------------|----------|\n| `json` | `application/json` | Standard API responses (default) |\n| `stream` | `text/event-stream` | Real-time streaming (AI chat, live updates) |\n| `file` | Varies | File downloads (reports, exports) |\n\n### Error Codes\n\n| Status | Description |\n|--------|-------------|\n| `400` | Invalid input / validation error (also `GUARD_FIELD_PROTECTED` for direct protected-field writes) |\n| `401` | Not authenticated |\n| `403` | Access role check failed (`ACCESS_ROLE_REQUIRED`) |\n| `404` | Record not found (record-based actions) |\n| `409` | Record is in the wrong state for this action — `access.record` predicate or `transition` policy failed (`ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`) |\n| `500` | Handler execution error |\n\n### Validation Error Response\n\n```json\n{\n \"error\": \"Invalid request data\",\n \"layer\": \"validation\",\n \"code\": \"VALIDATION_FAILED\",\n \"details\": {\n \"fields\": {\n \"amount\": \"Expected positive number\"\n }\n },\n \"hint\": \"Check the input schema for this action\"\n}\n```\n\n### Error Handling\n\n**Option 1: Return a JSON error response** (recommended for most cases)\n\nSince action handlers receive the Hono context (`c`), you can return error responses directly:\n\n```typescript\nasync execute({ ctx, record, input, c }) {\n if (record.stage === 'hired') {\n return c.json({\n error: 'Cannot modify a hired application',\n code: 'ALREADY_HIRED',\n details: { currentStage: record.stage },\n }, 400);\n }\n // ... continue\n}\n```\n\n**Option 2: Throw an ActionError**\n\n```typescript\n\nasync execute({ ctx, record, input }) {\n if (record.stage === 'hired') {\n throw new ActionError('Cannot modify a hired application', 'ALREADY_HIRED', 400, {\n currentStage: record.stage,\n });\n }\n // ... continue\n}\n```\n\nThe `ActionError` constructor signature is `(message, code, statusCode = 400, details?)`. The compile step rewrites the `@quickback/compiler` import to the generated runtime class (`src/lib/types.ts`), and the route handler catches it by name and returns `{ error, code, details }` with your `statusCode`.\n\n## Protected Fields\n\nActions can modify fields that are protected from regular CRUD operations:\n\n```typescript\n// In the table file (defineTable config)\nguards: {\n protected: {\n status: [\"advance\", \"reject\", \"hire\", \"withdraw\"], // Only these actions can modify status\n }\n}\n```\n\nThis allows the `advance` action to set `status = \"interview\"` even though the field is protected from regular PATCH requests. Direct `PATCH /:id` attempts to set `status` are rejected by the guards layer with **400 GUARD_FIELD_PROTECTED**, and the field is omitted from the generated POST/PATCH body Zod schemas — clients cannot even send it past validation.\n\n## Transition (state-machine policy)\n\nFor protected fields that follow a state machine — application status, invoice\nlifecycle, order fulfilment — use `transition` on the action so the compiler\ngenerates a runtime guard that enforces the *from/to pair*, not just the\ncurrent state. Without it, an `advance` action whose input enum allows\n`[\"screening\", \"interview\", \"offer\"]` and whose `access.record` allows\n`status in [\"applied\", \"screening\", \"interview\"]` will happily run\n`applied → offer` (a skip) or `interview → screening` (a regression).\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\", // read target from input.nextStatus\n fromTo: {\n applied: [\"screening\"],\n screening: [\"interview\"],\n interview: [\"offer\"],\n },\n },\n async execute({ db, record, input, whereTransition }) { /* … */ },\n});\n```\n\n```typescript\n// features/applications/actions/hire.ts\n\nexport default defineAction({\n description: \"Finalize an offer.\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n transition: {\n field: \"status\",\n to: \"hired\", // fixed target — same value every call\n fromTo: { offer: [\"hired\"] },\n },\n async execute({ db, record, whereTransition }) { /* … */ },\n});\n```\n\n| Field | Required | Description |\n|---|---|---|\n| `field` | Yes | Record column to validate (e.g. `\"status\"`) |\n| `fromTo` | Yes | Map of current value → permitted next values. Keys also enumerate the legal source states. |\n| `via` | Yes (or `to`) | Input key that carries the target value. Use for variable-target actions like `advance`. |\n| `to` | Yes (or `via`) | Literal target value the action always writes. Use for fixed-target actions like `hire`/`reject`. |\n\nExactly one of `via` or `to` must be provided. The compiler rejects both at\nvalidate time. When `to` is set, it must appear in some `fromTo[*]` array —\notherwise the action would be unreachable, which is almost certainly a bug.\n\n### Wire-level errors\n\nThe compiled guard returns **409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`** with\nthe field, the current value, the requested target, and the allowed set:\n\n```json\n{\n \"error\": \"Action not allowed for current record state\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ACTION_NOT_ALLOWED_FOR_STATE\",\n \"details\": {\n \"field\": \"status\",\n \"current\": \"interview\",\n \"target\": \"screening\",\n \"allowedTargets\": [\"offer\"]\n },\n \"hint\": \"From \\\"interview\\\", status can transition to: offer\"\n}\n```\n\nThis is distinct from a role failure: if the caller has the wrong role they\nget **403 `ACCESS_ROLE_REQUIRED`** as before. Splitting the two lets clients\ntell *\"you can't do this\"* from *\"you can't do this *yet*\"* — the latter is\nrecoverable by the user, the former isn't.\n\nThe same 409 code is used when an `access.record` predicate (without\n`transition`) fails — for example `record: { status: { equals: \"pending\" } }`\ncalled against a paid invoice now returns 409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`,\nnot a misleading 403.\n\n## Examples\n\n### Bulk Import (Standalone, No Record)\n\n```typescript\n// features/candidates/actions/bulk-import.ts\n\nexport default defineAction({\n description: \"Import candidates from job board CSV\",\n path: \"/candidates/import\",\n input: z.object({\n data: z.array(z.object({\n email: z.string().email(),\n name: z.string(),\n })),\n }),\n access: { roles: [\"hiring-manager\", \"recruiter\"] },\n async execute({ db, input }) {\n const inserted = await db\n .insert(candidates)\n .values(input.data)\n .returning();\n return { imported: inserted.length };\n },\n});\n```"
86
+ "content": "Actions are custom API endpoints for business logic beyond CRUD operations. They enable workflows, integrations, and complex operations.\n\n## Overview\n\nQuickback supports two types of actions:\n\n| Aspect | Record-Based | Standalone |\n|--------|--------------|------------|\n| Route | `{METHOD} /:id/{actionName}` | Custom `path` (required) |\n| Record fetching | Automatic | None (`record` is `undefined`) |\n| Firewall applied | Yes | No |\n| Preconditions | Supported via `access.record` | Not applicable |\n| Response types | JSON only | JSON, stream, file |\n| Use case | Advance application, reject candidate | AI chat, bulk import from job board, webhooks |\n\nStandalone actions are signalled by the presence of a `path:` field in the action config. Record-based actions omit `path` and bind to the feature's primary table.\n\n## Where do actions live?\n\n**One file per action.** Each action is its own module under the feature's\n`actions/` directory:\n\n```\nfeatures/applications/\n├── applications.ts ← defineTable (primary table)\n├── candidates.ts ← defineTable (sibling table)\n├── actions/\n│ ├── advance.ts ← defineAction, binds to applications\n│ ├── reject.ts ← defineAction, binds to applications\n│ ├── stats.ts ← defineAction, standalone (has `path:`)\n│ └── candidates/\n│ └── disqualify.ts ← defineAction, binds to candidates\n└── lib/\n └── inputs.ts ← shared schemas (optional, copied verbatim)\n```\n\n| Layout | Binds to |\n|--------|----------|\n| `actions/<name>.ts` | The feature's primary table (table file matching the feature name), or standalone if `path:` is set. |\n| `actions/<table>/<name>.ts` | The sibling table file `<table>.ts` at the feature root. Standalone actions inside a subdir ignore the binding. |\n\nThe action's filename (sans `.ts`) is the action name and the URL segment, and\nit must be a valid **camelCase identifier** — `sendMessage.ts`, not\n`send-message.ts` (hyphenated names are a compile error, since the name becomes\na generated identifier).\nUniqueness is enforced per `(bound table, name)` pair — sibling-bound\nactions on **different** tables may share a verb (`actions/episodes/publish.ts`\nand `actions/shows/publish.ts` mount at `/episodes/:id/publish` and\n`/shows/:id/publish` and compile cleanly). The compiler errors only when\ntwo action files would mount at the same URL — for example, a flat\n`actions/foo.ts` (binds to primary) plus `actions/<primary>/foo.ts`, or\ntwo standalones with the same `(method, path)`. Standalone actions are\nunique per `(method, path)`.\n\nTableless features have no top-level `*.ts` files; every action under\n`actions/` must be standalone (have `path:`). Use this for utility endpoints\nlike webhooks, reports, or integrations that don't operate on a specific\nrecord.\n\n### Retired layouts\n\nThese are rejected at load time with migration guidance:\n\n- **`actions.ts`** (bundled multi-action file)\n- **`_feature.ts`** (shared schemas + non-table-bound actions)\n- **`handlers/`** (separate handler-file directory)\n- **`defineActions(table, {...})`** (the multi-action factory)\n- **`defineActions(null, {...})`** (tableless variant)\n- **`*-actions.ts` / `*.actions.ts`** filename patterns\n\nFor shared Zod schemas or helpers, put them under `<feature>/lib/` and import\nfrom each action file. Files under `lib/` are copied verbatim into the\ngenerated output.\n\n## Defining Actions\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n notes: z.string().max(2000).optional(),\n }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: {\n applied: [\"screening\"],\n screening: [\"interview\"],\n interview: [\"offer\"],\n },\n },\n async execute({ db, record, input, whereTransition }) {\n const [updated] = await db\n .update(applications)\n .set({\n status: input.nextStatus,\n notes: input.notes ?? record.notes,\n })\n .where(whereTransition!(applications))\n .returning();\n return updated;\n },\n});\n```\n\n> **`defineAction` import.** Import from `\"../.quickback/define-action\"` —\n> the `.quickback/` directory is generated alongside your feature with a\n> typed helper that infers `record` and `input` types from the rest of the\n> action config. Audit fields (`createdAt`, `createdBy`, `modifiedAt`,\n> `modifiedBy`) are hard-stamped by the audit DB wrapper on every\n> `db.insert().values()` and `db.update().set()` — handlers don't pass\n> them and can't override them.\n\n### Configuration Options\n\n| Option | Required | Description |\n|--------|----------|-------------|\n| `description` | Yes | Human-readable description of the action |\n| `input` | Yes | Zod schema for request validation |\n| `access` | Yes | Access control (roles, record conditions, or function) |\n| `execute` | Yes | Inline async arrow function (`async (ctx) => { … }`) |\n| `path` | Standalone only | Custom route path. Presence of `path` makes the action standalone. |\n| `method` | No | HTTP method: GET, POST, PUT, PATCH, DELETE (default: POST). GET actions parse `input` from query params; all other methods parse from the JSON body. See [GET vs POST for input](#get-vs-post-for-input). |\n| `responseType` | No | Response format: json, stream, file (default: json) |\n| `sideEffects` | No | Hint for AI tools: `'sync'`, `'async'`, or `'fire-and-forget'` |\n| `allowRawSql` | No | Explicit compile-time opt-in for raw SQL in execute code |\n| `unsafe` | No | Unsafe raw DB mode. Object config (`reason`, `adminOnly`, `crossTenant`, `targetScope`). |\n| `transition` | No | State-machine policy enforcing the from/to pair (record-based actions). See [Transitions](#transition-state-machine-policy) |\n| `bulkVariant` | No | Auto-generate a `POST /:resource/batch/{action}` route alongside the per-record route (record-based actions). See [Bulk Variant](#bulk-variant) |\n| `cms` | No | Pass-through metadata blob for CMS surfaces |\n\n`execute` must be an `async (ctx) => { … }` arrow function. `async function`\ndeclarations and non-async forms are rejected at parse time.\n\n## Record-Based Actions\n\nRecord-based actions operate on an existing record. The record is automatically loaded and validated before your action executes.\n\n**Route pattern:** `{METHOD} /:id/{actionName}`\n\n```\nPOST /applications/:id/advance\nPOST /applications/:id/reject\nPOST /applications/:id/schedule-interview\n```\n\n### Runtime Flow\n\n1. **Authentication** - User token is validated\n2. **Input Validation** - Request body validated against Zod schema\n3. **Role Gate** - The access roles are checked *before* the record is\n fetched (v0.46+), so a wrong-role caller gets a uniform\n `403 ACCESS_ROLE_REQUIRED` whether or not the record exists — the\n response can't be used to probe for record ids\n4. **Record Loading** - The record is fetched by ID **through the firewall**\n (a cross-tenant or missing id is a standard firewall miss)\n5. **Access Check** - Record preconditions (`access.record`) and transition\n policy are validated against the loaded record\n6. **Execution** - Your action handler runs\n7. **Response** - Result is returned to client\n\n### Example: Advance Application Stage\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move application to the next pipeline stage\",\n input: z.object({\n stage: z.enum([\"screening\", \"interview\", \"offer\", \"hired\"]),\n notes: z.string().optional(),\n }),\n access: {\n roles: [\"owner\", \"hiring-manager\"],\n record: { stage: { notEquals: \"rejected\" } },\n },\n async execute({ db, record, input }) {\n const [updated] = await db\n .update(applications)\n .set({\n stage: input.stage,\n notes: input.notes ?? record.notes,\n })\n .where(eq(applications.id, record.id))\n .returning();\n return updated;\n },\n});\n```\n\n### Request Example\n\n```\nPOST /applications/app_123/advance\nContent-Type: application/json\n\n{\n \"stage\": \"interview\",\n \"notes\": \"Strong technical background, moving to interview\"\n}\n```\n\n### Response Example\n\n```json\n{\n \"data\": {\n \"id\": \"app_123\",\n \"stage\": \"interview\",\n \"notes\": \"Strong technical background, moving to interview\"\n }\n}\n```\n\n### Bulk variant\n\nSet `bulkVariant: true` to auto-generate a bulk version of the action at\n`POST /:resource/batch/{action}`. The compiler emits a second route alongside\nthe per-record one, looping the same access + transition + execute pipeline\nover an array of ids. This is the answer to \"I need to advance 50\napplications at once\" — you don't have to hand-roll a parallel standalone\naction that duplicates the per-record logic.\n\n```typescript\n// features/applications/actions/advance.ts\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n bulkVariant: true,\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: { applied: [\"screening\"], screening: [\"interview\"], interview: [\"offer\"] },\n },\n async execute({ db, record, input, whereTransition }) {\n const [updated] = await db\n .update(applications)\n .set({ status: input.nextStatus })\n .where(whereTransition!(applications))\n .returning();\n if (!updated) throw new TransitionLostError(\"status\", record.status, input.nextStatus);\n return updated;\n },\n});\n```\n\n**Request shape:**\n\n```http\nPOST /applications/batch/advance\nContent-Type: application/json\n\n{\n \"ids\": [\"app_001\", \"app_002\", \"app_003\"],\n \"input\": { \"nextStatus\": \"interview\" },\n \"failFast\": false\n}\n```\n\nThe `input` is shared across the batch — the action's Zod schema is\nvalidated once, not per id. For per-record input variation, use the\nsingle-record endpoint (`POST /:id/{action}`) or write a standalone action.\n\n**Response (207 Multi-Status when any record fails, 200 when clean):**\n\n```json\n{\n \"success\": [{ \"id\": \"app_001\", \"status\": \"interview\" }],\n \"errors\": [\n {\n \"index\": 1,\n \"id\": \"app_002\",\n \"error\": {\n \"error\": \"Action not allowed for current state\",\n \"code\": \"ACCESS_ACTION_NOT_ALLOWED_FOR_STATE\",\n \"details\": { \"field\": \"status\", \"currentValue\": \"rejected\" }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"failFast\": false,\n \"transactional\": false\n }\n}\n```\n\n**Per-record pipeline** mirrors the single-record route exactly — the same\nfirewall fetch, access reason split (403 vs 409), transition pre-check,\n`whereTransition` factory, and `TransitionLostError` handling. Per-record\nfailures land in `errors[]` with their original index; successful records\nland in `success[]` masked the same way the single-record response is.\n\n**Transactional matrix** (same as `PATCH /batch`):\n\n| Provider | failFast | transactional | Behavior |\n|---|---|---|---|\n| tx-supporting (postgres, neon over websocket) | `true` | `true` | `db.transaction()` wraps the loop; any throw rolls back all writes |\n| (any) | `false` | `false` | Independent per-record outcomes, partial success |\n| cloudflare-d1, neon over http (Cloudflare default) | `true` | `false` | Fail-fast loop without rollback — earlier records stay committed (the driver has no `db.transaction`; `drizzle-orm/neon-http` throws at runtime) |\n\n**Constraints:**\n\n- Record-based actions only. Standalone actions reject `bulkVariant: true`\n at compile time (no record context to loop over).\n- `unsafe` actions reject `bulkVariant: true` in v1 — the cross-tenant\n per-record audit story is not yet wired through.\n- Method is forced to POST regardless of the action's `method` setting. The\n semantic asymmetry (one row → many rows) makes inheriting GET/DELETE\n confusing.\n- Max batch size is 100 ids per request.\n\n## Standalone Actions\n\nStandalone actions are independent endpoints that don't require a record context. Set a `path:` to declare the action standalone.\n\n**Route pattern:** Custom `path`\n\n```\nPOST /chat\nGET /reports/summary\nPOST /webhooks/stripe\n```\n\n### Example: AI Chat with Streaming\n\n```typescript\n// features/sessions/actions/chat.ts\n\nexport default defineAction({\n description: \"Send a message to AI\",\n path: \"/chat\",\n method: \"POST\",\n responseType: \"stream\",\n input: z.object({\n message: z.string().min(1).max(2000),\n }),\n access: { roles: [\"recruiter\", \"hiring-manager\"] },\n async execute({ input, c }) {\n // Stream response back to client...\n return c.newResponse(/* ReadableStream */);\n },\n});\n```\n\n### Streaming Response Example\n\nFor actions with `responseType: 'stream'`:\n\n```\nContent-Type: text/event-stream\n\ndata: {\"type\": \"start\"}\ndata: {\"type\": \"chunk\", \"content\": \"Hello\"}\ndata: {\"type\": \"chunk\", \"content\": \"! I'm\"}\ndata: {\"type\": \"chunk\", \"content\": \" here to help.\"}\ndata: {\"type\": \"done\"}\n```\n\n### Tableless Features\n\nA feature directory with no top-level `*.ts` files is \"tableless\" — every\naction under `actions/` must be standalone. Use this for utility endpoints\nlike reports, integrations, or webhooks that don't map to a specific\nresource.\n\n```\nquickback/features/\n└── reports/\n └── actions/\n ├── trial-balance.ts ← standalone (has path:)\n └── profit-loss.ts ← standalone (has path:)\n```\n\n```typescript\n// features/reports/actions/trial-balance.ts\n\nexport default defineAction({\n description: \"Generate trial balance report\",\n path: \"/reports/trial-balance\",\n method: \"GET\",\n input: z.object({\n startDate: z.string(),\n endDate: z.string(),\n }),\n access: { roles: [\"admin\", \"accountant\"] },\n async execute({ db, input }) {\n // ... build report\n return { rows: [] };\n },\n});\n```\n\n### GET vs POST for input\n\nGET actions read `input` from URL query parameters; every other method (POST,\nPUT, PATCH, DELETE) reads from the JSON body. The Zod schema is the same in\nboth cases — the compiler picks the right parser based on `method`.\n\n```typescript\n// GET — input populated from ?q=…&limit=…\ndefineAction({\n method: \"GET\",\n path: \"/search\",\n input: z.object({\n q: z.string(),\n limit: z.coerce.number().int().positive().max(100).default(20),\n }),\n access: { roles: [\"AUTHENTICATED\"] },\n async execute({ input }) {\n // input is { q: string, limit: number } — fully typed.\n },\n});\n```\n\nRepeated query keys (`?tag=a&tag=b`) come through as arrays automatically;\nsingle values stay as strings. Use Zod's `.coerce.number()` /\n`.coerce.boolean()` when you want typed primitives from the parsed strings.\n\n**Use POST when input is structured.** GET requests cannot carry a JSON body\nin any of the surfaces Quickback APIs are commonly called from:\n\n- Browsers throw on `fetch(url, { method: 'GET', body })`.\n- CDNs and caches key on URL+method; a GET with a body either gets the body\n stripped at the edge or cache-collides with semantically different requests.\n- OpenAPI client generators (axios, openapi-fetch, openapi-typescript-codegen)\n refuse to emit GET-with-body, so the generated SDKs break.\n- The MCP agent surface treats GET as parameter-only — agents calling a GET\n action will only see what the URL exposes.\n\nIf your action takes nested objects, arrays of objects, or large inputs that\ndon't serialize cleanly to a query string, set `method: \"POST\"`. POST doesn't\nimply \"this writes data\" — it's the right method whenever the request body is\nload-bearing. Use the response shape (`responseType: \"json\"`, or just the data\nyour handler returns) to convey read semantics; HTTP method choice is about\ninput transport, not action intent.\n\n## Access Configuration\n\nAccess controls who can execute an action and under what conditions.\n\n### Role-Based Access\n\n```typescript\naccess: {\n roles: [\"hiring-manager\", \"recruiter\"] // OR logic: user needs any of these roles\n}\n```\n\n### Public Access\n\nUse `roles: [\"PUBLIC\"]` for unauthenticated endpoints (contact forms, webhooks, public APIs). Every invocation is **mandatory audit logged** with IP address, input, result, and timing.\n\n```typescript\n// features/contact/actions/submit.ts\n\nexport default defineAction({\n description: \"Public contact form submission\",\n path: \"/submit\",\n input: z.object({\n name: z.string().min(1),\n email: z.string().email(),\n message: z.string().min(10),\n }),\n access: { roles: [\"PUBLIC\"] },\n async execute({ db, input }) {\n // ... persist submission\n return { ok: true };\n },\n});\n```\n\nThe wildcard `\"*\"` is not supported and will throw a compile-time error. Use `\"PUBLIC\"` explicitly.\n\n### Record Conditions\n\nFor record-based actions, you can require the record to be in a specific state:\n\n```typescript\naccess: {\n roles: [\"hiring-manager\"],\n record: {\n stage: { equals: \"screening\" } // Precondition\n }\n}\n```\n\n**Supported operators:**\n\n| Operator | Description |\n|----------|-------------|\n| `equals` | Field must equal value |\n| `notEquals` | Field must not equal value |\n| `in` | Field must be one of the values |\n| `notIn` | Field must not be one of the values |\n\n### Context Substitution\n\nUse `$ctx` to reference the current user's context:\n\n```typescript\naccess: {\n record: {\n ownerId: { equals: \"$ctx.userId\" },\n organizationId: { equals: \"$ctx.activeOrgId\" }\n }\n}\n```\n\n### OR/AND Combinations\n\n```typescript\naccess: {\n or: [\n { roles: [\"hiring-manager\"] },\n {\n roles: [\"recruiter\"],\n record: { ownerId: { equals: \"$ctx.userId\" } }\n }\n ]\n}\n```\n\n### Function Access\n\nFor complex logic, use an access function:\n\n```typescript\naccess: async (ctx, record) => {\n return ctx.roles.includes('admin') || record.ownerId === ctx.userId;\n}\n```\n\n### Relationship-roles in actions\n\n**v0.19+** — standalone actions now support relationship-roles in `access.roles` directly. Declare the relationship under `authz.relationships` with optional `loads` / `exposeAs` for ctx hydration, and reference the role by name on the action:\n\n```ts\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n roles: { attendee: { via: 'attendeeOf' } },\n}\n\n// features/chat/actions/getInbox.ts\nexport default defineAction({\n path: '/chat/get-inbox',\n input: z.object({ eventId: z.number().int().positive() }),\n access: { roles: ['admin', 'member', 'attendee'] },\n execute: async ({ db, ctx, input }) => {\n // The resolver already verified attendance and loaded ctx.event.\n // No hand-rolled `SELECT … FROM guests WHERE …` needed.\n },\n});\n```\n\nThe action's surface (path params + input fields) must expose the relationship's `resource.column`. At v0.19 a missing key emits a `[quickback:authz]` warning and skips resolver emission; at v0.20 it becomes a compile error. See [Access — standalone actions](/compiler/definitions/access#standalone-actions-surface-keys-and-loads--exposeas-v019) for the full mechanism.\n\n**Record-based actions** are NOT yet supported — the runtime evaluator fail-closes (403) on relationship arms reached without an inline gate. Until inline emission for record-based actions lands, either:\n\n- Set `firewall: { exception: true }` on the action and gate manually in `execute()`, OR\n- Apply the relationship at the resource's firewall layer (worked example below).\n\n**Resource-layer workaround for record-based actions**: gate the action on BA roles only and apply the relationship at the resource layer via a firewall `via:` predicate:\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n },\n },\n}\n\n// features/sessions/sessions.ts — firewall scopes rows; action gates on BA role\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' }, // ← row-level relationship check\n],\nactions: {\n comment: defineAction({\n access: { roles: ['member', 'admin'] }, // ← BA role only on the action\n input: z.object({ text: z.string() }),\n execute: async (input, ctx, db, record) => {\n // record is already filtered by the firewall — guest membership\n // is enforced before this handler runs.\n return db.insert(comments).values({ ... });\n },\n }),\n}\n```\n\nThis pattern composes cleanly: the firewall guarantees the caller has the relationship to the record being acted on; the action's access list keeps the role surface obvious.\n\nSee [Access — relationship authorization](/compiler/definitions/access#relationship-based-authorization) for the full picture, including `loads` / `exposeAs` and the `firewall: { exception: true }` escape hatch.\n\n## Scoped Database\n\nAll actions receive a **scoped `db`** instance that automatically enforces security:\n\n| Operation | Org Scoping | Owner Scoping | Soft Delete Filter | Auto-inject on INSERT |\n|-----------|-------------|---------------|--------------------|-----------------------|\n| `SELECT` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n| `INSERT` | n/a | n/a | n/a | `organizationId`, `ownerId` from ctx |\n| `UPDATE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n| `DELETE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n\nScoping is duck-typed at runtime — tables with an `organizationId` column get org scoping, tables with `ownerId` get owner scoping, tables with `deletedAt` get soft delete filtering.\n\n```typescript\nasync execute({ db, ctx, input }) {\n // This query automatically includes WHERE organizationId = ? AND deletedAt IS NULL\n const items = await db.select().from(applications).where(eq(applications.stage, 'interview'));\n\n // Inserts automatically include organizationId\n await db.insert(applications).values({ candidateId: input.candidateId, jobId: input.jobId, stage: 'applied' });\n\n return items;\n}\n```\n\n**Not enforced** in scoped DB (by design):\n- **Guards** — actions ARE the authorized way to modify guarded fields\n- **Masking** — actions are backend code that may need raw data\n- **Access** — already checked before action execution\n\n### Relational queries are blocked (fail-closed)\n\nDrizzle's relational query API — `db.query.<table>.findFirst()` /\n`findMany()` (including nested `with:` relations) — builds its SQL from the\nrelations config and your `where` alone, so the scoped wrapper cannot inject\nthe org/owner/team firewall into it. Rather than silently returning rows from\nevery tenant, the scoped `db` **throws** on any `db.query.<table>` access:\n\n```typescript\nasync execute({ db, input }) {\n // ❌ Throws: relational queries aren't org-scoped\n const item = await db.query.media.findFirst({ where: eq(media.id, input.id) });\n\n // ✅ Scoped builder — firewall conditions injected automatically\n const [item] = await db.select().from(media).where(eq(media.id, input.id));\n}\n```\n\nIf you genuinely need the relational API, declare the action `unsafe: true`\nand query `unsafeDb.query` with an **explicit** scope predicate in the WHERE\n(e.g. `eq(media.organizationId, ctx.activeOrgId)`), exactly like any other\nunsafe read.\n\n### Unsafe Mode\n\nActions that need to bypass scoped DB filters (for example, platform-level support operations) can enable unsafe mode.\n\nUse object form for explicit policy and mandatory audit metadata:\n\n```typescript\n// features/admin/actions/cross-tenant-report.ts\n\nexport default defineAction({\n description: \"Generate cross-org hiring report\",\n path: \"/admin/cross-tenant-report\",\n input: z.object({ startDate: z.string() }),\n access: { roles: [\"owner\"] },\n unsafe: {\n reason: \"Support investigation for enterprise customer\",\n adminOnly: true, // default true\n crossTenant: true, // default true\n targetScope: \"all\", // \"all\" | \"organization\"\n },\n async execute({ unsafeDb, input }) {\n // unsafeDb bypasses scoped filters\n const allOrgs = await unsafeDb.select().from(applications);\n return allOrgs;\n },\n});\n```\n\nUnsafe cross-tenant actions are generated with:\n\n- Better Auth authentication required (no unauthenticated path)\n- sysadmin gate (`ctx.userRole === \"sysadmin\"`)\n- mandatory audit logging on deny/success/error\n\n**Provider note (Neon):** on Neon the request-scoped db enforces Row Level\nSecurity with the *caller's* org claims, which would filter out exactly the\ncross-tenant rows unsafe actions exist to reach. Unsafe handlers therefore\nacquire a dedicated service-role handle (`createServiceDb`) that sets the\n`quickback.service_role` transaction marker instead of caller claims; the\ngenerated RLS grants that context an explicit per-table bypass policy. The\naudit-logging contract is identical to D1. Neon with\n`connectionMode: 'websocket'` does not support unsafe actions yet and fails\nthe compile with a descriptive error.\n\n`PUBLIC` actions also receive mandatory audit logging (same audit table), since unauthenticated endpoints are high-risk by nature.\n\nWithout unsafe mode, `unsafeDb` is `undefined` in the executor params.\n\n### Raw SQL Policy\n\nBy default, the compiler rejects raw SQL in action code. Use Drizzle query-builder syntax whenever possible.\n\nIf a specific action must use raw SQL, opt in explicitly:\n\n```typescript\n// features/ledgers/actions/reconcile.ts\n\nexport default defineAction({\n description: \"Run custom reconciliation query\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n allowRawSql: true,\n async execute({ db }) {\n return db.execute(sql`select 1`);\n },\n});\n```\n\nWithout `allowRawSql: true`, compilation fails with a loud error pointing to the action and snippet.\n\nThe detector checks for SQL keywords in string arguments, so non-SQL method calls like `headers.get(\"X-Forwarded-For\")` or `map.get(\"key\")` will not trigger false positives.\n\n## Sharing Code Between Actions\n\nFor Zod schemas, helpers, or constants used across multiple actions in a\nfeature, put them under `<feature>/lib/` and import from each action file.\nFiles under `lib/` are copied verbatim into the generated output.\n\n```\nfeatures/applications/\n├── applications.ts\n├── actions/\n│ ├── advance.ts\n│ └── reject.ts\n└── lib/\n ├── inputs.ts ← shared Zod schemas\n └── transitions.ts ← state-machine helpers\n```\n\n```typescript\n// features/applications/lib/inputs.ts\n\nexport const advanceInput = z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n notes: z.string().max(2000).optional(),\n});\n```\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move forward\",\n input: advanceInput,\n access: { roles: [\"owner\"] },\n async execute({ db, record, input }) { /* … */ },\n});\n```\n\n### Importing Tables\n\nAction files import tables from their own feature or other features. The compiler generates alias files for each table, so you import by the table's file name:\n\n```typescript\n// features/applications/actions/advance.ts\n\n// Same feature — import from parent directory using the table's file name\n\n// Cross-feature — go up to the features directory, then into the other feature\n\n```\n\n**Path pattern from `features/{name}/actions/`:**\n- Same feature table: `../{table-file-name}` (e.g., `../applications`)\n- Other feature table: `../../{other-feature}/{table-file-name}` (e.g., `../../candidates/candidates`)\n- Generated lib files: `../../../lib/{module}` (e.g., `../../../lib/realtime`, `../../../lib/webhooks`)\n\n### Executor Parameters\n\n```typescript\n\ninterface ActionExecutorParams {\n db: DrizzleDB; // Scoped database (auto-applies org/owner/soft-delete filters)\n unsafeDb?: DrizzleDB; // Unscoped database (only available when unsafe mode is enabled)\n ctx: AppContext; // User context (userId, roles, activeOrgId, activeTeamId, userRole)\n record?: TRecord; // The record (record-based only, undefined for standalone)\n input: TInput; // Validated input from Zod schema\n services: TServices; // Configured integrations (billing, notifications, etc.)\n c: HonoContext; // Raw Hono context for advanced use\n env: Env; // Runtime bindings (Cloudflare env / process env). Alias for c.env.\n auth: Auth; // Better Auth instance — call auth.api.getSession(...) etc. Lazy on Cloudflare.\n whereRecord?: (table) => SQL; // Pre-built WHERE: firewall + soft-delete + eq(table.id, record.id). Record-based actions only.\n whereTransition?: (table) => SQL; // whereRecord plus the transition's \"from\" precondition. Transition actions only.\n}\n```\n\n#### `auth` — Better Auth instance\n\n`auth` is the Better Auth instance, ready to call from inside an action\nhandler. Use it for things like minting an OAuth access token, fetching the\ncurrent session in a custom way, or invoking a Better Auth plugin method\nthat isn't already exposed by the generated middleware.\n\n```typescript\n// features/integrations/actions/connect-google-drive.ts\n\nexport default defineAction({\n description: \"Get a fresh Google Drive access token for the signed-in user\",\n input: z.object({}),\n access: { roles: [\"AUTHENTICATED\"] },\n async execute({ auth, ctx, c }) {\n // genericOAuth plugin method — needs a cast since the default-generic\n // `Auth` type doesn't carry plugin-specific API surface.\n const token = await (auth.api as any).getAccessToken({\n headers: c.req.raw.headers,\n body: { providerId: \"google\", userId: ctx.userId },\n });\n return { accessToken: token.accessToken };\n },\n});\n```\n\n**Lazy on Cloudflare**: the generated handler emits a `Proxy` so\n`createAuth(c.env, c.req.raw.cf)` only runs the first time you read a\nproperty on `auth`. Actions that never touch `auth` pay zero construction\ncost. On Bun/Node `auth` is the imported singleton (an IIFE that lazy-loads\nthe database adapter) wrapped in the same proxy shape — call sites are\nidentical across runtimes.\n\n**Typing**: `auth` is typed as `Auth` from `better-auth`. The base API\n(`getSession`, `signOut`, `signInEmail`, etc.) is fully typed. Plugin-only\nmethods (`getAccessToken` from `genericOAuth`, admin-plugin methods, etc.)\nneed a cast at the call site — the default-generic `Auth` doesn't infer\nthe project's specific plugin set.\n\n#### `whereRecord` — explicit, scope-safe WHERE\n\nFor protected-field writes inside record-based actions, prefer\n`whereRecord(table)` over `eq(table.id, record.id)`. It returns a Drizzle\nexpression that AND-merges the resource's firewall and soft-delete predicates\nwith the record id, so the WHERE is explicit even if a future refactor swaps\n`db` back to an unscoped client:\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Advance\",\n input: /* … */,\n access: { roles: [\"owner\"] },\n async execute({ db, record, input, whereRecord }) {\n const [updated] = await db\n .update(applications)\n .set({\n status: input.nextStatus,\n notes: input.notes ?? record.notes,\n })\n .where(whereRecord!(applications)) // firewall + soft-delete + id, all in one\n .returning();\n return updated;\n },\n});\n```\n\nThe audit DB wrapper hard-stamps `modifiedAt`/`modifiedBy` on every\n`.set()` call, so handlers don't write them. The same wrapper hard-stamps\n`createdAt`/`createdBy`/`modifiedAt`/`modifiedBy` on every `.values()`.\nCaller-supplied audit fields are dropped on the floor — the audit log\nalways reflects the real actor and the real moment.\n\n`whereRecord` is undefined for standalone actions (they have no record), so\nthe parameter is typed as optional. `whereTransition` extends `whereRecord`\nwith the transition's \"from\" precondition for transition actions.\n\n#### Reaching Better Auth tables (`authDb`)\n\nThe scoped `db` only sees your feature tables. To read Better Auth tables —\nusers, organizations, members — use the auth database connection from the\nHono context plus the generated `lib/org-access.ts` helper:\n\n```typescript\n// features/projects/actions/assign.ts — validate a userId is an org member\n\nexport default defineAction({\n description: \"Assign a project to an org member\",\n input: z.object({ assigneeId: z.string() }),\n access: { roles: [\"member\", \"admin\"] },\n async execute({ db, record, input, ctx, c, whereRecord }) {\n // getOrgMemberRole(authDb, userId, organizationId) → role string | null\n const role = await getOrgMemberRole(c.get(\"authDb\"), input.assigneeId, ctx.activeOrgId!);\n if (!role) {\n throw new ActionError(\"Assignee is not a member of this organization\", \"NOT_A_MEMBER\", 400);\n }\n const [updated] = await db\n .update(projects)\n .set({ assigneeId: input.assigneeId })\n .where(whereRecord!(projects))\n .returning();\n return updated;\n },\n});\n```\n\n`c.get(\"authDb\")` is the Drizzle connection to the auth database (in dual-DB\nmode it's a separate D1 from your features). For richer queries, import the\nauth schema tables from `../../../auth/schema` and query `authDb` directly.\n\n## HTTP API Reference\n\n### Request Format\n\n| Method | Input Source | Use Case |\n|--------|--------------|----------|\n| `GET` | Query parameters | Read-only operations, fetching data |\n| `POST` | JSON body | Default, state-changing operations |\n| `PUT` | JSON body | Full replacement operations |\n| `PATCH` | JSON body | Partial updates |\n| `DELETE` | JSON body | Deletion with optional payload |\n\n### Response Formats\n\n| Type | Content-Type | Use Case |\n|------|--------------|----------|\n| `json` | `application/json` | Standard API responses (default) |\n| `stream` | `text/event-stream` | Real-time streaming (AI chat, live updates) |\n| `file` | Varies | File downloads (reports, exports) |\n\n### Error Codes\n\n| Status | Description |\n|--------|-------------|\n| `400` | Invalid input / validation error (also `GUARD_FIELD_PROTECTED` for direct protected-field writes) |\n| `401` | Not authenticated |\n| `403` | Access role check failed (`ACCESS_ROLE_REQUIRED`) |\n| `404` | Record not found (record-based actions) |\n| `409` | Record is in the wrong state for this action — `access.record` predicate or `transition` policy failed (`ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`) |\n| `500` | Handler execution error |\n\n### Validation Error Response\n\n```json\n{\n \"error\": \"Invalid request data\",\n \"layer\": \"validation\",\n \"code\": \"VALIDATION_FAILED\",\n \"details\": {\n \"fields\": {\n \"amount\": \"Expected positive number\"\n }\n },\n \"hint\": \"Check the input schema for this action\"\n}\n```\n\n### Error Handling\n\n**Option 1: Return a JSON error response** (recommended for most cases)\n\nSince action handlers receive the Hono context (`c`), you can return error responses directly:\n\n```typescript\nasync execute({ ctx, record, input, c }) {\n if (record.stage === 'hired') {\n return c.json({\n error: 'Cannot modify a hired application',\n code: 'ALREADY_HIRED',\n details: { currentStage: record.stage },\n }, 400);\n }\n // ... continue\n}\n```\n\n**Option 2: Throw an ActionError**\n\n```typescript\n\nasync execute({ ctx, record, input }) {\n if (record.stage === 'hired') {\n throw new ActionError('Cannot modify a hired application', 'ALREADY_HIRED', 400, {\n currentStage: record.stage,\n });\n }\n // ... continue\n}\n```\n\nThe `ActionError` constructor signature is `(message, code, statusCode = 400, details?)`. The compile step rewrites the `@quickback/compiler` import to the generated runtime class (`src/lib/types.ts`), and the route handler catches it by name and returns `{ error, code, details }` with your `statusCode`.\n\n## Protected Fields\n\nActions can modify fields that are protected from regular CRUD operations:\n\n```typescript\n// In the table file (defineTable config)\nguards: {\n protected: {\n status: [\"advance\", \"reject\", \"hire\", \"withdraw\"], // Only these actions can modify status\n }\n}\n```\n\nThis allows the `advance` action to set `status = \"interview\"` even though the field is protected from regular PATCH requests. Direct `PATCH /:id` attempts to set `status` are rejected by the guards layer with **400 GUARD_FIELD_PROTECTED**, and the field is omitted from the generated POST/PATCH body Zod schemas — clients cannot even send it past validation.\n\n## Transition (state-machine policy)\n\nFor protected fields that follow a state machine — application status, invoice\nlifecycle, order fulfilment — use `transition` on the action so the compiler\ngenerates a runtime guard that enforces the *from/to pair*, not just the\ncurrent state. Without it, an `advance` action whose input enum allows\n`[\"screening\", \"interview\", \"offer\"]` and whose `access.record` allows\n`status in [\"applied\", \"screening\", \"interview\"]` will happily run\n`applied → offer` (a skip) or `interview → screening` (a regression).\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\", // read target from input.nextStatus\n fromTo: {\n applied: [\"screening\"],\n screening: [\"interview\"],\n interview: [\"offer\"],\n },\n },\n async execute({ db, record, input, whereTransition }) { /* … */ },\n});\n```\n\n```typescript\n// features/applications/actions/hire.ts\n\nexport default defineAction({\n description: \"Finalize an offer.\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n transition: {\n field: \"status\",\n to: \"hired\", // fixed target — same value every call\n fromTo: { offer: [\"hired\"] },\n },\n async execute({ db, record, whereTransition }) { /* … */ },\n});\n```\n\n| Field | Required | Description |\n|---|---|---|\n| `field` | Yes | Record column to validate (e.g. `\"status\"`) |\n| `fromTo` | Yes | Map of current value → permitted next values. Keys also enumerate the legal source states. |\n| `via` | Yes (or `to`) | Input key that carries the target value. Use for variable-target actions like `advance`. |\n| `to` | Yes (or `via`) | Literal target value the action always writes. Use for fixed-target actions like `hire`/`reject`. |\n\nExactly one of `via` or `to` must be provided. The compiler rejects both at\nvalidate time. When `to` is set, it must appear in some `fromTo[*]` array —\notherwise the action would be unreachable, which is almost certainly a bug.\n\n### Wire-level errors\n\nThe compiled guard returns **409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`** with\nthe field, the current value, the requested target, and the allowed set:\n\n```json\n{\n \"error\": \"Action not allowed for current record state\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ACTION_NOT_ALLOWED_FOR_STATE\",\n \"details\": {\n \"field\": \"status\",\n \"current\": \"interview\",\n \"target\": \"screening\",\n \"allowedTargets\": [\"offer\"]\n },\n \"hint\": \"From \\\"interview\\\", status can transition to: offer\"\n}\n```\n\nThis is distinct from a role failure: if the caller has the wrong role they\nget **403 `ACCESS_ROLE_REQUIRED`** as before. Splitting the two lets clients\ntell *\"you can't do this\"* from *\"you can't do this *yet*\"* — the latter is\nrecoverable by the user, the former isn't.\n\nThe same 409 code is used when an `access.record` predicate (without\n`transition`) fails — for example `record: { status: { equals: \"pending\" } }`\ncalled against a paid invoice now returns 409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`,\nnot a misleading 403.\n\n## Examples\n\n### Bulk Import (Standalone, No Record)\n\n```typescript\n// features/candidates/actions/bulk-import.ts\n\nexport default defineAction({\n description: \"Import candidates from job board CSV\",\n path: \"/candidates/import\",\n input: z.object({\n data: z.array(z.object({\n email: z.string().email(),\n name: z.string(),\n })),\n }),\n access: { roles: [\"hiring-manager\", \"recruiter\"] },\n async execute({ db, input }) {\n const inserted = await db\n .insert(candidates)\n .values(input.data)\n .returning();\n return { imported: inserted.length };\n },\n});\n```"
83
87
  },
84
88
  "compiler/definitions/arrows": {
85
89
  "title": "Arrows",
@@ -95,11 +99,11 @@ export const DOCS = {
95
99
  },
96
100
  "compiler/definitions/encryption": {
97
101
  "title": "Encryption",
98
- "content": "Mark a text column `.encrypted()` and Quickback envelope-encrypts it at rest with a **per-organization key**:\n\n```typescript\nexport default feature('guests', {\n columns: {\n id: q.id(),\n organizationId: q.scope('organization'), // required — keys are per-org\n name: q.text().required(),\n emergencyContact: q.text().encrypted(),\n dietaryNotes: q.text().encrypted(),\n },\n read: { access: { roles: ['member+'] } },\n create: { access: { roles: ['member+'] } },\n});\n```\n\nThat one modifier changes what a database breach means: a leaked D1 backup, export, or stolen database token yields only ciphertext for those columns. The keys live separately, wrapped under a worker secret the database never sees.\n\n## What the compiler generates\n\n- **`org_data_keys`** — one row per organization holding a random 256-bit data key (DEK), stored **wrapped** under the `ENCRYPTION_KEK` worker secret. Created lazily on the org's first encrypted write.\n- **Write path** — every write (CRUD routes, batch routes, and `db.insert`/`db.update` inside your actions) flows through the same chokepoint, which AES-256-GCM-encrypts the column before anything else sees it. Audit snapshots, webhook payloads, and realtime deltas therefore carry ciphertext by construction.\n- **Read path** — generated routes decrypt behind the firewall and then apply masking, so authorized callers see plaintext and everyone else sees the redaction — never ciphertext.\n- **`ctx.crypto`** — explicit `await ctx.crypto.decrypt(value)` / `ctx.crypto.encrypt(value)` for action code that processes the field server-side (building a manifest, sending an email). Scoped to the caller's active organization.\n- **Boot guard** — a project with encrypted columns refuses to serve without `ENCRYPTION_KEK` (503 `MISSING_ENV`), instead of silently storing plaintext.\n\nValues at rest look like `qbenc:1:<keyVersion>:<iv>:<ciphertext>` — the prefix makes accidental plaintext detectable, and the embedded key version supports rotation with lazy re-encryption on write.\n\n## Setup\n\nScaffolded projects already have a generated `ENCRYPTION_KEK` in `.dev.vars`, so local dev works with zero setup. For production:\n\n```bash\nopenssl rand -hex 32 | wrangler secret put ENCRYPTION_KEK\n```\n\n## Rules the compiler enforces\n\nCiphertext cannot be queried, so encrypted columns are **excluded from every query surface at compile time** — these are errors, not warnings:\n\n- No `.filterable()` / `.searchable()`, and never listed in a view's `query.{searchable,filterable,sortable}`\n- No `.unique()` (AES-GCM randomizes ciphertext per write), no primary keys, no `.references()`, no `q.scope()` columns, no defaults (a SQL default would bypass the encrypting chokepoint)\n- Never an `embeddings.fields` source (embedding a value ships its plaintext to the model)\n- The table must carry a `q.scope('organization')` column — keys are per-organization\n- Text-shaped columns only (v1)\n- Database provider must be **Cloudflare D1** or **Neon over HTTP** (the Cloudflare default). Anything else — including Neon's websocket mode — is a compile error, never silently-plaintext output. On Neon, `org_data_keys` lives in the `app` Postgres schema with org-scoped row-level security: a request-scoped connection can read and lazily create exactly its own organization's wrapped-key row; rotation and crypto-shredding are service-role operations.\n\nEncrypted columns **may** appear in view projections and responses — they decrypt through the generated prepare path. Masking composes on top as defense-in-depth.\n\n## Per-organization keys: blast radius and crypto-shredding\n\nEach organization's data is encrypted under its own DEK, so one compromised key never exposes another tenant. Deleting an org's `org_data_keys` row makes every encrypted value it ever wrote **permanently unreadable** — the cleanest possible GDPR-erasure and offboarding story.\n\n## What this tier does and doesn't claim\n\nThe envelope tier protects against **storage compromise**: backups, exports, dashboard access, leaked database tokens, SQL injection, and insiders with database read access all get ciphertext. The server *can* decrypt — that's the point; your actions still process the field. It does not protect against full Worker compromise — for that, use the **sealed tier** below, where the server structurally cannot read the value at all.\n\nTwo practical notes:\n\n- **Action responses**: rows returned from `db.insert(...).returning()` inside your own actions contain ciphertext — decrypt explicitly with `ctx.crypto.decrypt()` if your action returns the field. Generated CRUD routes handle this automatically.\n- **No server-side equality lookups** on encrypted values (blind indexes are a roadmap item). If you need to filter by it, it probably shouldn't be encrypted — or it needs a separate non-sensitive derived column.\n\n---\n\n# Sealed tier — end-to-end encryption\n\nMark a text column `.sealed()` instead of `.encrypted()` and you cross a line the envelope tier never claims: **the server cannot read the value.** It holds only ciphertext plus a content key *wrapped to a public key it has no private half for*. A full Worker compromise — leaked secrets, malicious code, a coerced admin — still yields nothing but ciphertext. Decryption happens only on the client, after a fresh step-up.\n\n```typescript\nexport default feature('candidates', {\n columns: {\n id: q.id(),\n organizationId: q.scope('organization'), // required — keys are per-scope\n name: q.text().required(),\n governmentId: q.text().encrypted(), // envelope tier: server CAN read (to mask)\n backgroundCheck: q.text({ maxLength: 8000 }).sealed(), // sealed tier: server CANNOT read\n },\n read: { access: { roles: ['member+'] } },\n create: { access: { roles: ['admin+'] } },\n});\n```\n\nUse it for data that is legally sensitive and need-to-know, where you want a database breach **and the server itself** to yield only ciphertext: background checks, health findings, raw identity documents, anything you'd rather not be able to read by accident.\n\nThe page below is the *usage* view. For the on-the-wire contract — the versioned `qbseal:1` envelope format, the full `/seal/v1` lifecycle, the Argon2id floor, passkey expectations, canonical conformance vectors, and the first-party **Swift / Kotlin / TypeScript SDKs** (with install + usage) — see [Sealed protocol](/compiler/definitions/sealed-protocol).\n\n## The key model\n\nThree nested keys. A breach of any layer above plaintext yields only more wrapped keys:\n\n```\nUSER key ──unwrap──▶ SCOPE private key ──unwrap──▶ content key ──decrypt──▶ plaintext\n```\n\n- **USER key** — derived on the client from a **vault passphrase** (Argon2id → an Ed25519 signing key + an X25519 wrap key). This is **never** the Better Auth login password — reusing the login password would collapse the zero-knowledge property back to server-trust. The server stores only the Ed25519 *public* key (to verify step-ups) and the Argon2id params.\n- **SCOPE keypair** — one per scope (per organization). The content key is wrapped to the scope's public key, so any authorized reader can be granted access without re-encrypting the data.\n- **Content key** — a random AES-256-GCM key, one per sealed value, wrapped to the scope.\n\nA **writer** needs only the scope's *public* key — no key of their own. Only **readers** (staff doing a reveal) need a grant of the scope private key, wrapped to their USER key.\n\n## The client ships with your backend\n\nFor any project with a `.sealed()` column the compiler emits the E2EE client **into your project** — there's nothing to `npm install`:\n\n```\nsrc/\n├─ lib/\n│ ├─ seal-routes.ts # server: the /seal/v1/* reveal rails (verify-only)\n│ └─ seal-client/ # client: the browser SDK you import — emitted for you\n│ └─ index.ts sdk.ts flow.ts wrap.ts kdf.ts envelope.ts ...\n```\n\n`@noble/curves` and `@noble/hashes` are added to your `package.json` automatically. The client is emitted from the *same compiler version* as the server routes, so the wire format (`qbseal:` envelopes, the step-up message, the key-wrap method) can never drift between the two — a class of silent decrypt-time bug that a separately-versioned package would reintroduce.\n\n## Writing a sealed value\n\nThe writer seals the plaintext to the scope's public key, then writes the result like any other field. The server stores ciphertext and is none the wiser.\n\n```typescript\n\nconst seal = new SealClient(transport); // transport = POST to /seal/v1/*\n\n// Fetches the scope's PUBLIC key and seals to it — the writer needs no key.\nconst sealed = await seal.sealField(\n 'scope:organization:org_123',\n new TextEncoder().encode('Background check: clear'),\n);\n\n// Write it like any field. At rest this is a `qbseal:` sealed-cell envelope.\nawait api.post('/api/v1/candidates', { name: 'Ada', backgroundCheck: sealed });\n```\n\n## Revealing a sealed value\n\nA reveal is a deliberate, audited, **step-up-gated** action — not an ambient read. The SDK runs the whole handshake; you provide the reader's passphrase-derived session:\n\n```typescript\n// Derive the reader's keys once from their vault passphrase (NOT their login password).\nconst session = seal.session(passphrase, enrollment);\n\nconst plaintext = await seal.reveal({\n session,\n scopeRef: 'scope:organization:org_123',\n vaultItemId: candidate.id,\n});\nnew TextDecoder().decode(plaintext); // \"Background check: clear\"\n```\n\nBehind that one call:\n\n1. **`/seal/v1/my-grant`** → the reader's wrapped scope private key.\n2. **`/seal/v1/challenge`** → a fresh, single-use nonce bound to this reader + item.\n3. The client signs a **step-up proof** over the nonce (Ed25519 from the passphrase, or a passkey assertion whose WebAuthn challenge *is* the nonce).\n4. **`/seal/v1/reveal`** verifies the proof, writes an append-only reveal-log entry, and mints a short-lived (≤180s) `scope:seal:reveal` capability.\n5. **`/seal/v1/key`** (bearer that capability) passes three fail-closed gates — tenant, capability, live-grant — and returns the still-wrapped content key.\n6. The client unwraps the scope key, unwraps the content key, and decrypts. **None of this touches the server with a readable key.**\n\nPasskey reveal is the same call as `revealWithPasskey({ ..., getAssertion })`, where `getAssertion(nonce)` runs the WebAuthn ceremony.\n\n## Rules the compiler enforces\n\nSealed values are opaque references at rest, so they're fenced off from every surface that would need to read them — these are compile errors:\n\n- **Never** in a view projection, `?search`, or a `masking` rule (there's no plaintext to project, search, or redact — it leaves the system *only* through the reveal rails).\n- No `.filterable()` / `.searchable()` / `.unique()` / defaults / `embeddings.fields` (same reasons as the envelope tier).\n- The table **must** carry a `q.scope('organization')` column — keys are per-scope.\n- Reading a sealed column server-side is a **type error**: the column is branded `$type<SealedValue>()`, an opaque non-string, so `db.select()` on it won't typecheck. The server's structural inability to read it is enforced by `tsc`, not convention.\n- Sealed projects **force-enable** KV-backed JWT revocation (so a revoked reader's in-flight reveal token dies); a project with sealed columns and no KV binding **fails to compile**.\n- Database provider must be **Cloudflare D1** or **Neon over HTTP** (the Cloudflare default) — anything else fails to compile. On Neon, the seal/vault tables carry **deny-all row-level security for request connections**: only the worker-internal service-role lane (the generated `/seal/v1` routes, `ctx.seal`, and the sealed write chokepoint) can touch them, and every one of those queries is still explicitly organization-scoped.\n\n## What this tier does and doesn't claim\n\nThe sealed tier protects against **full Worker compromise** — leaked secrets, malicious or buggy server code, a coerced operator. All of them get ciphertext; the keys to read it never exist server-side. What it asks in return:\n\n- **A reveal needs a real second factor.** The vault passphrase (or passkey) is separate from login and never leaves the client. Lose it with no recovery grant and the data is unrecoverable *by design* — that's the guarantee, not a bug. Recovery/escrow and rotation re-granting are roadmap.\n- **No server-side processing.** Your actions can't read, mask, search, or index a sealed value — it's plaintext only in a client that just revealed it. If the server needs to process the field, you want the envelope tier instead.\n- **Passkey reveal** verify logic is in place but should be exercised with a real browser/authenticator before production; the passphrase lane is fully round-trip tested."
102
+ "content": "Mark a text column `.encrypted()` and Quickback envelope-encrypts it at rest with a **per-organization key**:\n\n```typescript\nexport default feature('guests', {\n columns: {\n id: q.id(),\n organizationId: q.scope('organization'), // required — keys are per-org\n name: q.text().required(),\n emergencyContact: q.text().encrypted(),\n dietaryNotes: q.text().encrypted(),\n },\n // \"+\" role expansion requires auth.roleHierarchy in quickback.config.ts\n read: { access: { roles: ['member+'] } },\n create: { access: { roles: ['member+'] } },\n});\n```\n\nThat one modifier changes what a database breach means: a leaked D1 backup, export, or stolen database token yields only ciphertext for those columns. The keys live separately, wrapped under a worker secret the database never sees.\n\n## What the compiler generates\n\n- **`org_data_keys`** — one row per organization holding a random 256-bit data key (DEK), stored **wrapped** under the `ENCRYPTION_KEK` worker secret. Created lazily on the org's first encrypted write.\n- **Write path** — every write (CRUD routes, batch routes, and `db.insert`/`db.update` inside your actions) flows through the same chokepoint, which AES-256-GCM-encrypts the column before anything else sees it. Audit snapshots, webhook payloads, and realtime deltas therefore carry ciphertext by construction.\n- **Read path** — generated routes decrypt behind the firewall and then apply masking, so authorized callers see plaintext and everyone else sees the redaction — never ciphertext.\n- **`ctx.crypto`** — explicit `await ctx.crypto.decrypt(value)` / `ctx.crypto.encrypt(value)` for action code that processes the field server-side (building a manifest, sending an email). Scoped to the caller's active organization.\n- **Boot guard** — a project with encrypted columns refuses to serve without `ENCRYPTION_KEK` (503 `MISSING_ENV`), instead of silently storing plaintext.\n\nValues at rest look like `qbenc:1:<keyVersion>:<iv>:<ciphertext>` — the prefix makes accidental plaintext detectable, and the embedded key version supports rotation with lazy re-encryption on write.\n\n## Setup\n\nScaffolded projects already have a generated `ENCRYPTION_KEK` in `.dev.vars`, so local dev works with zero setup. For production:\n\n```bash\nopenssl rand -hex 32 | wrangler secret put ENCRYPTION_KEK\n```\n\n## Rules the compiler enforces\n\nCiphertext cannot be queried, so encrypted columns are **excluded from every query surface at compile time** — these are errors, not warnings:\n\n- No `.filterable()` / `.searchable()`, and never listed in a view's `query.{searchable,filterable,sortable}`\n- No `.unique()` (AES-GCM randomizes ciphertext per write), no primary keys, no `.references()`, no `q.scope()` columns, no defaults (a SQL default would bypass the encrypting chokepoint)\n- Never an `embeddings.fields` source (embedding a value ships its plaintext to the model)\n- The table must carry a `q.scope('organization')` column — keys are per-organization\n- Text-shaped columns only (v1)\n- Database provider must be **Cloudflare D1** or **Neon over HTTP** (the Cloudflare default). Anything else — including Neon's websocket mode — is a compile error, never silently-plaintext output. On Neon, `org_data_keys` lives in the `app` Postgres schema with org-scoped row-level security: a request-scoped connection can read and lazily create exactly its own organization's wrapped-key row; rotation and crypto-shredding are service-role operations.\n\nEncrypted columns **may** appear in view projections and responses — they decrypt through the generated prepare path. Masking composes on top as defense-in-depth.\n\n## Per-organization keys: blast radius and crypto-shredding\n\nEach organization's data is encrypted under its own DEK, so one compromised key never exposes another tenant. Deleting an org's `org_data_keys` row makes every encrypted value it ever wrote **permanently unreadable** — the cleanest possible GDPR-erasure and offboarding story.\n\n## What this tier does and doesn't claim\n\nThe envelope tier protects against **storage compromise**: backups, exports, dashboard access, leaked database tokens, SQL injection, and insiders with database read access all get ciphertext. The server *can* decrypt — that's the point; your actions still process the field. It does not protect against full Worker compromise — for that, use the **sealed tier** below, where the server structurally cannot read the value at all.\n\nTwo practical notes:\n\n- **Action responses**: rows returned from `db.insert(...).returning()` inside your own actions contain ciphertext — decrypt explicitly with `ctx.crypto.decrypt()` if your action returns the field. Generated CRUD routes handle this automatically.\n- **No server-side equality lookups** on encrypted values (blind indexes are a roadmap item). If you need to filter by it, it probably shouldn't be encrypted — or it needs a separate non-sensitive derived column.\n\n---\n\n# Sealed tier — end-to-end encryption\n\nMark a text column `.sealed()` instead of `.encrypted()` and you cross a line the envelope tier never claims: **the server cannot read the value.** It holds only ciphertext plus a content key *wrapped to a public key it has no private half for*. A full Worker compromise — leaked secrets, malicious code, a coerced admin — still yields nothing but ciphertext. Decryption happens only on the client, after a fresh step-up.\n\n```typescript\nexport default feature('candidates', {\n columns: {\n id: q.id(),\n organizationId: q.scope('organization'), // required — keys are per-scope\n name: q.text().required(),\n governmentId: q.text().encrypted(), // envelope tier: server CAN read (to mask)\n backgroundCheck: q.text({ maxLength: 8000 }).sealed(), // sealed tier: server CANNOT read\n },\n read: { access: { roles: ['member+'] } },\n create: { access: { roles: ['admin+'] } },\n});\n```\n\nUse it for data that is legally sensitive and need-to-know, where you want a database breach **and the server itself** to yield only ciphertext: background checks, health findings, raw identity documents, anything you'd rather not be able to read by accident.\n\nThe page below is the *usage* view. For the on-the-wire contract — the versioned `qbseal:1` envelope format, the full `/seal/v1` lifecycle, the Argon2id floor, passkey expectations, canonical conformance vectors, and the first-party **Swift / Kotlin / TypeScript SDKs** (with install + usage) — see [Sealed protocol](/compiler/definitions/sealed-protocol).\n\n## The key model\n\nThree nested keys. A breach of any layer above plaintext yields only more wrapped keys:\n\n```\nUSER key ──unwrap──▶ SCOPE private key ──unwrap──▶ content key ──decrypt──▶ plaintext\n```\n\n- **USER key** — derived on the client from a **vault passphrase** (Argon2id → an Ed25519 signing key + an X25519 wrap key). This is **never** the Better Auth login password — reusing the login password would collapse the zero-knowledge property back to server-trust. The server stores only the Ed25519 *public* key (to verify step-ups) and the Argon2id params.\n- **SCOPE keypair** — one per scope (per organization). The content key is wrapped to the scope's public key, so any authorized reader can be granted access without re-encrypting the data.\n- **Content key** — a random AES-256-GCM key, one per sealed value, wrapped to the scope.\n\nA **writer** needs only the scope's *public* key — no key of their own. Only **readers** (staff doing a reveal) need a grant of the scope private key, wrapped to their USER key.\n\n## The client ships with your backend\n\nFor any project with a `.sealed()` column the compiler emits the E2EE client **into your project** — there's nothing to `npm install`:\n\n```\nsrc/\n├─ lib/\n│ ├─ seal-routes.ts # server: the /seal/v1/* reveal rails (verify-only)\n│ └─ seal-client/ # client: the browser SDK you import — emitted for you\n│ └─ index.ts sdk.ts flow.ts wrap.ts kdf.ts envelope.ts ...\n```\n\n`@noble/curves` and `@noble/hashes` are added to your `package.json` automatically. The client is emitted from the *same compiler version* as the server routes, so the wire format (`qbseal:` envelopes, the step-up message, the key-wrap method) can never drift between the two — a class of silent decrypt-time bug that a separately-versioned package would reintroduce.\n\n## Writing a sealed value\n\nThe writer seals the plaintext to the scope's public key, then writes the result like any other field. The server stores ciphertext and is none the wiser.\n\n```typescript\n\nconst seal = new SealClient(transport); // transport = POST to /seal/v1/*\n\n// Fetches the scope's PUBLIC key and seals to it — the writer needs no key.\nconst sealed = await seal.sealField(\n 'scope:organization:org_123',\n new TextEncoder().encode('Background check: clear'),\n);\n\n// Write it like any field. At rest this is a `qbseal:` sealed-cell envelope.\nawait api.post('/api/v1/candidates', { name: 'Ada', backgroundCheck: sealed });\n```\n\n## Revealing a sealed value\n\nA reveal is a deliberate, audited, **step-up-gated** action — not an ambient read. The SDK runs the whole handshake; you provide the reader's passphrase-derived session:\n\n```typescript\n// Derive the reader's keys once from their vault passphrase (NOT their login password).\nconst session = seal.session(passphrase, enrollment);\n\nconst plaintext = await seal.reveal({\n session,\n scopeRef: 'scope:organization:org_123',\n vaultItemId: candidate.id,\n});\nnew TextDecoder().decode(plaintext); // \"Background check: clear\"\n```\n\nBehind that one call:\n\n1. **`/seal/v1/my-grant`** → the reader's wrapped scope private key.\n2. **`/seal/v1/challenge`** → a fresh, single-use nonce bound to this reader + item.\n3. The client signs a **step-up proof** over the nonce (Ed25519 from the passphrase, or a passkey assertion whose WebAuthn challenge *is* the nonce).\n4. **`/seal/v1/reveal`** verifies the proof, writes an append-only reveal-log entry, and mints a short-lived (≤180s) `scope:seal:reveal` capability.\n5. **`/seal/v1/key`** (bearer that capability) passes three fail-closed gates — tenant, capability, live-grant — and returns the still-wrapped content key.\n6. The client unwraps the scope key, unwraps the content key, and decrypts. **None of this touches the server with a readable key.**\n\nPasskey reveal is the same call as `revealWithPasskey({ ..., getAssertion })`, where `getAssertion(nonce)` runs the WebAuthn ceremony.\n\n## Rules the compiler enforces\n\nSealed values are opaque references at rest, so they're fenced off from every surface that would need to read them — these are compile errors:\n\n- **Never** in a view projection, `?search`, or a `masking` rule (there's no plaintext to project, search, or redact — it leaves the system *only* through the reveal rails).\n- No `.filterable()` / `.searchable()` / `.unique()` / defaults / `embeddings.fields` (same reasons as the envelope tier).\n- The table **must** carry a `q.scope('organization')` column — keys are per-scope.\n- Reading a sealed column server-side is a **type error**: the column is branded `$type<SealedValue>()`, an opaque non-string, so `db.select()` on it won't typecheck. The server's structural inability to read it is enforced by `tsc`, not convention.\n- Sealed projects **force-enable** KV-backed JWT revocation (so a revoked reader's in-flight reveal token dies); a project with sealed columns and no KV binding **fails to compile**.\n- Database provider must be **Cloudflare D1** or **Neon over HTTP** (the Cloudflare default) — anything else fails to compile. On Neon, the seal/vault tables carry **deny-all row-level security for request connections**: only the worker-internal service-role lane (the generated `/seal/v1` routes, `ctx.seal`, and the sealed write chokepoint) can touch them, and every one of those queries is still explicitly organization-scoped.\n\n## What this tier does and doesn't claim\n\nThe sealed tier protects against **full Worker compromise** — leaked secrets, malicious or buggy server code, a coerced operator. All of them get ciphertext; the keys to read it never exist server-side. What it asks in return:\n\n- **A reveal needs a real second factor.** The vault passphrase (or passkey) is separate from login and never leaves the client. Lose it with no recovery grant and the data is unrecoverable *by design* — that's the guarantee, not a bug. Recovery/escrow and rotation re-granting are roadmap.\n- **No server-side processing.** Your actions can't read, mask, search, or index a sealed value — it's plaintext only in a client that just revealed it. If the server needs to process the field, you want the envelope tier instead.\n- **Passkey reveal** verify logic is in place but should be exercised with a real browser/authenticator before production; the passphrase lane is fully round-trip tested."
99
103
  },
100
104
  "compiler/definitions/feature": {
101
105
  "title": "feature() — the canonical form",
102
- "content": "`feature()` is **the** way to write a Quickback feature: one file, one default export, the table and its security contract together. The older `q.table()` + `defineTable()` pair still exists underneath (it's what `feature()` expands into), but it means two exports and two concepts for something a feature file treats as one unit.\n\n## Before\n\n```ts title=\"quickback/features/contacts.ts\"\n\nexport const contacts = q.table(\"contacts\", {\n id: q.id(),\n organizationId: q.text().required().index(),\n address: q.text().required().index(),\n name: q.text().optional(),\n});\n\nexport default defineTable(contacts, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: { access: { roles: [\"member+\"] } },\n create: { access: { roles: [\"member+\"] } },\n update: { access: { roles: [\"member+\"] } },\n delete: { access: { roles: [\"admin+\"] }, mode: \"soft\" },\n guards: { createable: [\"address\", \"name\"] },\n});\n\nexport type Contact = typeof contacts.$infer;\n```\n\n## After\n\n```ts title=\"quickback/features/contacts.ts\"\n\nexport default feature(\"contacts\", {\n columns: {\n id: q.id(),\n organizationId: q.text().required().index(),\n address: q.text().required().index(),\n name: q.text().optional(),\n },\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: { access: { roles: [\"member+\"] } },\n create: { access: { roles: [\"member+\"] } },\n update: { access: { roles: [\"member+\"] } },\n delete: { access: { roles: [\"admin+\"] }, mode: \"soft\" },\n guards: { createable: [\"address\", \"name\"] },\n});\n```\n\nType inference still works — `typeof import(\"./contacts\").default.$infer` gives you the `Contact` row type.\n\n## How it works\n\n`feature(name, config)` is a **compile-time sugar**, not a runtime abstraction. When the compiler sees `export default feature(...)`, it rewrites the source to the canonical two-export form before any parsing runs. Every downstream layer — dialect pass, audit injection, security contracts, generated routes, OpenAPI, MCP tools, RLS emission — runs on the same Drizzle source it always did. Zero runtime cost; zero semantic difference from `q.table()` + `defineTable()`.\n\nThat means:\n\n- **Both forms remain supported indefinitely.** Mix them freely — some files `feature(...)`, some files `q.table() + defineTable()`, some files Drizzle `sqliteTable() + defineTable()`. The compiler dispatches per file.\n- **Action files reference the table by default import.** `import contacts from \"./contacts\"` gives you the same typed handle `q.table(\"contacts\", ...)` would have returned, so `defineActions(contacts, { … })` still works.\n- **Diagnostics are identical.** Missing firewall → same warning. Protected-field wiring → same check. Nothing about `feature()` weakens the secure-by-default posture.\n\n## Aliases\n\n`q` is canonical (matches Zod's `z.`, Superstruct's `s.`). `qb` is exported as an alias if you'd rather self-document the namespace:\n\n```ts\n\nexport default feature(\"contacts\", {\n columns: { id: qb.id(), name: qb.text().required() },\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n // …\n});\n```\n\nSame object, two names — pick one.\n\n## When to use which\n\n| Pattern | When |\n|---|---|\n| `feature(name, {...})` | Default. One table, one security contract, one file. |\n| `q.table()` + `defineTable()` | Multiple tables per file (rare), or you want to reference the table identifier before the default export. |\n| `sqliteTable()` / `pgTable()` + `defineTable()` | Interop with existing Drizzle code / migrations. |\n| `q.table(...)` alone (no `defineTable`) | Internal join/lookup/pivot tables with no public API. Compiler warns so you confirm the opt-out is intentional. |\n\n## Feature directory layout\n\nA feature directory holds tables, optional shared schemas, and the handler files that back any actions:\n\n```\nfeatures/podcast/\n├── episodes.ts ← defineTable + (optional) defineActions(episodes, {…})\n├── shows.ts ← defineTable + (optional) defineActions(shows, {…})\n├── episode-tags.ts ← defineTable only (junction)\n├── _feature.ts ← non-table-bound actions + shared zod schemas\n├── handlers/\n│ ├── episodes/{publish,revertToDraft}.ts\n│ └── shows/…\n└── lib/\n └── shared.ts ← feature-local helpers, copied verbatim\n```\n\nThree things to know:\n\n- **`handlers/` walks recursively**, keyed by relative path (`handlers/episodes/publish.ts`). The canonical layout is per-table subdirectories so action handlers stay grouped with the table they act on.\n- **`lib/` rides along** — feature-local helper modules get copied verbatim into the generated output. Use this for shared utilities that both handlers and inline `execute:` bodies reference.\n- **`_feature.ts` is the universal slot** for non-table-bound actions and shared schemas. Top-level decls in `_feature.ts` get prepended once to the merged actions module, so a `const sharedSchema = z.object({…})` in `_feature.ts` is referenceable from any sibling action's `input:` without re-declaring it.\n\nFor everything action-related — three modes, conflict rules, the `_feature.ts` shape — see [Actions](/compiler/definitions/actions).\n\n## Handlers — one `q` namespace for everything\n\nCustom action handlers need to run queries against the database. Quickback's compiled projects expose the Drizzle query-builder helpers on the same `q` namespace you use for schema authoring, so handler code stays inside one DSL:\n\n```ts title=\"quickback/features/mail/handlers/inbound.ts\"\n\nexport const execute = async ({ unsafeDb, input }) => {\n // Find the mailbox this email was addressed to\n const mailbox = await unsafeDb.query.mailboxes.findFirst({\n where: q.eq(mailboxes.address, input.mailboxAddress),\n });\n if (!mailbox) return { error: \"unknown mailbox\" };\n\n // Look up the thread by in-reply-to + organization scope\n const thread = input.parsed.inReplyTo\n ? await unsafeDb.query.threads.findFirst({\n where: q.and(\n q.eq(threads.organizationId, mailbox.organizationId),\n q.eq(threads.lastMessageId, input.parsed.inReplyTo),\n ),\n })\n : null;\n\n // Insert the new message\n await unsafeDb.insert(messages).values({\n id: crypto.randomUUID(),\n threadId: thread?.id,\n organizationId: mailbox.organizationId,\n subject: input.parsed.subject,\n createdAt: new Date().toISOString(),\n });\n\n return { ok: true };\n};\n```\n\nThe `q` in handlers is a runtime re-export of Drizzle's query builder — `q.eq`, `q.and`, `q.or`, `q.not`, `q.ne`, `q.gt`, `q.gte`, `q.lt`, `q.lte`, `q.like`, `q.ilike`, `q.inArray`, `q.notInArray`, `q.isNull`, `q.isNotNull`, `q.between`, `q.desc`, `q.asc`, `q.sql`. Pure re-export, zero wrapper cost.\n\n**The compiler generates `src/lib/q.ts`** in every project so the runtime `q` is always available. You never need to `import { eq } from \"drizzle-orm\"` in a handler — though you can if you want (Quickback doesn't hide drizzle, it just offers a consistent surface that matches the schema DSL).\n\n## Why one namespace\n\nQuickback is an opinionated wrapper with opinionated security. One DSL for schema (`q.table`, `q.text`, `q.id`), one DSL for queries (`q.eq`, `q.and`, `q.gte`), one opt-in for routes (`feature()` / `defineTable`). You never need to learn the names of the underlying tools to write a feature — the same way Next.js users don't need to know they're using webpack, or Astro users don't need to know they're using Vite."
106
+ "content": "`feature()` is **the** way to write a Quickback feature: one file, one default export, the table and its security contract together. The older `q.table()` + `defineTable()` pair still exists underneath (it's what `feature()` expands into), but it means two exports and two concepts for something a feature file treats as one unit.\n\n## Before\n\n```ts title=\"quickback/features/contacts.ts\"\n\nexport const contacts = q.table(\"contacts\", {\n id: q.id(),\n organizationId: q.text().required().index(),\n address: q.text().required().index(),\n name: q.text().optional(),\n});\n\nexport default defineTable(contacts, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n // \"+\" role expansion requires auth.roleHierarchy in quickback.config.ts\n read: { access: { roles: [\"member+\"] } },\n create: { access: { roles: [\"member+\"] } },\n update: { access: { roles: [\"member+\"] } },\n delete: { access: { roles: [\"admin+\"] }, mode: \"soft\" },\n guards: { createable: [\"address\", \"name\"] },\n});\n\nexport type Contact = typeof contacts.$infer;\n```\n\n## After\n\n```ts title=\"quickback/features/contacts.ts\"\n\nexport default feature(\"contacts\", {\n columns: {\n id: q.id(),\n organizationId: q.text().required().index(),\n address: q.text().required().index(),\n name: q.text().optional(),\n },\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n // \"+\" role expansion requires auth.roleHierarchy in quickback.config.ts\n read: { access: { roles: [\"member+\"] } },\n create: { access: { roles: [\"member+\"] } },\n update: { access: { roles: [\"member+\"] } },\n delete: { access: { roles: [\"admin+\"] }, mode: \"soft\" },\n guards: { createable: [\"address\", \"name\"] },\n});\n```\n\nType inference still works — `typeof import(\"./contacts\").default.$infer` gives you the `Contact` row type.\n\n## How it works\n\n`feature(name, config)` is a **compile-time sugar**, not a runtime abstraction. When the compiler sees `export default feature(...)`, it rewrites the source to the canonical two-export form before any parsing runs. Every downstream layer — dialect pass, audit injection, security contracts, generated routes, OpenAPI, MCP tools, RLS emission — runs on the same Drizzle source it always did. Zero runtime cost; zero semantic difference from `q.table()` + `defineTable()`.\n\nThat means:\n\n- **Both forms remain supported indefinitely.** Mix them freely — some files `feature(...)`, some files `q.table() + defineTable()`, some files Drizzle `sqliteTable() + defineTable()`. The compiler dispatches per file.\n- **Action files reference the table by default import.** `import contacts from \"./contacts\"` gives you the same typed handle `q.table(\"contacts\", ...)` would have returned, so `defineActions(contacts, { … })` still works.\n- **Diagnostics are identical.** Missing firewall → same warning. Protected-field wiring → same check. Nothing about `feature()` weakens the secure-by-default posture.\n\n## Aliases\n\n`q` is canonical (matches Zod's `z.`, Superstruct's `s.`). `qb` is exported as an alias if you'd rather self-document the namespace:\n\n```ts\n\nexport default feature(\"contacts\", {\n columns: { id: qb.id(), name: qb.text().required() },\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n // …\n});\n```\n\nSame object, two names — pick one.\n\n## When to use which\n\n| Pattern | When |\n|---|---|\n| `feature(name, {...})` | Default. One table, one security contract, one file. |\n| `q.table()` + `defineTable()` | Multiple tables per file (rare), or you want to reference the table identifier before the default export. |\n| `sqliteTable()` / `pgTable()` + `defineTable()` | Interop with existing Drizzle code / migrations. |\n| `q.table(...)` alone (no `defineTable`) | Internal join/lookup/pivot tables with no public API. Compiler warns so you confirm the opt-out is intentional. |\n\n## Feature directory layout\n\nA feature directory holds tables, optional shared schemas, and the handler files that back any actions:\n\n```\nfeatures/podcast/\n├── episodes.ts ← defineTable + (optional) defineActions(episodes, {…})\n├── shows.ts ← defineTable + (optional) defineActions(shows, {…})\n├── episode-tags.ts ← defineTable only (junction)\n├── _feature.ts ← non-table-bound actions + shared zod schemas\n├── handlers/\n│ ├── episodes/{publish,revertToDraft}.ts\n│ └── shows/…\n└── lib/\n └── shared.ts ← feature-local helpers, copied verbatim\n```\n\nThree things to know:\n\n- **`handlers/` walks recursively**, keyed by relative path (`handlers/episodes/publish.ts`). The canonical layout is per-table subdirectories so action handlers stay grouped with the table they act on.\n- **`lib/` rides along** — feature-local helper modules get copied verbatim into the generated output. Use this for shared utilities that both handlers and inline `execute:` bodies reference.\n- **`_feature.ts` is the universal slot** for non-table-bound actions and shared schemas. Top-level decls in `_feature.ts` get prepended once to the merged actions module, so a `const sharedSchema = z.object({…})` in `_feature.ts` is referenceable from any sibling action's `input:` without re-declaring it.\n\nFor everything action-related — three modes, conflict rules, the `_feature.ts` shape — see [Actions](/compiler/definitions/actions).\n\n## Handlers — one `q` namespace for everything\n\nCustom action handlers need to run queries against the database. Quickback's compiled projects expose the Drizzle query-builder helpers on the same `q` namespace you use for schema authoring, so handler code stays inside one DSL:\n\n```ts title=\"quickback/features/mail/handlers/inbound.ts\"\n\nexport const execute = async ({ unsafeDb, input }) => {\n // Find the mailbox this email was addressed to\n const mailbox = await unsafeDb.query.mailboxes.findFirst({\n where: q.eq(mailboxes.address, input.mailboxAddress),\n });\n if (!mailbox) return { error: \"unknown mailbox\" };\n\n // Look up the thread by in-reply-to + organization scope\n const thread = input.parsed.inReplyTo\n ? await unsafeDb.query.threads.findFirst({\n where: q.and(\n q.eq(threads.organizationId, mailbox.organizationId),\n q.eq(threads.lastMessageId, input.parsed.inReplyTo),\n ),\n })\n : null;\n\n // Insert the new message\n await unsafeDb.insert(messages).values({\n id: crypto.randomUUID(),\n threadId: thread?.id,\n organizationId: mailbox.organizationId,\n subject: input.parsed.subject,\n createdAt: new Date().toISOString(),\n });\n\n return { ok: true };\n};\n```\n\nThe `q` in handlers is a runtime re-export of Drizzle's query builder — `q.eq`, `q.and`, `q.or`, `q.not`, `q.ne`, `q.gt`, `q.gte`, `q.lt`, `q.lte`, `q.like`, `q.ilike`, `q.inArray`, `q.notInArray`, `q.isNull`, `q.isNotNull`, `q.between`, `q.desc`, `q.asc`, `q.sql`. Pure re-export, zero wrapper cost.\n\n**The compiler generates `src/lib/q.ts`** in every project so the runtime `q` is always available. You never need to `import { eq } from \"drizzle-orm\"` in a handler — though you can if you want (Quickback doesn't hide drizzle, it just offers a consistent surface that matches the schema DSL).\n\n## Why one namespace\n\nQuickback is an opinionated wrapper with opinionated security. One DSL for schema (`q.table`, `q.text`, `q.id`), one DSL for queries (`q.eq`, `q.and`, `q.gte`), one opt-in for routes (`feature()` / `defineTable`). You never need to learn the names of the underlying tools to write a feature — the same way Next.js users don't need to know they're using webpack, or Astro users don't need to know they're using Vite."
103
107
  },
104
108
  "compiler/definitions/fga": {
105
109
  "title": "FGA - Relationship-Based Access (Zanzibar)",
@@ -119,7 +123,7 @@ export const DOCS = {
119
123
  },
120
124
  "compiler/definitions/masking": {
121
125
  "title": "Masking - Field Redaction",
122
- "content": "Hide sensitive data from unauthorized users while showing it to those with permission.\n\n## Automatic Masking (Secure by Default)\n\nQuickback automatically applies masking to columns that match sensitive naming patterns. This ensures a high security posture even if you don't explicitly configure masking.\n\n### Sensitive Keywords & Default Masks\n\n| Pattern | Default Mask | Description |\n| :--- | :--- | :--- |\n| `email` | `email` | p***@e******.com |\n| `phone`, `mobile`, `fax` | `phone` | ******4567 |\n| `ssn`, `socialsecurity`, `nationalid` | `ssn` | *****6789 |\n| `creditcard`, `cc`, `cardnumber`, `cvv` | `creditCard` | ************1234 |\n| `iban` | `redact` | [REDACTED] |\n| `password`, `secret`, `token`, `apikey`, `privatekey` | `redact` | [REDACTED] |\n| `accesstoken`, `refreshtoken`, `clientsecret`, `signingsecret`, `bearer` | `redact` | [REDACTED] |\n| `stripe`, `webhook` | `redact` | [REDACTED] |\n\n### Build-Time Alerts\n\nIf the compiler auto-detects a sensitive column that you haven't explicitly configured, it will emit a warning:\n\n```bash\n[Warning] Auto-masking enabled for sensitive column \"users.email\". Explicitly configure masking to silence this warning.\n```\n\nTo silence this warning or change the behavior, simply define the field explicitly in your `masking` configuration. Explicit configurations always take precedence over auto-detected defaults.\n\n#### Tables without an owner column\n\nThe default auto-mask predicate is `show: { or: 'owner', roles: ['admin'] }` — admins always see the value, the row's owner sees their own. If the table has no owner column at all (no `userId` / `ownerId` and no `q.scope('owner')`), the compiler drops the `owner` clause and emits a second warning so the rule is still safe but transparent:\n\n```bash\n[Warning] Auto-masking on \"people.email\" requested owner OR-show, but \"people\"\n has no \"ownerId\" column. Falling back to roles-only (roles: [\"admin\"]).\n Declare `masking: { email: { show: { roles: [...] } } }` explicitly to\n silence this and pick a real predicate.\n```\n\nThis is a real behavioral signal, not boilerplate — the auto-detector can't tell whether the table is \"ownerless on purpose\" (e.g. a shared lookup table) or \"should have an owner column but was authored without one.\" Declare the predicate explicitly to silence the warning and lock in the intent.\n\n### Overriding Defaults\n\nIf you want to show a sensitive field to everyone (disable masking) or use a different rule, define it explicitly in the `resource.masking` block:\n\n```typescript\nexport default defineTable(candidates, {\n masking: {\n // Show email to everyone (overrides auto-masking)\n email: { type: 'email', show: { roles: ['everyone'] } },\n\n // Silence warning but keep secure (recruiter and above only)\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } }\n }\n});\n```\n\n## Basic Usage\n\n```typescript\n// features/candidates/candidates.ts\n\nexport default feature('candidates', {\n columns: {\n id: q.id(),\n name: q.text().required(),\n email: q.text().required(),\n phone: q.text().optional(),\n resumeUrl: q.text().optional(),\n organizationId: q.scope('organization'),\n },\n guards: { createable: [\"name\", \"email\", \"phone\", \"resumeUrl\"], updatable: [\"name\", \"phone\"] },\n masking: {\n email: { type: 'email', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n },\n read: { access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] } },\n create: { /* ... */ },\n update: { /* ... */ },\n delete: { /* ... */ },\n});\n```\n\n## Built-in Mask Types\n\n| Type | Example Input | Masked Output |\n|------|---------------|---------------|\n| `'email'` | `john@yourdomain.com` | `j***@y*********.com` |\n| `'phone'` | `555-123-4567` | `******4567` |\n| `'ssn'` | `123-45-6789` | `*****6789` |\n| `'creditCard'` | `4111111111111111` | `************1111` |\n| `'name'` | `John Smith` | `J*** S****` |\n| `'redact'` | `anything` | `[REDACTED]` |\n| `'custom'` | (your logic) | (your output) |\n\n## Configuration\n\n```typescript\nmasking: {\n // Basic masking - everyone sees masked value\n phone: { type: 'phone' },\n\n // Show unmasked to specific roles\n email: {\n type: 'email',\n show: { roles: ['hiring-manager', 'recruiter'] }\n },\n\n // Show unmasked to owner (createdBy === ctx.userId)\n resumeUrl: {\n type: 'redact',\n show: { or: 'owner' }\n },\n\n // Custom mask function\n externalProfileUrl: {\n type: 'custom',\n mask: (value) => value.slice(0, 4) + '...' + value.slice(-4),\n show: { roles: ['recruiter'] }\n },\n}\n```\n\n## Show Conditions\n\n```typescript\nshow: {\n roles?: string[]; // Unmasked if user has any of these roles\n or?: 'owner'; // Unmasked if user is the record owner\n}\n```\n\nThe `'owner'` condition compares against the owner column declared via `q.scope('owner')` (or auto-detected from a `userId` / `ownerId` column). If no owner scope is present, it falls back to `createdBy`.\n\n### Relationship-roles in masking (v1 limitation)\n\nRelationship-roles declared under `authz.roles` (e.g. `guest: { via: 'guestOf' }`) are **not yet supported in `show:` clauses**. The compiler refuses to build with a clear error message because async, db-aware mask functions plus a batched relationship matcher (to avoid N+1 on list responses) are required to ship safely — that pipeline has not yet landed. The runtime evaluator fails closed on unrecognized arms, so silent grants are impossible.\n\n**Workarounds**, depending on intent:\n\n- **Gate on BA roles only**: keep masking simple and put the relationship check at the access layer instead — `read.views.<v>.access: { roles: ['guest'] }` returns a curated field projection that excludes the sensitive column entirely for non-staff callers, without involving masking.\n- **Move the field into a view that's gated by the relationship-role at access**: same pattern — column-level security via field projection rather than per-row masking.\n\nA future async-mask pipeline with batched lookups will lift this limitation; the schema slot is reserved so the v2 add will be non-breaking.\n\n## Query Gate (filter / sort / search)\n\nMasking has a second concern beyond hiding values in the response: a non-admin caller could enumerate masked PII via the query string — e.g. `?filter=email:like:%@target.com` — and infer presence even when the response payload is redacted. The `query` allowlist closes this:\n\n```typescript\nmasking: {\n email: {\n type: 'email',\n show: { roles: ['admin'] },\n // Optional — defaults to show.roles when omitted\n query: { roles: ['admin'] },\n },\n}\n```\n\n`query` is a single role gate that covers `?filter`, `?sort`, and `?search` uniformly. When omitted, it inherits from `show.roles` — \"if you can see it, you can query it\" — which is the right shape for almost all PII.\n\nA view can opt back in for a higher-privileged role pair by listing the column in its own `query.{filterable,searchable,sortable}` allowlist. The compiler validates at build time that the view's access roles intersect the masking `query.roles` (or `show.roles` when `query` is omitted), so the opt-in can never reach a caller who'd see the value masked.\n\n```typescript\nmasking: {\n email: { type: 'email', show: { roles: ['admin'] } },\n // query: defaults to show.roles → ['admin']\n},\nread: {\n views: {\n pipeline: {\n fields: ['id', 'name'],\n access: { roles: ['member', 'admin'] },\n query: {\n searchable: ['name'], // email NOT listed → not searchable on this view\n },\n },\n full: {\n fields: ['id', 'name', 'email'],\n access: { roles: ['admin'] },\n query: {\n filterable: ['email'], // ✓ admin satisfies email's query gate\n searchable: ['name', 'email'],\n },\n },\n },\n},\n```\n\n`query` replaces the legacy per-capability flags (`filterable`, `searchable`, `sortable`). Setting any of those is rejected at compile time with a migration hint.\n\n## Egress protection\n\nMasking redacts a column on the **read paths** (`GET /:id`, list, views, realtime) per role. It does **not** automatically follow the value if you copy it into a *derived* artifact that bypasses those read paths — a different record, an html/text string, or an outbound payload. Quickback guards those egress points so a masked token/PII can't quietly ship in the clear:\n\n- **Compile-time block (declarative).** A masked column is rejected at build time if it appears in `embeddings.fields` / `embeddings.metadata` (the value would be embedded and stored beside the vector, and returned in search hits) or is used as the table's `displayColumn` (it would render as the FK label inside every referencing record).\n- **Compile-time scan (actions).** A record-based action that copies `record.<maskedColumn>` into another record's column, an html/text template that gets stored, or a payload object fails compilation. Plain reads, comparisons, logging, and tagged templates (`sql\\`…\\${record.col}\\``) are fine — only the storage/payload sinks are flagged.\n- **Realtime → webhook.** Rows pushed to a realtime webhook sink are masked (an external sink carries no role, so masked columns are redacted), matching what WebSocket subscribers see.\n\n### Revealing a value on purpose: `unmask()`\n\nWhen an action legitimately needs the raw value (e.g. calling an external API with a token), route it through `unmask()` — the sanctioned, audited reveal. It returns the raw value and records a best-effort `masked_reveal` entry in the audit database when one is configured.\n\n```typescript\n\n// in an action's execute():\nconst token = await unmask(c, record.apiToken, 'apiToken');\nawait fetch(externalUrl, { headers: { Authorization: `Bearer ${token}` } });\n```\n\n### Opting a column out: `egress: 'allow'`\n\nIf a column is masked for display tidiness rather than secrecy, opt it out of both the compile-time block and the action scan:\n\n```typescript\nmasking: {\n shortCode: { type: 'redact', show: { roles: ['admin'] }, egress: 'allow' },\n}\n```\n\n`egress` defaults to `'block'` (fail-closed). Note the action scan is a heuristic — it catches the obvious accidental copy (`record.col` straight into a sink) but not values first aliased into another variable, the whole row returned/spread, or a re-fetch via `db.select()`. Treat it as a guardrail against accidents, not a cryptographic boundary; for true secrecy use the [encryption pillar](/docs/compiler/definitions/encryption).\n\n## Complete Example\n\n```typescript\n// features/candidates/candidates.ts\n\nexport default feature('candidates', {\n columns: {\n id: q.id(),\n name: q.text().required().filterable('like').searchable(),\n email: q.text().required().filterable('eq').searchable(),\n phone: q.text().optional().filterable('eq'),\n resumeUrl: q.text().optional(),\n organizationId: q.scope('organization'),\n },\n guards: {\n createable: ['name', 'email', 'phone', 'resumeUrl'],\n updatable: ['name', 'phone'],\n },\n masking: {\n email: { type: 'email', show: { roles: ['admin+'] } },\n phone: { type: 'phone', show: { roles: ['admin+'] } },\n resumeUrl: {\n type: 'custom',\n mask: () => '[RESUME LINK HIDDEN]',\n show: { roles: ['admin+'] },\n },\n },\n read: {\n access: { roles: ['member+'] },\n views: {\n pipeline: {\n fields: ['id', 'name'],\n access: { roles: ['member+'] },\n query: { searchable: ['name'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'phone', 'resumeUrl'],\n access: { roles: ['admin+'] },\n query: {\n filterable: ['email', 'phone'],\n searchable: ['name', 'email'],\n },\n },\n },\n },\n create: { access: { roles: ['admin+'] } },\n update: { access: { roles: ['admin+'] } },\n delete: { access: { roles: ['owner'] }, mode: 'soft' },\n});\n```"
126
+ "content": "Hide sensitive data from unauthorized users while showing it to those with permission.\n\n## Automatic Masking (Secure by Default)\n\nQuickback automatically applies masking to columns that match sensitive naming patterns. This ensures a high security posture even if you don't explicitly configure masking.\n\n### Sensitive Keywords & Default Masks\n\n| Pattern | Default Mask | Description |\n| :--- | :--- | :--- |\n| `email` | `email` | p***@e******.com |\n| `phone`, `mobile`, `fax` | `phone` | ******4567 |\n| `ssn`, `socialsecurity`, `nationalid` | `ssn` | *****6789 |\n| `creditcard`, `cc`, `cardnumber`, `cvv` | `creditCard` | ************1234 |\n| `iban` | `redact` | [REDACTED] |\n| `password`, `secret`, `token`, `apikey`, `privatekey` | `redact` | [REDACTED] |\n| `accesstoken`, `refreshtoken`, `clientsecret`, `signingsecret`, `bearer` | `redact` | [REDACTED] |\n| `stripe`, `webhook` | `redact` | [REDACTED] |\n\n### Build-Time Alerts\n\nIf the compiler auto-detects a sensitive column that you haven't explicitly configured, it will emit a warning:\n\n```bash\n[Warning] Auto-masking enabled for sensitive column \"users.email\". Explicitly configure masking to silence this warning.\n```\n\nTo silence this warning or change the behavior, simply define the field explicitly in your `masking` configuration. Explicit configurations always take precedence over auto-detected defaults.\n\n#### Tables without an owner column\n\nThe default auto-mask predicate is `show: { or: 'owner', roles: ['admin'] }` — admins always see the value, the row's owner sees their own. If the table has no owner column at all (no `userId` / `ownerId` and no `q.scope('owner')`), the compiler drops the `owner` clause and emits a second warning so the rule is still safe but transparent:\n\n```bash\n[Warning] Auto-masking on \"people.email\" requested owner OR-show, but \"people\"\n has no \"ownerId\" column. Falling back to roles-only (roles: [\"admin\"]).\n Declare `masking: { email: { show: { roles: [...] } } }` explicitly to\n silence this and pick a real predicate.\n```\n\nThis is a real behavioral signal, not boilerplate — the auto-detector can't tell whether the table is \"ownerless on purpose\" (e.g. a shared lookup table) or \"should have an owner column but was authored without one.\" Declare the predicate explicitly to silence the warning and lock in the intent.\n\n### Overriding Defaults\n\nIf you want to show a sensitive field to everyone (disable masking) or use a different rule, define it explicitly in the `resource.masking` block:\n\n```typescript\nexport default defineTable(candidates, {\n masking: {\n // Show email to everyone (overrides auto-masking)\n email: { type: 'email', show: { roles: ['everyone'] } },\n\n // Silence warning but keep secure (recruiter and above only)\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } }\n }\n});\n```\n\n## Basic Usage\n\n```typescript\n// features/candidates/candidates.ts\n\nexport default feature('candidates', {\n columns: {\n id: q.id(),\n name: q.text().required(),\n email: q.text().required(),\n phone: q.text().optional(),\n resumeUrl: q.text().optional(),\n organizationId: q.scope('organization'),\n },\n guards: { createable: [\"name\", \"email\", \"phone\", \"resumeUrl\"], updatable: [\"name\", \"phone\"] },\n masking: {\n email: { type: 'email', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n },\n read: { access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] } },\n create: { /* ... */ },\n update: { /* ... */ },\n delete: { /* ... */ },\n});\n```\n\n## Built-in Mask Types\n\n| Type | Example Input | Masked Output |\n|------|---------------|---------------|\n| `'email'` | `john@yourdomain.com` | `j***@y*********.com` |\n| `'phone'` | `555-123-4567` | `******4567` |\n| `'ssn'` | `123-45-6789` | `*****6789` |\n| `'creditCard'` | `4111111111111111` | `************1111` |\n| `'name'` | `John Smith` | `J*** S****` |\n| `'redact'` | `anything` | `[REDACTED]` |\n| `'custom'` | (your logic) | (your output) |\n\n## Configuration\n\n```typescript\nmasking: {\n // Basic masking - everyone sees masked value\n phone: { type: 'phone' },\n\n // Show unmasked to specific roles\n email: {\n type: 'email',\n show: { roles: ['hiring-manager', 'recruiter'] }\n },\n\n // Show unmasked to owner (createdBy === ctx.userId)\n resumeUrl: {\n type: 'redact',\n show: { or: 'owner' }\n },\n\n // Custom mask function\n externalProfileUrl: {\n type: 'custom',\n mask: (value) => value.slice(0, 4) + '...' + value.slice(-4),\n show: { roles: ['recruiter'] }\n },\n}\n```\n\n## Show Conditions\n\n```typescript\nshow: {\n roles?: string[]; // Unmasked if user has any of these roles\n or?: 'owner'; // Unmasked if user is the record owner\n}\n```\n\nThe `'owner'` condition compares against the owner column declared via `q.scope('owner')` (or auto-detected from a `userId` / `ownerId` column). If no owner scope is present, it falls back to `createdBy`.\n\n### Relationship-roles in masking (v1 limitation)\n\nRelationship-roles declared under `authz.roles` (e.g. `guest: { via: 'guestOf' }`) are **not yet supported in `show:` clauses**. The compiler refuses to build with a clear error message because async, db-aware mask functions plus a batched relationship matcher (to avoid N+1 on list responses) are required to ship safely — that pipeline has not yet landed. The runtime evaluator fails closed on unrecognized arms, so silent grants are impossible.\n\n**Workarounds**, depending on intent:\n\n- **Gate on BA roles only**: keep masking simple and put the relationship check at the access layer instead — `read.views.<v>.access: { roles: ['guest'] }` returns a curated field projection that excludes the sensitive column entirely for non-staff callers, without involving masking.\n- **Move the field into a view that's gated by the relationship-role at access**: same pattern — column-level security via field projection rather than per-row masking.\n\nA future async-mask pipeline with batched lookups will lift this limitation; the schema slot is reserved so the v2 add will be non-breaking.\n\n## Query Gate (filter / sort / search)\n\nMasking has a second concern beyond hiding values in the response: a non-admin caller could enumerate masked PII via the query string — e.g. `?filter=email:like:%@target.com` — and infer presence even when the response payload is redacted. The `query` allowlist closes this:\n\n```typescript\nmasking: {\n email: {\n type: 'email',\n show: { roles: ['admin'] },\n // Optional — defaults to show.roles when omitted\n query: { roles: ['admin'] },\n },\n}\n```\n\n`query` is a single role gate that covers `?filter`, `?sort`, and `?search` uniformly. When omitted, it inherits from `show.roles` — \"if you can see it, you can query it\" — which is the right shape for almost all PII.\n\nA view can opt back in for a higher-privileged role pair by listing the column in its own `query.{filterable,searchable,sortable}` allowlist. The compiler validates at build time that the view's access roles intersect the masking `query.roles` (or `show.roles` when `query` is omitted), so the opt-in can never reach a caller who'd see the value masked.\n\n```typescript\nmasking: {\n email: { type: 'email', show: { roles: ['admin'] } },\n // query: defaults to show.roles → ['admin']\n},\nread: {\n views: {\n pipeline: {\n fields: ['id', 'name'],\n access: { roles: ['member', 'admin'] },\n query: {\n searchable: ['name'], // email NOT listed → not searchable on this view\n },\n },\n full: {\n fields: ['id', 'name', 'email'],\n access: { roles: ['admin'] },\n query: {\n filterable: ['email'], // ✓ admin satisfies email's query gate\n searchable: ['name', 'email'],\n },\n },\n },\n},\n```\n\n`query` replaces the legacy per-capability flags (`filterable`, `searchable`, `sortable`). Setting any of those is rejected at compile time with a migration hint.\n\n## Egress protection\n\nMasking redacts a column on the **read paths** (`GET /:id`, list, views, realtime) per role. It does **not** automatically follow the value if you copy it into a *derived* artifact that bypasses those read paths — a different record, an html/text string, or an outbound payload. Quickback guards those egress points so a masked token/PII can't quietly ship in the clear:\n\n- **Compile-time block (declarative).** A masked column is rejected at build time if it appears in `embeddings.fields` / `embeddings.metadata` (the value would be embedded and stored beside the vector, and returned in search hits) or is used as the table's `displayColumn` (it would render as the FK label inside every referencing record).\n- **Compile-time scan (actions).** A record-based action that copies `record.<maskedColumn>` into another record's column, an html/text template that gets stored, or a payload object fails compilation. Plain reads, comparisons, logging, and tagged templates (`sql\\`…\\${record.col}\\``) are fine — only the storage/payload sinks are flagged.\n- **Realtime → webhook.** Rows pushed to a realtime webhook sink are masked (an external sink carries no role, so masked columns are redacted), matching what WebSocket subscribers see.\n\n### Revealing a value on purpose: `unmask()`\n\nWhen an action legitimately needs the raw value (e.g. calling an external API with a token), route it through `unmask()` — the sanctioned, audited reveal. It returns the raw value and records a best-effort `masked_reveal` entry in the audit database when one is configured.\n\n```typescript\n\n// in an action's execute():\nconst token = await unmask(c, record.apiToken, 'apiToken');\nawait fetch(externalUrl, { headers: { Authorization: `Bearer ${token}` } });\n```\n\n### Opting a column out: `egress: 'allow'`\n\nIf a column is masked for display tidiness rather than secrecy, opt it out of both the compile-time block and the action scan:\n\n```typescript\nmasking: {\n shortCode: { type: 'redact', show: { roles: ['admin'] }, egress: 'allow' },\n}\n```\n\n`egress` defaults to `'block'` (fail-closed). Note the action scan is a heuristic — it catches the obvious accidental copy (`record.col` straight into a sink) but not values first aliased into another variable, the whole row returned/spread, or a re-fetch via `db.select()`. Treat it as a guardrail against accidents, not a cryptographic boundary; for true secrecy use the [encryption pillar](/docs/compiler/definitions/encryption).\n\n## Complete Example\n\n```typescript\n// features/candidates/candidates.ts\n\nexport default feature('candidates', {\n columns: {\n id: q.id(),\n name: q.text().required().filterable('like').searchable(),\n email: q.text().required().filterable('eq').searchable(),\n phone: q.text().optional().filterable('eq'),\n resumeUrl: q.text().optional(),\n organizationId: q.scope('organization'),\n },\n guards: {\n createable: ['name', 'email', 'phone', 'resumeUrl'],\n updatable: ['name', 'phone'],\n },\n masking: {\n email: { type: 'email', show: { roles: ['admin+'] } },\n phone: { type: 'phone', show: { roles: ['admin+'] } },\n resumeUrl: {\n type: 'custom',\n mask: () => '[RESUME LINK HIDDEN]',\n show: { roles: ['admin+'] },\n },\n },\n read: {\n // \"+\" role expansion requires auth.roleHierarchy in quickback.config.ts\n access: { roles: ['member+'] },\n views: {\n pipeline: {\n fields: ['id', 'name'],\n access: { roles: ['member+'] },\n query: { searchable: ['name'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'phone', 'resumeUrl'],\n access: { roles: ['admin+'] },\n query: {\n filterable: ['email', 'phone'],\n searchable: ['name', 'email'],\n },\n },\n },\n },\n create: { access: { roles: ['admin+'] } },\n update: { access: { roles: ['admin+'] } },\n delete: { access: { roles: ['owner'] }, mode: 'soft' },\n});\n```"
123
127
  },
124
128
  "compiler/definitions/permissions": {
125
129
  "title": "Permissions",
@@ -167,7 +171,7 @@ export const DOCS = {
167
171
  },
168
172
  "compiler/getting-started/hand-crafted": {
169
173
  "title": "Hand-Crafted Setup",
170
- "content": "If you have an existing project and want to add Quickback-generated API endpoints, you can set up the definitions directory manually instead of using a template.\n\n## Prerequisites\n\n- An existing Hono-based project (Cloudflare Workers or Bun)\n- Node.js 18+ or Bun installed\n- The Quickback CLI: `npm install -g @quickback-dev/cli`\n\n## Setup\n\n### 1. Create the Quickback Directory\n\nCreate a `quickback/` directory in your project root with the following structure:\n\n```\nyour-project/\n├── quickback/\n│ ├── quickback.config.ts\n│ └── features/\n│ └── (your features go here)\n├── src/ # Your existing code\n├── package.json\n└── ...\n```\n\n```bash\nmkdir -p quickback/features\n```\n\n### 2. Write Your Config\n\nCreate `quickback/quickback.config.ts`:\n\n```typescript\n\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n features: [\"organizations\"],\n providers: {\n runtime: { name: \"cloudflare\", config: {} },\n database: {\n name: \"cloudflare-d1\",\n config: { binding: \"DB\" },\n },\n auth: { name: \"better-auth\", config: {} },\n },\n});\n```\n\nAdjust the providers to match your existing stack. See [Providers](/compiler/config/providers) for all options.\n\n### 3. Create Your First Feature\n\nCreate a feature directory with a schema + security definition:\n\n```bash\nmkdir quickback/features/candidates\n```\n\nCreate `quickback/features/candidates/candidates.ts`:\n\n```typescript\n\nexport const candidates = sqliteTable(\"candidates\", {\n id: text(\"id\").primaryKey(),\n name: text(\"name\").notNull(),\n email: text(\"email\").notNull(),\n phone: text(\"phone\"),\n source: text(\"source\"),\n organizationId: text(\"organization_id\").notNull(),\n});\n\nexport default defineTable(candidates, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"name\", \"email\", \"phone\", \"source\"],\n updatable: [\"name\", \"phone\"],\n },\n masking: {\n email: { type: \"email\", show: { roles: [\"hiring-manager\", \"recruiter\"] } },\n phone: { type: \"phone\", show: { roles: [\"hiring-manager\", \"recruiter\"] } },\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] }, mode: \"soft\" },\n});\n```\n\n### 4. Log In and Compile\n\n```bash\nquickback login\nquickback compile\n```\n\nThe compiler generates a complete `src/` directory with route handlers, middleware, database schemas, and migrations.\n\n### 5. Integrate with Your Existing Code\n\nThe compiled output creates a self-contained Hono app in `src/index.ts`. If you need to integrate the generated routes into an existing Hono app, you can import the feature routes directly:\n\n```typescript\n\nconst app = new Hono();\n\n// Your existing routes\napp.get(\"/\", (c) => c.json({ status: \"ok\" }));\n\n// Mount generated feature routes\napp.route(\"/api/v1/candidates\", candidatesRoutes);\n\nexport default app;\n```\n\n## Directory Structure\n\nThe compiler expects this structure inside `quickback/`:\n\n```\nquickback/\n├── quickback.config.ts # Required: compiler configuration\n└── features/ # Required: feature definitions\n ├── candidates/\n │ ├── candidates.ts # Schema + security (defineTable)\n │ └── actions.ts # Optional: custom actions\n ├── jobs/\n │ ├── jobs.ts\n │ └── actions.ts\n └── ...\n```\n\nEach feature directory should contain:\n- **`{name}.ts`** — The main definition file using `defineTable()` (required)\n- **`actions.ts`** — Custom actions using `defineActions()` (optional)\n\n## Adding Features\n\nTo add a new feature, create a new directory under `quickback/features/` and recompile:\n\n```bash\nmkdir quickback/features/jobs\n# Create jobs/jobs.ts with defineTable(...)\nquickback compile\n```\n\nThe compiler detects all features automatically — no registration needed.\n\n## Recompiling\n\nAfter any change to your definitions, recompile to regenerate the output:\n\n```bash\nquickback compile\n```\n\nThe compiler regenerates the entire `src/` directory. Your definitions in `quickback/` are the source of truth — never edit the generated files directly.\n\n**Warning:** Don't edit files in `src/` manually. They will be overwritten on the next compile. All changes should be made in your `quickback/` definitions.\n\n## Next Steps\n\n- [Configuration reference](/compiler/config) — All config options\n- [Schema definitions](/compiler/definitions/schema) — Define tables with `defineTable()`\n- [Security pillars](/compiler/definitions) — Firewall, Access, Guards, Masking\n- [Templates](/compiler/getting-started/templates) — Use a template for new projects instead"
174
+ "content": "If you have an existing project and want to add Quickback-generated API endpoints, you can set up the definitions directory manually instead of using a template.\n\n## Prerequisites\n\n- An existing Hono-based project (Cloudflare Workers or Bun)\n- Node.js 18+ or Bun installed\n- The Quickback CLI: `npm install -g @quickback-dev/cli`\n\n## Setup\n\n### 1. Create the Quickback Directory\n\nCreate a `quickback/` directory in your project root with the following structure:\n\n```\nyour-project/\n├── quickback/\n│ ├── quickback.config.ts\n│ └── features/\n│ └── (your features go here)\n├── src/ # Your existing code\n├── package.json\n└── ...\n```\n\n```bash\nmkdir -p quickback/features\n```\n\n### 2. Write Your Config\n\nCreate `quickback/quickback.config.ts`:\n\n```typescript\n\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n features: {\n organizations: true,\n },\n auth: {\n // Required for \"+\" role expansion in access rules (e.g. roles: [\"member+\"]).\n // Lowest → highest. Omit if you always list roles explicitly.\n roleHierarchy: [\"member\", \"admin\", \"owner\"],\n },\n providers: {\n runtime: { name: \"cloudflare\", config: {} },\n database: {\n name: \"cloudflare-d1\",\n config: { binding: \"DB\" },\n },\n auth: { name: \"better-auth\", config: {} },\n },\n});\n```\n\nAdjust the providers to match your existing stack. See [Providers](/compiler/config/providers) for all options.\n\n### 3. Create Your First Feature\n\nCreate a feature directory with a schema + security definition:\n\n```bash\nmkdir quickback/features/candidates\n```\n\nCreate `quickback/features/candidates/candidates.ts`:\n\n```typescript\n\nexport const candidates = sqliteTable(\"candidates\", {\n id: text(\"id\").primaryKey(),\n name: text(\"name\").notNull(),\n email: text(\"email\").notNull(),\n phone: text(\"phone\"),\n source: text(\"source\"),\n organizationId: text(\"organization_id\").notNull(),\n});\n\nexport default defineTable(candidates, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"name\", \"email\", \"phone\", \"source\"],\n updatable: [\"name\", \"phone\"],\n },\n masking: {\n email: { type: \"email\", show: { roles: [\"hiring-manager\", \"recruiter\"] } },\n phone: { type: \"phone\", show: { roles: [\"hiring-manager\", \"recruiter\"] } },\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] }, mode: \"soft\" },\n});\n```\n\n### 4. Log In and Compile\n\n```bash\nquickback login\nquickback compile\n```\n\nThe compiler generates a complete `src/` directory with route handlers, middleware, database schemas, and migrations.\n\n### 5. Integrate with Your Existing Code\n\nThe compiled output creates a self-contained Hono app in `src/index.ts`. If you need to integrate the generated routes into an existing Hono app, you can import the feature routes directly:\n\n```typescript\n\nconst app = new Hono();\n\n// Your existing routes\napp.get(\"/\", (c) => c.json({ status: \"ok\" }));\n\n// Mount generated feature routes\napp.route(\"/api/v1/candidates\", candidatesRoutes);\n\nexport default app;\n```\n\n## Directory Structure\n\nThe compiler expects this structure inside `quickback/`:\n\n```\nquickback/\n├── quickback.config.ts # Required: compiler configuration\n└── features/ # Required: feature definitions\n ├── candidates/\n │ ├── candidates.ts # Schema + security (defineTable)\n │ └── actions.ts # Optional: custom actions\n ├── jobs/\n │ ├── jobs.ts\n │ └── actions.ts\n └── ...\n```\n\nEach feature directory should contain:\n- **`{name}.ts`** — The main definition file using `defineTable()` (required)\n- **`actions.ts`** — Custom actions using `defineActions()` (optional)\n\n## Adding Features\n\nTo add a new feature, create a new directory under `quickback/features/` and recompile:\n\n```bash\nmkdir quickback/features/jobs\n# Create jobs/jobs.ts with defineTable(...)\nquickback compile\n```\n\nThe compiler detects all features automatically — no registration needed.\n\n## Recompiling\n\nAfter any change to your definitions, recompile to regenerate the output:\n\n```bash\nquickback compile\n```\n\nThe compiler regenerates the entire `src/` directory. Your definitions in `quickback/` are the source of truth — never edit the generated files directly.\n\n**Warning:** Don't edit files in `src/` manually. They will be overwritten on the next compile. All changes should be made in your `quickback/` definitions.\n\n## Next Steps\n\n- [Configuration reference](/compiler/config) — All config options\n- [Schema definitions](/compiler/definitions/schema) — Define tables with `defineTable()`\n- [Security pillars](/compiler/definitions) — Firewall, Access, Guards, Masking\n- [Templates](/compiler/getting-started/templates) — Use a template for new projects instead"
171
175
  },
172
176
  "compiler/getting-started": {
173
177
  "title": "Getting Started",
@@ -175,7 +179,7 @@ export const DOCS = {
175
179
  },
176
180
  "compiler/getting-started/patterns": {
177
181
  "title": "Common Patterns",
178
- "content": "Quick recipes for common scenarios. Each pattern shows the complete `defineTable` configuration.\n\n## Team-Wide Read, Manager-Only Write\n\nA job board where all team members can browse open positions but only hiring managers can create or edit jobs:\n\n```typescript\n// quickback/features/jobs/jobs.ts\nexport default defineTable(jobs, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"title\", \"department\", \"status\", \"salaryMin\", \"salaryMax\"],\n updatable: [\"title\", \"department\", \"status\"],\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n});\n```\n\n## User-Scoped Personal Data\n\nInterview notes that belong to a specific interviewer. Each interviewer only sees their own notes:\n\n```typescript\n// Schema includes both organizationId AND ownerId (q DSL)\n\nexport const interviewNotes = q.table(\"interview_notes\", {\n id: q.id(),\n candidateId: q.text().required(),\n content: q.text().required(),\n rating: q.int().optional(),\n organizationId: q.scope(\"organization\"),\n ownerId: q.text().required(),\n});\n\nexport default defineTable(interviewNotes, {\n firewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'ownerId', equals: 'ctx.userId' }, // Only the interviewer can see their own notes\n ],\n guards: {\n createable: [\"candidateId\", \"content\", \"rating\"],\n updatable: [\"content\", \"rating\"],\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] } },\n});\n```\n\nThe owner predicate (`{ field: 'ownerId', equals: 'ctx.userId' }`) means even hiring managers can only see notes they authored. To let hiring managers see all notes regardless of author, drop the owner predicate from the firewall and gate per-id access via record conditions instead.\n\n## Multi-Table Feature with Internal Tables\n\nA feature with a main table exposed via API and a junction table used only in actions:\n\n```typescript\n// quickback/features/applications/applications.ts — exposed via API\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"candidateId\", \"jobId\", \"stage\", \"notes\"],\n updatable: [\"notes\"],\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n});\n```\n\n```typescript\n// quickback/features/applications/interview-scores.ts — internal, no API routes\n// No default export = no routes generated\nexport const interviewScores = sqliteTable(\"interview_scores\", {\n applicationId: text(\"application_id\").notNull(),\n interviewerId: text(\"interviewer_id\").notNull(),\n score: integer(\"score\").notNull(),\n feedback: text(\"feedback\"),\n organizationId: text(\"organization_id\").notNull(), // Always scope junction tables\n});\n```\n\n```typescript\n// quickback/features/applications/actions.ts — uses the internal table\n\nexport default defineActions(applications, {\n // No `path:` → record-based action, mounted at POST /applications/:id/submitScore\n submitScore: {\n input: z.object({ score: z.number().min(1).max(5), feedback: z.string() }),\n access: { roles: [\"owner\", \"hiring-manager\", \"interviewer\"] },\n execute: async ({ db, record, input, ctx }) => {\n // The scoped db auto-injects organizationId (and audit fields) on insert.\n await db.insert(interviewScores).values({\n applicationId: record.id,\n interviewerId: ctx.userId,\n score: input.score,\n feedback: input.feedback,\n });\n return record;\n },\n },\n});\n```\n\n## Referencing Users / Org Members (Assignees)\n\nAssignee-style features need to validate that a submitted `userId` is actually a member of the caller's organization. The scoped `db` only sees feature tables — reach the Better Auth tables via `c.get(\"authDb\")` and the generated `getOrgMemberRole` helper:\n\n```typescript\n// quickback/features/projects/actions/assign.ts\n\nexport default defineAction({\n description: \"Assign a project to an org member\",\n input: z.object({ assigneeId: z.string() }),\n access: { roles: [\"member+\"] },\n async execute({ db, record, input, ctx, c, whereRecord }) {\n const role = await getOrgMemberRole(c.get(\"authDb\"), input.assigneeId, ctx.activeOrgId!);\n if (!role) {\n throw new ActionError(\"Assignee is not a member of this organization\", \"NOT_A_MEMBER\", 400);\n }\n const [updated] = await db\n .update(projects)\n .set({ assigneeId: input.assigneeId })\n .where(whereRecord!(projects))\n .returning();\n return updated;\n },\n});\n```\n\nStore the assignee as a plain text column (e.g. `assigneeId: q.text().optional()`) — don't name it `userId`, which the firewall validator treats as an ownership column on feature tables.\n\n## Admin-Only Status Field\n\nA field that only hiring managers can modify, but everyone can see:\n\n```typescript\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"candidateId\", \"jobId\", \"notes\"],\n updatable: [\"notes\"], // Recruiters can only update notes\n protected: { stage: [\"advanceStage\"] }, // Stage only changes via the named action\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"hiring-manager\"] } },\n});\n```\n\nThen create an action that hiring managers use to change stage:\n\n```typescript\n// quickback/features/applications/actions.ts\nexport default defineActions(applications, {\n advanceStage: {\n input: z.object({ stage: z.enum([\"applied\", \"screening\", \"interview\", \"offer\", \"hired\", \"rejected\"]) }),\n access: { roles: [\"hiring-manager\"] },\n execute: async ({ db, record, input }) => {\n await db.update(applications).set({ stage: input.stage }).where(eq(applications.id, record.id));\n return { ...record, stage: input.stage };\n },\n },\n});\n```\n\n## Sensitive Data with Role-Based Masking\n\nA candidate record where PII is masked differently per role:\n\n```typescript\nexport default defineTable(candidates, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"name\", \"email\", \"phone\", \"resumeUrl\", \"source\"],\n updatable: [\"name\", \"phone\"],\n },\n masking: {\n email: { type: \"email\", show: { roles: [\"hiring-manager\", \"recruiter\"] } },\n phone: { type: \"phone\", show: { roles: [\"hiring-manager\", \"recruiter\"] } },\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"hiring-manager\"] } },\n});\n```\n\n| Role | email | phone |\n|------|-------|-------|\n| hiring-manager | `jane@example.com` | `555-123-4567` |\n| recruiter | `jane@example.com` | `555-123-4567` |\n| interviewer | `j***@e******.com` | `***-***-4567` |\n\n## External System Sync\n\nAn import table for syncing candidates from an external ATS via upsert:\n\n```typescript\n// quickback/features/ats-imports/ats-imports.ts\nexport default defineTable(atsImports, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"externalId\", \"source\", \"candidateName\", \"candidateEmail\", \"rawPayload\"],\n updatable: [\"candidateName\", \"candidateEmail\", \"rawPayload\", \"syncedAt\"],\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n delete: { access: { roles: [\"owner\"] } },\n});\n```\n\n## See Also\n\n- [Full Example](/compiler/getting-started/full-example) — Complete walkthrough with generated code\n- [Firewall](/compiler/definitions/firewall) — All data isolation options\n- [Actions](/compiler/definitions/actions) — Custom business logic"
182
+ "content": "Quick recipes for common scenarios. Each pattern shows the complete `defineTable` configuration.\n\n## Team-Wide Read, Manager-Only Write\n\nA job board where all team members can browse open positions but only hiring managers can create or edit jobs:\n\n```typescript\n// quickback/features/jobs/jobs.ts\nexport default defineTable(jobs, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"title\", \"department\", \"status\", \"salaryMin\", \"salaryMax\"],\n updatable: [\"title\", \"department\", \"status\"],\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n});\n```\n\n## User-Scoped Personal Data\n\nInterview notes that belong to a specific interviewer. Each interviewer only sees their own notes:\n\n```typescript\n// Schema includes both organizationId AND ownerId (q DSL)\n\nexport const interviewNotes = q.table(\"interview_notes\", {\n id: q.id(),\n candidateId: q.text().required(),\n content: q.text().required(),\n rating: q.int().optional(),\n organizationId: q.scope(\"organization\"),\n ownerId: q.text().required(),\n});\n\nexport default defineTable(interviewNotes, {\n firewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'ownerId', equals: 'ctx.userId' }, // Only the interviewer can see their own notes\n ],\n guards: {\n createable: [\"candidateId\", \"content\", \"rating\"],\n updatable: [\"content\", \"rating\"],\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] } },\n});\n```\n\nThe owner predicate (`{ field: 'ownerId', equals: 'ctx.userId' }`) means even hiring managers can only see notes they authored. To let hiring managers see all notes regardless of author, drop the owner predicate from the firewall and gate per-id access via record conditions instead.\n\n## Multi-Table Feature with Internal Tables\n\nA feature with a main table exposed via API and a junction table used only in actions:\n\n```typescript\n// quickback/features/applications/applications.ts — exposed via API\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"candidateId\", \"jobId\", \"stage\", \"notes\"],\n updatable: [\"notes\"],\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n});\n```\n\n```typescript\n// quickback/features/applications/interview-scores.ts — internal, no API routes\n// No default export = no routes generated\nexport const interviewScores = sqliteTable(\"interview_scores\", {\n applicationId: text(\"application_id\").notNull(),\n interviewerId: text(\"interviewer_id\").notNull(),\n score: integer(\"score\").notNull(),\n feedback: text(\"feedback\"),\n organizationId: text(\"organization_id\").notNull(), // Always scope junction tables\n});\n```\n\n```typescript\n// quickback/features/applications/actions.ts — uses the internal table\n\nexport default defineActions(applications, {\n // No `path:` → record-based action, mounted at POST /applications/:id/submitScore\n submitScore: {\n input: z.object({ score: z.number().min(1).max(5), feedback: z.string() }),\n access: { roles: [\"owner\", \"hiring-manager\", \"interviewer\"] },\n execute: async ({ db, record, input, ctx }) => {\n // The scoped db auto-injects organizationId (and audit fields) on insert.\n await db.insert(interviewScores).values({\n applicationId: record.id,\n interviewerId: ctx.userId,\n score: input.score,\n feedback: input.feedback,\n });\n return record;\n },\n },\n});\n```\n\n## Referencing Users / Org Members (Assignees)\n\nAssignee-style features need to validate that a submitted `userId` is actually a member of the caller's organization. The scoped `db` only sees feature tables — reach the Better Auth tables via `c.get(\"authDb\")` and the generated `getOrgMemberRole` helper:\n\n```typescript\n// quickback/features/projects/actions/assign.ts\n\nexport default defineAction({\n description: \"Assign a project to an org member\",\n input: z.object({ assigneeId: z.string() }),\n access: { roles: [\"member+\"] }, // \"+\" requires auth.roleHierarchy in quickback.config.ts\n async execute({ db, record, input, ctx, c, whereRecord }) {\n const role = await getOrgMemberRole(c.get(\"authDb\"), input.assigneeId, ctx.activeOrgId!);\n if (!role) {\n throw new ActionError(\"Assignee is not a member of this organization\", \"NOT_A_MEMBER\", 400);\n }\n const [updated] = await db\n .update(projects)\n .set({ assigneeId: input.assigneeId })\n .where(whereRecord!(projects))\n .returning();\n return updated;\n },\n});\n```\n\nStore the assignee as a plain text column (e.g. `assigneeId: q.text().optional()`) — don't name it `userId`, which the firewall validator treats as an ownership column on feature tables.\n\n## Admin-Only Status Field\n\nA field that only hiring managers can modify, but everyone can see:\n\n```typescript\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"candidateId\", \"jobId\", \"notes\"],\n updatable: [\"notes\"], // Recruiters can only update notes\n protected: { stage: [\"advanceStage\"] }, // Stage only changes via the named action\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"hiring-manager\"] } },\n});\n```\n\nThen create an action that hiring managers use to change stage:\n\n```typescript\n// quickback/features/applications/actions.ts\nexport default defineActions(applications, {\n advanceStage: {\n input: z.object({ stage: z.enum([\"applied\", \"screening\", \"interview\", \"offer\", \"hired\", \"rejected\"]) }),\n access: { roles: [\"hiring-manager\"] },\n execute: async ({ db, record, input }) => {\n await db.update(applications).set({ stage: input.stage }).where(eq(applications.id, record.id));\n return { ...record, stage: input.stage };\n },\n },\n});\n```\n\n## Sensitive Data with Role-Based Masking\n\nA candidate record where PII is masked differently per role:\n\n```typescript\nexport default defineTable(candidates, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"name\", \"email\", \"phone\", \"resumeUrl\", \"source\"],\n updatable: [\"name\", \"phone\"],\n },\n masking: {\n email: { type: \"email\", show: { roles: [\"hiring-manager\", \"recruiter\"] } },\n phone: { type: \"phone\", show: { roles: [\"hiring-manager\", \"recruiter\"] } },\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"hiring-manager\"] } },\n});\n```\n\n| Role | email | phone |\n|------|-------|-------|\n| hiring-manager | `jane@example.com` | `555-123-4567` |\n| recruiter | `jane@example.com` | `555-123-4567` |\n| interviewer | `j***@e******.com` | `***-***-4567` |\n\n## External System Sync\n\nAn import table for syncing candidates from an external ATS via upsert:\n\n```typescript\n// quickback/features/ats-imports/ats-imports.ts\nexport default defineTable(atsImports, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"externalId\", \"source\", \"candidateName\", \"candidateEmail\", \"rawPayload\"],\n updatable: [\"candidateName\", \"candidateEmail\", \"rawPayload\", \"syncedAt\"],\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n delete: { access: { roles: [\"owner\"] } },\n});\n```\n\n## See Also\n\n- [Full Example](/compiler/getting-started/full-example) — Complete walkthrough with generated code\n- [Firewall](/compiler/definitions/firewall) — All data isolation options\n- [Actions](/compiler/definitions/actions) — Custom business logic"
179
183
  },
180
184
  "compiler/getting-started/template-blog": {
181
185
  "title": "Blog Template",
@@ -211,7 +215,7 @@ export const DOCS = {
211
215
  },
212
216
  "compiler/targets/hono-api/database/neon": {
213
217
  "title": "Neon",
214
- "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.query.registrations.findFirst({\n where: eq(registrations.id, input.registrationId),\n lock: \"for update\", // row lock held to commit\n });\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\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 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"
215
219
  },
216
220
  "compiler/targets/hono-api/database/using-d1": {
217
221
  "title": "Using D1",
@@ -239,7 +243,7 @@ export const DOCS = {
239
243
  },
240
244
  "compiler/targets/hono-api/using-the-api/errors": {
241
245
  "title": "Errors",
242
- "content": "The generated API returns structured error responses with consistent fields across all security layers.\n\n## Status Codes\n\n| Code | Meaning | When |\n|------|---------|------|\n| `200` | OK | Successful GET, PATCH, DELETE |\n| `201` | Created | Successful POST |\n| `207` | Multi-Status | Batch operation with mixed results |\n| `400` | Bad Request | Guard violation, validation error, invalid input |\n| `401` | Unauthorized | Missing or expired authentication |\n| `403` | Forbidden | Access denied (wrong role, condition failed) or firewall blocked it |\n| `404` | Not Found | Record doesn't exist (or firewall blocked with `errorMode: 'hide'`) |\n| `429` | Too Many Requests | Rate limit exceeded |\n\n## Error Response Format\n\nAll errors use a flat structure with contextual fields. Every structured error response also carries a `request` block with the HTTP method, URL, request ID, and a redacted+truncated copy of the request body — enough to triage or hand the response to an LLM agent without grepping logs:\n\n```json\n{\n \"error\": \"Insufficient permissions\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ROLE_REQUIRED\",\n \"details\": {\n \"required\": [\"hiring-manager\"],\n \"current\": [\"interviewer\"]\n },\n \"hint\": \"Contact an administrator to grant necessary permissions\",\n \"request\": {\n \"method\": \"POST\",\n \"url\": \"/api/v1/candidates/cnd_01H.../advance\",\n \"body\": \"{\\\"stage\\\":\\\"offer\\\"}\",\n \"requestId\": \"0c4f2c9e-...\"\n }\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `error` | string | Human-readable error message |\n| `layer` | string | Security layer that rejected the request |\n| `code` | string | Machine-readable error code |\n| `details` | object | Layer-specific context (optional) |\n| `hint` | string | Actionable guidance for resolution (optional) |\n| `request` | object | Method, URL, redacted body, and request ID. Auto-attached by the runtime so the error body is self-contained — bodies are capped at 4 KB and well-known sensitive keys (`password`, `token`, `secret`, `apiKey`, `otp`, `code`, `authorization`, …) are replaced with `\"[REDACTED]\"` |\n\n## Errors by Security Layer\n\n### Authentication (401)\n\nMissing or invalid authentication tokens.\n\n```json\n{\n \"error\": \"Authentication required\",\n \"layer\": \"authentication\",\n \"code\": \"AUTH_MISSING\",\n \"hint\": \"Include Authorization header with Bearer token\"\n}\n```\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `AUTH_MISSING` | No Authorization header provided |\n| `AUTH_INVALID_TOKEN` | Token is malformed or invalid |\n| `AUTH_EXPIRED` | Token has expired |\n| `AUTH_RATE_LIMITED` | Too many auth attempts |\n\n### Firewall (403)\n\nRecords outside the user's firewall scope return **403 Forbidden** by default with a structured error:\n\n```json\n{\n \"error\": \"Record not found or not accessible\",\n \"layer\": \"firewall\",\n \"code\": \"FIREWALL_NOT_FOUND\",\n \"hint\": \"Check the record ID and your organization membership\"\n}\n```\n\nFirewall filtering is transparent — the query is scoped by `WHERE organizationId = ?` so inaccessible records simply don't appear in results.\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `FIREWALL_NOT_FOUND` | Record not found behind firewall (wrong org, soft-deleted, or doesn't exist) |\n| `FIREWALL_ORG_ISOLATION` | Record belongs to a different organization |\n| `FIREWALL_USER_ISOLATION` | Record belongs to another user |\n| `FIREWALL_SOFT_DELETED` | Record has been soft deleted |\n\nFor security-hardened deployments, set `errorMode: 'hide'` in your firewall config to return opaque **404 Not Found** responses instead. This prevents attackers from distinguishing between \"record exists but you can't access it\" and \"record doesn't exist\".\n\n### Access (403)\n\nAccess violations return **403 Forbidden** when the user's role doesn't match the required roles for the operation.\n\n```json\n{\n \"error\": \"Insufficient permissions\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ROLE_REQUIRED\",\n \"details\": {\n \"required\": [\"hiring-manager\"],\n \"current\": [\"interviewer\"]\n },\n \"hint\": \"Contact an administrator to grant necessary permissions\"\n}\n```\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `ACCESS_ROLE_REQUIRED` | User doesn't have the required role |\n| `ACCESS_CONDITION_FAILED` | Record-level access condition not met |\n| `ACCESS_OWNERSHIP_REQUIRED` | User must own the record |\n| `ACCESS_NO_ORG` | No active organization set |\n\n### Guards (400)\n\nGuard violations return **400 Bad Request** when the request body contains fields that aren't allowed.\n\n```json\n{\n \"error\": \"Field cannot be set during creation\",\n \"layer\": \"guards\",\n \"code\": \"GUARD_FIELD_NOT_CREATEABLE\",\n \"details\": {\n \"fields\": [\"stage\"]\n },\n \"hint\": \"These fields are set automatically or must be omitted\"\n}\n```\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `GUARD_FIELD_NOT_CREATEABLE` | Field not in `createable` list |\n| `GUARD_FIELD_NOT_UPDATABLE` | Field not in `updatable` list |\n| `GUARD_FIELD_PROTECTED` | Field is action-only (protected) |\n| `GUARD_FIELD_IMMUTABLE` | Field cannot be modified after creation |\n| `GUARD_SYSTEM_MANAGED` | System field (createdAt, modifiedAt, etc.) |\n\n### Masking\n\nMasking doesn't produce errors — it silently transforms field values in the response.\n\n### Database\n\nSurfaced when a SQL write fails *post-validation* — most often a `NOT NULL` or `UNIQUE` constraint hit at the storage layer (e.g. an FK target was deleted concurrently, or a unique column collided with another tenant's row). All four codes share the same `layer: \"database\"` so consumers can switch on the layer alone and treat the rest as one bucket.\n\n```json\n{\n \"error\": \"Duplicate value\",\n \"layer\": \"database\",\n \"code\": \"DB_UNIQUE_VIOLATION\",\n \"details\": { \"column\": \"email\" },\n \"hint\": \"A record with this \\\"email\\\" already exists\"\n}\n```\n\n**Error codes:**\n\n| Code | Status | Description |\n|------|--------|-------------|\n| `DB_NOT_NULL_VIOLATION` | 400 | Required column was null at write time |\n| `DB_UNIQUE_VIOLATION` | 409 | Unique constraint hit |\n| `DB_INSERT_FAILED` | 500 | INSERT failed for an unrecognized reason |\n| `DB_UPDATE_FAILED` | 500 | UPDATE failed for an unrecognized reason |\n\nThe `details.column` field is only present when the driver's error message identified the offending column (SQLite/D1 do; some PG variants don't).\n\n## Batch Errors\n\nBatch operations can return:\n- **201** — All records succeeded\n- **207** — Partial success (some records failed)\n- **400** — Atomic mode and at least one record failed (all rolled back)\n\n### Partial Success (207)\n\n```json\n{\n \"success\": [{ \"id\": \"app_1\", \"candidateId\": \"cand_101\", \"stage\": \"applied\" }],\n \"errors\": [\n {\n \"index\": 1,\n \"record\": { \"candidateId\": \"cand_102\", \"jobId\": \"job_201\", \"stage\": \"interview\" },\n \"error\": {\n \"error\": \"Field cannot be set during creation\",\n \"layer\": \"guards\",\n \"code\": \"GUARD_FIELD_NOT_CREATEABLE\",\n \"details\": { \"fields\": [\"stage\"] },\n \"hint\": \"These fields are set automatically or must be omitted\"\n }\n }\n ],\n \"meta\": { \"total\": 2, \"succeeded\": 1, \"failed\": 1, \"atomic\": false }\n}\n```\n\n### Atomic Failure (400)\n\n```json\n{\n \"error\": \"Batch operation failed in atomic mode\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_ATOMIC_FAILED\",\n \"details\": {\n \"failedAt\": 2,\n \"reason\": { \"error\": \"Not found\", \"code\": \"NOT_FOUND\" }\n },\n \"hint\": \"Transaction rolled back. Fix the error and retry the entire batch.\"\n}\n```\n\n**Batch error codes:**\n\n| Code | Description |\n|------|-------------|\n| `BATCH_SIZE_EXCEEDED` | Too many records in a single request |\n| `BATCH_ATOMIC_FAILED` | Atomic batch failed, all changes rolled back |\n| `BATCH_MISSING_IDS` | Batch update/delete missing required IDs |\n\n## Action Failures (500)\n\nWhen an action's `execute()` body throws something that isn't a known\ntransition / state / FK / constraint failure (e.g. a `TypeError`, a\nfetch timeout, a third-party API error), the route returns\n`ACTION_EXECUTION_FAILED`. The body forwards as much of the underlying\nerror as is safe to expose: error class name, message, cause-chain\nmessage, and the top three stack frames with absolute paths sanitized\nto basename + line number.\n\n```json\n{\n \"error\": \"Cannot read properties of undefined (reading 'getXmlFragment')\",\n \"layer\": \"action\",\n \"code\": \"ACTION_EXECUTION_FAILED\",\n \"details\": {\n \"name\": \"TypeError\",\n \"frames\": [\n \"at updateContent (notebooks.ts:142:31)\",\n \"at execute (actions.ts:88:7)\"\n ]\n },\n \"hint\": \"The action handler threw an unhandled error. Check server logs for the underlying cause.\",\n \"request\": {\n \"method\": \"POST\",\n \"url\": \"/api/v1/notebooks/nb_123/updateContent\",\n \"body\": \"{\\\"content\\\":\\\"...\\\"}\",\n \"requestId\": \"0c4f2c9e-...\"\n }\n}\n```\n\n## Internal Errors (500)\n\nUncaught throws that escape every route handler land in the global\n`onError` and return `INTERNAL_ERROR`. The body carries the same\nunderlying-error context as `ACTION_EXECUTION_FAILED`: `name`, `cause`,\nsanitized `frames`, and the request block.\n\n```json\n{\n \"error\": \"Connection terminated unexpectedly\",\n \"layer\": \"database\",\n \"code\": \"INTERNAL_ERROR\",\n \"details\": {\n \"name\": \"Error\",\n \"cause\": \"ECONNRESET\",\n \"frames\": [\"at query (db.ts:54:12)\"]\n },\n \"hint\": \"Uncaught error during request handling. Look up the requestId in server logs for the full stack trace, or set EXPOSE_ERROR_STACK=1 to include it inline.\",\n \"requestId\": \"0c4f2c9e-...\",\n \"request\": {\n \"method\": \"GET\",\n \"url\": \"/api/v1/jobs\",\n \"requestId\": \"0c4f2c9e-...\"\n }\n}\n```\n\n### Exposing the full stack\n\nBy default the response body only carries the top three sanitized\nframes — full stack traces stay server-side so the worker bundle's\non-disk layout doesn't leak to API clients. To include the full stack\nin the response (useful in dev / staging), set `EXPOSE_ERROR_STACK=1`\non the worker (`wrangler.toml` `[vars]`, or `wrangler secret put`):\n\n```toml\n[vars]\nEXPOSE_ERROR_STACK = \"1\"\n```\n\nWhen set, both the global 500 and `ACTION_EXECUTION_FAILED` bodies\ngain a `details.stack` field with the unsanitized stack trace."
246
+ "content": "The generated API returns structured error responses with consistent fields across all security layers.\n\n## Status Codes\n\n| Code | Meaning | When |\n|------|---------|------|\n| `200` | OK | Successful GET, PATCH, DELETE |\n| `201` | Created | Successful POST |\n| `207` | Multi-Status | Batch operation with mixed results |\n| `400` | Bad Request | Guard violation, validation error, invalid input |\n| `401` | Unauthorized | Missing or expired authentication |\n| `403` | Forbidden | Access denied (wrong role, condition failed) or firewall blocked it |\n| `404` | Not Found | Record doesn't exist (or firewall blocked with `errorMode: 'hide'`) |\n| `429` | Too Many Requests | Rate limit exceeded |\n\n## Error Response Format\n\nAll errors use a flat structure with contextual fields. Every structured error response also carries a `request` block with the HTTP method, URL, request ID, and a redacted+truncated copy of the request body — enough to triage or hand the response to an LLM agent without grepping logs:\n\n```json\n{\n \"error\": \"Insufficient permissions\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ROLE_REQUIRED\",\n \"details\": {\n \"required\": [\"hiring-manager\"],\n \"current\": [\"interviewer\"]\n },\n \"hint\": \"Contact an administrator to grant necessary permissions\",\n \"request\": {\n \"method\": \"POST\",\n \"url\": \"/api/v1/candidates/cnd_01H.../advance\",\n \"body\": \"{\\\"stage\\\":\\\"offer\\\"}\",\n \"requestId\": \"0c4f2c9e-...\"\n }\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `error` | string | Human-readable error message |\n| `layer` | string | Security layer that rejected the request |\n| `code` | string | Machine-readable error code |\n| `details` | object | Layer-specific context (optional) |\n| `hint` | string | Actionable guidance for resolution (optional) |\n| `request` | object | Method, URL, redacted body, and request ID. Auto-attached by the runtime so the error body is self-contained — bodies are capped at 4 KB and well-known sensitive keys (`password`, `token`, `secret`, `apiKey`, `otp`, `code`, `authorization`, …) are replaced with `\"[REDACTED]\"` |\n\n## Errors by Security Layer\n\n### Authentication (401)\n\nMissing or invalid authentication tokens.\n\n```json\n{\n \"error\": \"Authentication required\",\n \"layer\": \"authentication\",\n \"code\": \"AUTH_MISSING\",\n \"hint\": \"Include Authorization header with Bearer token\"\n}\n```\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `AUTH_MISSING` | No Authorization header provided |\n| `AUTH_INVALID_TOKEN` | Token is malformed or invalid |\n| `AUTH_EXPIRED` | Token has expired |\n| `AUTH_RATE_LIMITED` | Too many auth attempts |\n| `AUTH_SESSION_REQUIRED` | The endpoint requires session (cookie) authentication — returned by `POST /api/v1/token` when called with a JWT, API key, or OAuth bearer, so a stolen or revoked token can't mint its own replacement |\n\n### Firewall (403)\n\nRecords outside the user's firewall scope return **403 Forbidden** by default with a structured error:\n\n```json\n{\n \"error\": \"Record not found or not accessible\",\n \"layer\": \"firewall\",\n \"code\": \"FIREWALL_NOT_FOUND\",\n \"hint\": \"Check the record ID and your organization membership\"\n}\n```\n\nFirewall filtering is transparent — the query is scoped by `WHERE organizationId = ?` so inaccessible records simply don't appear in results.\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `FIREWALL_NOT_FOUND` | Record not found behind firewall (wrong org, soft-deleted, or doesn't exist) |\n| `FIREWALL_ORG_ISOLATION` | Record belongs to a different organization |\n| `FIREWALL_USER_ISOLATION` | Record belongs to another user |\n| `FIREWALL_SOFT_DELETED` | Record has been soft deleted |\n\nFor security-hardened deployments, set `errorMode: 'hide'` in your firewall config to return opaque **404 Not Found** responses instead. This prevents attackers from distinguishing between \"record exists but you can't access it\" and \"record doesn't exist\".\n\n### Access (403)\n\nAccess violations return **403 Forbidden** when the user's role doesn't match the required roles for the operation.\n\n```json\n{\n \"error\": \"Insufficient permissions\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ROLE_REQUIRED\",\n \"details\": {\n \"required\": [\"hiring-manager\"],\n \"current\": [\"interviewer\"]\n },\n \"hint\": \"Contact an administrator to grant necessary permissions\"\n}\n```\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `ACCESS_ROLE_REQUIRED` | User doesn't have the required role |\n| `ACCESS_CONDITION_FAILED` | Record-level access condition not met |\n| `ACCESS_OWNERSHIP_REQUIRED` | User must own the record |\n| `ACCESS_NO_ORG` | No active organization set |\n\n### Guards (400)\n\nGuard violations return **400 Bad Request** when the request body contains fields that aren't allowed.\n\n```json\n{\n \"error\": \"Field cannot be set during creation\",\n \"layer\": \"guards\",\n \"code\": \"GUARD_FIELD_NOT_CREATEABLE\",\n \"details\": {\n \"fields\": [\"stage\"]\n },\n \"hint\": \"These fields are set automatically or must be omitted\"\n}\n```\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `GUARD_FIELD_NOT_CREATEABLE` | Field not in `createable` list |\n| `GUARD_FIELD_NOT_UPDATABLE` | Field not in `updatable` list |\n| `GUARD_FIELD_PROTECTED` | Field is action-only (protected) |\n| `GUARD_FIELD_IMMUTABLE` | Field cannot be modified after creation |\n| `GUARD_SYSTEM_MANAGED` | System field (createdAt, modifiedAt, etc.) |\n\n### Masking\n\nMasking doesn't produce errors — it silently transforms field values in the response.\n\n### Database\n\nSurfaced when a SQL write fails *post-validation* — most often a `NOT NULL` or `UNIQUE` constraint hit at the storage layer (e.g. an FK target was deleted concurrently, or a unique column collided with another tenant's row). All four codes share the same `layer: \"database\"` so consumers can switch on the layer alone and treat the rest as one bucket.\n\n```json\n{\n \"error\": \"Duplicate value\",\n \"layer\": \"database\",\n \"code\": \"DB_UNIQUE_VIOLATION\",\n \"details\": { \"column\": \"email\" },\n \"hint\": \"A record with this \\\"email\\\" already exists\"\n}\n```\n\n**Error codes:**\n\n| Code | Status | Description |\n|------|--------|-------------|\n| `DB_NOT_NULL_VIOLATION` | 400 | Required column was null at write time |\n| `DB_UNIQUE_VIOLATION` | 409 | Unique constraint hit |\n| `DB_INSERT_FAILED` | 500 | INSERT failed for an unrecognized reason |\n| `DB_UPDATE_FAILED` | 500 | UPDATE failed for an unrecognized reason |\n\nThe `details.column` field is only present when the driver's error message identified the offending column (SQLite/D1 do; some PG variants don't).\n\n## Batch Errors\n\nBatch operations can return:\n- **201** — All records succeeded\n- **207** — Partial success (some records failed)\n- **400** — Atomic mode and at least one record failed (all rolled back)\n\n### Partial Success (207)\n\n```json\n{\n \"success\": [{ \"id\": \"app_1\", \"candidateId\": \"cand_101\", \"stage\": \"applied\" }],\n \"errors\": [\n {\n \"index\": 1,\n \"record\": { \"candidateId\": \"cand_102\", \"jobId\": \"job_201\", \"stage\": \"interview\" },\n \"error\": {\n \"error\": \"Field cannot be set during creation\",\n \"layer\": \"guards\",\n \"code\": \"GUARD_FIELD_NOT_CREATEABLE\",\n \"details\": { \"fields\": [\"stage\"] },\n \"hint\": \"These fields are set automatically or must be omitted\"\n }\n }\n ],\n \"meta\": { \"total\": 2, \"succeeded\": 1, \"failed\": 1, \"atomic\": false }\n}\n```\n\n### Atomic Failure (400)\n\n```json\n{\n \"error\": \"Batch operation failed in atomic mode\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_ATOMIC_FAILED\",\n \"details\": {\n \"failedAt\": 2,\n \"reason\": { \"error\": \"Not found\", \"code\": \"NOT_FOUND\" }\n },\n \"hint\": \"Transaction rolled back. Fix the error and retry the entire batch.\"\n}\n```\n\n**Batch error codes:**\n\n| Code | Description |\n|------|-------------|\n| `BATCH_SIZE_EXCEEDED` | Too many records in a single request |\n| `BATCH_ATOMIC_FAILED` | Atomic batch failed, all changes rolled back |\n| `BATCH_MISSING_IDS` | Batch update/delete missing required IDs |\n\n## Action Failures (500)\n\nWhen an action's `execute()` body throws something that isn't a known\ntransition / state / FK / constraint failure (e.g. a `TypeError`, a\nfetch timeout, a third-party API error), the route returns\n`ACTION_EXECUTION_FAILED`. The body forwards as much of the underlying\nerror as is safe to expose: error class name, message, cause-chain\nmessage, and the top three stack frames with absolute paths sanitized\nto basename + line number.\n\n```json\n{\n \"error\": \"Cannot read properties of undefined (reading 'getXmlFragment')\",\n \"layer\": \"action\",\n \"code\": \"ACTION_EXECUTION_FAILED\",\n \"details\": {\n \"name\": \"TypeError\",\n \"frames\": [\n \"at updateContent (notebooks.ts:142:31)\",\n \"at execute (actions.ts:88:7)\"\n ]\n },\n \"hint\": \"The action handler threw an unhandled error. Check server logs for the underlying cause.\",\n \"request\": {\n \"method\": \"POST\",\n \"url\": \"/api/v1/notebooks/nb_123/updateContent\",\n \"body\": \"{\\\"content\\\":\\\"...\\\"}\",\n \"requestId\": \"0c4f2c9e-...\"\n }\n}\n```\n\n## Internal Errors (500)\n\nUncaught throws that escape every route handler land in the global\n`onError` and return `INTERNAL_ERROR`. The body carries the same\nunderlying-error context as `ACTION_EXECUTION_FAILED`: `name`, `cause`,\nsanitized `frames`, and the request block.\n\n```json\n{\n \"error\": \"Connection terminated unexpectedly\",\n \"layer\": \"database\",\n \"code\": \"INTERNAL_ERROR\",\n \"details\": {\n \"name\": \"Error\",\n \"cause\": \"ECONNRESET\",\n \"frames\": [\"at query (db.ts:54:12)\"]\n },\n \"hint\": \"Uncaught error during request handling. Look up the requestId in server logs for the full stack trace, or set EXPOSE_ERROR_STACK=1 to include it inline.\",\n \"requestId\": \"0c4f2c9e-...\",\n \"request\": {\n \"method\": \"GET\",\n \"url\": \"/api/v1/jobs\",\n \"requestId\": \"0c4f2c9e-...\"\n }\n}\n```\n\n### Exposing the full stack\n\nBy default the response body only carries the top three sanitized\nframes — full stack traces stay server-side so the worker bundle's\non-disk layout doesn't leak to API clients. To include the full stack\nin the response (useful in dev / staging), set `EXPOSE_ERROR_STACK=1`\non the worker (`wrangler.toml` `[vars]`, or `wrangler secret put`):\n\n```toml\n[vars]\nEXPOSE_ERROR_STACK = \"1\"\n```\n\nWhen set, both the global 500 and `ACTION_EXECUTION_FAILED` bodies\ngain a `details.stack` field with the unsanitized stack trace."
243
247
  },
244
248
  "compiler/targets/hono-api/using-the-api": {
245
249
  "title": "Using the API",
@@ -323,7 +327,7 @@ export const DOCS = {
323
327
  },
324
328
  "stack/account-ui/with-quickback": {
325
329
  "title": "With Quickback",
326
- "content": "Account UI is part of the Quickback Stack. The compiler builds it from source and bundles it into your Worker — there is no separate npm package or standalone deploy path.\n\n## Compiler-Embedded\n\nAdd `account` to your `quickback.config.ts`:\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default {\n name: \"my-app\",\n template: \"hono\",\n account: {\n domain: \"auth.example.com\",\n name: \"My App\",\n companyName: \"My Company\",\n auth: {\n password: true,\n passkey: true,\n organizations: true,\n admin: true,\n },\n },\n // ...providers\n};\n```\n\nThen compile and deploy:\n\n```bash\nquickback compile\nnpx wrangler deploy\n```\n\n### What Happens During Compilation\n\n1. The compiler reads your `account` config and generates a `.env` file with the correct Vite environment variables (`VITE_QUICKBACK_URL`, `VITE_QUICKBACK_API_URL`, `VITE_ENABLE_PASSWORD`, branding, etc.)\n2. The Account SPA source is copied to a temp directory, with disabled feature routes excluded\n3. Pre-installed dependencies are symlinked (no `npm install` during build)\n4. Vite builds the SPA with your settings baked in\n5. Built assets (content-hashed filenames) are placed in the output directory\n\nWhen CMS is also enabled, Account assets go to `src/apps/account/` and are served at `/account/`. When Account is the only SPA, assets go to `src/apps/` and are served at root.\n\n### Custom Domains\n\nWith a custom domain, the Account SPA is served at root (`/`) on that domain:\n\n```typescript\naccount: { domain: \"auth.example.com\" }\n```\n\nAdd an admin domain to serve the admin panel on its own subdomain:\n\n```typescript\naccount: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n}\n```\n\nSee [Multi-Domain Architecture](/compiler/config/domains) for details on hostname routing and cross-subdomain cookies.\n\n### Auth Feature Flags\n\nFeature flags control which pages are included in the build:\n\n```typescript\nauth: {\n password: true, // Email/password login + inline password change\n emailOTP: false, // Email OTP login flow\n passkey: true, // WebAuthn passkey setup + management\n organizations: true, // Dashboard, org management, invitations\n admin: true, // Admin panel (user management)\n}\n```\n\nDisabled features are excluded at compile time — their route files are removed before the Vite build. See [Configuration](/compiler/config) for all options.\n\n## Next Steps\n\n- [Configuration](/compiler/config) — CMS and Account config reference\n- [Multi-Domain Architecture](/compiler/config/domains) — Custom domains and hostname routing\n- [Environment Variables](/stack/account-ui/environment-variables) — Complete variable reference\n- [Feature Flags](/stack/account-ui/features) — Enable and disable features\n- [Auth Hooks](/stack/account-ui/hooks) — Run project code on signup, login, and session events\n- [Customization](/stack/account-ui/customization) — Branding, labels, and theming"
330
+ "content": "Account UI is part of the Quickback Stack. The compiler builds it from source and bundles it into your Worker — there is no separate npm package or standalone deploy path.\n\n## Compiler-Embedded\n\nAdd `account` to your `quickback.config.ts`:\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default {\n name: \"my-app\",\n template: \"hono\",\n account: {\n domain: \"auth.example.com\",\n name: \"My App\",\n companyName: \"My Company\",\n auth: {\n password: true,\n passkey: true,\n organizations: true,\n admin: true,\n },\n },\n // ...providers\n};\n```\n\nThen compile and deploy:\n\n```bash\nquickback compile\nnpx wrangler deploy\n```\n\n### What Happens During Compilation\n\n1. The compiler reads your `account` config and generates a `.env` file with the correct Vite environment variables (`VITE_QUICKBACK_URL`, `VITE_QUICKBACK_API_URL`, `VITE_ENABLE_PASSWORD`, branding, etc.)\n2. The Account SPA source is copied to a temp directory, with disabled feature routes excluded\n3. Pre-installed dependencies are symlinked (no `npm install` during build)\n4. Vite builds the SPA with your settings baked in\n5. Built assets (content-hashed filenames) are placed in the output directory\n\nThe generated worker **also** injects the same per-project values into every served Account shell as `window.__QUICKBACK_RUNTIME` (URLs, branding, auth feature flags). The SPA prefers that runtime blob over the baked `VITE_*` values, so a generic (no-`.env`) Account build served by the worker behaves identically to the baked build — the bake remains a fallback for serving the assets outside a Quickback worker.\n\nWhen CMS is also enabled, Account assets go to `src/apps/account/` and are served at `/account/`. When Account is the only SPA, assets go to `src/apps/` and are served at root.\n\n### Custom Domains\n\nWith a custom domain, the Account SPA is served at root (`/`) on that domain:\n\n```typescript\naccount: { domain: \"auth.example.com\" }\n```\n\nAdd an admin domain to serve the admin panel on its own subdomain:\n\n```typescript\naccount: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n}\n```\n\nSee [Multi-Domain Architecture](/compiler/config/domains) for details on hostname routing and cross-subdomain cookies.\n\n### Auth Feature Flags\n\nFeature flags control which pages are included in the build:\n\n```typescript\nauth: {\n password: true, // Email/password login + inline password change\n emailOTP: false, // Email OTP login flow\n passkey: true, // WebAuthn passkey setup + management\n organizations: true, // Dashboard, org management, invitations\n admin: true, // Admin panel (user management)\n}\n```\n\nDisabled features are excluded at compile time — their route files are removed before the Vite build. See [Configuration](/compiler/config) for all options.\n\n## Next Steps\n\n- [Configuration](/compiler/config) — CMS and Account config reference\n- [Multi-Domain Architecture](/compiler/config/domains) — Custom domains and hostname routing\n- [Environment Variables](/stack/account-ui/environment-variables) — Complete variable reference\n- [Feature Flags](/stack/account-ui/features) — Enable and disable features\n- [Auth Hooks](/stack/account-ui/hooks) — Run project code on signup, login, and session events\n- [Customization](/stack/account-ui/customization) — Branding, labels, and theming"
327
331
  },
328
332
  "stack/auth/api-keys": {
329
333
  "title": "API Keys",
@@ -339,7 +343,7 @@ export const DOCS = {
339
343
  },
340
344
  "stack/auth/jwt-optimization": {
341
345
  "title": "JWT Optimization",
342
- "content": "Quickback automatically optimizes authenticated API requests using JWT tokens. After the first request (which uses session cookies), subsequent requests skip the database entirely by sending a signed JWT that encodes the full auth context.\n\n## How It Works\n\n### Request Flow\n\n```\nFirst request (no JWT cached):\n Browser → Cookie auth → 2 DB queries → Response + set-auth-token header\n Browser caches JWT in localStorage\n\nSubsequent requests (JWT cached):\n Browser → Bearer JWT → Signature check only → Response (0 DB queries)\n```\n\n### What's in the JWT\n\nThe JWT encodes everything needed for auth middleware:\n\n| Claim | Description |\n|-------|-------------|\n| `sub` | User ID |\n| `orgId` | Active organization ID |\n| `role` | Organization membership role (`owner`, `admin`, `member`) |\n| `userRole` | Global user role (when admin panel is enabled) |\n| `email` | User email |\n| `name` | User display name |\n| `iat` | Issued-at timestamp |\n| `exp` | Expiry (15 minutes from issue) |\n\n### Signing\n\nJWTs are signed with HMAC-SHA256 using your `BETTER_AUTH_SECRET`. No additional configuration is needed — this uses the same secret you already set for Better Auth.\n\n---\n\n## Server-Side Validation\n\n**Every authenticated API request is validated server-side before it reaches your handler.** There is no \"trust the client\" shortcut — the middleware runs full signature verification on each request.\n\nValidation steps (in generated `src/middleware/auth.ts`):\n\n1. Extract the `Authorization: Bearer <token>` header\n2. Call `verifyJwt(token, BETTER_AUTH_SECRET)` from `src/lib/jwt.ts`\n3. Decode header + payload, recompute the HMAC-SHA256 signature, and compare via `crypto.subtle.verify()` (constant-time — no timing-attack surface)\n4. Check `exp` against the current time\n5. On success: hydrate `AppContext` from claims (`sub`, `orgId`, `role`, `userRole`, `email`, `name`) — no DB query\n6. On failure (bad signature, expired, malformed): **silently fall back** to Better Auth's session cookie auth; if that succeeds, mint a fresh JWT and return it in the `set-auth-token` response header\n\nThe Files worker (R2 uploads) performs the same verification using the shared secret — no network round-trip to the auth API for file operations.\n\n---\n\n## Token Lifecycle\n\n### Automatic Minting\n\nWhen a request arrives without a JWT (or with an expired one), the auth middleware:\n\n1. Authenticates via session cookie (existing Better Auth flow)\n2. Signs a JWT with the full auth context\n3. Returns it in the `set-auth-token` response header\n\nThe Quickback API client (`quickback-client.ts`) automatically captures this header and stores the JWT in `localStorage`.\n\n### Re-minting on Org Switch\n\nWhen a user switches organizations, the JWT must be re-minted because `orgId` and `role` change. The auth UI handles this automatically:\n\n```typescript\n// This happens automatically in the org switcher\nawait authClient.organization.setActive({ organizationSlug: slug });\n\n// Fetch fresh JWT with new org context\nconst res = await fetch('/api/v1/token', {\n method: 'POST',\n credentials: 'include',\n});\nconst { token } = await res.json();\nlocalStorage.setItem('bearer_token', token);\n```\n\n### Invalidation on Role Changes\n\nWhen an admin changes a user's role or removes them from an organization, the server broadcasts an `auth:token-invalidated` event via WebSocket. The client automatically clears the cached JWT, forcing the next request to fall back to session auth and mint a fresh token.\n\n```\nAdmin changes user role\n → databaseHooks fires on member update\n → Broadcasts auth:token-invalidated via realtime\n → Client clears localStorage JWT\n → Next request uses session cookie → gets fresh JWT\n```\n\n### Expiry\n\nJWTs expire after 15 minutes. This is a safety net — in practice, JWTs are re-minted well before expiry through the `set-auth-token` response header on session-fallback requests.\n\nWhen a JWT expires or is invalid:\n1. The middleware silently falls back to session cookie auth\n2. A fresh JWT is minted and returned in the response header\n3. The client stores the new JWT for subsequent requests\n\n---\n\n## Token Endpoint\n\n`POST /api/v1/token` mints a fresh JWT from the current session. This endpoint goes through normal auth middleware, so the user must have a valid session cookie.\n\n**Request:**\n```bash\ncurl -X POST https://your-api.example.com/api/v1/token \\\n -H \"Content-Type: application/json\" \\\n --cookie \"better-auth.session_token=...\"\n```\n\n**Response:**\n```json\n{\n \"token\": \"eyJhbGciOiJIUzI1NiJ9...\"\n}\n```\n\nUse this endpoint after operations that change auth context (like switching organizations) to get a JWT that reflects the new state.\n\n---\n\n## Client Integration\n\n### Quickback API Client\n\nThe `quickback-client.ts` API client handles JWT auth automatically:\n\n- **Sends** the cached JWT as `Authorization: Bearer <token>` on every request\n- **Captures** refreshed JWTs from `set-auth-token` response headers\n- **Clears** the JWT on `401` responses (falls back to session cookie)\n\nNo additional client configuration is needed.\n\n### Custom API Calls\n\nIf you make direct `fetch()` calls to your API (outside the Quickback client), include the JWT:\n\n```typescript\nconst jwt = localStorage.getItem('bearer_token');\n\nconst res = await fetch('https://your-api.example.com/api/v1/things', {\n headers: {\n 'Authorization': `Bearer ${jwt}`,\n 'Content-Type': 'application/json',\n },\n credentials: 'include', // Fallback to session cookie if no JWT\n});\n\n// Capture refreshed token\nconst newToken = res.headers.get('set-auth-token');\nif (newToken) {\n localStorage.setItem('bearer_token', newToken);\n}\n```\n\n### Sign Out\n\nClear the JWT on sign-out to prevent stale tokens:\n\n```typescript\nlocalStorage.removeItem('bearer_token');\nawait authClient.signOut();\n```\n\n---\n\n## Security\n\n### Threat Model\n\n| Threat | Mitigation |\n|--------|------------|\n| Token theft (XSS) | 15-minute expiry limits exposure window. `httpOnly` cookies protect the session. |\n| Token replay | Short expiry + `set-auth-token` rotation on session fallback |\n| Stale permissions | WebSocket `auth:token-invalidated` broadcast on role changes |\n| Token forgery | HMAC-SHA256 signature verified with `BETTER_AUTH_SECRET` |\n| Timing attacks | `crypto.subtle.verify()` provides constant-time comparison |\n\n### Key Points\n\n- JWTs are a **performance optimization**, not a replacement for session auth\n- Session cookies remain the source of truth — JWTs are derived from them\n- If a JWT is lost, stolen, or cleared, the system gracefully falls back to cookie auth\n- No additional secrets or configuration needed — uses your existing `BETTER_AUTH_SECRET`\n- The JWT contains no sensitive data beyond what's already in the auth context\n\n---\n\n## Files Worker\n\nThe files worker (for Cloudflare R2 file uploads) also supports JWT authentication. When a request includes a JWT `Authorization` header, the worker verifies it directly instead of calling back to the auth API — eliminating a network round-trip for file operations.\n\n---\n\n## Relation to Better Auth's JWT Plugin\n\nQuickback's JWT fast-path (documented above) is a **custom HMAC-SHA256 implementation**, separate from Better Auth's [`jwt` plugin](https://www.better-auth.com/docs/plugins/jwt). The distinction matters if you're comparing options.\n\n### What Quickback ships by default\n\n- Custom HMAC-SHA256 JWTs minted by the compiled API at `POST /api/v1/token`\n- Payload includes `sub`, `orgId`, `role`, `userRole`, `email`, `name` — everything the middleware needs to reconstruct `AppContext` with zero DB queries\n- Signed with `BETTER_AUTH_SECRET`\n- Used by the generated auth middleware as a fast-path ahead of `getSession()`\n\n### What Better Auth's JWT plugin gives you (opt-in)\n\nEnable it with `plugins: [\"jwt\"]` in your auth config:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: [\"jwt\"],\n}),\n```\n\nYou get:\n- JWKS endpoint at `/auth/v1/jwks` for asymmetric public-key verification by external services\n- BA's own `/auth/v1/token` endpoint (asymmetric-signed, EdDSA by default)\n- Standard OIDC-style claims via BA's `definePayload` hook\n\n### Why Quickback doesn't use BA's plugin internally\n\nBetter Auth's `definePayload` hook only receives `{ user }`. It cannot embed the active organization context (`orgId`, org-member `role`) that Quickback's Firewall and Access layers need. Without that context in the JWT, the middleware would have to do a DB lookup per request — defeating the whole point of the fast-path.\n\n### When to enable BA's JWT plugin anyway\n\nTurn it on if **external services** need to verify tokens without sharing `BETTER_AUTH_SECRET` — e.g. a third-party worker that wants to confirm a user's identity via JWKS. The BA-issued tokens won't have Quickback's org context, so they're useful for identity assertions, not for hitting the Quickback API directly.\n\nEnabling BA's plugin does **not** change how the compiled API authenticates requests — the middleware keeps using the custom HMAC JWT regardless.\n\n---\n\n## Related\n\n- [Auth Overview](/stack/auth) — Setup and configuration\n- [Auth Security](/stack/auth/security) — Cookie security, rate limiting, CORS\n- [API Keys](/stack/auth/api-keys) — Programmatic API access"
346
+ "content": "Quickback automatically optimizes authenticated API requests using JWT tokens. After the first request (which uses session cookies), subsequent requests skip the database entirely by sending a signed JWT that encodes the full auth context.\n\n## How It Works\n\n### Request Flow\n\n```\nFirst request (no JWT cached):\n Browser → Cookie auth → 2 DB queries → Response + set-auth-token header\n Browser caches JWT in localStorage\n\nSubsequent requests (JWT cached):\n Browser → Bearer JWT → Signature check only → Response (0 DB queries)\n```\n\n### What's in the JWT\n\nThe JWT encodes everything needed for auth middleware:\n\n| Claim | Description |\n|-------|-------------|\n| `sub` | User ID |\n| `orgId` | Active organization ID |\n| `role` | Organization membership role (`owner`, `admin`, `member`) |\n| `userRole` | Global user role (when admin panel is enabled) |\n| `email` | User email |\n| `name` | User display name |\n| `iat` | Issued-at timestamp |\n| `exp` | Expiry (15 minutes from issue) |\n\n### Signing\n\nJWTs are signed with HMAC-SHA256 using your `BETTER_AUTH_SECRET`. No additional configuration is needed — this uses the same secret you already set for Better Auth.\n\n---\n\n## Server-Side Validation\n\n**Every authenticated API request is validated server-side before it reaches your handler.** There is no \"trust the client\" shortcut — the middleware runs full signature verification on each request.\n\nValidation steps (in generated `src/middleware/auth.ts`):\n\n1. Extract the `Authorization: Bearer <token>` header\n2. Call `verifyJwt(token, BETTER_AUTH_SECRET)` from `src/lib/jwt.ts`\n3. Decode header + payload, recompute the HMAC-SHA256 signature, and compare via `crypto.subtle.verify()` (constant-time — no timing-attack surface)\n4. Check `exp` against the current time\n5. On success: hydrate `AppContext` from claims (`sub`, `orgId`, `role`, `userRole`, `email`, `name`) — no DB query\n6. On failure (bad signature, expired, malformed): **silently fall back** to Better Auth's session cookie auth; if that succeeds, mint a fresh JWT and return it in the `set-auth-token` response header\n\nThe Files worker (R2 uploads) performs the same verification using the shared secret — no network round-trip to the auth API for file operations.\n\n---\n\n## Token Lifecycle\n\n### Automatic Minting\n\nWhen a request arrives without a JWT (or with an expired one), the auth middleware:\n\n1. Authenticates via session cookie (existing Better Auth flow)\n2. Signs a JWT with the full auth context\n3. Returns it in the `set-auth-token` response header\n\nThe Quickback API client (`quickback-client.ts`) automatically captures this header and stores the JWT in `localStorage`.\n\n### Re-minting on Org Switch\n\nWhen a user switches organizations, the JWT must be re-minted because `orgId` and `role` change. The auth UI handles this automatically:\n\n```typescript\n// This happens automatically in the org switcher\nawait authClient.organization.setActive({ organizationSlug: slug });\n\n// Fetch fresh JWT with new org context\nconst res = await fetch('/api/v1/token', {\n method: 'POST',\n credentials: 'include',\n});\nconst { token } = await res.json();\nlocalStorage.setItem('bearer_token', token);\n```\n\n### Invalidation on Role Changes\n\nWhen an admin changes a user's role or removes them from an organization, the server broadcasts an `auth:token-invalidated` event via WebSocket. The client automatically clears the cached JWT, forcing the next request to fall back to session auth and mint a fresh token.\n\n```\nAdmin changes user role\n → databaseHooks fires on member update\n → Broadcasts auth:token-invalidated via realtime\n → Client clears localStorage JWT\n → Next request uses session cookie → gets fresh JWT\n```\n\n### Expiry\n\nJWTs expire after 15 minutes. This is a safety net — in practice, JWTs are re-minted well before expiry through the `set-auth-token` response header on session-fallback requests.\n\nWhen a JWT expires or is invalid:\n1. The middleware silently falls back to session cookie auth\n2. A fresh JWT is minted and returned in the response header\n3. The client stores the new JWT for subsequent requests\n\n---\n\n## Token Endpoint\n\n`POST /api/v1/token` mints a fresh JWT from the current session. This endpoint goes through normal auth middleware, so the user must have a valid session cookie.\n\n**Session authentication is required — and enforced.** A request authenticated\nby a bearer JWT (or an API key / OAuth access token) is rejected with `401\nAUTH_SESSION_REQUIRED` (\"Token refresh requires session authentication\").\nThis is deliberate: only the session path re-validates against Better Auth's\nsession store on every request, so bans, member removals, role demotions, and\nsign-outs take effect immediately. If a JWT could mint its own replacement, a\nstolen or revoked token could roll a short-TTL JWT forever without ever\nre-validating — the TTL would bound nothing.\n\n**Request:**\n```bash\ncurl -X POST https://your-api.example.com/api/v1/token \\\n -H \"Content-Type: application/json\" \\\n --cookie \"better-auth.session_token=...\"\n```\n\n**Response:**\n```json\n{\n \"token\": \"eyJhbGciOiJIUzI1NiJ9...\"\n}\n```\n\nUse this endpoint after operations that change auth context (like switching organizations) to get a JWT that reflects the new state.\n\n---\n\n## Client Integration\n\n### Quickback API Client\n\nThe `quickback-client.ts` API client handles JWT auth automatically:\n\n- **Sends** the cached JWT as `Authorization: Bearer <token>` on every request\n- **Captures** refreshed JWTs from `set-auth-token` response headers\n- **Clears** the JWT on `401` responses (falls back to session cookie)\n\nNo additional client configuration is needed.\n\n### Custom API Calls\n\nIf you make direct `fetch()` calls to your API (outside the Quickback client), include the JWT:\n\n```typescript\nconst jwt = localStorage.getItem('bearer_token');\n\nconst res = await fetch('https://your-api.example.com/api/v1/things', {\n headers: {\n 'Authorization': `Bearer ${jwt}`,\n 'Content-Type': 'application/json',\n },\n credentials: 'include', // Fallback to session cookie if no JWT\n});\n\n// Capture refreshed token\nconst newToken = res.headers.get('set-auth-token');\nif (newToken) {\n localStorage.setItem('bearer_token', newToken);\n}\n```\n\n### Sign Out\n\nClear the JWT on sign-out to prevent stale tokens:\n\n```typescript\nlocalStorage.removeItem('bearer_token');\nawait authClient.signOut();\n```\n\n---\n\n## Security\n\n### Threat Model\n\n| Threat | Mitigation |\n|--------|------------|\n| Token theft (XSS) | 15-minute expiry limits exposure window. `httpOnly` cookies protect the session. |\n| Token replay | Short expiry + `set-auth-token` rotation on session fallback |\n| Stale permissions | WebSocket `auth:token-invalidated` broadcast on role changes |\n| Token forgery | HMAC-SHA256 signature verified with `BETTER_AUTH_SECRET` |\n| Timing attacks | `crypto.subtle.verify()` provides constant-time comparison |\n\n### Key Points\n\n- JWTs are a **performance optimization**, not a replacement for session auth\n- Session cookies remain the source of truth — JWTs are derived from them\n- If a JWT is lost, stolen, or cleared, the system gracefully falls back to cookie auth\n- No additional secrets or configuration needed — uses your existing `BETTER_AUTH_SECRET`\n- The JWT contains no sensitive data beyond what's already in the auth context\n\n---\n\n## Files Worker\n\nThe files worker (for Cloudflare R2 file uploads) also supports JWT authentication. When a request includes a JWT `Authorization` header, the worker verifies it directly instead of calling back to the auth API — eliminating a network round-trip for file operations.\n\n---\n\n## Relation to Better Auth's JWT Plugin\n\nQuickback's JWT fast-path (documented above) is a **custom HMAC-SHA256 implementation**, separate from Better Auth's [`jwt` plugin](https://www.better-auth.com/docs/plugins/jwt). The distinction matters if you're comparing options.\n\n### What Quickback ships by default\n\n- Custom HMAC-SHA256 JWTs minted by the compiled API at `POST /api/v1/token`\n- Payload includes `sub`, `orgId`, `role`, `userRole`, `email`, `name` — everything the middleware needs to reconstruct `AppContext` with zero DB queries\n- Signed with `BETTER_AUTH_SECRET`\n- Used by the generated auth middleware as a fast-path ahead of `getSession()`\n\n### What Better Auth's JWT plugin gives you (opt-in)\n\nEnable it with `plugins: [\"jwt\"]` in your auth config:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: [\"jwt\"],\n}),\n```\n\nYou get:\n- JWKS endpoint at `/auth/v1/jwks` for asymmetric public-key verification by external services\n- BA's own `/auth/v1/token` endpoint (asymmetric-signed, EdDSA by default)\n- Standard OIDC-style claims via BA's `definePayload` hook\n\n### Why Quickback doesn't use BA's plugin internally\n\nBetter Auth's `definePayload` hook only receives `{ user }`. It cannot embed the active organization context (`orgId`, org-member `role`) that Quickback's Firewall and Access layers need. Without that context in the JWT, the middleware would have to do a DB lookup per request — defeating the whole point of the fast-path.\n\n### When to enable BA's JWT plugin anyway\n\nTurn it on if **external services** need to verify tokens without sharing `BETTER_AUTH_SECRET` — e.g. a third-party worker that wants to confirm a user's identity via JWKS. The BA-issued tokens won't have Quickback's org context, so they're useful for identity assertions, not for hitting the Quickback API directly.\n\nEnabling BA's plugin does **not** change how the compiled API authenticates requests — the middleware keeps using the custom HMAC JWT regardless.\n\n---\n\n## Related\n\n- [Auth Overview](/stack/auth) — Setup and configuration\n- [Auth Security](/stack/auth/security) — Cookie security, rate limiting, CORS\n- [API Keys](/stack/auth/api-keys) — Programmatic API access"
343
347
  },
344
348
  "stack/auth/plugins/agent-auth": {
345
349
  "title": "Agent Auth Plugin",
@@ -435,7 +439,7 @@ export const DOCS = {
435
439
  },
436
440
  "stack/realtime": {
437
441
  "title": "Realtime",
438
- "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\nws-ticket connection route; it does **not** by itself make any resource\nbroadcast (that's the per-resource `realtime` block above). The compiler\ngenerates the Durable Object class, helper functions, and wrangler bindings —\nall within your main worker.\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\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 | 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"
439
443
  },
440
444
  "stack/realtime/live-views": {
441
445
  "title": "Live Views",
@@ -503,6 +507,7 @@ export const TOPIC_LIST = [
503
507
  "compiler/claude-code-skill",
504
508
  "compiler/cloud-compiler/authentication",
505
509
  "compiler/cloud-compiler/cli",
510
+ "compiler/cloud-compiler/deploy",
506
511
  "compiler/cloud-compiler/endpoints",
507
512
  "compiler/cloud-compiler",
508
513
  "compiler/cloud-compiler/local-compiler",