@quickback-dev/cli 0.54.0 → 0.55.1

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 (95) hide show
  1. package/dist/commands/compile.d.ts.map +1 -1
  2. package/dist/commands/compile.js +41 -4
  3. package/dist/commands/compile.js.map +1 -1
  4. package/dist/commands/create.d.ts.map +1 -1
  5. package/dist/commands/create.js +5 -1
  6. package/dist/commands/create.js.map +1 -1
  7. package/dist/docs/content.d.ts.map +1 -1
  8. package/dist/docs/content.js +37 -22
  9. package/dist/docs/content.js.map +1 -1
  10. package/dist/index.js +1 -1
  11. package/dist/lib/action-harvest.d.ts +16 -1
  12. package/dist/lib/action-harvest.d.ts.map +1 -1
  13. package/dist/lib/action-harvest.js +21 -1
  14. package/dist/lib/action-harvest.js.map +1 -1
  15. package/dist/lib/action-harvest.test.js +122 -3
  16. package/dist/lib/action-harvest.test.js.map +1 -1
  17. package/dist/lib/api-client.d.ts +11 -0
  18. package/dist/lib/api-client.d.ts.map +1 -1
  19. package/dist/lib/api-client.js.map +1 -1
  20. package/dist/lib/artifact-routing.d.ts.map +1 -1
  21. package/dist/lib/artifact-routing.js +3 -0
  22. package/dist/lib/artifact-routing.js.map +1 -1
  23. package/dist/lib/compiler-floor.d.ts +39 -0
  24. package/dist/lib/compiler-floor.d.ts.map +1 -0
  25. package/dist/lib/compiler-floor.js +75 -0
  26. package/dist/lib/compiler-floor.js.map +1 -0
  27. package/dist/lib/compiler-floor.test.d.ts +2 -0
  28. package/dist/lib/compiler-floor.test.d.ts.map +1 -0
  29. package/dist/lib/compiler-floor.test.js +67 -0
  30. package/dist/lib/compiler-floor.test.js.map +1 -0
  31. package/dist/lib/compiler-stubs.d.ts +6 -0
  32. package/dist/lib/compiler-stubs.d.ts.map +1 -1
  33. package/dist/lib/compiler-stubs.js +8 -0
  34. package/dist/lib/compiler-stubs.js.map +1 -1
  35. package/dist/lib/file-loader.d.ts +45 -4
  36. package/dist/lib/file-loader.d.ts.map +1 -1
  37. package/dist/lib/file-loader.js +116 -19
  38. package/dist/lib/file-loader.js.map +1 -1
  39. package/dist/lib/file-loader.test.js +80 -4
  40. package/dist/lib/file-loader.test.js.map +1 -1
  41. package/dist/skill/SKILL.md +3 -1
  42. package/dist/skill/docs/changelog.md +66 -0
  43. package/dist/skill/docs/compiler/config/index.md +14 -1
  44. package/dist/skill/docs/compiler/config/providers.md +13 -9
  45. package/dist/skill/docs/compiler/definitions/access.md +134 -2
  46. package/dist/skill/docs/compiler/definitions/actions.md +22 -0
  47. package/dist/skill/docs/compiler/definitions/changesets.md +375 -0
  48. package/dist/skill/docs/compiler/definitions/feature-areas.md +189 -0
  49. package/dist/skill/docs/compiler/definitions/feature.md +33 -0
  50. package/dist/skill/docs/compiler/definitions/firewall.md +60 -1
  51. package/dist/skill/docs/compiler/definitions/guards.md +14 -0
  52. package/dist/skill/docs/compiler/definitions/index.md +28 -3
  53. package/dist/skill/docs/compiler/definitions/masking.md +8 -0
  54. package/dist/skill/docs/compiler/definitions/read.md +13 -0
  55. package/dist/skill/docs/compiler/definitions/schema.md +36 -1
  56. package/dist/skill/docs/compiler/definitions/scopes.md +23 -1
  57. package/dist/skill/docs/compiler/targets/hono-api/database/neon.md +27 -28
  58. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/batch-operations.md +2 -0
  59. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/errors.md +49 -17
  60. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/query-params.md +66 -0
  61. package/dist/skill/docs/stack/api-contract/index.md +136 -0
  62. package/dist/skill/docs/stack/realtime/durable-objects.md +7 -0
  63. package/dist/skill/docs/stack/realtime/index.md +22 -0
  64. package/dist/skill/docs/stack/realtime/live-views.md +56 -0
  65. package/dist/skill/docs/stack/realtime/using-realtime.md +53 -0
  66. package/dist/skill/docs/stack/webhooks/inbound.md +79 -0
  67. package/dist/skill/docs/stack/webhooks/outbound.md +33 -0
  68. package/package.json +1 -1
  69. package/src/skill/SKILL.md +3 -1
  70. package/src/skill/docs/changelog.md +66 -0
  71. package/src/skill/docs/compiler/config/index.md +14 -1
  72. package/src/skill/docs/compiler/config/providers.md +13 -9
  73. package/src/skill/docs/compiler/definitions/access.md +134 -2
  74. package/src/skill/docs/compiler/definitions/actions.md +22 -0
  75. package/src/skill/docs/compiler/definitions/changesets.md +375 -0
  76. package/src/skill/docs/compiler/definitions/feature-areas.md +189 -0
  77. package/src/skill/docs/compiler/definitions/feature.md +33 -0
  78. package/src/skill/docs/compiler/definitions/firewall.md +60 -1
  79. package/src/skill/docs/compiler/definitions/guards.md +14 -0
  80. package/src/skill/docs/compiler/definitions/index.md +28 -3
  81. package/src/skill/docs/compiler/definitions/masking.md +8 -0
  82. package/src/skill/docs/compiler/definitions/read.md +13 -0
  83. package/src/skill/docs/compiler/definitions/schema.md +36 -1
  84. package/src/skill/docs/compiler/definitions/scopes.md +23 -1
  85. package/src/skill/docs/compiler/targets/hono-api/database/neon.md +27 -28
  86. package/src/skill/docs/compiler/targets/hono-api/using-the-api/batch-operations.md +2 -0
  87. package/src/skill/docs/compiler/targets/hono-api/using-the-api/errors.md +49 -17
  88. package/src/skill/docs/compiler/targets/hono-api/using-the-api/query-params.md +66 -0
  89. package/src/skill/docs/stack/api-contract/index.md +136 -0
  90. package/src/skill/docs/stack/realtime/durable-objects.md +7 -0
  91. package/src/skill/docs/stack/realtime/index.md +22 -0
  92. package/src/skill/docs/stack/realtime/live-views.md +56 -0
  93. package/src/skill/docs/stack/realtime/using-realtime.md +53 -0
  94. package/src/skill/docs/stack/webhooks/inbound.md +79 -0
  95. package/src/skill/docs/stack/webhooks/outbound.md +33 -0
@@ -3,7 +3,7 @@
3
3
  export const DOCS = {
4
4
  "changelog": {
5
5
  "title": "Changelog",
6
- "content": "## v0.54.0 — July 17, 2026\n\n### Realtime: named invalidations\n\nActions can now fire typed, targeted *\"this changed — refresh\"* signals after commit. A `defineRealtime` registry declares typed events (wire name, contract `version`, named variants with strict Zod payloads); a `defineRealtimeDelivery` profile sets the maximum audience (a scope room or the org/user lane + required roles); and an optional `defineRealtimeRecipients` resolver narrows delivery to a resolved identity set — post-commit on the firewalled db, intersecting `scope ∩ roles ∩ recipients`, fail-closed (a throw or `[]` reaches nobody, never a wider audience). Bind them with `invalidates:` on an action and call `invalidate.<binding>.<variant>(payload)` inside `execute`. Delivery is after-commit + best-effort (discarded on throw/dryRun), projects the payload to declared keys, and works on every action kind — standalone, per-record, bulk, and namespace-hoisted. See [Named invalidations](/stack/realtime/named-invalidations).\n\n### Access: `SESSION` and `SCOPED` pseudo-role tiers\n\n`AUTHENTICATED` is now explicitly the wrapper over two auth flavors: **`SESSION`** (a full Better Auth session only) and **`SCOPED`** (a sessionless scope-token principal only — e.g. an event attendee with no account). Use the specific tier when a route must admit or exclude one flavor; `AUTHENTICATED` still admits both and excludes only external delegated principals. See [Access → Pseudo-roles](/compiler/definitions/access).\n\n### Access: fail-closed scope/firewall coherence guardrail\n\nGranting a scope caller (`SCOPED` or a `scope:<kind>:<role>` role) on a resource whose firewall can't filter that caller now **fails the build** instead of silently returning `200 + []` — the trap that pushes apps toward a fake \"active organization.\" The fix is named in the error: compose org **or** scope in an `{ any: [...] }` firewall group, use a `via:` relationship, or `firewall: [{ exception: true }]`.\n\n## v0.53.0 — July 17, 2026\n\n### Realtime: the broadcast surface tracks `contract.version`\n\nThe `/api` and `/auth` bases already move to `/api/v2` and `/auth/v2` under\n`contract.version: 'v2'`, but the realtime/broadcast surface stayed pinned\nat `/broadcast/v1` — so a v2 project's WebSocket mount, ws-ticket mint, DO\nroute matcher, notify helper, auth skip-set, and discovery all disagreed\nwith the rest of the contract. The broadcast base now derives from the same\nresolved contract version (single source of truth in `resolveSystemRoutes`),\nthreaded through every emitter:\n\n- **contract v1 (or omitted)** → `/broadcast/v1` everywhere, byte-identical\n to prior output.\n- **contract v2** → `/broadcast/v2` everywhere, with **no hidden v1 alias**.\n\nAn explicit `compiler.routes.broadcast` override still wins. Existing v1\nprojects are unaffected.\n\n### Web Push: VAPID delivery, queue fan-out, and identity-tag targeting\n\n`push.provider: 'web-push'` turns on a full push pillar: a self-contained\ndelivery module (RFC 8292 VAPID JWTs + RFC 8291 aes128gcm, `crypto.subtle`\nonly — no Node polyfills), a Cloudflare Queues fan-out with a dead-letter\nqueue, and a hardened `push_subscriptions` schema. The crypto core is\nverified against the RFC 8291 Appendix A known-answer vector — the emitted\nmodule reproduces the RFC's ciphertext byte-for-byte.\n\n- **Send path** — `enqueuePushFanout(queue, target, payload)` from an\n action's after-commit phase (`effects.enqueue`), so rolled-back writes\n never notify and `dryRun` sends nothing. Declarative targets\n (`{ userIds }`, `{ targetTags }`, `{ targetRoles }`, `{ all: true }`)\n resolve server-side in the queue consumer — subscription crypto never\n enters action code. Targeting speaks the realtime identity-tag dialect\n and is fail-closed: `[]` selects nobody, broadcast requires an explicit\n `{ all: true }`.\n- **Default schema** (`push.defaultSchema: true`) — owner-firewalled,\n INTERNAL-read `push_subscriptions` with a `views.mine` device list.\n Creates validate `https:` endpoints (SSRF blocker), 65-byte P-256\n `p256dh`, 16-byte `auth`; `tags` is stamped server-side from the\n session's proven identity (client tags ignored); 10/min create rate\n limit; per-user cap keeps the newest 10 live subscriptions.\n- **Fail-closed config** — a literal `vapidPrivateKey` in config is a\n compile error (`env:VAPID_PRIVATE_KEY` only); the worker refuses to boot\n without the three VAPID vars; the private key never lands in\n `wrangler.toml`, SPA bundles, or logs (DLQ chunks log counts only).\n- **SPA bake** — the VAPID public key ships to CMS/Account bundles as\n `VITE_QUICKBACK_VAPID_PUBLIC_KEY` and `window.__QUICKBACK_RUNTIME.vapidPublicKey`.\n- **CLI** — `quickback push generate-keys [--out <file>]`; `--out` writes\n the private key to a `0600` file so it never touches stdout or shell\n history.\n\nSee [Web Push](/stack/push) for the full guide.\n\n## v0.52.1 — July 17, 2026\n\n### CLI: cold-start tolerance for the cloud compiler\n\nRight after a service deploy, the first compile pays a fresh container image\npull — which routinely exceeds the CLI's old 60-second readiness budget and\nsurfaced as `Compiler container did not become ready in time` even while\n`/health` was green. `waitForReady` now allows 4 minutes, reports elapsed\nwarm-up progress, and the timeout message explains the deploy-in-progress\ncase.\n\n## v0.52.0 — July 17, 2026\n\n### Five action primitives: afterCommit, realtime emit, transitions v2, refs, bundles\n\nOne release, five primitives that collapse the most-repeated hand-written\npatterns in real Quickback projects (measured across a 349-action production\ncorpus). Every one is additive — existing projects compile unchanged, and\nplain `{ field, fromTo, to|via }` transitions keep their emission\nbyte-identical.\n\n- **`afterCommit` hooks + `effects.enqueue`** — named best-effort side\n effects that run after `execute` returns. Each hook is independently\n wrapped (failures log as `[<action>] afterCommit:<hook> failed`, never\n touching the response), non-blocking hooks ride `executionCtx.waitUntil`,\n `{ blocking: true }` awaits before responding, and everything skips when\n `execute` throws or returns `dryRun: true`. The execute context also gains\n `effects.enqueue(name, fn)` for mid-execute captures and `now` — one ISO\n timestamp per invocation. Replaces the per-leg `try/catch + waitUntil`\n idiom. See [After-commit hooks](/compiler/definitions/actions#after-commit-hooks).\n\n- **Realtime emit for custom actions** — tables that lock auto-CRUD no\n longer hand-roll frames. `realtime: { emitFromActions: true, scopeKeyFrom:\n \"events:{eventId}\" }` makes scoped-db writes inside record-bound and bulk\n actions emit auto-CRUD-byte-compatible frames after commit (masking +\n audience applied at fanout; the fail-closed audience requirement extends to\n action emission). Actions can also declare `emit:` for a pre-bound\n `emitCrud(row, oldRow?)`. Updates/deletes pre-select old rows on the same\n WHERE; raw `unsafeDb` writes stay invisible. See\n [When auto-broadcast fires](/stack/realtime/durable-objects#when-auto-broadcast-fires-and-when-you-call-it-manually).\n\n- **Transitions v2** — `transition` grows `guard` (equality / null / notNull\n / `custom(record)`), `onIllegal { code, status, message }`, `idempotent:\n \"noop\"`, and `stamp`/`clears` that ride a compiler-applied, TOCTOU-safe\n UPDATE (guards fold into the WHERE; a lost race is 409\n `ACCESS_TRANSITION_LOST`). With an applied write, `execute` becomes\n optional. Table-level `transitions: { publish: { field, from, to, access } }`\n *generates* the action files — including `undo:` inverses and `onEnter`\n cascades — mounted exactly where hand-written files would be (explicit\n files win, with a warning). The ten byte-identical publish/revert files in\n the podcast fixture become two lines per entity. See\n [Transitions](/compiler/definitions/transitions).\n\n- **`refs` — scoped foreign-key inputs** — the \"load the id, 404 if missing,\n assert it belongs to this event\" preamble becomes declarative. Loads run\n through the scoped db (a cross-org id 404s by construction), batch into one\n `Promise.all`, assert `matchScope` / cross-input `matchWith` parenthood, and\n inject rows under their `as` names. Ref keys are validated against the\n inline `z.object` input (with agreeing optionality) at compile time. See\n [Refs](/compiler/definitions/actions#refs-scoped-foreign-key-inputs).\n\n- **`defineBundle` — single-round-trip bootstrap reads** — declarative\n `list()` slices with the firewall, the table's *real* mask functions, and\n `{ data }` cache-seed envelopes; `custom()` escape-hatch sections; a SHA-1\n ETag over `{ scopeSeed, userId, payload }` with the `ifNoneMatch →\n notModified` short-circuit; and `Server-Timing`. Fail-closed: a bundle's\n roles must be a subset of every list table's `read.access` roles — a bundle\n can never widen read access. The digest ships as `sha1Hex` in `lib/etag`\n so hand-written reads can delete their copies. See\n [Bundles](/compiler/definitions/bundles).\n\nSupporting changes: `ActionError` / `TransitionLostError` are re-exported\nfrom the generated `.quickback/define-action` helpers (routes duck-type on\n`error.name`, so project-local copies keep working); `sendQueueBatched` in\n`lib/effects` chunks queue sends at the Cloudflare 100-message cap; and the\n`$record.*` / `$ctx.*` substitution grammar used by `onEnter` and bundle\n`where` is one strict allowlist, always parameterized — never interpolated\ninto SQL.\n\n### CLI device login fixed: /cli/authorize now claims the code before approving\n\nBetter Auth's `deviceAuthorization` plugin requires the verifying session to\nclaim a device code (`GET /device?user_code=…`) before it accepts an approve\nor deny. The account SPA's `/cli/authorize` page posted the approval directly,\nso every `quickback login` failed with *\"Device code has not been claimed by\na verifying session.\"* The page now claims first, then approves — and surfaces\nclaim failures (expired or mistyped codes) with the server's message.\n### Generated builds no longer rewrite the auth schema\n\nGenerated Better Auth projects now run `tsc` directly from `npm run build`.\n`quickback compile` already generates, qualifies, and envelopes\n`src/auth/schema.ts`; invoking `auth:schema` again during every build rewrote\nthat compiler-owned artifact and made an otherwise clean release worktree\ndirty. The explicit `auth:schema` diagnostic command remains available, while\nnormal build, Wrangler, and deployment preflight paths are source-read-only.\nWhen recompiling an existing project, compiler-owned `package.json` script\nnames now converge to their current generated commands while unrelated custom\nscripts are preserved. This upgrades projects whose previous generated\n`build` script still invoked `auth:schema`.\n\n### Non-cross-tenant unsafe actions preserve delegated RLS claims\n\nGenerated Neon handlers now reserve `createServiceDb` for actions that\nexplicitly enable `unsafe.crossTenant`. An action that enables raw database\naccess with `crossTenant: false` keeps the request database, so organization\nand delegated-principal claims survive into Hyperdrive transactions instead of\nbeing cleared by the service-role preamble. True cross-tenant sysadmin actions\nretain their audited RLS bypass.\n\nNeon Hyperdrive guidance now also calls out Postgres' `SELECT … FOR UPDATE`\nauthorization rule: a locked row must pass both `SELECT` and `UPDATE` policies.\nDelegated actions should use ordinary selects for read-only eligibility tables\nand lock only mutable rows they are authorized to update. A PGlite regression\nproves that ordinary delegated reads remain visible while the generated\nrestrictive update fence blocks an unauthorized row lock.\n\n### Atomic email-OTP auth routing no longer recurses on ordinary requests\n\nThe generated atomic email-OTP wrapper now captures and binds Better Auth's\noriginal request handler before replacing the public `handler` property.\nSession reads and every other non-atomic auth route therefore forward to Better\nAuth exactly once instead of re-entering the wrapper until the Worker exhausts\nits call stack. The exact email-OTP sign-in route retains its transactional\nadmission and rollback behavior.\n\n### Generated Better Auth CLI dependencies no longer retain vulnerable Lodash\n\nBetter Auth projects now emit a root npm override for `lodash@4.18.1`. This\nkeeps the supported stable `auth@1.6.x` CLI and its `better-auth` executable,\nwhile lifting the CLI's dev-only Prisma parser chain off Lodash releases\naffected by the 2026 code-injection and prototype-pollution advisories. Runtime\nBetter Auth packages and generated authentication behavior are unchanged.\n\nThe CLI now merges generated npm overrides explicitly when recompiling an\nexisting project: unrelated user overrides remain, while compiler-owned\nsecurity pins win a conflict. Recompile and reinstall dependencies to refresh\nthe project lockfile. `npm audit --omit=dev` remains the production dependency\nview; upstream development-server advisories may still appear separately.\n\n### Postgres constraint replacements apply in dependency-safe order\n\nNeon migration post-processing now orders both halves of a Drizzle constraint\nreplacement. A dependent foreign key is dropped before its referenced unique\nor primary-key constraint, then the replacement key is added before the\nforeign key that consumes it. This prevents Postgres `2BP01` failures when\nDrizzle emits the parent key drop first, while preserving byte-identical output\nfor already-correct migrations and the relative order of unrelated statements.\n\n### Schema registry output is byte-reproducible\n\n`schema-registry.json` no longer includes the wall-clock `generatedAt` field.\nIts remaining metadata and schema content are derived entirely from compiler\ninputs, so consecutive compiles of identical logical input now produce the\nsame registry bytes. This makes artifact hashes, caches, and deployment diffs\nstable without timestamp normalization.\n\n### Generated auth and discovery surfaces now remain truthful and type-safe\n\nAtomic email-OTP generation now imports and invokes\n`before-email-otp-activate.ts` exactly once and preserves the transaction's\nreal Drizzle `select` capability in the hook context. Strict generated\nTypeScript therefore accepts both the base Neon service database and its\ninteractive transaction without erasing the hook's read contract.\n\nContract-v2 projects that omit `auth.jwt` no longer advertise the disabled\nQuickback JWT fast path in `llms.txt` or RFC 8414 metadata. Bearer-JWT guidance,\nthe fallback `/api/v2/token` endpoint, and JWT scopes are emitted only when the\ncorresponding JWT surface exists; real Better Auth OAuth-provider discovery is\nunchanged.\n\nCloudflare Email callbacks now all enter the shared credential-delivery\nscheduler exactly once. The scheduler anchors the observed rejection with\n`waitUntil`, emits the metadata-only `auth.credential_delivery_failed` event,\nand never leaks the provider error. Generated CRUD routes also keep delegated\nprincipal and account authority disjoint: `?organizationId=` is rejected for a\ndelegated principal instead of synthesizing `activeOrgId` on its context. This\ncloses both the authority ambiguity and the generated `AppContext` union type\nerrors.\n\n### Email-OTP activation can be admitted atomically in the API layer\n\nContract-v2 Cloudflare projects using one Neon Hyperdrive database can opt the\nexact Better Auth `POST /sign-in/email-otp` handler into an interactive\ntransaction with `atomicAuthRoutes: [\"emailOtpSignIn\"]`. The paired recognized\nhook, `quickback/hooks/before-email-otp-activate.ts`, receives a proven dormant\nuser `{ userId, email, user }` plus transaction-bound `db` / full `schema` and\n`authDb` / `authSchema` handles. Quickback owns only identity proof and atomic\norchestration; application admission, status, event, pass, and eligibility\nrules remain authored in the project API hook.\n\nThe hook executes after OTP validation but in Better Auth's\n`databaseHooks.user.update.before`, before the user update lock. This preserves\napplication-first lock ordering and avoids the user-to-application inversion a\nsession-create hook would introduce. Unknown-email signup must be disabled;\nalready-verified users do not rerun dormant activation.\n\nThe generated handler rebuilds Better Auth over the transaction handle, so OTP\nconsumption, project hook writes, the `emailVerified` update, and session insert\ncommit together. Admission denial, a non-ok response after activation starts,\nand any 5xx response throw a private rollback sentinel. Expected policy denial\nreturns a generic 403. Operational rollback emits the metadata-only\n`auth.atomic_email_otp_operational_rollback` event and returns a generic 503,\nwithout exposing raw errors. Ordinary invalid-OTP 4xx responses still commit\nBetter Auth's attempt accounting, and the OTP-send route remains outside the\ntransaction. Unsupported contracts, runtimes, database modes,\nmissing/duplicated config, enabled signup,\nand a hook/config mismatch now fail at compile time.\n\n### Neon migrations can declare cross-schema foreign keys\n\nNeon projects can now declare fully qualified, single-column or composite\nforeign keys under `compiler.migrations.foreignKeys`. Each entry names the\nconstraint, source and target schema/table/column tuples, and explicit\n`onDelete` / `onUpdate` actions. The compiler rejects unsafe identifiers,\nmismatched tuple arity, duplicate or ambiguous declarations, unknown keys,\nand non-Neon providers before generating SQL.\n\nDeclared constraints are sorted deterministically and folded into Quickback's\ncontent-addressed Postgres journal after the Drizzle schema migration. A new\nconstraint is added `NOT VALID` and then validated, so existing orphan rows\nfail the migration; replay verifies an exact catalog match and rejects a\nsame-named constraint with different semantics. This surface enforces\nrelational integrity only—business rules remain in generated or authored API\nactions, not database triggers.\n\n### Compile completion steps honor the Neon connection mode\n\nThe CLI's successful-compile footer now distinguishes Neon HTTP from\nHyperdrive. HTTP projects retain the direct `DATABASE_URL` Worker setup.\nHyperdrive projects show `DATABASE_MIGRATION_URL` only as a local or CI\nmigration input, point local development at the configured Hyperdrive\n`localConnectionString`, and never recommend deploying `DATABASE_URL` as a\nWorker secret.\n\nNamed Hyperdrive environments also show their configured Neon branches,\nrequired-secret inventories, and explicit Wrangler `--env` targets. The footer\nno longer suggests the unnamed `.env.neon` / `.dev.vars` workflow or a bare\ndeploy for an isolated `dev` / `prod` setup.\n\n### Cloudflare email delivery and named Neon targets fail visibly and deploy explicitly\n\nGenerated Cloudflare email code now uses the native Workers `SendEmail`,\n`EmailAddress`, attachment, and `EmailSendResult` contracts. The Workers\nbuilder keeps its camel-case fields and `{ email, name }` address shape, while\nthe REST transport retains its separate snake-case fields and `{ address,\nname }` shape. Generated projects move to `@cloudflare/workers-types` v5 with\nWrangler 4.110 so the binding and result types agree without `any` casts.\n\nEvery Better Auth email callback now creates an observed delivery promise. On\nWorkers, the callback hands that still-rejecting promise to\n`executionCtx.waitUntil(...)` and returns after the task is accepted; outside a\nrequest lifecycle it returns the promise for the caller to await. Failures emit\nonly a structured generic event, never provider error content, and remain\nrejected instead of being detached or swallowed. SES and SNS background sends\nuse the same lifecycle rule.\n\nNeon Hyperdrive's generated postgres.js client now caps each request-scoped\npool at five connections. Named environments gain explicit `deploy:dev` and\n`deploy:prod` package scripts (mapped to their configured Wrangler environment\nnames), while the unsafe bare `deploy` script remains absent and migrations\nremain a separate target-owned step.\n\n### Contract v2 auth and Neon authority boundaries are fail-closed\n\nContract-v2 projects no longer emit Quickback's generic JWT mint endpoint,\nJWT helper, middleware verification/mint fast-path, or related imports unless\nthe project explicitly declares `auth.jwt`. Contract v1 retains its existing\ndefault for compatibility. Adding `auth.jwt: {}` to a v2 config opts back into\nthe custom Quickback JWT with its normal default settings.\n\nConfigured delegated authenticators now produce closed TypeScript unions in\nboth generated `AppContext` and Neon RLS context. Request contexts contain only\nresolved principal variants; the compiler-internal credential-lookup variants\nexist only in the database context. Delegated standalone actions do not require\nBetter Auth `activeOrgId` / `activeTeamId` before their declared principal\naccess tree runs, and their context cannot acquire account, organization, team,\nmembership, or scope authority.\n\nOn Cloudflare + Neon, the API-key organization membership lookup now runs with\nrequest-scoped user/org RLS claims before it stamps verified organization and\nrole authority into `AppContext`. Generated security migrations also converge\ndirect privilege drift: the audit schema/table revoke all direct grants from\n`PUBLIC`, the runtime, and admin before restoring their exact write-only/admin\nsets, while the Drizzle journal schema/table/sequences and database `CREATE`\ncapability explicitly revoke `PUBLIC` and runtime access before granting the\nmigration role.\n\n### Standalone action routes preserve their exact authority context\n\nGenerated standalone routes now pass each action the context and scoped\ndatabase types inferred from that action's own `execute` signature. Account actions therefore receive a\nrequired account identity, while `event_pass`, `event_delegate`, and other\ndelegated-principal actions retain their exact principal literal at the route\nboundary. Relationship `loads` / `exposeAs` hydration is intersected with that\nauthority context, including required shared targets and optional distinct\nmulti-lane targets, instead of replacing it with the broad application\ncontext.\n\nThe same boundary keeps ordinary request databases and temporary\nservice-role-backed scoped databases assignable to the generated Hyperdrive\naction helper without widening the handler's schema-aware `db` type.\n\nGenerated principal-auth identity guards also emit explicit strict TypeScript\nparameter and return types. Contract-v2 Cloudflare + Neon output no longer\nfails `tsc` on implicit-`any` guard parameters.\n\n### Parameterized actions keep complete v2 schema harvests\n\nThe action-input harvest plan now converts Hono-style `:param` segments to the\nOpenAPI `{param}` form for standalone actions and parameterized resource paths.\nPreviously the CLI could harvest every schema successfully, but the compiler\ncould apply only parameter-free actions because it looked up parameterized\noperations under the wrong OpenAPI key. Contract v2 now counts and patches the\nsame canonical path emitted by OpenAPI and MCP.\n\nGenerated standalone-action routes also remove template-only trailing spaces\nwhen optional audit blocks are absent, keeping regenerated source diffs clean.\n\n### Action-schema harvest uses the generated runtime dependency tree\n\nThe CLI now resolves action-harvest dependencies from the configured\n`build.outputDir/node_modules` before unrelated ancestor installs. This fixes\nisolated projects that keep authored definitions under `quickback/` and the\ngenerated runtime under a sibling directory such as `src/`: their actions can\nuse the runtime's Zod 4 and Drizzle installation without adding workspace-root\nsymlinks. An older user-level or monorepo-level Zod can no longer shadow the\nruntime's declared version during schema evaluation.\n\nSchema-only evaluation also emits inert named table proxies for authored\nDrizzle exports. Shared input/DTO modules may therefore construct top-level\nselection objects such as `{ id: records.id }` without executing a database\noperation or losing the action's Zod schema.\n\nHarvest failures now retain the exact action key, failing phase (`bundle` or\n`evaluation`), and bounded underlying error. Contract v2 includes those\nper-action diagnostics in its fail-closed compile error; v1 retains its\nbest-effort static-schema fallback.\n\n### Contract v2 delegated principals and RLS-only action tables\n\nCloudflare + Neon Hyperdrive projects on `contract.version: \"v2\"` can now\ndeclare framework-generic delegated authenticators under `auth.principals`.\nEach named principal owns an exact, non-`Bearer` Authorization scheme, a\nproject hook that proves the credential and returns only `{ digest }`, and one\ncompiler-owned indexed lookup that resolves the actor, optional session/family,\nstring claims, and active status. The hook receives no database handle. Proof\nhooks authored under `quickback/lib` are staged into generated `src/lib`, even\nwhen no action imports them directly.\n\nDelegated authority is structurally disjoint from Better Auth accounts:\n`ctx.principal` is populated while user, organization, team, and membership\nfields remain absent. Access arms may use `principals: [...]`; fields inside an\narm are ANDed and sibling arms are ORed. Generated action helpers preserve\nthat boundary in TypeScript, including the anonymous possibility of a\n`PUBLIC` sibling arm. Mixed credential transport rejects Authorization plus an\nAPI key or an actual Better Auth session cookie, while unrelated analytics\ncookies do not create a false conflict. `Bearer` remains reserved for account\nauthentication.\n\nResources can also declare operation-specific `databaseAccess` policies for\nauthored actions and support tables. This is an RLS-only surface: it emits no\ngeneric route or OpenAPI operation and is accepted only on Cloudflare + Neon\nHyperdrive. Every authorization path must contain a nonempty SQL-lowerable\nrecord equality; unbounded principal/role leaves, any unbounded OR arm, empty\nrecords, ambiguous mixed boolean nodes, app-only predicates, and unsupported\nproviders fail compilation. This keeps business logic in authored API actions\nwhile Postgres independently enforces the same event/person or account/org row\nboundary.\n\nPrincipal claims use the same transaction-local Hyperdrive preamble as account\nclaims, with query caching disabled. Restrictive per-operation principal\nfences prevent a public, exception, or legacy permissive policy from admitting\nthe wrong principal type. Credential lookup indexes and RLS journal entries are\ncontent-addressed and converge when a table, digest column, or definition\nchanges; generated Postgres identifiers include collision-resistant hashes and\nstay within the 63-byte limit. Each security migration also drops the complete\ncompiler-owned `databaseAccess` policy family before recreating the current\noperations, so removing or moving an operation revokes the old permissive\npolicy instead of leaving it active. Record fields resolve through authoritative\nDrizzle metadata to exact quoted physical identifiers, unknown fields fail the\ncompile, and DB-only pseudo-roles follow the same ADMIN/SYSADMIN/INTERNAL\ncontract as the application surface.\n\n### Action execute helpers preserve their typed boundary\n\nGenerated per-feature `defineAction` helpers no longer erase `services`, the\nHono request context, record predicates, or the action's return value to\n`any`. Zod input and record inference remain intact, `whereRecord` and\n`whereTransition` accept only the helper's bound table, and the existing D1 /\nNeon Hyperdrive scoped `db` and interactive `tx` types now flow through the\nsame execute boundary. The returned value is inferred exactly; this does not\nadd a response schema, invalid-return rule, or new output contract.\n\nHTTP/WebSocket Neon retains its intentionally dynamic `db`, and `AppContext`\nretains its open index signature for runtime-hydrated namespace fields.\n\n### Neon Hyperdrive is now the only Worker database lane, including Better Auth\n\nFor `connectionMode: \"hyperdrive\"`, generated Better Auth code now uses the\nsame HYPERDRIVE-backed, service-role-scoped database handle as the rest of the\ngenerated API. `DATABASE_URL` is no longer emitted or required as a Worker\nsecret in Hyperdrive mode; migration credentials remain inputs to the compiler\nor CI environment. HTTP-mode Neon retains its existing `DATABASE_URL` runtime\ncontract.\n\n### Public contract v2 now compiles as one coherent API/auth surface\n\nProjects may set `contract: { version: \"v2\" }` to select `/api/v2/*` feature\nroutes and `/auth/v2/*` Better Auth routes. The compiler now threads that\nselection through generated route mounts, Better Auth configuration and\nmiddleware, OpenAPI paths and server metadata, MCP internal tool calls, OAuth\ndiscovery, `llms.txt`, schema/embeddings/system routes, live views, namespace\nactions, and dedicated-domain `/v2/*` shortcuts. The option is no longer\nfail-closed. Omitting `contract` or selecting `v1` preserves the existing v1\noutput.\n\nBundled CMS and Account clients now receive the selected API and auth base\npaths through both their Vite build environment and the Worker-injected runtime\nconfig. CMS CRUD, schema, sysadmin, and live-view requests and Account auth,\ndata, and live-view requests therefore stay on `/api/v2` and `/auth/v2` for a\nv2 project instead of falling back to client-side v1 literals. V1 SPA config\nretains its historical byte shape.\n\nV2 compiles also require a complete client-side action input-schema harvest.\nThe current CLI reports the exact action files that failed to produce a JSON\nSchema, and the compiler independently rejects missing, invalid, or partial\nmaps at the shared parse boundary used by both complete and validation-only\ncompiles. `POST /compile?complete=false` can no longer bypass the v2 gate. For\nrecord actions with `bulkVariant: true`, the harvested schema now patches both\nthe single-record request body and the bulk operation's nested `input`; the\naction is counted complete only when both OpenAPI targets exist. Harvest\nplanning also normalizes filename-based action bindings to the table's declared\nname and resource path, so kebab-case filenames exporting snake/camel-case\ntables are not silently omitted. V1 remains best-effort for backward\ncompatibility.\n\n### Complete, isolated Wrangler targets for named Neon environments\n\n`providers.database.environments` now defines deployable Neon Hyperdrive\ntargets instead of emitting empty `[env.*]` shells. Because Wrangler does not\ninherit vars or bindings into named environments, each target must explicitly\nown its generated vars, required-secret contract, Hyperdrive and KV IDs,\nrate-limit namespace IDs, and Cloudflare Email binding. The compiler rejects\nmissing overrides, shared stateful IDs, optional secret declarations, invalid\ntarget semantics, and unsupported binding families rather than generating a\nWorker that starts without part of its runtime.\n\nThe required-secret inventory is now centralized and includes generated\ncredentials as well as custom declarations: `BETTER_AUTH_SECRET`, a configured\n`auth.jwt.secretEnv`, `ENCRYPTION_KEK` when envelope encryption is present, and\nevery `bindings.secrets` entry marked `required`. Generated Better Auth SES/SNS\ncredentials, AWS-backed anonymous-upgrade credentials, enabled social-provider\nclient id/secret pairs, and R2 presign credential env names are included as\nwell. Cloudflare social auth now reads those credentials from the Worker `env`\nbinding instead of relying on `process.env` compatibility behavior. Named\ntargets also reject every generated top-level custom-domain source — including\nruntime routes, the primary/CMS/Account/Admin/Auth/API domains, and app domains\nor aliases — until routes can be declared with explicit per-environment\nownership; top-level routes can no longer produce an ambiguous deployment\ntarget.\n\nNamed targets are currently limited to Neon Hyperdrive with Better Auth.\nExternal auth remains fail-closed until its service binding can be declared\nindependently for every named environment.\n\nFor named-environment projects, the base Worker has no deployable stateful\nbindings, local development selects a named target, and that selected target\nis always the required logical `dev` environment, which must own an explicit\ndevelopment-only Hyperdrive `localConnectionString`. Quickback emits it only\nin the selected named binding, rejects a top-level\noverride when named environments exist, and rejects local URLs on staging or\nproduction targets; deployed targets continue to resolve the remote\nHyperdrive configuration by ID. The generated package omits the unsafe bare\ndeploy script. Existing projects that omit\n`environments` keep byte-identical Wrangler output and the existing dev/deploy\nscripts. See [Neon → Named Cloudflare deployment environments](/compiler/targets/hono-api/database/neon#named-cloudflare-deployment-environments).\n\n### Local compiler trust boundary and deterministic Drizzle commands\n\nThe supported Docker launcher now opts into unauthenticated local compilation\nexplicitly and publishes the compiler only on `127.0.0.1`; missing or unknown\ncompiler modes retain hosted authentication. The CLI recognizes only exact\nloopback hostnames as local. Migration post-commands now use the configured\npackage manager's local binary execution form, with npm forced offline and its\nimplicit install prompt disabled, so a missing `drizzle-kit` fails clearly\ninstead of fetching an unpinned package.\n\n### Action rate limits now emit — documented since the rate-limit pillar, wired now\n\nThe [rate-limit docs](/compiler/definitions/rate-limit#actions) have described\nper-action rate limiting since the pillar shipped: record-based actions inherit\nthe resource's `update` bucket, standalone actions inherit the project-default\n`update` bucket, and actions may declare a `rateLimit` override or opt out with\n`rateLimit: false`. The generated routes never contained the checks. They now\ndo, exactly per the documented contract:\n\n- Record-based actions (and their bulk variants, which share the same counter —\n one token per batch request) are keyed\n `<resource>:action:<name>:<user>`; standalone actions are keyed\n `standalone:<declaredPath>:<user>`. The `:action:`/`standalone:` infixes mean\n action counters never collide with CRUD counters.\n- `rateLimit: { limit, period }` on an action emits its own binding\n (deduped by tuple, same `RL_<limit>_<period>` scheme); `rateLimit: false`\n opts the action out entirely.\n- Record-based action routes are now **exempted** from the per-resource CRUD\n catch-all middleware. Previously a `POST /:id/approve` was incidentally\n counted against the resource's `create` bucket — wrong bucket, wrong key.\n- Actions-only (tableless) projects now provision the project-default binding;\n previously they shipped with none.\n\n**Behavior change:** standalone actions were previously *unlimited*; they now\ninherit the project-default `update` bucket (200 requests / 60s per user/IP\nwith shipped defaults). PUBLIC webhook-style endpoints that absorb provider\nbursts should declare their own budget (`rateLimit: { limit: 1000, period: 10 }`)\nor opt out (`rateLimit: false`). The compiler emits a warning when a PUBLIC\nstandalone action silently inherits the default, so affected actions are\nflagged at compile time.\n\n### Better Auth CLI pinned and shipped as a generated devDependency\n\nThe generated `auth:schema` script runs `npx better-auth generate`, but the\n`better-auth` runtime package ships no executable — the `better-auth` bin\nlives in the npm package `auth` (the official Better Auth CLI; the team took\nover that name at 1.5.0, superseding the frozen `@better-auth/cli`). Generated\nprojects now declare `auth` as a devDependency pinned to the runtime's minor\nline, so `npm run auth:schema` resolves the CLI locally instead of requiring a\nglobal install. The compiler image's global CLI is pinned to the same version,\neliminating silent skew between the CLI on `latest` and the pinned runtime.\n\n### Compile warning when an action's input schema degrades to untyped\n\nWhen action input schemas aren't harvested client-side (older CLI, or a direct\n`/compile` API call), the static Zod parser supplies OpenAPI/MCP input schemas\n— and silently degrades unrecognized constructs (discriminated unions,\nrefinements, `z.record`, transforms) to the accept-anything `{}`. That\ndegradation is no longer silent: the compile result now carries a warning per\naffected action naming the route, source file, and the exact untyped field\npaths. Actions covered by the CLI harvest are never warned on, and actions\nthat declare no input are skipped.\n\n### Auth docs: JWT security posture stated up front\n\nThe [Auth & JWT page](/compiler/config/auth) now leads with the posture\nsummary instead of burying it: the default 180-second auto-refreshed TTL plus\n`revocationCheck: 'kv'` (seconds-level revocation, auto-stamped on ban /\nmember removal / role change / scope-conferring row changes) is the\nrecommended configuration and covers the vast majority of deployments — with\nthe residual trade-offs (per-principal granularity, fail-open on KV outage,\n~60s cross-PoP propagation) stated explicitly for strict threat models.\n\n### Neon via-user reads: generated list handlers now typecheck against the concretely-typed service handle\n\nOn Neon, a read firewall carrying a via-user multi-hop relationship predicate\nroutes the generated read handlers to `createServiceDb(c.env)` — a genuine\n`NeonHttpDatabase<typeof schema>` — instead of the loosely-typed request db.\nThe list handler's query construction declared drizzle select builders with\n`let` and reassigned them (`query = query.where(…)`, `.orderBy(…)`,\n`.limit(…).offset(…)`, and the count/aggregation/group-by variants), which is\na type error against drizzle's immutable builder typing: `.where()` returns\n`Omit\n</Button>\n```\n\n`ResponsiveModal` survived the migration unchanged — it composes the higher-level Dialog + Drawer wrappers (preserved public API), not the underlying primitives.\n\n#### Caller-side API changes worth noting\n\nBase-ui ships some real behavioural changes the Radix variants didn't:\n\n- `<Select onValueChange>` now receives `(value: string | null, eventDetails) => void` (was `(value: string) => void`). Existing `Dispatch<SetStateAction<string>>` setters reject `null` — wrap callbacks defensively: `onValueChange={(v) => v != null && setX(v)}`.\n- `<DropdownMenuContent forceMount>` removed (base-ui has no `forceMount`). Use base-ui's `keepMounted` on the Popup/Positioner if you need to preserve unmounted state.\n- Component sub-names shifted (`Dialog.Content` → `Dialog.Popup`, `Dialog.Overlay` → `Dialog.Backdrop`). Data attributes are now `data-open` / `data-closed` (no more `data-state=\"open\"`).\n\n#### Adding a new primitive after this release\n\n```bash\ncd packages/ui\npnpm dlx shadcn@latest add <component> --overwrite --yes\n# Sweep generated `@/` imports to relative paths — the SPAs' vite-tsconfig-paths\n# plugin doesn't see packages/ui's @/* mapping at bundle time:\nsed -i.bak \\\n -e 's|\"@/lib/utils\"|\"../lib/utils\"|g' \\\n -e 's|\"@/components/|\"./|g' \\\n -e 's|\"@/hooks/|\"../hooks/|g' \\\n components/<component>.tsx && rm components/<component>.tsx.bak\n```\n\nIf the new primitive pulls in fresh deps, mirror them into `apps/compiler/deps-spa-{cms,account}-package.json` per the SPA build pipeline or Docker SPA builds will fail.\n\n---\n\n## v0.18.1 — May 18, 2026\n\n### Account SPA — teams, active-team picker, permission-aware UI\n\nThe Account SPA's organization surface is now feature-parity with Better Auth's `organization` plugin for the basic team workflow, and replaces the long-standing hardcoded `role === 'owner' || 'admin'` checks with `checkRolePermission` so projects that ship custom roles get a UI that respects them.\n\n#### Teams (opt-in)\n\nWhen the BA config enables teams — `organization({ teams: { enabled: true } })` — the compiler emits `VITE_ENABLE_ORG_TEAMS=true` and the Account SPA exposes a Teams tab on each organization:\n\n- **Teams index** (`/$slug/teams`) — splits into \"Your teams\" (from `listUserTeams`) and \"Other teams\" so non-admins land on what's relevant. Create / rename / delete from the list, gated on `team:create` / `team:update` / `team:delete`.\n- **Team detail** (`/$slug/teams/$teamId`) — member roster with add / remove, joining `listTeamMembers` against the org's full member list for display.\n- **Active-team picker** in the org header — calls `setActiveTeam` and exposes the choice via `OrganizationContext.activeTeamId` so downstream routes (and the BA `session.activeTeamId` server-side) stay in sync.\n- **Team-aware invites** — `InviteMemberDialog` shows an optional team picker when teams are on and forwards `teamId` to `inviteMember`, so accepting the invite drops the new member straight into the right team.\n\nTeams are loaded once by the `$slug` layout (`listTeams` + `listUserTeams`) and exposed via `OrganizationContext.teams` / `userTeamIds` / `refreshTeams`, so individual team routes don't re-fetch the list.\n\n#### Permission-aware UI via `checkRolePermission`\n\n`OrganizationContext.isOwnerOrAdmin` is gone. Routes now read `can(resource, action)` from context, which delegates to `authClient.organization.checkRolePermission` — synchronous, no roundtrip, and aware of any custom roles registered via the BA `ac` option. Multi-role users (BA stores multiple roles comma-separated) are handled by checking each role; the action is allowed if any role grants it.\n\nMigrated sites:\n\n- `$slug.tsx` tab gates → `can('invitation', 'create')`, `can('organization', 'update')`\n- `members.tsx` action menu → `can('member', 'update' | 'delete')`; the owner-hierarchy guard (non-owners can't touch owner-role members) is preserved as a client-side mirror of BA's server enforcement\n- `invitations.tsx` → `can('invitation', 'create' | 'cancel')` gates the Invite button, resend, and cancel separately\n- `settings.tsx` → `can('organization', 'update')` for the form, `can('organization', 'delete')` for the danger zone (was owner-only)\n- `teams.tsx` / `teams.$teamId.tsx` → `can('team', 'create' | 'update' | 'delete')`\n\nProjects on the default three-role hierarchy see no behaviour change; projects that defined `admin`/`member` overrides via BA's access-control API now get a UI that matches what the server will actually authorize.\n\n#### Editable slug + metadata on organization settings\n\nThe `$slug/settings.tsx` form now edits two more `organization.update` fields:\n\n- **URL slug** — full debounced `checkSlug` flow (mirroring the create-org form); on rename, the SPA navigates to `/${newSlug}/settings` and the layout re-fetches with the new slug.\n- **Metadata** — single `Record<string, any> | null` JSON textarea, parsed on submit with inline error messaging. Empty clears the field.\n\nSlug rename is non-breaking for the SPA itself, but every external link / bookmark that references the old slug becomes a 404 — the form warns about this before saving.\n\n#### Auth client wiring\n\nWhen `VITE_ENABLE_ORG_TEAMS=true`, the SPA's `organizationClient(...)` is instantiated with `teams: { enabled: true }` so the team APIs are typed end-to-end. When the flag is off, team methods aren't surfaced — and the Teams tab is hidden — keeping the bundle and UI honest about what the server actually supports.\n\n---\n\n## v0.18.0 — May 17, 2026\n\n### `config.apps` — mount user-authored SPAs on dedicated hostnames\n\nThe compiler now generates per-hostname Worker middleware for arbitrary user SPAs alongside the built-in CMS and Account UIs. Previously the only way to host a product app next to a Quickback API was a second Worker; `config.apps` brings the full stack — API, account, and product UI — onto one deployment with same-origin auth.\n\n```ts\napps: {\n www: {\n domain: \"www.example.com\",\n aliasDomains: [\"example.com\"], // apex serves the same SPA\n },\n}\n```\n\nEach entry binds one or more hostnames to a directory under `src/apps/<name>/` and inherits the Account-domain pass-through behavior — `/api/`, `/auth/`, `/admin/`, `/storage/`, and `/health` route to Hono so the SPA fetches its API without CORS. The compiler:\n\n- emits a `custom_domain = true` route in `wrangler.toml` for the primary hostname and every alias\n- adds each hostname to Better Auth's `TRUSTED_ORIGINS` (when `trustedOrigins` is left unset)\n- widens the CSP `connect-src` to cover the SPA-baked origins\n- folds the new hostnames into shared-parent detection for `crossSubDomainCookies`\n\nDrop the prebuilt SPA bundle at `quickback/apps/<name>/` — the existing source-apps passthrough copies it byte-for-byte into `src/apps/<name>/`. The compiler doesn't build the SPA; it only emits routing for whatever's already there. The names `cms`, `account`, and `public` are reserved; hostname collisions with `cms.domain` / `account.domain` / `account.adminDomain` or between two `apps[*]` entries fail at compile time.\n\nWhen `cms` and `account` are both configured, the multi-domain catchall now explicitly skips app hostnames — an API miss on an app host returns the standard 404 JSON via `app.notFound` instead of stray-serving a sibling SPA's HTML shell.\n\n### Cross-subdomain cookie inference handles apex aliases\n\nThe shared-parent detection that drives `advanced.crossSubDomainCookies` previously reduced any hostname by stripping the leftmost label — `'example.com'` collapsed to `'com'`, which broke equality against sibling subdomains. Apex hostnames (exactly two dot-segments) are now treated as already being the parent, so apex aliases (`example.com` listed alongside `www.example.com`) coexist cleanly with `auth.example.com` / `cms.example.com` and the compiler still emits `crossSubDomainCookies: { enabled: true, domain: '.example.com' }`.\n\n---\n\n## v0.17.2 — May 15, 2026\n\n### `customPlugins` escape hatch on `defineAuth(\"better-auth\", …)`\n\nThe Better Auth provider now accepts `customPlugins` alongside the named-plugin registry — a path to ship third-party plugins (`@better-auth-kit/audit`, …), unregistered built-ins, or one-off project-local plugins without forking the compiler.\n\nEach entry is an explicit import descriptor:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: { passkey: true, organization: true },\n customPlugins: [\n // (1) Project-local plugin file at quickback/plugins/long-session.ts\n { from: \"./plugins/long-session\", export: \"longSessionPlugin\" },\n // (2) Third-party npm package\n {\n from: \"@better-auth-kit/audit\",\n export: \"auditPlugin\",\n args: { events: [\"sign-in\"] },\n dependencies: { \"@better-auth-kit/audit\": \"^1.0.0\" },\n },\n ],\n}),\n```\n\n`from` is either a relative path under `./plugins/` (the CLI auto-uploads matching files from `quickback/plugins/`; the compiler copies them into `src/plugins/<name>.ts` and rewrites the emitted import) or a bare npm specifier (emitted verbatim; declare `dependencies` so the package lands in the generated `package.json`). Omit `args` to emit the symbol uncalled (plugin instance); provide `args` to emit a JSON-serialized factory call.\n\nThe descriptor is validated with Zod — typos in `from`/`export`, paths that escape `./plugins/`, and references to files the CLI didn't ship all fail at compile time with a targeted message.\n\n---\n\n## v0.17.1 — May 14, 2026\n\n### `quickback start` — interactive onboarding\n\n```bash\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n```\n\n`start` walks new users through template selection, scaffolds the project on disk, and only prompts for an account when it's ready to compile. Cancelling at the login prompt leaves the scaffold intact — sign in and run `quickback compile` whenever you're ready.\n\nThe same deferred-auth flow applies to `quickback create`. Scaffolding and (optional) Cloudflare D1 setup run before authentication, so you can preview the project on disk before committing to an account.\n\n### Named views on the free tier\n\nThe `todos` template now ships a `dashboard` named view, exposing a projected response at `GET /api/v1/todos/views/dashboard`. Named views support per-view access rules and per-view field selection while inheriting the table's firewall and masking — the canonical way to ship list-view payloads that are cheaper to fetch and easier to cache than a full collection read.\n\n### `quickback init` removed\n\nFolded into `start` and `create`. The legacy command name prints a deprecation notice pointing at its replacements.\n\n### Minor\n\n- `quickback whoami` reads the stored tier from your credentials.\n- Pro upsell copy in `quickback login` is shown only when the server returns an explicit free-tier subscription.\n- Bare scaffolds (`cloudflare`, `empty`) report accurately when there are no features to generate migrations for.\n\n---\n\n## v0.16.10 — May 14, 2026\n\n### D1-specific safety pass on generated migrations\n\nThe `cloudflare-d1` provider now runs a post-generation pass over every Drizzle migration directory (auth, features, webhooks, audit) before the compile finishes. Better Auth cleanup for retired managed tables is stripped from raw `DROP TABLE` statements. Drop-only cleanup migrations are reordered child-first when foreign-key dependencies require it. Every generated D1 migration directory is replayed against SQLite during compile, so a D1-breaking migration fails at compile time rather than at `wrangler d1 migrations apply`.\n\n---\n\n## v0.16.9 — May 13, 2026\n\n### Resource-scoped realtime tickets\n\n`providers.database.config.realtime` accepts an object form for projects whose WebSocket subscribers aren't org members:\n\n```ts\nrealtime: {\n wsTicket: {\n role: \"attendee\",\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n}\n```\n\nThe generated `/broadcast/v1/ws-ticket` route authenticates the caller, evaluates the declared relationship role against the request, and mints a short-lived WebSocket ticket scoped to the resolved resource. `realtime: true` continues to enable the org-scoped broadcaster.\n\n### Unified broadcast targeting\n\nThe realtime helper and Broadcaster now route by `scopeKey || organizationId || userId`. String targets remain shorthand for `organizationId`; explicit targets can scope a broadcast to a resource or a single user:\n\n```ts\nawait realtime.broadcast(\"event-page-updated\", payload, { scopeKey: \"events:evt_123\" });\nawait realtime.broadcast(\"dm\", payload, { userId: recipientId });\n```\n\nWebSocket tickets are Quickback-minted (signed with `BETTER_AUTH_SECRET`), not Better Auth tokens — Better Auth remains the front-door auth check; Quickback signs the upgrade ticket after authorization succeeds.\n\n---\n\n## v0.16.8 — May 13, 2026\n\n### One auth transport per request\n\nGenerated middleware treats `Cookie`, `Authorization: Bearer`, and `x-api-key` as distinct auth methods and rejects mixed requests with `400 AUTH_METHOD_CONFLICT`. Query-string API keys (`?api_key=` / `?key=`) are no longer accepted. Machine-to-machine auth is explicit; precedence rules between transports are gone.\n\n### Cookie-backed CSRF gate\n\nGenerated apps now block cross-site `POST` / `PUT` / `PATCH` / `DELETE` requests from cookie-relying callers. The middleware skips explicit `Authorization` clients, requires a trusted `Origin` or `Referer`, and blocks `Sec-Fetch-Site: cross-site`. This matters most for cross-subdomain session setups where `SameSite=None` is intentional.\n\n### First-class Wrangler observability\n\n`providers.runtime.config.observability` now supports nested `logs` / `traces` blocks for `headSamplingRate`, `destinations`, `persist`, and `logs.invocationLogs`, emitting matching `[observability]`, `[observability.logs]`, and `[observability.traces]` TOML.\n\n---\n\n## v0.16.7 — May 12, 2026\n\n### Bearer wins over cookie\n\nA request carrying both `Authorization` and a session `Cookie` resolves entirely from the bearer; the cookie is dropped before `getSession()` runs. All three Bearer flavors (API key, JWT, session-token) now behave consistently — no more silent cookie precedence on session-token bearers.\n\n### Bearer plugin defaults to `requireSignature: true`\n\nBetter Auth's `bearer` plugin defaults to unsigned tokens; Quickback now emits `bearer({ requireSignature: true })`. Tokens emitted in the CORS-exposed `set-auth-token` header are server-signed with `BETTER_AUTH_SECRET` and verified on every request. Projects that genuinely need unsigned bearers can override via `providers.auth.config.plugins.bearer`.\n\nSee [Authentication Security → Bearer Tokens and Cookie Precedence](/stack/auth/security#bearer-tokens-and-cookie-precedence).\n\n---\n\n## v0.16.5 — May 12, 2026\n\n### Flat write DSL\n\nResource write operations are now declared at the table level alongside `read`, replacing the nested `crud` block:\n\n```ts\ndefineTable(customers, {\n read: { ... },\n create: { access: { roles: [\"admin\"] } },\n update: { access: { roles: [\"admin\"] } },\n delete: { access: { roles: [\"admin\"] }, mode: \"soft\" },\n upsert: { access: { roles: [\"admin\"] } },\n guards: { ... },\n});\n```\n\n`crud` and top-level `put` still compile as deprecated compatibility aliases. Mixed usage on the same resource is rejected. `schema-registry.json` emits both shapes during the transition.\n\n### CMS placement for multi-table feature actions\n\nStandalone actions on multi-table features have an explicit placement model:\n\n- `cms.placement: \"feature\"` shows the action on every table toolbar in the feature\n- `cms.placement: \"tables\"` with `cms.tables` scopes it to specific tables\n- `cms.hidden: true` keeps it API-only\n\nFeature-root standalone actions are emitted under a new `featureActions` bucket in `schema-registry.json`. Ambiguous multi-table standalone actions without placement compile with a warning.\n\n### `openapi.types` accepts a string array\n\nOne compile can write the generated types file to multiple locations, keeping colocated SPA clients in sync:\n\n```ts\nopenapi: { types: ['api-types.gen.ts', 'apps/web/src/lib/api-types.gen.ts'] }\n```\n\n### Stable artifact ordering\n\nGenerated route files and `schema-registry.json` are emitted in a stable order across runs. Identical logical input produces identical artifacts.\n\n---\n\n## v0.16.4 — May 12, 2026\n\n### Drizzle snapshot integrity\n\nDrizzle metadata files (`<n>_snapshot.json`) are no longer stamped with a Quickback warning key. The warning is now journal-only. Projects whose snapshots were corrupted by an earlier release self-heal on the next compile — the stripped header is removed during staging and the rewritten snapshot is clean.\n\n### `account.auth.*` drives the server, not just the SPA\n\nThe Account UI's auth flags (`signup`, `password`, `passkey`, `emailOTP`, `emailVerification`) now configure the Better Auth server alongside the SPA bundle. A normalizer maps them into the server config:\n\n- `signup → emailAndPassword.disableSignUp` (inverted)\n- `password → emailAndPassword.enabled`\n- `emailVerification → emailAndPassword.requireEmailVerification`\n- `passkey` / `emailOTP` → plugin additions\n\nThe SPA's `VITE_ENABLE_*` flags are derived from the same canonicalized server config, so the bundle and the server cannot drift. Two new flags ride along: `VITE_ENABLE_API_KEYS` and `VITE_ENABLE_MAGIC_LINK`.\n\n**Breaking** for projects that implicitly relied on the SPA-only behaviour: `account.auth.signup: false` now actually disables `POST /auth/v1/sign-up/email` on the server. Set `providers.auth.config.emailAndPassword.disableSignUp: false` explicitly to keep server signup open while hiding the SPA screen.\n\n---\n\n## v0.16.3 — May 9, 2026\n\n### Standalone action mount order\n\nFeature-level standalone action routers now register before sibling CRUD routers when both mount at the exact same prefix. A literal path like `GET /api/v1/records/today-bundle` resolves to the standalone handler instead of falling through to `GET /:id` and treating `\"today-bundle\"` as a record ID.\n\n---\n\n## v0.16.1 — May 9, 2026\n\n### Cloudflare ASSETS canonicalization\n\nWorker SPA fallbacks now request `/<dir>/` instead of `/<dir>/index.html`. Cloudflare's static-assets binding rewrites `/index.html` requests as 307 redirects to the trailing-slash path under the default `html_handling=auto-trailing-slash`, which previously caused redirect loops in SPA fallback handlers. Affects CMS, Account, admin, and the multi-domain catchall.\n\n### `account.customLogin`\n\nSet `account: { customLogin: true }` to drop a project-branded sign-in page in front of the bundled SPA. Place the page at `quickback/public/account/login/index.html` (as a directory) and the existing public passthrough serves it. The route registers before the `/account/*` SPA catch-all so the static handler wins; everything else under `/account/` continues to route through the bundled SPA.\n\n### Project-level realtime defaults\n\n`providers.database.config.realtime: true` now treats every resource as realtime-enabled by default. Per-resource `realtime: { enabled: false }` still wins.\n\n### Compile-time validators\n\nTwo new compile-time errors over silent runtime failures:\n\n- `AUTHENTICATED` + org-scoped firewall is rejected. The combination silently returned empty lists to sign-in-only callers who lacked an active org; the validator names three valid resolutions (drop the org scope, use `USER`, or split the route).\n- `createRealtime` imports without `realtime: true` enabled in the config are rejected at compile.\n\n### Drizzle metadata hardening\n\nDrizzle journal files carry a \"do not edit\" header. The compiler warns when the journal entry count exceeds the snapshot file count (typically the trace of a hand-deleted snapshot).\n\n### Minor\n\n- `SYSADMIN` is now recognised by the standalone-action org gate's pseudo-role matcher.\n- Apex `/` and `/account/login` get fallback redirects to `auth.loginUrl` when neither bundled SPA is enabled.\n- Record-based action URLs are kebab-case to match the OpenAPI spec (e.g. `/api/v1/widgets/:id/send-invite`).\n\n---\n\n## v0.16.0 — May 9, 2026\n\n### Agent Auth Protocol\n\nQuickback ships a server implementation of the [Agent Auth Protocol](https://agentauthprotocol.com) via `@better-auth/agent-auth`. Enable with `auth.plugins.agentAuth: true` and the compiler emits the full agent-auth surface: discovery at `/.well-known/agent-configuration`, capability projection from the project's OpenAPI spec, a device-authorization approval page in the Account SPA at `/agents/approve`, and the four agent-auth tables added to the auth schema automatically.\n\n**OpenAPI capability projection runs by default.** Every operation with an `operationId` becomes an agent capability. Default `approvalStrength` map: `GET → \"session\"`, `POST/PUT/PATCH/DELETE → \"webauthn\"`. The proxy `onExecute` makes a self-fetch with a Better Auth JWT minted for the agent session, so the inner request hits the existing JWT fast-path and runs the full firewall + access + masking pipeline. Opt out of OpenAPI projection with `agentAuth: { fromOpenAPI: false }` and wire `capabilities` + `onExecute` by hand.\n\n### Bearer-only on `/mcp` and the agent-auth surface\n\n`/mcp` forwards only `Authorization: Bearer …` into the inner request. Cookie and `x-api-key` forwarding are removed. Three Bearer flavors land on the same header — Better Auth session token (via the `bearer` plugin), OAuth access token (via OAuth Provider), and agent JWT (via `@better-auth/agent-auth`).\n\n### Auth DSL gains first-class plugin entries\n\n`bearer`, `oauthProvider`, and `agentAuth` are now typed entries in both the array-form union and the `BetterAuthPlugins` interface, with their own options shapes (`OAuthProviderOptions`, `AgentAuthOptions`). Existing `as any` casts can come out.\n\nAuto-enable rule: turning on `agentAuth` force-adds `bearer` + `oauthProvider`. No useful agent-auth deployment ships without those two.\n\n### `queue-consumer.ts` gating\n\nThe queue consumer is emitted when any of the following are true: embeddings are configured, queue handlers exist under `services/queues/*`, or `additionalQueues` is declared. Previously the third case left projects with a wrangler binding pointing at a missing handler.\n\n---\n\n## v0.15.0 — May 7, 2026\n\n### Sysadmin tier for the CMS\n\nA new opt-in `cms: { sysadmin: true }` flag turns the CMS into a cross-tenant DB-admin tool gated by `user.role === 'sysadmin'`. Distinct from the Better Auth `'admin'` plugin role, so user-management powers and DB-admin powers stay decoupled. Off by default.\n\nWhen enabled, the compiler emits a `SYSADMIN` pseudo-role (a fifth marker alongside `PUBLIC` / `AUTHENTICATED` / `USER` / `ADMIN`), a firewall escape hatch that drops tenant scopes for sysadmins while preserving soft-delete, a true cross-tenant `/admin/v1/sysadmin/organizations` endpoint, and a relaxed cross-tenant guard for list routes.\n\nThe CMS SPA gains a two-mode design: org admins keep the existing membership-based switcher, sysadmins get an \"All organizations\" selector that pins tenants via `?organizationId=` on every API call.\n\n### Durable Object `[[migrations]]` order is preserved\n\nCloudflare's migration list is append-only. The compiler now reads your existing `wrangler.toml` (when present) and emits auto-generated DO `[[migrations]]` blocks in two phases: deployed entries first (preserving order), net-new entries appended last. Reordering DOs in the config array no longer reshuffles deployed migrations.\n\n### `quickback/public/` — static-asset passthrough\n\nAnything dropped under `quickback/public/` is copied verbatim into `src/apps/` on every compile and served by the wrangler `[assets]` binding. Use for favicons, `robots.txt`, OG images, `.well-known/` files, marketing PDFs — anything that needs to ride past the compiler as bytes.\n\n- Optional. Missing folder is a no-op.\n- Stale-cleaned. Files removed from `quickback/public/` disappear on the next compile.\n- Hidden entries (`.DS_Store`, dotfiles) are skipped.\n- Collisions with compiler-emitted manifest paths fail the compile loudly.\n\n### Minor\n\n- Standalone-action wrapper skips the org gate when the access tree references any pseudo-role.\n- Queue handler emit no longer drops the `queue` export when there are no embeddings.\n\n---\n\n## v0.14.7 — May 7, 2026\n\n### Codegen fixes for projects with non-`id` primary keys and DO-only features\n\nFour surgical fixes to the generated output:\n\n- Duplicate table imports in relationship-role routes are deduplicated.\n- `db` references in single-record and bulk action handlers now resolve correctly during pre-fetch.\n- PartyServer auth gates pass the in-scope `db` handle into firewall calls.\n- Durable-object-only features keep their `lib/` files in the output.\n\n### `emailOtp` + AWS SES is OTP-only\n\n`auth.emailOtp` with the AWS SES email provider no longer auto-wires the magic-link companion. Mail-client URL prefetching can burn the one-time code before the human sees it; the Account SPA's `/email-otp` route is the single canonical entry point. Projects that explicitly want the magic-link arm can wire `sendVerificationOTP` directly.\n\n---\n\n## v0.14.6 — May 7, 2026\n\n### MCP transport correctness\n\nFour fixes to the MCP-over-HTTP path:\n\n- `tools/call` URLs are no longer double-prefixed for action tools.\n- Auth middleware accepts API keys via `Authorization: Bearer` in addition to `x-api-key` and query parameters — the channel MCP clients use exclusively.\n- `auth.roleHierarchy` is expanded for runtime role checks across api-key, JWT, and session auth paths. A higher role inherits the privileges of every lower role.\n- Team-scoped firewall predicates degrade gracefully when no team is active (org scoping continues to apply; team scoping is optional).\n\n---\n\n## v0.14.5 — May 7, 2026\n\n### MCP environment threading\n\nThe generated MCP server's `tools/call` dispatch threads `env` and `executionCtx` into the inner request, so action tools that touch Cloudflare bindings (D1, KV, R2, Queues) no longer crash with `undefined` env access.\n\n---\n\n## v0.14.4 — May 7, 2026\n\n### `via:` firewall predicates pull required imports\n\nThe relationship-role generator emits `inArray` and `sql` imports when the firewall has any `via:` predicate, and `buildFirewallConditions` accepts `(ctx, db)` so the relationship subquery has a Drizzle client to evaluate against. Every CRUD and action call site passes `db` through automatically.\n\n---\n\n## v0.14.3 — May 7, 2026\n\n### Relationship-role table re-exports\n\nGenerated `<table>.resource.ts` files now re-export their Drizzle table binding. Cross-feature relationship subqueries that import the binding from the resource file (rather than the schema) resolve correctly.\n\n---\n\n## v0.14.2 — May 7, 2026\n\n### Historical DO `[[migrations]]` are preserved\n\nA new `bindings.durableObjectMigrations` config slot carries forward `deleted_classes`, `renamed_classes`, and `transferred_classes` lifecycle entries across recompiles. Cloudflare's migration list is append-only; entries declared here are emitted first in `wrangler.toml`, then auto-generated current-class entries follow:\n\n```ts\nbindings: {\n durableObjects: [{ name: 'NOTEPAD', className: 'Notepad', from: 'lib/Notepad' }],\n durableObjectMigrations: [\n { tag: 'qb-do-deleted-legacy-notes-2026-05-05', deletedClasses: ['LegacyNotes'] },\n ],\n}\n```\n\nAll four lifecycle shapes are supported. User-declared entries can override auto-emit by reusing the same tag.\n\n---\n\n## v0.14.1 — May 7, 2026\n\n### Bulk action variants in `openapi.json`\n\nRecord-based actions with `bulkVariant: true` are now emitted as sibling operations in the OpenAPI spec, with the documented `{ ids, input, failFast? }` request shape, 200/207/400 responses, and a separate `<Resource><Action>Bulk` `operationId` so typed-client codegen distinguishes single from bulk.\n\n### Cross-tenant \"my events\" patterns\n\nThe access docs now include a worked example for the cross-tenant aggregation pattern (e.g. `GET /my-events` returning resources across all tenants a caller is invited to). See [Access → Cross-tenant dashboards](/compiler/definitions/access#cross-tenant-my-events-dashboards-are-not-this).\n\n---\n\n## v0.14.0 — May 7, 2026\n\n### Relationship-based authorization\n\nRoles can now be bound to a domain-table membership (\"user is a confirmed guest of this event\") rather than an org membership or a pseudo-role. Declare the relationship once and reference it from `firewall:` or `access.roles:`:\n\n```ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n },\n },\n roles: {\n guest: { via: 'guestOf' },\n eventStaff: { or: [{ via: 'guestOf' }, { roles: ['admin', 'owner'] }] },\n },\n}\n\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' },\n],\nread: { access: { roles: ['admin', 'member', 'guest'] } },\ncreate: { access: { roles: ['admin', 'guest'] } },\nupdate: { access: { roles: ['admin'] } },\n```\n\nThe compiler emits an inline Drizzle subquery against the relationship table and AND-composes it as the outermost firewall clause. The relationship table's own firewall (tenant scope, soft-delete) is honored inside the subquery; cross-tenant grants are impossible because the resource's tenant filter sits outermost.\n\nSupported surfaces: row-level scoping via `firewall: [{ field, via }]`, role gates on writes and reads, view access. Masking and action access reject relationship-roles at compile time with pointers to the working pattern (gate the row at the firewall layer, gate the role at the access layer).\n\nCross-tenant aggregation dashboards aren't solved by relationship-roles — the tenant firewall remains the outermost AND. For that pattern, use a user-scoped firewall or function-form access on a dedicated route.\n\nSee [Firewall → Relationship-based scoping](/compiler/definitions/firewall#relationship-based-scoping-via) and [Access → Relationship-based authorization](/compiler/definitions/access#relationship-based-authorization).\n\n### Bulk variants on record-based actions\n\n`defineAction({ bulkVariant: true })` emits `POST /:resource/batch/{action}` alongside the per-record route. The bulk handler loops the same access + transition + execute pipeline over a `{ ids, input, failFast? }` body:\n\n```ts\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n bulkVariant: true,\n transition: { field: \"status\", via: \"nextStatus\", fromTo: { /* ... */ } },\n async execute({ db, record, input, whereTransition }) {\n // exact same body — runs once per id\n },\n});\n```\n\nPer-record outcomes return as 207 Multi-Status. `failFast: true` aborts on the first failure and wraps the loop in `db.transaction()` on tx-supporting providers; D1 fails fast without rollback. Max 100 IDs per request. Rejected on standalone actions and `unsafe` actions.\n\n### Aggregations on read views\n\nRead views can declare pre-computed metrics that surface alongside the row payload:\n\n```ts\nread: {\n views: {\n pipeline: {\n fields: [\"id\", \"jobId\", \"candidateId\", \"status\", \"appliedAt\"],\n aggregations: {\n totalApplications: { fn: \"count\" },\n byStatus: { fn: \"groupBy\", field: \"status\" },\n },\n },\n },\n}\n```\n\nAggregations run over the same firewalled, filtered set as the row query; pagination is intentionally ignored. Supported functions: `sum`, `avg`, `min`, `max`, `count`, `count_distinct`, `groupBy`. See [Views → Aggregations](/compiler/definitions/views#aggregations).\n\n---\n\n## v0.13.5 — May 6, 2026\n\n### Object-form `auth.plugins` config is honored\n\nThe documented `plugins: { oauthProvider: {...} }`, `plugins: { organization: { teams: { enabled: true } } }` shapes now flow through the compiler unchanged. Per-plugin options reach the generated `auth.ts` as written.\n\n### `roles: [\"PUBLIC\"]` allowed on writes and actions\n\n`PUBLIC` is the explicit, uppercase opt-in for unauthenticated access on every access node — reads, writes, views, and actions. The runtime trusts the marker; row-level safety comes from firewall, masking, and the action's own validation. `PUBLIC` actions continue to receive mandatory audit logging.\n\nCommon pattern: pair `roles: [\"PUBLIC\"]` with `firewall: { exception: true }` on the resource so the row predicate doesn't reject every unauthenticated caller.\n\n---\n\n## v0.12.0 — May 5, 2026\n\n### Per-room authorization for PartyServer\n\n`bindings.durableObjects[].access` declares a path-scoped gate that runs the declared resource's firewall and `read.access` pipeline before the WebSocket upgrade:\n\n```ts\ndurableObjects: [\n // Single-resource: roomId IS the chat row id.\n { name: 'Chat', className: 'Chat', from: 'lib/Chat',\n access: { resource: 'chats' } },\n\n // Multi-resource: regex dispatches kind → resource.\n { name: 'Notepad', className: 'Notepad', from: 'lib/Notepad',\n access: {\n roomId: { pattern: '^(day-note|interaction|record):([A-Za-z0-9_-]+)$', kindGroup: 1, idGroup: 2 },\n resources: {\n 'day-note': { resource: 'day-notes' },\n 'interaction': { resource: 'interactions' },\n 'record': { resource: 'records' },\n },\n } },\n\n // Anonymous lobbies / public pads: explicit opt-out.\n { name: 'PublicLobby', className: 'PublicLobby', from: 'lib/PublicLobby',\n access: 'public' },\n]\n```\n\nThe gate 401s unauthenticated callers, 403s when the firewall hides the row, 404s when the row is missing. Resource references are validated against feature names at compile time. See [PartyServer Rooms → Per-room authorization](/stack/realtime/partyserver-rooms#per-room-authorization-via-access-v012).\n\n---\n\n## v0.11.1 — May 5, 2026\n\n### PartyServer auto-mount is secure by default\n\nThe `/realtime/*` auto-mount now wraps `partyserverMiddleware` in an auth check. Unauthenticated upgrades return 401; the four auth mechanisms (session cookie, JWT bearer, `x-api-key` header, query parameter) all unlock connections. Per-room access remains the `Server` class's responsibility in `onConnect`.\n\n---\n\n## v0.11.0 — May 5, 2026\n\n### OAuth Provider (MCP-ready)\n\nQuickback can act as a standards-compliant OAuth 2.1 + OIDC authorization server via [`@better-auth/oauth-provider`](https://better-auth.com/docs/plugins/oauth-provider). Enable with `plugins: [\"oauthProvider\"]`. The compiler auto-includes Better Auth's `jwt` plugin and the Account SPA gains a `/consent` page for the standard authorization-code flow.\n\nThis replaces Better Auth's deprecated `mcp` plugin and gives every MCP client (Cursor, Claude Desktop, claude.ai connectors, custom tooling) RFC 7591 dynamic client registration plus the discovery documents they need to bootstrap. See [Auth Plugins → OAuth Provider](/stack/auth/plugins#oauth-provider-mcp-ready).\n\n### API keys via query parameter\n\nThe auth middleware now accepts API keys as `?api_key=…` or `?key=…` query parameters. The `x-api-key` header takes precedence when both are sent. Prefer the header whenever the client supports it — query parameters land in access logs and `Referer` headers.\n\n### PartyServer rooms + realtime URL split\n\nThe realtime URL space is reorganized so names match what each primitive does:\n\n- **`/realtime/v1/*` → `/broadcast/v1/*`** — the org-wide Broadcaster moves to its semantically accurate prefix.\n- **`/realtime/<binding>/<room-id>`** — new mount for [PartyServer](/stack/realtime/partyserver-rooms) rooms. Per-room Durable Objects with presence and lifecycle hooks. Auto-mounted whenever a project declares any in-worker DO.\n\n**Breaking** — recompile + redeploy required:\n\n- `REALTIME_URL` env var renamed to `BROADCAST_URL`.\n- SPA helpers `getRealtimeWsUrl()` / `getRealtimeTicketUrl()` renamed to `getBroadcastWsUrl()` / `getBroadcastTicketUrl()`.\n- `appConfig.routes.api.realtime` renamed to `appConfig.routes.api.broadcast`.\n\n`partyserver`, `partysocket`, and `hono-party` are pre-installed in the compiler image; collab projects compile without an extra `npm install` step.\n\n---\n\n## v0.10.20 — May 4, 2026\n\n### In-worker Durable Objects\n\n`bindings.durableObjects[].from` flips a DO binding into in-worker mode and emits the export, the `[[migrations]]` block, and the `CloudflareBindings` type all together:\n\n```ts\ndurableObjects: [{\n name: \"ITEM_STREAM\",\n className: \"ItemStream\",\n from: \"features/loops/lib/ItemStream\",\n}]\n```\n\nDO class files live under `quickback/lib/` or `quickback/features/<feature>/lib/` — both copy verbatim into the generated `src/` tree on every compile. `from` and `scriptName` are mutually exclusive; cross-worker DOs (`scriptName` set) skip the re-export and migration block.\n\n`migrationTag` (default `qb-do-${className}`) is stable across regenerations and must never be removed or renamed once deployed. `useSqlite` defaults to `true`. See [Bindings → Durable Objects](/compiler/config/bindings#durableobjects).\n\n---\n\n## v0.10.18 — May 2, 2026\n\n### `experimentalRemote` — share deployed D1 with `wrangler dev`\n\nPer-binding `experimental_remote = true` lets `wrangler dev` read/write deployed D1 for selected bindings:\n\n```ts\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n splitDatabases: true,\n experimentalRemote: { auth: true, features: false },\n }),\n}\n```\n\nUseful for \"share prod auth in dev, keep feature writes sandboxed.\" Off by default.\n\n### Google OAuth + signup ToS\n\nThe Account SPA wires Google OAuth end-to-end when configured under `auth.config.socialProviders.google.enabled`. The signup flow gains a Terms-of-Service checkbox gate (configurable via the Account SPA branding).\n\n### CLI compile auth gate\n\n`quickback compile` now requires authentication for cloud-compiler runs. Device-flow `?redirect=` parameters are standardized across the login + signup pages so a user clicking \"Create one\" no longer loses their return URL.\n\n---\n\n## v0.10.15–v0.10.17 — May 2, 2026\n\n### CSP auto-config\n\nWhen `security.csp` is set, the compiler widens directives additively based on the project's enabled features:\n\n| Trigger | Auto-added | Directive |\n|---|---|---|\n| `cms: true` OR `account: true` | `'unsafe-inline'`, `https://fonts.googleapis.com` | `styleSrc` |\n| `cms: true` OR `account: true` | `https://fonts.gstatic.com` | `fontSrc` |\n| `csp` set (always) | `@trustedOrigins` | `connectSrc` |\n| Bundled SPA enabled | SPA-baked API origin (`config.domain`, `quickback.{baseDomain}`, `cms.domain`, `account.domain`) | `connectSrc` |\n\nAnything you already wrote stays — auto-config never removes or overrides. Each applied addition is logged to stderr. Opt out with `security: { cspAutoConfig: false }`.\n\nMost projects can write the minimal:\n\n```ts\nsecurity: {\n csp: {\n defaultSrc: ['@self'],\n scriptSrc: ['@self'],\n objectSrc: ['@none'],\n upgradeInsecureRequests: true,\n },\n}\n```\n\n…and the compiler fills in font hosts, trusted origins, and SPA-baked URLs.\n\nWhen a target directive is missing, auto-config scaffolds it from `default-src` baseline rather than widening `default-src` itself — CSP3 fall-back semantics would otherwise leak the addition to every directive that falls back to `default-src`.\n\n---\n\n## v0.10.14 — May 1, 2026\n\n### `auth.jwt` config\n\nThe bearer-token JWT used by the auth fast-path is configurable. Tune `expiresIn` to bound the post-revocation replay window without affecting browser SPAs (which auto-refresh on every authed call):\n\n```ts\nauth: {\n jwt: {\n expiresIn: 30,\n issuer: 'my-api',\n audience: 'partner-svc',\n secretEnv: 'CUSTOM_JWT_SECRET',\n },\n}\n```\n\n### Admin MCP endpoints filtered\n\nBetter Auth admin endpoints (`/admin/list-users`, `/admin/ban-user`, etc.) now carry `x-access: { userRole: ['admin'] }` in the generated OpenAPI spec. The MCP `tools/list` access-filter drops them for non-admin callers.\n\n### Declarative `security` config\n\nEvery security response header (`Content-Security-Policy`, COOP, COEP, CORP, HSTS, `X-Frame-Options`, `Referrer-Policy`, `Permissions-Policy`) is configurable from `quickback.config.ts`. `@`-prefixed sentinels (`@self`, `@none`, `@unsafe-inline`, `@trustedOrigins`, etc.) replace awkward `\"'self'\"` quoting.\n\nThe compiler lints the resolved config for known footguns: `@unsafe-inline` in `script-src`, wildcard sources, missing `default-src`, HSTS preload-list misconfiguration.\n\n### HSTS skipped on localhost\n\nGenerated middleware skips `Strict-Transport-Security` when the request hostname is `localhost`, `127.0.0.1`, or `*.localhost`. Without this gate, `wrangler dev` would pin a developer's browser to HTTPS across every project on that machine.\n\n---\n\n## v0.10.13 — May 1, 2026\n\n### Clickjacking defence on every Worker\n\nEvery Worker emits `Content-Security-Policy: frame-ancestors 'self' <TRUSTED_ORIGINS…>` and `X-Frame-Options: SAMEORIGIN` on every response. The CSP allowlist is sourced from the same `TRUSTED_ORIGINS` constant that gates CORS.\n\n---\n\n## v0.10.11 — May 1, 2026\n\n### MCP `tools/list` is access-filtered\n\nEach MCP tool now carries sanitised access metadata. `tools/list` filters against the caller's `ctx`: unauthenticated callers see only `PUBLIC` tools, authenticated callers see only role-gated tools they pass.\n\n- Wildcard CORS removed from the MCP endpoint.\n- Unauthenticated `GET /mcp` no longer enumerates tool names.\n- Internal flavor text is removed; `annotations.destructiveHint` and `_unsafe` remain — those are the spec-correct signals for clients.\n\n`tools/call` continues to re-enter the Hono app and run every middleware (auth, firewall, access, guards, masking), so hiding a tool from list never weakens the underlying gate.\n\n---\n\n## v0.10.10 — April 29, 2026\n\n### Reserved keys in `access.record` are rejected\n\n`access.record` is a flat field map evaluated as implicit AND between entries — keys must be column names. The compiler now rejects reserved keys (`and`, `or`, `roles`, `userRole`) inside `record` with migration guidance pointing at the working pattern (top-level siblings with their own `record:` blocks).\n\n---\n\n## v0.10.8 — April 29, 2026\n\n### Audit logging on Postgres targets\n\n`audit_events` previously only existed on `cloudflare-d1`. The audit table now lives in a dedicated `audit` schema (`drizzle.pgSchema('audit')`) on Postgres targets. The `hasSecurityAudit` gate accepts D1 or any PG dialect; `auditDatabaseId` remains a D1-only requirement.\n\n### `auditDatabaseId` is a compile-time requirement\n\nProjects with unsafe or `PUBLIC` actions that previously produced a placeholder `database_id = \"local-audit\"` in production now fail at compile time with the exact `wrangler d1 create <project>-audit` command and the config key where the returned ID goes.\n\n### Action input → OpenAPI / MCP\n\n`defineAction({ input: z.object({...}) })` schemas flow into the OpenAPI `requestBody` and the MCP tool's `inputSchema.properties`. Simple `z.object` shapes are extracted at compile time; discriminated unions, refinements, recursive schemas, and bare-identifier references run through Zod's native `z.toJSONSchema()` for full-fidelity output.\n\n### OpenAPI fidelity\n\n- Response schemas emit `required[]` for every non-nullable column.\n- `text(_, { enum: [...] })` columns emit as closed `{ type: \"string\", enum: [...] }`.\n- `id` claims `format: \"uuid\"` only when the project's `generateId` actually produces UUIDs. cuid2 / prefixed / nanoid / serial generators emit plain `{ type: \"string\" }`.\n\n### Minor\n\n- Auto-mask predicate verifies the resolved owner column exists before emitting an `or: 'owner'` clause; falls back to roles-only with a warning otherwise.\n- Generated CRUD errors emit canonical `QuickbackErrorCode` enum values (`DB_NOT_NULL_VIOLATION`, `DB_UNIQUE_VIOLATION`, etc.) so generated SDKs can exhaustively switch on `code`. See [API errors](/compiler/targets/hono-api/using-the-api/errors#database).\n\n---\n\n## DSL: one file per action, multi-table per feature\n\n### One file per action\n\nAction authoring is one file per action under `<feature>/actions/<name>.ts`. The filename is the action name and the URL segment:\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: { applied: [\"screening\"], screening: [\"interview\"], interview: [\"offer\"] },\n },\n async execute({ db, record, input, auditFields, whereTransition }) { /* … */ },\n});\n```\n\n`defineAction` is imported from a generated per-feature helper at `<feature>/.quickback/define-action.ts` — `record`, `input`, and audit fields are typed without manual annotations.\n\n**Discovery rules:**\n- `actions/<name>.ts` binds to the feature's primary table.\n- `actions/<table>/<name>.ts` binds to the sibling table file.\n- Setting `path:` makes the action standalone (custom URL, no record fetch).\n- Tableless features require every action to be standalone.\n\n**Retired** (rejected at load time with migration guidance): `actions.ts` (bundled multi-action file), `_feature.ts`, `handlers/` directory + `handler:` string ref, `defineActions(table, {…})`, colocated `defineActions` inside table files, `standalone: true` flag, `*-actions.ts` / `*.actions.ts` filename patterns.\n\nSee [Actions docs](/compiler/definitions/actions).\n\n### Multi-table actions per feature\n\nOne feature directory can own actions on multiple tables. Three discovery modes:\n\n- **Colocated** (canonical) — `<table>.ts` containing both `defineTable` and `defineActions(<table>, …)`. One file per entity.\n- **`actions.ts`** — single primary-table actions file at feature root.\n- **`actions/<table>.ts`** — per-table action files for strict schema/behavior separation.\n\nPlus a universal `_feature.ts` slot for non-table-bound feature-level actions and shared Zod schemas.\n\nAction names are unique per `(bindTable, name)` pair. Sibling-bound `actions/episodes/publish.ts` and `actions/shows/publish.ts` mount at `/episodes/:id/publish` and `/shows/:id/publish` and compile cleanly.\n\n---\n\n## Firewall: named-scope shape\n\nThe named-scope firewall shape is a co-equal user-facing input alongside the predicate array:\n\n```typescript\nfirewall: { organization: { column: 'tenant_id' } } // named-scope (compact)\nfirewall: { owner: { column: 'account_user_id' } }\nfirewall: { exception: true }\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n] // predicate array (explicit)\n```\n\nPick the form that reads better — named-scope for the common one-line case, predicate array when you need custom `in`-lists or non-scope predicates.\n\n**Auto-detection synonyms.** When `firewall:` is omitted, the compiler scans the schema for an isolation column. The org-scope list accepts `organizationId`, `organisationId`, `orgId`, `organization`, `organisation`, `org` (American + British). User-scope accepts `userId`.\n\n**`ownerId` is a targeted error signal.** When a table carries `ownerId` but no isolation column and no explicit `firewall:`, the compiler raises a specific error — `ownerId` is business-logic ownership, not access control. Use `userId` for access control, declare an explicit `firewall:`, or add a separate isolation column.\n\n---\n\n## v0.10.0 — April 26, 2026\n\n### `q.scope()` — single-declaration tenant scoping\n\n`q.scope(kind)` replaces the three-place pattern (column declaration + firewall predicate + ownership-guard) with one column:\n\n```typescript\ncolumns: {\n organizationId: q.scope('organization'), // → ctx.activeOrgId\n ownerId: q.scope('owner'), // → ctx.userId\n teamId: q.scope('team'), // → ctx.activeTeamId\n}\n```\n\n`q.scope()` columns auto-derive the firewall predicate, register with the guards layer as `systemManaged` (client input rejected), and auto-populate from `ctx` on create / upsert. The systemManaged extension generalises beyond `q.scope()`: any firewall predicate whose `equals` references `ctx.*` registers its `field` automatically.\n\nSee [`q.scope()`](/compiler/definitions/schema#qscope--tenant-scope-columns).\n\n### `masking[col].query.roles` — unified filter / sort / search gate\n\nThe three legacy per-capability flags (`filterable`, `searchable`, `sortable`) are replaced by a single `query.roles` allowlist:\n\n```typescript\nmasking: {\n email: {\n type: 'email',\n show: { roles: ['admin'] },\n query: { roles: ['admin'] }, // defaults to show.roles when omitted\n },\n}\n```\n\nA view's own `query.{filterable,searchable,sortable}` allowlist is the opt-in for higher-privileged roles; the existing intersection validator gates it at compile time.\n\n**Breaking:** `masking[col].filterable / .searchable / .sortable` is rejected at compile time with a migration hint. Replace with `query.roles` (or delete the flags — `query` defaults to `show.roles`).\n\n---\n\n## v0.9.0 — April 25, 2026\n\n### Unified `read:` pipeline\n\nThe read side of every resource has its own block — `read:` — that owns the collection-level `GET /` endpoint, single-record `GET /:id`, and named view projections.\n\n**Breaking changes** (compile-time errors with migration hints):\n\n- `crud.list` → `read.access` (plus `read.pageSize` / `read.maxPageSize`)\n- `crud.get` → `read.access` (single-record GET inherits automatically)\n- Top-level `views: {...}` → `read.views: {...}`\n- `crud.list.fields` / `crud.get.fields` → declare a named view under `read.views` and call `/views/{name}`\n\n### Pre-record access ordering\n\nHandlers on `/:id` run a role-only access check before the firewall query. A caller without a matching role gets 403 before the database is touched. This closes the 404-vs-403 ID-probe channel — an unauthorized caller can no longer distinguish \"row exists in another tenant\" from \"row doesn't exist.\" See [Access evaluation order](/compiler/definitions/access#evaluation-order).\n\n### Transactional batch operations\n\nBatch endpoints expose `failFast` and a `meta.transactional` response field. On tx-supporting providers (postgres, supabase, neon, libsql, better-sqlite3, bun-sqlite), `failFast: true` wraps the per-record loop in `db.transaction(...)` so any failure rolls back the entire batch. On Cloudflare D1 (no `db.transaction`), `failFast: true` stops on the first error but prior writes stay committed.\n\nEmbedding queue messages and realtime broadcasts emit after the transaction commits — rolled-back batches produce no orphan jobs.\n\nSee [Batch Operations → Transactional semantics](/compiler/targets/hono-api/using-the-api/batch-operations#transactional-semantics).\n\n---\n\n## v0.8.7 — April 17, 2026\n\n### Hono CVE bump\n\nHono is bumped to `^4.12.14` across the monorepo, the compiler Docker image's pre-installed deps, and every generator path that emits Hono into compiled projects. Older ranges covered the vulnerable window. Recompile to pick up the fix in your generated project's `package.json`.\n\n### Cloudflare Email Sending in public beta\n\nQuickback defaults to the Workers `send_email` binding for Cloudflare deploys. Cloudflare Email Sending has graduated to public beta — production-ready with zero-config. AWS SES remains a fully supported opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes. See [Email Configuration](/compiler/config#email-configuration).\n\n### Dependency sweep\n\n`wrangler@^4.83.0`, `drizzle-orm@^0.45.2`, `drizzle-kit@^0.31.10`, `zod@^4.3.6`, `@cloudflare/workers-types@^4.20260417.1`.\n\n---\n\n## v0.8.5 — April 15, 2026\n\n### `userRole` access primitive\n\nA new `userRole?: string[]` field in the declarative `Access` config evaluates against `ctx.userRole` (the Better Auth admin-plugin `user.role` column). Distinct from `roles`, which matches `ctx.roles` (org membership).\n\n```typescript\n// Org owner OR platform admin\naccess: { or: [{ roles: ['owner'] }, { userRole: ['admin'] }] }\n\n// Platform admins see SSNs across every org\nmasking: { ssn: { type: 'ssn', show: { userRole: ['admin'] } } }\n```\n\n`userRole` works everywhere `Access` is accepted — CRUD, actions, views, masking, and inside `or` / `and` combinators. See [Access → userRole vs roles](/compiler/definitions/access#userrole-vs-roles).\n\n### CMS admin gate enforced server-side\n\n`cms: { access: \"admin\" }` previously only hid the CMS link in Account UI and rendered an \"Access Denied\" screen inside the SPA. Server-side enforcement now applies at every CMS-facing surface: the SPA shell, `/api/v1/schema`, and `custom_view` CRUD.\n\n### Better Auth 1.5 + `@cloudflare/workers-types` compatibility\n\nGenerated API code typechecks against the new versions. The org-member role-change broadcast hook is emitted via `organizationHooks.afterUpdateMemberRole` (the supported shape after the 1.5 deprecation of `databaseHooks.member.update.after`). `REALTIME_URL` and `ACCESS_TOKEN` are always emitted as optional bindings when the organization plugin is active.\n\n---\n\n## v0.8.4 — April 14, 2026\n\n### `generateId: \"short\"` strategy\n\nA compact ID option for tables where short, shareable codes matter more than collision resistance at scale:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", { generateId: \"short\" }),\n}\n```\n\nGenerates 6-character alphanumeric IDs (e.g. `a3F9xK`) using nanoid's `customAlphabet` with the full 62-char alphabet (`0-9A-Za-z`). Requires the `nanoid` package.\n\n**When to use:** room codes, invite links, share URLs, ephemeral records.\n\n**When not to use:** high-volume tables. 62^6 ≈ 56.8B combinations means ~238K rows before a 50% collision probability. For large tables stick with `\"uuid\"`, `\"cuid\"`, or `\"prefixed\"`. See [Providers → ID Generation Options](/compiler/config/providers#id-generation-options).\n\n---\n\n## v0.8.2 — April 11, 2026\n\n### Catch-all `VITE_QUICKBACK_URL`\n\nA single Quickback origin can be set in place of four separate URL env vars:\n\n```bash\nVITE_QUICKBACK_URL=https://secure.example.com\n```\n\n| Individual var (explicit) | Fallback when unset |\n|---|---|\n| `VITE_QUICKBACK_API_URL` | `${VITE_QUICKBACK_URL}` |\n| `VITE_QUICKBACK_ACCOUNT_URL` | `${VITE_QUICKBACK_URL}/account` |\n| `VITE_QUICKBACK_CMS_URL` | `${VITE_QUICKBACK_URL}/cms` |\n\n`VITE_QUICKBACK_APP_URL` stays independent — it points at the tenant's own frontend. Non-breaking; individual vars take precedence when set. Library users can set `__QUICKBACK_URL__` on `globalThis`. See [Environment Variables](/stack/account-ui/environment-variables).\n\n---\n\n## v0.8.1 — April 9, 2026\n\n### Role hierarchy with `+` suffix\n\nDefine a hierarchy and use `+` to mean \"this role and above\":\n\n```typescript\nauth: { roleHierarchy: ['member', 'admin', 'owner'] }\n\ncrud: {\n list: { access: { roles: [\"member+\"] } }, // member, admin, owner\n create: { access: { roles: [\"admin+\"] } }, // admin, owner\n delete: { access: { roles: [\"owner\"] } }, // owner only\n}\n```\n\nRoles are expanded at compile time. No `+` = exact match. See [Access → Role Hierarchy](/compiler/definitions/access#role-hierarchy).\n\n---\n\n## v0.8.0 — April 9, 2026\n\n### Breaking: VITE URL environment variables namespaced\n\nAll Quickback-generated URL environment variables are namespaced under `VITE_QUICKBACK_*` to avoid collisions with other Vite projects.\n\n| Old | New |\n|-----|-----|\n| `VITE_API_URL` | `VITE_QUICKBACK_API_URL` |\n| `VITE_ACCOUNT_URL` | `VITE_QUICKBACK_ACCOUNT_URL` |\n| `VITE_APP_URL` | `VITE_QUICKBACK_APP_URL` |\n| `VITE_CMS_URL` | `VITE_QUICKBACK_CMS_URL` |\n\nNon-URL variables are unchanged (`VITE_ENABLE_*`, branding vars, `VITE_STRIPE_PUBLISHABLE_KEY`).\n\n**Action required:**\n- Compiled projects: re-run `quickback compile`.\n- Standalone deploys: update `.env`, `.env.production`, and `wrangler.toml` files manually.\n- Library users: `__QUICKBACK_API_URL__` / `__QUICKBACK_APP_URL__` globals are unchanged.\n\n### CMS access control\n\n`cms.access: \"admin\"` enforces access at the CMS level, not just link visibility. Non-admin users (`user.role !== \"admin\"`) see an \"Access Denied\" screen with a sign-out button.\n\n---\n\n## v0.5.11 — February 24, 2026\n\n### Mandatory unsafe action audit trail\n\nStructured `unsafe` config (`unsafe: { reason, adminOnly, crossTenant, targetScope }`). Cross-tenant unsafe actions require Better Auth authentication plus platform admin role (`ctx.userRole === \"admin\"`). Mandatory audit logging on success, denial, and error paths. Cloudflare output includes `AUDIT_DB` wiring, `drizzle.audit.config.ts`, and `db:migrate:audit:*` scripts when unsafe actions are present.\n\nCompile-time raw SQL guard for actions and handlers (`allowRawSql: true` required per action).\n\n### Security contract report artifacts\n\nGenerated security contract artifacts: `reports/security-contracts.report.json`, `reports/security-contracts.report.sig.json`. Config-driven signing controls (`compiler.securityContracts.report.signature.*`). Missing required signing keys fail loudly with explicit remediation.\n\n### Headless Drizzle rename hints\n\n`compiler.migrations.renames` configuration for CI/CD environments where Drizzle's interactive rename prompts block compilation. See [Configuration](/compiler/config).\n\n### Minor\n\n- Email OTP magic links work correctly.\n- Auth is required for all API routes when running locally.\n- Single-file multi-table exports alongside `defineTable()` produce a clear error.\n\n---\n\n## v0.5.8 — February 14, 2026\n\n### Quickback CMS\n\nA schema-driven admin panel that connects to your generated API. The compiler now outputs a JSON schema registry consumed by the CMS at runtime. Firewall error modes (`reveal` for 403 with details, `hide` for opaque 404) are configurable per resource for security-sensitive deployments.\n\n---\n\n## v0.5.7 — February 12, 2026\n\n### Scoped database for actions\n\nActions receive a security-scoped database instead of a raw Drizzle instance. The compiler generates a proxy wrapper that automatically enforces org isolation, owner filtering, and soft-delete visibility — the same protections that CRUD routes have always had.\n\nDuck-typed column detection at runtime:\n\n| Column Detected | SELECT / UPDATE / DELETE | INSERT |\n|---|---|---|\n| `organizationId` | Adds `WHERE organizationId = ?` | Auto-injects `organizationId` from context |\n| `ownerId` | Adds `WHERE ownerId = ?` | Auto-injects `ownerId` from context |\n| `deletedAt` | Adds `WHERE deletedAt IS NULL` | — |\n\nEvery action is secure by default — no manual `WHERE` clauses needed.\n\nActions that intentionally need to bypass security (admin reports, cross-org queries, migrations) can declare `unsafe: true` to receive a raw, unscoped database handle via `rawDb`:\n\n```typescript\ndefineActions(analytics, {\n globalReport: {\n unsafe: true,\n execute: async ({ db, rawDb, ctx, input }) => {\n // db → still scoped (safety net)\n // rawDb → bypasses all security filters\n const allOrgs = await rawDb.select().from(organizations);\n },\n },\n});\n```\n\nWithout `unsafe: true`, `rawDb` is `undefined`. See [Actions](/compiler/definitions/actions).\n\n### Cascading soft delete\n\nSoft-deleting a parent record automatically cascades to child and junction tables within the same feature. The compiler detects foreign key references at build time and generates cascade `UPDATE` statements.\n\nRules:\n- Applies to soft delete only. Hard delete relies on database-level `ON DELETE CASCADE`.\n- Cascades within the same feature only — cross-feature references are not affected.\n- Child tables must have `deletedAt` / `deletedBy` columns (auto-added by the compiler).\n\nSee [Actions API → Cascading Soft Delete](/compiler/targets/hono-api/using-the-api/actions-api#cascading-soft-delete).\n\n### Advanced query parameters\n\nNew capabilities for all list endpoints:\n\n- **Field selection** — `?fields=id,name,status`\n- **Multi-sort** — `?sort=status:asc,createdAt:desc`\n- **Total count** — `?count=true` returns total matching records in `X-Total-Count`\n- **Full-text search** — `?search=keyword` searches across all text columns\n\nSee [Query Parameters](/compiler/targets/hono-api/using-the-api/query-params).\n\n---\n\n## v0.5.5 — February 5, 2026\n\n### OpenAPI spec generation\n\nGenerated APIs include a full OpenAPI specification at `/openapi.json`. Better Auth endpoints are included in the spec.\n\n### Better Auth plugins\n\nPublished `@quickback-dev/better-auth-upgrade-anonymous` (post-passkey email collection flow), `@quickback-dev/better-auth-combo-auth` (combined email + password + OTP), and `@quickback-dev/better-auth-aws-ses` (AWS SES email provider).\n\n### Security headers\n\nGlobal error handler prevents leaking internal error details. Security headers middleware (CSP, HSTS, X-Frame-Options, X-Content-Type-Options). `BETTER_AUTH_SECRET` properly passed to generated config.\n\n---\n\n## v0.5.4 — January 30, 2026\n\n### Account UI\n\nPre-built authentication UI deployed as Cloudflare Workers. Sessions, organizations, passkeys, passwordless, admin panel, API keys. Dual-mode: standalone (degit template) or embedded with Quickback projects.\n\n### Webhook system\n\nInbound webhook endpoints with signature verification. Outbound webhooks via Cloudflare Queues with automatic retries. Configurable per-feature webhook events.\n\n### Realtime & vector search\n\nDurable Objects + WebSocket realtime subscriptions. Vector embeddings via Cloudflare Vectorize. KV and R2 storage integrations.\n\n---\n\n## v0.5.0 — January 2026\n\n### Initial release\n\n- **Quickback Compiler** — TypeScript-first backend compiler.\n- **Four security pillars** — Firewall, Access, Guards, Masking.\n- **`defineTable()`** — schema + security configuration in a single file.\n- **Templates** — Cloudflare Workers, B2B SaaS.\n- **Cloud compiler** — remote compilation via `compiler.quickback.dev`.\n- **CLI** — `quickback create`, `quickback compile`.\n- **Better Auth integration** — organizations, roles, sessions.\n- **Drizzle ORM** — schema-first with automatic migrations.\n- **Cloudflare D1** — split database support (auth + features)."
6
+ "content": "## Unreleased\n\n### Feature areas — hierarchical authz grouping (`_area.ts`)\n\nA folder under `features/` carrying an `_area.ts` (`export default defineArea({...})`) is now\nan **area**: it declares a route prefix + admission lanes (the same shape as a project\nnamespace, incl. `mintScope`/`acceptScope`) and an authz vocabulary — relationships, composed\nroles, named gates, tenant anchors, scope kinds — that every feature inside the folder\nreferences by bare name. The vocabulary is visible to the area's subtree ONLY: the compiler\nchecks every reference channel (access roles/gates/scoped aliases, action `access`/`anchor`,\nfirewall `via`/`{ rule }`/`{ tenant }` arms, `ctx.scope.<kind>` accessors, auth-view tenant\nincludes, realtime handshake roles, table-level namespace lanes, and other `_area.ts` nodes)\nand fails the build on any outside reference. Root `authz` stays the global level, and root\nbodies may reference root-declared names only (no laundering an area name project-wide).\n\nFail-closed rules shipped with it: re-declaring an inherited name is a compile error (no\noverrides in v1); a descendant action whose path opts out of the area prefix must carry an\nexplicit `route: 'self'` marker; relative `path: './…'` resolves against the area prefix with\ndot segments rejected; foreign features can't claim paths (or table-level namespace prefixes)\nunder an area's prefix; nested areas may add vocabulary but not mount a second prefix under a\nmounted ancestor (unlinked parent/child admission never compiles); and area-tree projects\nmust declare `requires: ['feature-areas']` — the marker reaches the compiler through ANY CLI\nversion, so an area-unaware toolchain is rejected instead of silently dropping nested\nfeatures. Area projects also emit a reviewed audit artifact, `quickback/authz-manifest.json`\n(area tree, declared names, member features, area-gated vs self-gated actions, root-config\nnamespace consumers), and the generated `AGENTS.md` gains a feature-areas section.\n\nByte-parity guarantee: a flat root-authz project re-expressed as an area tree compiles to\nbyte-identical output (the emit-site key-order determinism pass from v2 step 0 makes the fold\norder provably irrelevant). See [Feature areas](/compiler/definitions/feature-areas).\n\nOne cosmetic side effect of that determinism pass: the first recompile of an existing project\non this release may reorder generated relationship-table **import lines** (they are now\nemitted in sorted order instead of authz-map insertion order). The reordering is a one-time,\nbehavior-free diff.\n\n### Access rules: named gates (`authz.rules`) and tenant anchors (`authz.tenants`)\n\nTwo new root-`authz` blocks let you declare a row/role rule once and stamp it by name instead\nof copying predicates across files. A **named gate** in `authz.rules` bundles up to three\narms — `who` (roles), `record:` (record-aware predicates), and `firewall` lanes — under one\nname, referenced by bare name in any `access: { roles: [...] }` array (applies who + record)\nand as `{ rule: '<name>' }` in a resource's `firewall:` (splices the lanes into the top-level\nAND array — a reference can only *narrow* row admission, never widen it). A **tenant anchor**\nin `authz.tenants` names the tenant predicate (`{ column, equals }`, claim side locked to\nverified ctx claims) and is written `{ tenant: 'org' }` in firewalls — with an optional\nper-site column override — and `tenant: 'org'` in auth-view includes. Expansion happens at\ncompile time; emitted SQL is byte-identical to the inline spelling.\n\nEverything fails closed: gate/role/scoped-role/`+`/`:` name collisions, `+` hierarchy sugar\ninside rule bodies, `{ rule }` inside `all`/`any` groups, firewall-less gates referenced from\n`firewall:`, firewall-bearing gates on actions or in `masking.show`, and an access-side\nreference to a firewall-bearing gate whose lanes the resource doesn't also stamp are all\ncompile errors. Gates in `realtime.requiredRoles` lower to static who-roles at the handshake;\na declared non-empty list that lowers to nothing is a compile error, never a silent `[]`. A\nnew `AUTHZ_UNKNOWN_ROLE_NAME` warning flags reference-shaped names that resolve to nothing.\nSee [named gates](/compiler/definitions/access#named-gates-authzrules) ·\n[`{ tenant }`](/compiler/definitions/firewall#named-tenant-anchors-tenant) ·\n[`{ rule }`](/compiler/definitions/firewall#named-gate-references-rule).\n\n## v0.55.0 — July 17, 2026\n\n### Generated projects ship an `AGENTS.md`\n\nEvery compiled project now emits an `AGENTS.md` at its root — the file coding agents read first — weaving Quickback's security model and a *\"when to use what\"* decision guide into the output. An agent editing the features is steered to the right primitive: a **view** for a filtered read, a **transition** for a guarded state change, an **action** for custom logic, **guards**/**masking** for field-level control, **named invalidations** for realtime refresh — each with a `docs.quickback.dev` link. It also documents the access tiers (incl. `SESSION`/`SCOPED`), the `WHERE column = value` firewall model with the org-OR-scope `{ any: [...] }` pattern for non-org callers, and the fail-closed coherence guardrail (with the *\"never `exception: true` as a workaround\"* rule). Regenerated on every compile.\n\n## v0.54.0 — July 17, 2026\n\n### Realtime: named invalidations\n\nActions can now fire typed, targeted *\"this changed — refresh\"* signals after commit. A `defineRealtime` registry declares typed events (wire name, contract `version`, named variants with strict Zod payloads); a `defineRealtimeDelivery` profile sets the maximum audience (a scope room or the org/user lane + required roles); and an optional `defineRealtimeRecipients` resolver narrows delivery to a resolved identity set — post-commit on the firewalled db, intersecting `scope ∩ roles ∩ recipients`, fail-closed (a throw or `[]` reaches nobody, never a wider audience). Bind them with `invalidates:` on an action and call `invalidate.<binding>.<variant>(payload)` inside `execute`. Delivery is after-commit + best-effort (discarded on throw/dryRun), projects the payload to declared keys, and works on every action kind — standalone, per-record, bulk, and namespace-hoisted. See [Named invalidations](/stack/realtime/named-invalidations).\n\n### Access: `SESSION` and `SCOPED` pseudo-role tiers\n\n`AUTHENTICATED` is now explicitly the wrapper over two auth flavors: **`SESSION`** (a full Better Auth session only) and **`SCOPED`** (a sessionless scope-token principal only — e.g. an event attendee with no account). Use the specific tier when a route must admit or exclude one flavor; `AUTHENTICATED` still admits both and excludes only external delegated principals. See [Access → Pseudo-roles](/compiler/definitions/access).\n\n### Access: fail-closed scope/firewall coherence guardrail\n\nGranting a scope caller (`SCOPED` or a `scope:<kind>:<role>` role) on a resource whose firewall can't filter that caller now **fails the build** instead of silently returning `200 + []` — the trap that pushes apps toward a fake \"active organization.\" The fix is named in the error: compose org **or** scope in an `{ any: [...] }` firewall group, use a `via:` relationship, or `firewall: [{ exception: true }]`.\n\n## v0.53.0 — July 17, 2026\n\n### Realtime: the broadcast surface tracks `contract.version`\n\nThe `/api` and `/auth` bases already move to `/api/v2` and `/auth/v2` under\n`contract.version: 'v2'`, but the realtime/broadcast surface stayed pinned\nat `/broadcast/v1` — so a v2 project's WebSocket mount, ws-ticket mint, DO\nroute matcher, notify helper, auth skip-set, and discovery all disagreed\nwith the rest of the contract. The broadcast base now derives from the same\nresolved contract version (single source of truth in `resolveSystemRoutes`),\nthreaded through every emitter:\n\n- **contract v1 (or omitted)** → `/broadcast/v1` everywhere, byte-identical\n to prior output.\n- **contract v2** → `/broadcast/v2` everywhere, with **no hidden v1 alias**.\n\nAn explicit `compiler.routes.broadcast` override still wins. Existing v1\nprojects are unaffected.\n\n### Web Push: VAPID delivery, queue fan-out, and identity-tag targeting\n\n`push.provider: 'web-push'` turns on a full push pillar: a self-contained\ndelivery module (RFC 8292 VAPID JWTs + RFC 8291 aes128gcm, `crypto.subtle`\nonly — no Node polyfills), a Cloudflare Queues fan-out with a dead-letter\nqueue, and a hardened `push_subscriptions` schema. The crypto core is\nverified against the RFC 8291 Appendix A known-answer vector — the emitted\nmodule reproduces the RFC's ciphertext byte-for-byte.\n\n- **Send path** — `enqueuePushFanout(queue, target, payload)` from an\n action's after-commit phase (`effects.enqueue`), so rolled-back writes\n never notify and `dryRun` sends nothing. Declarative targets\n (`{ userIds }`, `{ targetTags }`, `{ targetRoles }`, `{ all: true }`)\n resolve server-side in the queue consumer — subscription crypto never\n enters action code. Targeting speaks the realtime identity-tag dialect\n and is fail-closed: `[]` selects nobody, broadcast requires an explicit\n `{ all: true }`.\n- **Default schema** (`push.defaultSchema: true`) — owner-firewalled,\n INTERNAL-read `push_subscriptions` with a `views.mine` device list.\n Creates validate `https:` endpoints (SSRF blocker), 65-byte P-256\n `p256dh`, 16-byte `auth`; `tags` is stamped server-side from the\n session's proven identity (client tags ignored); 10/min create rate\n limit; per-user cap keeps the newest 10 live subscriptions.\n- **Fail-closed config** — a literal `vapidPrivateKey` in config is a\n compile error (`env:VAPID_PRIVATE_KEY` only); the worker refuses to boot\n without the three VAPID vars; the private key never lands in\n `wrangler.toml`, SPA bundles, or logs (DLQ chunks log counts only).\n- **SPA bake** — the VAPID public key ships to CMS/Account bundles as\n `VITE_QUICKBACK_VAPID_PUBLIC_KEY` and `window.__QUICKBACK_RUNTIME.vapidPublicKey`.\n- **CLI** — `quickback push generate-keys [--out <file>]`; `--out` writes\n the private key to a `0600` file so it never touches stdout or shell\n history.\n\nSee [Web Push](/stack/push) for the full guide.\n\n## v0.52.1 — July 17, 2026\n\n### CLI: cold-start tolerance for the cloud compiler\n\nRight after a service deploy, the first compile pays a fresh container image\npull — which routinely exceeds the CLI's old 60-second readiness budget and\nsurfaced as `Compiler container did not become ready in time` even while\n`/health` was green. `waitForReady` now allows 4 minutes, reports elapsed\nwarm-up progress, and the timeout message explains the deploy-in-progress\ncase.\n\n## v0.52.0 — July 17, 2026\n\n### Five action primitives: afterCommit, realtime emit, transitions v2, refs, bundles\n\nOne release, five primitives that collapse the most-repeated hand-written\npatterns in real Quickback projects (measured across a 349-action production\ncorpus). Every one is additive — existing projects compile unchanged, and\nplain `{ field, fromTo, to|via }` transitions keep their emission\nbyte-identical.\n\n- **`afterCommit` hooks + `effects.enqueue`** — named best-effort side\n effects that run after `execute` returns. Each hook is independently\n wrapped (failures log as `[<action>] afterCommit:<hook> failed`, never\n touching the response), non-blocking hooks ride `executionCtx.waitUntil`,\n `{ blocking: true }` awaits before responding, and everything skips when\n `execute` throws or returns `dryRun: true`. The execute context also gains\n `effects.enqueue(name, fn)` for mid-execute captures and `now` — one ISO\n timestamp per invocation. Replaces the per-leg `try/catch + waitUntil`\n idiom. See [After-commit hooks](/compiler/definitions/actions#after-commit-hooks).\n\n- **Realtime emit for custom actions** — tables that lock auto-CRUD no\n longer hand-roll frames. `realtime: { emitFromActions: true, scopeKeyFrom:\n \"events:{eventId}\" }` makes scoped-db writes inside record-bound and bulk\n actions emit auto-CRUD-byte-compatible frames after commit (masking +\n audience applied at fanout; the fail-closed audience requirement extends to\n action emission). Actions can also declare `emit:` for a pre-bound\n `emitCrud(row, oldRow?)`. Updates/deletes pre-select old rows on the same\n WHERE; raw `unsafeDb` writes stay invisible. See\n [When auto-broadcast fires](/stack/realtime/durable-objects#when-auto-broadcast-fires-and-when-you-call-it-manually).\n\n- **Transitions v2** — `transition` grows `guard` (equality / null / notNull\n / `custom(record)`), `onIllegal { code, status, message }`, `idempotent:\n \"noop\"`, and `stamp`/`clears` that ride a compiler-applied, TOCTOU-safe\n UPDATE (guards fold into the WHERE; a lost race is 409\n `ACCESS_TRANSITION_LOST`). With an applied write, `execute` becomes\n optional. Table-level `transitions: { publish: { field, from, to, access } }`\n *generates* the action files — including `undo:` inverses and `onEnter`\n cascades — mounted exactly where hand-written files would be (explicit\n files win, with a warning). The ten byte-identical publish/revert files in\n the podcast fixture become two lines per entity. See\n [Transitions](/compiler/definitions/transitions).\n\n- **`refs` — scoped foreign-key inputs** — the \"load the id, 404 if missing,\n assert it belongs to this event\" preamble becomes declarative. Loads run\n through the scoped db (a cross-org id 404s by construction), batch into one\n `Promise.all`, assert `matchScope` / cross-input `matchWith` parenthood, and\n inject rows under their `as` names. Ref keys are validated against the\n inline `z.object` input (with agreeing optionality) at compile time. See\n [Refs](/compiler/definitions/actions#refs-scoped-foreign-key-inputs).\n\n- **`defineBundle` — single-round-trip bootstrap reads** — declarative\n `list()` slices with the firewall, the table's *real* mask functions, and\n `{ data }` cache-seed envelopes; `custom()` escape-hatch sections; a SHA-1\n ETag over `{ scopeSeed, userId, payload }` with the `ifNoneMatch →\n notModified` short-circuit; and `Server-Timing`. Fail-closed: a bundle's\n roles must be a subset of every list table's `read.access` roles — a bundle\n can never widen read access. The digest ships as `sha1Hex` in `lib/etag`\n so hand-written reads can delete their copies. See\n [Bundles](/compiler/definitions/bundles).\n\nSupporting changes: `ActionError` / `TransitionLostError` are re-exported\nfrom the generated `.quickback/define-action` helpers (routes duck-type on\n`error.name`, so project-local copies keep working); `sendQueueBatched` in\n`lib/effects` chunks queue sends at the Cloudflare 100-message cap; and the\n`$record.*` / `$ctx.*` substitution grammar used by `onEnter` and bundle\n`where` is one strict allowlist, always parameterized — never interpolated\ninto SQL.\n\n### CLI device login fixed: /cli/authorize now claims the code before approving\n\nBetter Auth's `deviceAuthorization` plugin requires the verifying session to\nclaim a device code (`GET /device?user_code=…`) before it accepts an approve\nor deny. The account SPA's `/cli/authorize` page posted the approval directly,\nso every `quickback login` failed with *\"Device code has not been claimed by\na verifying session.\"* The page now claims first, then approves — and surfaces\nclaim failures (expired or mistyped codes) with the server's message.\n### Generated builds no longer rewrite the auth schema\n\nGenerated Better Auth projects now run `tsc` directly from `npm run build`.\n`quickback compile` already generates, qualifies, and envelopes\n`src/auth/schema.ts`; invoking `auth:schema` again during every build rewrote\nthat compiler-owned artifact and made an otherwise clean release worktree\ndirty. The explicit `auth:schema` diagnostic command remains available, while\nnormal build, Wrangler, and deployment preflight paths are source-read-only.\nWhen recompiling an existing project, compiler-owned `package.json` script\nnames now converge to their current generated commands while unrelated custom\nscripts are preserved. This upgrades projects whose previous generated\n`build` script still invoked `auth:schema`.\n\n### Non-cross-tenant unsafe actions preserve delegated RLS claims\n\nGenerated Neon handlers now reserve `createServiceDb` for actions that\nexplicitly enable `unsafe.crossTenant`. An action that enables raw database\naccess with `crossTenant: false` keeps the request database, so organization\nand delegated-principal claims survive into Hyperdrive transactions instead of\nbeing cleared by the service-role preamble. True cross-tenant sysadmin actions\nretain their audited RLS bypass.\n\nNeon Hyperdrive guidance now also calls out Postgres' `SELECT … FOR UPDATE`\nauthorization rule: a locked row must pass both `SELECT` and `UPDATE` policies.\nDelegated actions should use ordinary selects for read-only eligibility tables\nand lock only mutable rows they are authorized to update. A PGlite regression\nproves that ordinary delegated reads remain visible while the generated\nrestrictive update fence blocks an unauthorized row lock.\n\n### Atomic email-OTP auth routing no longer recurses on ordinary requests\n\nThe generated atomic email-OTP wrapper now captures and binds Better Auth's\noriginal request handler before replacing the public `handler` property.\nSession reads and every other non-atomic auth route therefore forward to Better\nAuth exactly once instead of re-entering the wrapper until the Worker exhausts\nits call stack. The exact email-OTP sign-in route retains its transactional\nadmission and rollback behavior.\n\n### Generated Better Auth CLI dependencies no longer retain vulnerable Lodash\n\nBetter Auth projects now emit a root npm override for `lodash@4.18.1`. This\nkeeps the supported stable `auth@1.6.x` CLI and its `better-auth` executable,\nwhile lifting the CLI's dev-only Prisma parser chain off Lodash releases\naffected by the 2026 code-injection and prototype-pollution advisories. Runtime\nBetter Auth packages and generated authentication behavior are unchanged.\n\nThe CLI now merges generated npm overrides explicitly when recompiling an\nexisting project: unrelated user overrides remain, while compiler-owned\nsecurity pins win a conflict. Recompile and reinstall dependencies to refresh\nthe project lockfile. `npm audit --omit=dev` remains the production dependency\nview; upstream development-server advisories may still appear separately.\n\n### Postgres constraint replacements apply in dependency-safe order\n\nNeon migration post-processing now orders both halves of a Drizzle constraint\nreplacement. A dependent foreign key is dropped before its referenced unique\nor primary-key constraint, then the replacement key is added before the\nforeign key that consumes it. This prevents Postgres `2BP01` failures when\nDrizzle emits the parent key drop first, while preserving byte-identical output\nfor already-correct migrations and the relative order of unrelated statements.\n\n### Schema registry output is byte-reproducible\n\n`schema-registry.json` no longer includes the wall-clock `generatedAt` field.\nIts remaining metadata and schema content are derived entirely from compiler\ninputs, so consecutive compiles of identical logical input now produce the\nsame registry bytes. This makes artifact hashes, caches, and deployment diffs\nstable without timestamp normalization.\n\n### Generated auth and discovery surfaces now remain truthful and type-safe\n\nAtomic email-OTP generation now imports and invokes\n`before-email-otp-activate.ts` exactly once and preserves the transaction's\nreal Drizzle `select` capability in the hook context. Strict generated\nTypeScript therefore accepts both the base Neon service database and its\ninteractive transaction without erasing the hook's read contract.\n\nContract-v2 projects that omit `auth.jwt` no longer advertise the disabled\nQuickback JWT fast path in `llms.txt` or RFC 8414 metadata. Bearer-JWT guidance,\nthe fallback `/api/v2/token` endpoint, and JWT scopes are emitted only when the\ncorresponding JWT surface exists; real Better Auth OAuth-provider discovery is\nunchanged.\n\nCloudflare Email callbacks now all enter the shared credential-delivery\nscheduler exactly once. The scheduler anchors the observed rejection with\n`waitUntil`, emits the metadata-only `auth.credential_delivery_failed` event,\nand never leaks the provider error. Generated CRUD routes also keep delegated\nprincipal and account authority disjoint: `?organizationId=` is rejected for a\ndelegated principal instead of synthesizing `activeOrgId` on its context. This\ncloses both the authority ambiguity and the generated `AppContext` union type\nerrors.\n\n### Email-OTP activation can be admitted atomically in the API layer\n\nContract-v2 Cloudflare projects using one Neon Hyperdrive database can opt the\nexact Better Auth `POST /sign-in/email-otp` handler into an interactive\ntransaction with `atomicAuthRoutes: [\"emailOtpSignIn\"]`. The paired recognized\nhook, `quickback/hooks/before-email-otp-activate.ts`, receives a proven dormant\nuser `{ userId, email, user }` plus transaction-bound `db` / full `schema` and\n`authDb` / `authSchema` handles. Quickback owns only identity proof and atomic\norchestration; application admission, status, event, pass, and eligibility\nrules remain authored in the project API hook.\n\nThe hook executes after OTP validation but in Better Auth's\n`databaseHooks.user.update.before`, before the user update lock. This preserves\napplication-first lock ordering and avoids the user-to-application inversion a\nsession-create hook would introduce. Unknown-email signup must be disabled;\nalready-verified users do not rerun dormant activation.\n\nThe generated handler rebuilds Better Auth over the transaction handle, so OTP\nconsumption, project hook writes, the `emailVerified` update, and session insert\ncommit together. Admission denial, a non-ok response after activation starts,\nand any 5xx response throw a private rollback sentinel. Expected policy denial\nreturns a generic 403. Operational rollback emits the metadata-only\n`auth.atomic_email_otp_operational_rollback` event and returns a generic 503,\nwithout exposing raw errors. Ordinary invalid-OTP 4xx responses still commit\nBetter Auth's attempt accounting, and the OTP-send route remains outside the\ntransaction. Unsupported contracts, runtimes, database modes,\nmissing/duplicated config, enabled signup,\nand a hook/config mismatch now fail at compile time.\n\n### Neon migrations can declare cross-schema foreign keys\n\nNeon projects can now declare fully qualified, single-column or composite\nforeign keys under `compiler.migrations.foreignKeys`. Each entry names the\nconstraint, source and target schema/table/column tuples, and explicit\n`onDelete` / `onUpdate` actions. The compiler rejects unsafe identifiers,\nmismatched tuple arity, duplicate or ambiguous declarations, unknown keys,\nand non-Neon providers before generating SQL.\n\nDeclared constraints are sorted deterministically and folded into Quickback's\ncontent-addressed Postgres journal after the Drizzle schema migration. A new\nconstraint is added `NOT VALID` and then validated, so existing orphan rows\nfail the migration; replay verifies an exact catalog match and rejects a\nsame-named constraint with different semantics. This surface enforces\nrelational integrity only—business rules remain in generated or authored API\nactions, not database triggers.\n\n### Compile completion steps honor the Neon connection mode\n\nThe CLI's successful-compile footer now distinguishes Neon HTTP from\nHyperdrive. HTTP projects retain the direct `DATABASE_URL` Worker setup.\nHyperdrive projects show `DATABASE_MIGRATION_URL` only as a local or CI\nmigration input, point local development at the configured Hyperdrive\n`localConnectionString`, and never recommend deploying `DATABASE_URL` as a\nWorker secret.\n\nNamed Hyperdrive environments also show their configured Neon branches,\nrequired-secret inventories, and explicit Wrangler `--env` targets. The footer\nno longer suggests the unnamed `.env.neon` / `.dev.vars` workflow or a bare\ndeploy for an isolated `dev` / `prod` setup.\n\n### Cloudflare email delivery and named Neon targets fail visibly and deploy explicitly\n\nGenerated Cloudflare email code now uses the native Workers `SendEmail`,\n`EmailAddress`, attachment, and `EmailSendResult` contracts. The Workers\nbuilder keeps its camel-case fields and `{ email, name }` address shape, while\nthe REST transport retains its separate snake-case fields and `{ address,\nname }` shape. Generated projects move to `@cloudflare/workers-types` v5 with\nWrangler 4.110 so the binding and result types agree without `any` casts.\n\nEvery Better Auth email callback now creates an observed delivery promise. On\nWorkers, the callback hands that still-rejecting promise to\n`executionCtx.waitUntil(...)` and returns after the task is accepted; outside a\nrequest lifecycle it returns the promise for the caller to await. Failures emit\nonly a structured generic event, never provider error content, and remain\nrejected instead of being detached or swallowed. SES and SNS background sends\nuse the same lifecycle rule.\n\nNeon Hyperdrive's generated postgres.js client now caps each request-scoped\npool at five connections. Named environments gain explicit `deploy:dev` and\n`deploy:prod` package scripts (mapped to their configured Wrangler environment\nnames), while the unsafe bare `deploy` script remains absent and migrations\nremain a separate target-owned step.\n\n### Contract v2 auth and Neon authority boundaries are fail-closed\n\nContract-v2 projects no longer emit Quickback's generic JWT mint endpoint,\nJWT helper, middleware verification/mint fast-path, or related imports unless\nthe project explicitly declares `auth.jwt`. Contract v1 retains its existing\ndefault for compatibility. Adding `auth.jwt: {}` to a v2 config opts back into\nthe custom Quickback JWT with its normal default settings.\n\nConfigured delegated authenticators now produce closed TypeScript unions in\nboth generated `AppContext` and Neon RLS context. Request contexts contain only\nresolved principal variants; the compiler-internal credential-lookup variants\nexist only in the database context. Delegated standalone actions do not require\nBetter Auth `activeOrgId` / `activeTeamId` before their declared principal\naccess tree runs, and their context cannot acquire account, organization, team,\nmembership, or scope authority.\n\nOn Cloudflare + Neon, the API-key organization membership lookup now runs with\nrequest-scoped user/org RLS claims before it stamps verified organization and\nrole authority into `AppContext`. Generated security migrations also converge\ndirect privilege drift: the audit schema/table revoke all direct grants from\n`PUBLIC`, the runtime, and admin before restoring their exact write-only/admin\nsets, while the Drizzle journal schema/table/sequences and database `CREATE`\ncapability explicitly revoke `PUBLIC` and runtime access before granting the\nmigration role.\n\n### Standalone action routes preserve their exact authority context\n\nGenerated standalone routes now pass each action the context and scoped\ndatabase types inferred from that action's own `execute` signature. Account actions therefore receive a\nrequired account identity, while `event_pass`, `event_delegate`, and other\ndelegated-principal actions retain their exact principal literal at the route\nboundary. Relationship `loads` / `exposeAs` hydration is intersected with that\nauthority context, including required shared targets and optional distinct\nmulti-lane targets, instead of replacing it with the broad application\ncontext.\n\nThe same boundary keeps ordinary request databases and temporary\nservice-role-backed scoped databases assignable to the generated Hyperdrive\naction helper without widening the handler's schema-aware `db` type.\n\nGenerated principal-auth identity guards also emit explicit strict TypeScript\nparameter and return types. Contract-v2 Cloudflare + Neon output no longer\nfails `tsc` on implicit-`any` guard parameters.\n\n### Parameterized actions keep complete v2 schema harvests\n\nThe action-input harvest plan now converts Hono-style `:param` segments to the\nOpenAPI `{param}` form for standalone actions and parameterized resource paths.\nPreviously the CLI could harvest every schema successfully, but the compiler\ncould apply only parameter-free actions because it looked up parameterized\noperations under the wrong OpenAPI key. Contract v2 now counts and patches the\nsame canonical path emitted by OpenAPI and MCP.\n\nGenerated standalone-action routes also remove template-only trailing spaces\nwhen optional audit blocks are absent, keeping regenerated source diffs clean.\n\n### Action-schema harvest uses the generated runtime dependency tree\n\nThe CLI now resolves action-harvest dependencies from the configured\n`build.outputDir/node_modules` before unrelated ancestor installs. This fixes\nisolated projects that keep authored definitions under `quickback/` and the\ngenerated runtime under a sibling directory such as `src/`: their actions can\nuse the runtime's Zod 4 and Drizzle installation without adding workspace-root\nsymlinks. An older user-level or monorepo-level Zod can no longer shadow the\nruntime's declared version during schema evaluation.\n\nSchema-only evaluation also emits inert named table proxies for authored\nDrizzle exports. Shared input/DTO modules may therefore construct top-level\nselection objects such as `{ id: records.id }` without executing a database\noperation or losing the action's Zod schema.\n\nHarvest failures now retain the exact action key, failing phase (`bundle` or\n`evaluation`), and bounded underlying error. Contract v2 includes those\nper-action diagnostics in its fail-closed compile error; v1 retains its\nbest-effort static-schema fallback.\n\n### Contract v2 delegated principals and RLS-only action tables\n\nCloudflare + Neon Hyperdrive projects on `contract.version: \"v2\"` can now\ndeclare framework-generic delegated authenticators under `auth.principals`.\nEach named principal owns an exact, non-`Bearer` Authorization scheme, a\nproject hook that proves the credential and returns only `{ digest }`, and one\ncompiler-owned indexed lookup that resolves the actor, optional session/family,\nstring claims, and active status. The hook receives no database handle. Proof\nhooks authored under `quickback/lib` are staged into generated `src/lib`, even\nwhen no action imports them directly.\n\nDelegated authority is structurally disjoint from Better Auth accounts:\n`ctx.principal` is populated while user, organization, team, and membership\nfields remain absent. Access arms may use `principals: [...]`; fields inside an\narm are ANDed and sibling arms are ORed. Generated action helpers preserve\nthat boundary in TypeScript, including the anonymous possibility of a\n`PUBLIC` sibling arm. Mixed credential transport rejects Authorization plus an\nAPI key or an actual Better Auth session cookie, while unrelated analytics\ncookies do not create a false conflict. `Bearer` remains reserved for account\nauthentication.\n\nResources can also declare operation-specific `databaseAccess` policies for\nauthored actions and support tables. This is an RLS-only surface: it emits no\ngeneric route or OpenAPI operation and is accepted only on Cloudflare + Neon\nHyperdrive. Every authorization path must contain a nonempty SQL-lowerable\nrecord equality; unbounded principal/role leaves, any unbounded OR arm, empty\nrecords, ambiguous mixed boolean nodes, app-only predicates, and unsupported\nproviders fail compilation. This keeps business logic in authored API actions\nwhile Postgres independently enforces the same event/person or account/org row\nboundary.\n\nPrincipal claims use the same transaction-local Hyperdrive preamble as account\nclaims, with query caching disabled. Restrictive per-operation principal\nfences prevent a public, exception, or legacy permissive policy from admitting\nthe wrong principal type. Credential lookup indexes and RLS journal entries are\ncontent-addressed and converge when a table, digest column, or definition\nchanges; generated Postgres identifiers include collision-resistant hashes and\nstay within the 63-byte limit. Each security migration also drops the complete\ncompiler-owned `databaseAccess` policy family before recreating the current\noperations, so removing or moving an operation revokes the old permissive\npolicy instead of leaving it active. Record fields resolve through authoritative\nDrizzle metadata to exact quoted physical identifiers, unknown fields fail the\ncompile, and DB-only pseudo-roles follow the same ADMIN/SYSADMIN/INTERNAL\ncontract as the application surface.\n\n### Action execute helpers preserve their typed boundary\n\nGenerated per-feature `defineAction` helpers no longer erase `services`, the\nHono request context, record predicates, or the action's return value to\n`any`. Zod input and record inference remain intact, `whereRecord` and\n`whereTransition` accept only the helper's bound table, and the existing D1 /\nNeon Hyperdrive scoped `db` and interactive `tx` types now flow through the\nsame execute boundary. The returned value is inferred exactly; this does not\nadd a response schema, invalid-return rule, or new output contract.\n\nHTTP/WebSocket Neon retains its intentionally dynamic `db`, and `AppContext`\nretains its open index signature for runtime-hydrated namespace fields.\n\n### Neon Hyperdrive is now the only Worker database lane, including Better Auth\n\nFor `connectionMode: \"hyperdrive\"`, generated Better Auth code now uses the\nsame HYPERDRIVE-backed, service-role-scoped database handle as the rest of the\ngenerated API. `DATABASE_URL` is no longer emitted or required as a Worker\nsecret in Hyperdrive mode; migration credentials remain inputs to the compiler\nor CI environment. HTTP-mode Neon retains its existing `DATABASE_URL` runtime\ncontract.\n\n### Public contract v2 now compiles as one coherent API/auth surface\n\nProjects may set `contract: { version: \"v2\" }` to select `/api/v2/*` feature\nroutes and `/auth/v2/*` Better Auth routes. The compiler now threads that\nselection through generated route mounts, Better Auth configuration and\nmiddleware, OpenAPI paths and server metadata, MCP internal tool calls, OAuth\ndiscovery, `llms.txt`, schema/embeddings/system routes, live views, namespace\nactions, and dedicated-domain `/v2/*` shortcuts. The option is no longer\nfail-closed. Omitting `contract` or selecting `v1` preserves the existing v1\noutput.\n\nBundled CMS and Account clients now receive the selected API and auth base\npaths through both their Vite build environment and the Worker-injected runtime\nconfig. CMS CRUD, schema, sysadmin, and live-view requests and Account auth,\ndata, and live-view requests therefore stay on `/api/v2` and `/auth/v2` for a\nv2 project instead of falling back to client-side v1 literals. V1 SPA config\nretains its historical byte shape.\n\nV2 compiles also require a complete client-side action input-schema harvest.\nThe current CLI reports the exact action files that failed to produce a JSON\nSchema, and the compiler independently rejects missing, invalid, or partial\nmaps at the shared parse boundary used by both complete and validation-only\ncompiles. `POST /compile?complete=false` can no longer bypass the v2 gate. For\nrecord actions with `bulkVariant: true`, the harvested schema now patches both\nthe single-record request body and the bulk operation's nested `input`; the\naction is counted complete only when both OpenAPI targets exist. Harvest\nplanning also normalizes filename-based action bindings to the table's declared\nname and resource path, so kebab-case filenames exporting snake/camel-case\ntables are not silently omitted. V1 remains best-effort for backward\ncompatibility.\n\n### Complete, isolated Wrangler targets for named Neon environments\n\n`providers.database.environments` now defines deployable Neon Hyperdrive\ntargets instead of emitting empty `[env.*]` shells. Because Wrangler does not\ninherit vars or bindings into named environments, each target must explicitly\nown its generated vars, required-secret contract, Hyperdrive and KV IDs,\nrate-limit namespace IDs, and Cloudflare Email binding. The compiler rejects\nmissing overrides, shared stateful IDs, optional secret declarations, invalid\ntarget semantics, and unsupported binding families rather than generating a\nWorker that starts without part of its runtime.\n\nThe required-secret inventory is now centralized and includes generated\ncredentials as well as custom declarations: `BETTER_AUTH_SECRET`, a configured\n`auth.jwt.secretEnv`, `ENCRYPTION_KEK` when envelope encryption is present, and\nevery `bindings.secrets` entry marked `required`. Generated Better Auth SES/SNS\ncredentials, AWS-backed anonymous-upgrade credentials, enabled social-provider\nclient id/secret pairs, and R2 presign credential env names are included as\nwell. Cloudflare social auth now reads those credentials from the Worker `env`\nbinding instead of relying on `process.env` compatibility behavior. Named\ntargets also reject every generated top-level custom-domain source — including\nruntime routes, the primary/CMS/Account/Admin/Auth/API domains, and app domains\nor aliases — until routes can be declared with explicit per-environment\nownership; top-level routes can no longer produce an ambiguous deployment\ntarget.\n\nNamed targets are currently limited to Neon Hyperdrive with Better Auth.\nExternal auth remains fail-closed until its service binding can be declared\nindependently for every named environment.\n\nFor named-environment projects, the base Worker has no deployable stateful\nbindings, local development selects a named target, and that selected target\nis always the required logical `dev` environment, which must own an explicit\ndevelopment-only Hyperdrive `localConnectionString`. Quickback emits it only\nin the selected named binding, rejects a top-level\noverride when named environments exist, and rejects local URLs on staging or\nproduction targets; deployed targets continue to resolve the remote\nHyperdrive configuration by ID. The generated package omits the unsafe bare\ndeploy script. Existing projects that omit\n`environments` keep byte-identical Wrangler output and the existing dev/deploy\nscripts. See [Neon → Named Cloudflare deployment environments](/compiler/targets/hono-api/database/neon#named-cloudflare-deployment-environments).\n\n### Local compiler trust boundary and deterministic Drizzle commands\n\nThe supported Docker launcher now opts into unauthenticated local compilation\nexplicitly and publishes the compiler only on `127.0.0.1`; missing or unknown\ncompiler modes retain hosted authentication. The CLI recognizes only exact\nloopback hostnames as local. Migration post-commands now use the configured\npackage manager's local binary execution form, with npm forced offline and its\nimplicit install prompt disabled, so a missing `drizzle-kit` fails clearly\ninstead of fetching an unpinned package.\n\n### Action rate limits now emit — documented since the rate-limit pillar, wired now\n\nThe [rate-limit docs](/compiler/definitions/rate-limit#actions) have described\nper-action rate limiting since the pillar shipped: record-based actions inherit\nthe resource's `update` bucket, standalone actions inherit the project-default\n`update` bucket, and actions may declare a `rateLimit` override or opt out with\n`rateLimit: false`. The generated routes never contained the checks. They now\ndo, exactly per the documented contract:\n\n- Record-based actions (and their bulk variants, which share the same counter —\n one token per batch request) are keyed\n `<resource>:action:<name>:<user>`; standalone actions are keyed\n `standalone:<declaredPath>:<user>`. The `:action:`/`standalone:` infixes mean\n action counters never collide with CRUD counters.\n- `rateLimit: { limit, period }` on an action emits its own binding\n (deduped by tuple, same `RL_<limit>_<period>` scheme); `rateLimit: false`\n opts the action out entirely.\n- Record-based action routes are now **exempted** from the per-resource CRUD\n catch-all middleware. Previously a `POST /:id/approve` was incidentally\n counted against the resource's `create` bucket — wrong bucket, wrong key.\n- Actions-only (tableless) projects now provision the project-default binding;\n previously they shipped with none.\n\n**Behavior change:** standalone actions were previously *unlimited*; they now\ninherit the project-default `update` bucket (200 requests / 60s per user/IP\nwith shipped defaults). PUBLIC webhook-style endpoints that absorb provider\nbursts should declare their own budget (`rateLimit: { limit: 1000, period: 10 }`)\nor opt out (`rateLimit: false`). The compiler emits a warning when a PUBLIC\nstandalone action silently inherits the default, so affected actions are\nflagged at compile time.\n\n### Better Auth CLI pinned and shipped as a generated devDependency\n\nThe generated `auth:schema` script runs `npx better-auth generate`, but the\n`better-auth` runtime package ships no executable — the `better-auth` bin\nlives in the npm package `auth` (the official Better Auth CLI; the team took\nover that name at 1.5.0, superseding the frozen `@better-auth/cli`). Generated\nprojects now declare `auth` as a devDependency pinned to the runtime's minor\nline, so `npm run auth:schema` resolves the CLI locally instead of requiring a\nglobal install. The compiler image's global CLI is pinned to the same version,\neliminating silent skew between the CLI on `latest` and the pinned runtime.\n\n### Compile warning when an action's input schema degrades to untyped\n\nWhen action input schemas aren't harvested client-side (older CLI, or a direct\n`/compile` API call), the static Zod parser supplies OpenAPI/MCP input schemas\n— and silently degrades unrecognized constructs (discriminated unions,\nrefinements, `z.record`, transforms) to the accept-anything `{}`. That\ndegradation is no longer silent: the compile result now carries a warning per\naffected action naming the route, source file, and the exact untyped field\npaths. Actions covered by the CLI harvest are never warned on, and actions\nthat declare no input are skipped.\n\n### Auth docs: JWT security posture stated up front\n\nThe [Auth & JWT page](/compiler/config/auth) now leads with the posture\nsummary instead of burying it: the default 180-second auto-refreshed TTL plus\n`revocationCheck: 'kv'` (seconds-level revocation, auto-stamped on ban /\nmember removal / role change / scope-conferring row changes) is the\nrecommended configuration and covers the vast majority of deployments — with\nthe residual trade-offs (per-principal granularity, fail-open on KV outage,\n~60s cross-PoP propagation) stated explicitly for strict threat models.\n\n### Neon via-user reads: generated list handlers now typecheck against the concretely-typed service handle\n\nOn Neon, a read firewall carrying a via-user multi-hop relationship predicate\nroutes the generated read handlers to `createServiceDb(c.env)` — a genuine\n`NeonHttpDatabase<typeof schema>` — instead of the loosely-typed request db.\nThe list handler's query construction declared drizzle select builders with\n`let` and reassigned them (`query = query.where(…)`, `.orderBy(…)`,\n`.limit(…).offset(…)`, and the count/aggregation/group-by variants), which is\na type error against drizzle's immutable builder typing: `.where()` returns\n`Omit\n</Button>\n```\n\n`ResponsiveModal` survived the migration unchanged — it composes the higher-level Dialog + Drawer wrappers (preserved public API), not the underlying primitives.\n\n#### Caller-side API changes worth noting\n\nBase-ui ships some real behavioural changes the Radix variants didn't:\n\n- `<Select onValueChange>` now receives `(value: string | null, eventDetails) => void` (was `(value: string) => void`). Existing `Dispatch<SetStateAction<string>>` setters reject `null` — wrap callbacks defensively: `onValueChange={(v) => v != null && setX(v)}`.\n- `<DropdownMenuContent forceMount>` removed (base-ui has no `forceMount`). Use base-ui's `keepMounted` on the Popup/Positioner if you need to preserve unmounted state.\n- Component sub-names shifted (`Dialog.Content` → `Dialog.Popup`, `Dialog.Overlay` → `Dialog.Backdrop`). Data attributes are now `data-open` / `data-closed` (no more `data-state=\"open\"`).\n\n#### Adding a new primitive after this release\n\n```bash\ncd packages/ui\npnpm dlx shadcn@latest add <component> --overwrite --yes\n# Sweep generated `@/` imports to relative paths — the SPAs' vite-tsconfig-paths\n# plugin doesn't see packages/ui's @/* mapping at bundle time:\nsed -i.bak \\\n -e 's|\"@/lib/utils\"|\"../lib/utils\"|g' \\\n -e 's|\"@/components/|\"./|g' \\\n -e 's|\"@/hooks/|\"../hooks/|g' \\\n components/<component>.tsx && rm components/<component>.tsx.bak\n```\n\nIf the new primitive pulls in fresh deps, mirror them into `apps/compiler/deps-spa-{cms,account}-package.json` per the SPA build pipeline or Docker SPA builds will fail.\n\n---\n\n## v0.18.1 — May 18, 2026\n\n### Account SPA — teams, active-team picker, permission-aware UI\n\nThe Account SPA's organization surface is now feature-parity with Better Auth's `organization` plugin for the basic team workflow, and replaces the long-standing hardcoded `role === 'owner' || 'admin'` checks with `checkRolePermission` so projects that ship custom roles get a UI that respects them.\n\n#### Teams (opt-in)\n\nWhen the BA config enables teams — `organization({ teams: { enabled: true } })` — the compiler emits `VITE_ENABLE_ORG_TEAMS=true` and the Account SPA exposes a Teams tab on each organization:\n\n- **Teams index** (`/$slug/teams`) — splits into \"Your teams\" (from `listUserTeams`) and \"Other teams\" so non-admins land on what's relevant. Create / rename / delete from the list, gated on `team:create` / `team:update` / `team:delete`.\n- **Team detail** (`/$slug/teams/$teamId`) — member roster with add / remove, joining `listTeamMembers` against the org's full member list for display.\n- **Active-team picker** in the org header — calls `setActiveTeam` and exposes the choice via `OrganizationContext.activeTeamId` so downstream routes (and the BA `session.activeTeamId` server-side) stay in sync.\n- **Team-aware invites** — `InviteMemberDialog` shows an optional team picker when teams are on and forwards `teamId` to `inviteMember`, so accepting the invite drops the new member straight into the right team.\n\nTeams are loaded once by the `$slug` layout (`listTeams` + `listUserTeams`) and exposed via `OrganizationContext.teams` / `userTeamIds` / `refreshTeams`, so individual team routes don't re-fetch the list.\n\n#### Permission-aware UI via `checkRolePermission`\n\n`OrganizationContext.isOwnerOrAdmin` is gone. Routes now read `can(resource, action)` from context, which delegates to `authClient.organization.checkRolePermission` — synchronous, no roundtrip, and aware of any custom roles registered via the BA `ac` option. Multi-role users (BA stores multiple roles comma-separated) are handled by checking each role; the action is allowed if any role grants it.\n\nMigrated sites:\n\n- `$slug.tsx` tab gates → `can('invitation', 'create')`, `can('organization', 'update')`\n- `members.tsx` action menu → `can('member', 'update' | 'delete')`; the owner-hierarchy guard (non-owners can't touch owner-role members) is preserved as a client-side mirror of BA's server enforcement\n- `invitations.tsx` → `can('invitation', 'create' | 'cancel')` gates the Invite button, resend, and cancel separately\n- `settings.tsx` → `can('organization', 'update')` for the form, `can('organization', 'delete')` for the danger zone (was owner-only)\n- `teams.tsx` / `teams.$teamId.tsx` → `can('team', 'create' | 'update' | 'delete')`\n\nProjects on the default three-role hierarchy see no behaviour change; projects that defined `admin`/`member` overrides via BA's access-control API now get a UI that matches what the server will actually authorize.\n\n#### Editable slug + metadata on organization settings\n\nThe `$slug/settings.tsx` form now edits two more `organization.update` fields:\n\n- **URL slug** — full debounced `checkSlug` flow (mirroring the create-org form); on rename, the SPA navigates to `/${newSlug}/settings` and the layout re-fetches with the new slug.\n- **Metadata** — single `Record<string, any> | null` JSON textarea, parsed on submit with inline error messaging. Empty clears the field.\n\nSlug rename is non-breaking for the SPA itself, but every external link / bookmark that references the old slug becomes a 404 — the form warns about this before saving.\n\n#### Auth client wiring\n\nWhen `VITE_ENABLE_ORG_TEAMS=true`, the SPA's `organizationClient(...)` is instantiated with `teams: { enabled: true }` so the team APIs are typed end-to-end. When the flag is off, team methods aren't surfaced — and the Teams tab is hidden — keeping the bundle and UI honest about what the server actually supports.\n\n---\n\n## v0.18.0 — May 17, 2026\n\n### `config.apps` — mount user-authored SPAs on dedicated hostnames\n\nThe compiler now generates per-hostname Worker middleware for arbitrary user SPAs alongside the built-in CMS and Account UIs. Previously the only way to host a product app next to a Quickback API was a second Worker; `config.apps` brings the full stack — API, account, and product UI — onto one deployment with same-origin auth.\n\n```ts\napps: {\n www: {\n domain: \"www.example.com\",\n aliasDomains: [\"example.com\"], // apex serves the same SPA\n },\n}\n```\n\nEach entry binds one or more hostnames to a directory under `src/apps/<name>/` and inherits the Account-domain pass-through behavior — `/api/`, `/auth/`, `/admin/`, `/storage/`, and `/health` route to Hono so the SPA fetches its API without CORS. The compiler:\n\n- emits a `custom_domain = true` route in `wrangler.toml` for the primary hostname and every alias\n- adds each hostname to Better Auth's `TRUSTED_ORIGINS` (when `trustedOrigins` is left unset)\n- widens the CSP `connect-src` to cover the SPA-baked origins\n- folds the new hostnames into shared-parent detection for `crossSubDomainCookies`\n\nDrop the prebuilt SPA bundle at `quickback/apps/<name>/` — the existing source-apps passthrough copies it byte-for-byte into `src/apps/<name>/`. The compiler doesn't build the SPA; it only emits routing for whatever's already there. The names `cms`, `account`, and `public` are reserved; hostname collisions with `cms.domain` / `account.domain` / `account.adminDomain` or between two `apps[*]` entries fail at compile time.\n\nWhen `cms` and `account` are both configured, the multi-domain catchall now explicitly skips app hostnames — an API miss on an app host returns the standard 404 JSON via `app.notFound` instead of stray-serving a sibling SPA's HTML shell.\n\n### Cross-subdomain cookie inference handles apex aliases\n\nThe shared-parent detection that drives `advanced.crossSubDomainCookies` previously reduced any hostname by stripping the leftmost label — `'example.com'` collapsed to `'com'`, which broke equality against sibling subdomains. Apex hostnames (exactly two dot-segments) are now treated as already being the parent, so apex aliases (`example.com` listed alongside `www.example.com`) coexist cleanly with `auth.example.com` / `cms.example.com` and the compiler still emits `crossSubDomainCookies: { enabled: true, domain: '.example.com' }`.\n\n---\n\n## v0.17.2 — May 15, 2026\n\n### `customPlugins` escape hatch on `defineAuth(\"better-auth\", …)`\n\nThe Better Auth provider now accepts `customPlugins` alongside the named-plugin registry — a path to ship third-party plugins (`@better-auth-kit/audit`, …), unregistered built-ins, or one-off project-local plugins without forking the compiler.\n\nEach entry is an explicit import descriptor:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: { passkey: true, organization: true },\n customPlugins: [\n // (1) Project-local plugin file at quickback/plugins/long-session.ts\n { from: \"./plugins/long-session\", export: \"longSessionPlugin\" },\n // (2) Third-party npm package\n {\n from: \"@better-auth-kit/audit\",\n export: \"auditPlugin\",\n args: { events: [\"sign-in\"] },\n dependencies: { \"@better-auth-kit/audit\": \"^1.0.0\" },\n },\n ],\n}),\n```\n\n`from` is either a relative path under `./plugins/` (the CLI auto-uploads matching files from `quickback/plugins/`; the compiler copies them into `src/plugins/<name>.ts` and rewrites the emitted import) or a bare npm specifier (emitted verbatim; declare `dependencies` so the package lands in the generated `package.json`). Omit `args` to emit the symbol uncalled (plugin instance); provide `args` to emit a JSON-serialized factory call.\n\nThe descriptor is validated with Zod — typos in `from`/`export`, paths that escape `./plugins/`, and references to files the CLI didn't ship all fail at compile time with a targeted message.\n\n---\n\n## v0.17.1 — May 14, 2026\n\n### `quickback start` — interactive onboarding\n\n```bash\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n```\n\n`start` walks new users through template selection, scaffolds the project on disk, and only prompts for an account when it's ready to compile. Cancelling at the login prompt leaves the scaffold intact — sign in and run `quickback compile` whenever you're ready.\n\nThe same deferred-auth flow applies to `quickback create`. Scaffolding and (optional) Cloudflare D1 setup run before authentication, so you can preview the project on disk before committing to an account.\n\n### Named views on the free tier\n\nThe `todos` template now ships a `dashboard` named view, exposing a projected response at `GET /api/v1/todos/views/dashboard`. Named views support per-view access rules and per-view field selection while inheriting the table's firewall and masking — the canonical way to ship list-view payloads that are cheaper to fetch and easier to cache than a full collection read.\n\n### `quickback init` removed\n\nFolded into `start` and `create`. The legacy command name prints a deprecation notice pointing at its replacements.\n\n### Minor\n\n- `quickback whoami` reads the stored tier from your credentials.\n- Pro upsell copy in `quickback login` is shown only when the server returns an explicit free-tier subscription.\n- Bare scaffolds (`cloudflare`, `empty`) report accurately when there are no features to generate migrations for.\n\n---\n\n## v0.16.10 — May 14, 2026\n\n### D1-specific safety pass on generated migrations\n\nThe `cloudflare-d1` provider now runs a post-generation pass over every Drizzle migration directory (auth, features, webhooks, audit) before the compile finishes. Better Auth cleanup for retired managed tables is stripped from raw `DROP TABLE` statements. Drop-only cleanup migrations are reordered child-first when foreign-key dependencies require it. Every generated D1 migration directory is replayed against SQLite during compile, so a D1-breaking migration fails at compile time rather than at `wrangler d1 migrations apply`.\n\n---\n\n## v0.16.9 — May 13, 2026\n\n### Resource-scoped realtime tickets\n\n`providers.database.config.realtime` accepts an object form for projects whose WebSocket subscribers aren't org members:\n\n```ts\nrealtime: {\n wsTicket: {\n role: \"attendee\",\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n}\n```\n\nThe generated `/broadcast/v1/ws-ticket` route authenticates the caller, evaluates the declared relationship role against the request, and mints a short-lived WebSocket ticket scoped to the resolved resource. `realtime: true` continues to enable the org-scoped broadcaster.\n\n### Unified broadcast targeting\n\nThe realtime helper and Broadcaster now route by `scopeKey || organizationId || userId`. String targets remain shorthand for `organizationId`; explicit targets can scope a broadcast to a resource or a single user:\n\n```ts\nawait realtime.broadcast(\"event-page-updated\", payload, { scopeKey: \"events:evt_123\" });\nawait realtime.broadcast(\"dm\", payload, { userId: recipientId });\n```\n\nWebSocket tickets are Quickback-minted (signed with `BETTER_AUTH_SECRET`), not Better Auth tokens — Better Auth remains the front-door auth check; Quickback signs the upgrade ticket after authorization succeeds.\n\n---\n\n## v0.16.8 — May 13, 2026\n\n### One auth transport per request\n\nGenerated middleware treats `Cookie`, `Authorization: Bearer`, and `x-api-key` as distinct auth methods and rejects mixed requests with `400 AUTH_METHOD_CONFLICT`. Query-string API keys (`?api_key=` / `?key=`) are no longer accepted. Machine-to-machine auth is explicit; precedence rules between transports are gone.\n\n### Cookie-backed CSRF gate\n\nGenerated apps now block cross-site `POST` / `PUT` / `PATCH` / `DELETE` requests from cookie-relying callers. The middleware skips explicit `Authorization` clients, requires a trusted `Origin` or `Referer`, and blocks `Sec-Fetch-Site: cross-site`. This matters most for cross-subdomain session setups where `SameSite=None` is intentional.\n\n### First-class Wrangler observability\n\n`providers.runtime.config.observability` now supports nested `logs` / `traces` blocks for `headSamplingRate`, `destinations`, `persist`, and `logs.invocationLogs`, emitting matching `[observability]`, `[observability.logs]`, and `[observability.traces]` TOML.\n\n---\n\n## v0.16.7 — May 12, 2026\n\n### Bearer wins over cookie\n\nA request carrying both `Authorization` and a session `Cookie` resolves entirely from the bearer; the cookie is dropped before `getSession()` runs. All three Bearer flavors (API key, JWT, session-token) now behave consistently — no more silent cookie precedence on session-token bearers.\n\n### Bearer plugin defaults to `requireSignature: true`\n\nBetter Auth's `bearer` plugin defaults to unsigned tokens; Quickback now emits `bearer({ requireSignature: true })`. Tokens emitted in the CORS-exposed `set-auth-token` header are server-signed with `BETTER_AUTH_SECRET` and verified on every request. Projects that genuinely need unsigned bearers can override via `providers.auth.config.plugins.bearer`.\n\nSee [Authentication Security → Bearer Tokens and Cookie Precedence](/stack/auth/security#bearer-tokens-and-cookie-precedence).\n\n---\n\n## v0.16.5 — May 12, 2026\n\n### Flat write DSL\n\nResource write operations are now declared at the table level alongside `read`, replacing the nested `crud` block:\n\n```ts\ndefineTable(customers, {\n read: { ... },\n create: { access: { roles: [\"admin\"] } },\n update: { access: { roles: [\"admin\"] } },\n delete: { access: { roles: [\"admin\"] }, mode: \"soft\" },\n upsert: { access: { roles: [\"admin\"] } },\n guards: { ... },\n});\n```\n\n`crud` and top-level `put` still compile as deprecated compatibility aliases. Mixed usage on the same resource is rejected. `schema-registry.json` emits both shapes during the transition.\n\n### CMS placement for multi-table feature actions\n\nStandalone actions on multi-table features have an explicit placement model:\n\n- `cms.placement: \"feature\"` shows the action on every table toolbar in the feature\n- `cms.placement: \"tables\"` with `cms.tables` scopes it to specific tables\n- `cms.hidden: true` keeps it API-only\n\nFeature-root standalone actions are emitted under a new `featureActions` bucket in `schema-registry.json`. Ambiguous multi-table standalone actions without placement compile with a warning.\n\n### `openapi.types` accepts a string array\n\nOne compile can write the generated types file to multiple locations, keeping colocated SPA clients in sync:\n\n```ts\nopenapi: { types: ['api-types.gen.ts', 'apps/web/src/lib/api-types.gen.ts'] }\n```\n\n### Stable artifact ordering\n\nGenerated route files and `schema-registry.json` are emitted in a stable order across runs. Identical logical input produces identical artifacts.\n\n---\n\n## v0.16.4 — May 12, 2026\n\n### Drizzle snapshot integrity\n\nDrizzle metadata files (`<n>_snapshot.json`) are no longer stamped with a Quickback warning key. The warning is now journal-only. Projects whose snapshots were corrupted by an earlier release self-heal on the next compile — the stripped header is removed during staging and the rewritten snapshot is clean.\n\n### `account.auth.*` drives the server, not just the SPA\n\nThe Account UI's auth flags (`signup`, `password`, `passkey`, `emailOTP`, `emailVerification`) now configure the Better Auth server alongside the SPA bundle. A normalizer maps them into the server config:\n\n- `signup → emailAndPassword.disableSignUp` (inverted)\n- `password → emailAndPassword.enabled`\n- `emailVerification → emailAndPassword.requireEmailVerification`\n- `passkey` / `emailOTP` → plugin additions\n\nThe SPA's `VITE_ENABLE_*` flags are derived from the same canonicalized server config, so the bundle and the server cannot drift. Two new flags ride along: `VITE_ENABLE_API_KEYS` and `VITE_ENABLE_MAGIC_LINK`.\n\n**Breaking** for projects that implicitly relied on the SPA-only behaviour: `account.auth.signup: false` now actually disables `POST /auth/v1/sign-up/email` on the server. Set `providers.auth.config.emailAndPassword.disableSignUp: false` explicitly to keep server signup open while hiding the SPA screen.\n\n---\n\n## v0.16.3 — May 9, 2026\n\n### Standalone action mount order\n\nFeature-level standalone action routers now register before sibling CRUD routers when both mount at the exact same prefix. A literal path like `GET /api/v1/records/today-bundle` resolves to the standalone handler instead of falling through to `GET /:id` and treating `\"today-bundle\"` as a record ID.\n\n---\n\n## v0.16.1 — May 9, 2026\n\n### Cloudflare ASSETS canonicalization\n\nWorker SPA fallbacks now request `/<dir>/` instead of `/<dir>/index.html`. Cloudflare's static-assets binding rewrites `/index.html` requests as 307 redirects to the trailing-slash path under the default `html_handling=auto-trailing-slash`, which previously caused redirect loops in SPA fallback handlers. Affects CMS, Account, admin, and the multi-domain catchall.\n\n### `account.customLogin`\n\nSet `account: { customLogin: true }` to drop a project-branded sign-in page in front of the bundled SPA. Place the page at `quickback/public/account/login/index.html` (as a directory) and the existing public passthrough serves it. The route registers before the `/account/*` SPA catch-all so the static handler wins; everything else under `/account/` continues to route through the bundled SPA.\n\n### Project-level realtime defaults\n\n`providers.database.config.realtime: true` now treats every resource as realtime-enabled by default. Per-resource `realtime: { enabled: false }` still wins.\n\n### Compile-time validators\n\nTwo new compile-time errors over silent runtime failures:\n\n- `AUTHENTICATED` + org-scoped firewall is rejected. The combination silently returned empty lists to sign-in-only callers who lacked an active org; the validator names three valid resolutions (drop the org scope, use `USER`, or split the route).\n- `createRealtime` imports without `realtime: true` enabled in the config are rejected at compile.\n\n### Drizzle metadata hardening\n\nDrizzle journal files carry a \"do not edit\" header. The compiler warns when the journal entry count exceeds the snapshot file count (typically the trace of a hand-deleted snapshot).\n\n### Minor\n\n- `SYSADMIN` is now recognised by the standalone-action org gate's pseudo-role matcher.\n- Apex `/` and `/account/login` get fallback redirects to `auth.loginUrl` when neither bundled SPA is enabled.\n- Record-based action URLs are kebab-case to match the OpenAPI spec (e.g. `/api/v1/widgets/:id/send-invite`).\n\n---\n\n## v0.16.0 — May 9, 2026\n\n### Agent Auth Protocol\n\nQuickback ships a server implementation of the [Agent Auth Protocol](https://agentauthprotocol.com) via `@better-auth/agent-auth`. Enable with `auth.plugins.agentAuth: true` and the compiler emits the full agent-auth surface: discovery at `/.well-known/agent-configuration`, capability projection from the project's OpenAPI spec, a device-authorization approval page in the Account SPA at `/agents/approve`, and the four agent-auth tables added to the auth schema automatically.\n\n**OpenAPI capability projection runs by default.** Every operation with an `operationId` becomes an agent capability. Default `approvalStrength` map: `GET → \"session\"`, `POST/PUT/PATCH/DELETE → \"webauthn\"`. The proxy `onExecute` makes a self-fetch with a Better Auth JWT minted for the agent session, so the inner request hits the existing JWT fast-path and runs the full firewall + access + masking pipeline. Opt out of OpenAPI projection with `agentAuth: { fromOpenAPI: false }` and wire `capabilities` + `onExecute` by hand.\n\n### Bearer-only on `/mcp` and the agent-auth surface\n\n`/mcp` forwards only `Authorization: Bearer …` into the inner request. Cookie and `x-api-key` forwarding are removed. Three Bearer flavors land on the same header — Better Auth session token (via the `bearer` plugin), OAuth access token (via OAuth Provider), and agent JWT (via `@better-auth/agent-auth`).\n\n### Auth DSL gains first-class plugin entries\n\n`bearer`, `oauthProvider`, and `agentAuth` are now typed entries in both the array-form union and the `BetterAuthPlugins` interface, with their own options shapes (`OAuthProviderOptions`, `AgentAuthOptions`). Existing `as any` casts can come out.\n\nAuto-enable rule: turning on `agentAuth` force-adds `bearer` + `oauthProvider`. No useful agent-auth deployment ships without those two.\n\n### `queue-consumer.ts` gating\n\nThe queue consumer is emitted when any of the following are true: embeddings are configured, queue handlers exist under `services/queues/*`, or `additionalQueues` is declared. Previously the third case left projects with a wrangler binding pointing at a missing handler.\n\n---\n\n## v0.15.0 — May 7, 2026\n\n### Sysadmin tier for the CMS\n\nA new opt-in `cms: { sysadmin: true }` flag turns the CMS into a cross-tenant DB-admin tool gated by `user.role === 'sysadmin'`. Distinct from the Better Auth `'admin'` plugin role, so user-management powers and DB-admin powers stay decoupled. Off by default.\n\nWhen enabled, the compiler emits a `SYSADMIN` pseudo-role (a fifth marker alongside `PUBLIC` / `AUTHENTICATED` / `USER` / `ADMIN`), a firewall escape hatch that drops tenant scopes for sysadmins while preserving soft-delete, a true cross-tenant `/admin/v1/sysadmin/organizations` endpoint, and a relaxed cross-tenant guard for list routes.\n\nThe CMS SPA gains a two-mode design: org admins keep the existing membership-based switcher, sysadmins get an \"All organizations\" selector that pins tenants via `?organizationId=` on every API call.\n\n### Durable Object `[[migrations]]` order is preserved\n\nCloudflare's migration list is append-only. The compiler now reads your existing `wrangler.toml` (when present) and emits auto-generated DO `[[migrations]]` blocks in two phases: deployed entries first (preserving order), net-new entries appended last. Reordering DOs in the config array no longer reshuffles deployed migrations.\n\n### `quickback/public/` — static-asset passthrough\n\nAnything dropped under `quickback/public/` is copied verbatim into `src/apps/` on every compile and served by the wrangler `[assets]` binding. Use for favicons, `robots.txt`, OG images, `.well-known/` files, marketing PDFs — anything that needs to ride past the compiler as bytes.\n\n- Optional. Missing folder is a no-op.\n- Stale-cleaned. Files removed from `quickback/public/` disappear on the next compile.\n- Hidden entries (`.DS_Store`, dotfiles) are skipped.\n- Collisions with compiler-emitted manifest paths fail the compile loudly.\n\n### Minor\n\n- Standalone-action wrapper skips the org gate when the access tree references any pseudo-role.\n- Queue handler emit no longer drops the `queue` export when there are no embeddings.\n\n---\n\n## v0.14.7 — May 7, 2026\n\n### Codegen fixes for projects with non-`id` primary keys and DO-only features\n\nFour surgical fixes to the generated output:\n\n- Duplicate table imports in relationship-role routes are deduplicated.\n- `db` references in single-record and bulk action handlers now resolve correctly during pre-fetch.\n- PartyServer auth gates pass the in-scope `db` handle into firewall calls.\n- Durable-object-only features keep their `lib/` files in the output.\n\n### `emailOtp` + AWS SES is OTP-only\n\n`auth.emailOtp` with the AWS SES email provider no longer auto-wires the magic-link companion. Mail-client URL prefetching can burn the one-time code before the human sees it; the Account SPA's `/email-otp` route is the single canonical entry point. Projects that explicitly want the magic-link arm can wire `sendVerificationOTP` directly.\n\n---\n\n## v0.14.6 — May 7, 2026\n\n### MCP transport correctness\n\nFour fixes to the MCP-over-HTTP path:\n\n- `tools/call` URLs are no longer double-prefixed for action tools.\n- Auth middleware accepts API keys via `Authorization: Bearer` in addition to `x-api-key` and query parameters — the channel MCP clients use exclusively.\n- `auth.roleHierarchy` is expanded for runtime role checks across api-key, JWT, and session auth paths. A higher role inherits the privileges of every lower role.\n- Team-scoped firewall predicates degrade gracefully when no team is active (org scoping continues to apply; team scoping is optional).\n\n---\n\n## v0.14.5 — May 7, 2026\n\n### MCP environment threading\n\nThe generated MCP server's `tools/call` dispatch threads `env` and `executionCtx` into the inner request, so action tools that touch Cloudflare bindings (D1, KV, R2, Queues) no longer crash with `undefined` env access.\n\n---\n\n## v0.14.4 — May 7, 2026\n\n### `via:` firewall predicates pull required imports\n\nThe relationship-role generator emits `inArray` and `sql` imports when the firewall has any `via:` predicate, and `buildFirewallConditions` accepts `(ctx, db)` so the relationship subquery has a Drizzle client to evaluate against. Every CRUD and action call site passes `db` through automatically.\n\n---\n\n## v0.14.3 — May 7, 2026\n\n### Relationship-role table re-exports\n\nGenerated `<table>.resource.ts` files now re-export their Drizzle table binding. Cross-feature relationship subqueries that import the binding from the resource file (rather than the schema) resolve correctly.\n\n---\n\n## v0.14.2 — May 7, 2026\n\n### Historical DO `[[migrations]]` are preserved\n\nA new `bindings.durableObjectMigrations` config slot carries forward `deleted_classes`, `renamed_classes`, and `transferred_classes` lifecycle entries across recompiles. Cloudflare's migration list is append-only; entries declared here are emitted first in `wrangler.toml`, then auto-generated current-class entries follow:\n\n```ts\nbindings: {\n durableObjects: [{ name: 'NOTEPAD', className: 'Notepad', from: 'lib/Notepad' }],\n durableObjectMigrations: [\n { tag: 'qb-do-deleted-legacy-notes-2026-05-05', deletedClasses: ['LegacyNotes'] },\n ],\n}\n```\n\nAll four lifecycle shapes are supported. User-declared entries can override auto-emit by reusing the same tag.\n\n---\n\n## v0.14.1 — May 7, 2026\n\n### Bulk action variants in `openapi.json`\n\nRecord-based actions with `bulkVariant: true` are now emitted as sibling operations in the OpenAPI spec, with the documented `{ ids, input, failFast? }` request shape, 200/207/400 responses, and a separate `<Resource><Action>Bulk` `operationId` so typed-client codegen distinguishes single from bulk.\n\n### Cross-tenant \"my events\" patterns\n\nThe access docs now include a worked example for the cross-tenant aggregation pattern (e.g. `GET /my-events` returning resources across all tenants a caller is invited to). See [Access → Cross-tenant dashboards](/compiler/definitions/access#cross-tenant-my-events-dashboards-are-not-this).\n\n---\n\n## v0.14.0 — May 7, 2026\n\n### Relationship-based authorization\n\nRoles can now be bound to a domain-table membership (\"user is a confirmed guest of this event\") rather than an org membership or a pseudo-role. Declare the relationship once and reference it from `firewall:` or `access.roles:`:\n\n```ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n },\n },\n roles: {\n guest: { via: 'guestOf' },\n eventStaff: { or: [{ via: 'guestOf' }, { roles: ['admin', 'owner'] }] },\n },\n}\n\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' },\n],\nread: { access: { roles: ['admin', 'member', 'guest'] } },\ncreate: { access: { roles: ['admin', 'guest'] } },\nupdate: { access: { roles: ['admin'] } },\n```\n\nThe compiler emits an inline Drizzle subquery against the relationship table and AND-composes it as the outermost firewall clause. The relationship table's own firewall (tenant scope, soft-delete) is honored inside the subquery; cross-tenant grants are impossible because the resource's tenant filter sits outermost.\n\nSupported surfaces: row-level scoping via `firewall: [{ field, via }]`, role gates on writes and reads, view access. Masking and action access reject relationship-roles at compile time with pointers to the working pattern (gate the row at the firewall layer, gate the role at the access layer).\n\nCross-tenant aggregation dashboards aren't solved by relationship-roles — the tenant firewall remains the outermost AND. For that pattern, use a user-scoped firewall or function-form access on a dedicated route.\n\nSee [Firewall → Relationship-based scoping](/compiler/definitions/firewall#relationship-based-scoping-via) and [Access → Relationship-based authorization](/compiler/definitions/access#relationship-based-authorization).\n\n### Bulk variants on record-based actions\n\n`defineAction({ bulkVariant: true })` emits `POST /:resource/batch/{action}` alongside the per-record route. The bulk handler loops the same access + transition + execute pipeline over a `{ ids, input, failFast? }` body:\n\n```ts\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n bulkVariant: true,\n transition: { field: \"status\", via: \"nextStatus\", fromTo: { /* ... */ } },\n async execute({ db, record, input, whereTransition }) {\n // exact same body — runs once per id\n },\n});\n```\n\nPer-record outcomes return as 207 Multi-Status. `failFast: true` aborts on the first failure and wraps the loop in `db.transaction()` on tx-supporting providers; D1 fails fast without rollback. Max 100 IDs per request. Rejected on standalone actions and `unsafe` actions.\n\n### Aggregations on read views\n\nRead views can declare pre-computed metrics that surface alongside the row payload:\n\n```ts\nread: {\n views: {\n pipeline: {\n fields: [\"id\", \"jobId\", \"candidateId\", \"status\", \"appliedAt\"],\n aggregations: {\n totalApplications: { fn: \"count\" },\n byStatus: { fn: \"groupBy\", field: \"status\" },\n },\n },\n },\n}\n```\n\nAggregations run over the same firewalled, filtered set as the row query; pagination is intentionally ignored. Supported functions: `sum`, `avg`, `min`, `max`, `count`, `count_distinct`, `groupBy`. See [Views → Aggregations](/compiler/definitions/views#aggregations).\n\n---\n\n## v0.13.5 — May 6, 2026\n\n### Object-form `auth.plugins` config is honored\n\nThe documented `plugins: { oauthProvider: {...} }`, `plugins: { organization: { teams: { enabled: true } } }` shapes now flow through the compiler unchanged. Per-plugin options reach the generated `auth.ts` as written.\n\n### `roles: [\"PUBLIC\"]` allowed on writes and actions\n\n`PUBLIC` is the explicit, uppercase opt-in for unauthenticated access on every access node — reads, writes, views, and actions. The runtime trusts the marker; row-level safety comes from firewall, masking, and the action's own validation. `PUBLIC` actions continue to receive mandatory audit logging.\n\nCommon pattern: pair `roles: [\"PUBLIC\"]` with `firewall: { exception: true }` on the resource so the row predicate doesn't reject every unauthenticated caller.\n\n---\n\n## v0.12.0 — May 5, 2026\n\n### Per-room authorization for PartyServer\n\n`bindings.durableObjects[].access` declares a path-scoped gate that runs the declared resource's firewall and `read.access` pipeline before the WebSocket upgrade:\n\n```ts\ndurableObjects: [\n // Single-resource: roomId IS the chat row id.\n { name: 'Chat', className: 'Chat', from: 'lib/Chat',\n access: { resource: 'chats' } },\n\n // Multi-resource: regex dispatches kind → resource.\n { name: 'Notepad', className: 'Notepad', from: 'lib/Notepad',\n access: {\n roomId: { pattern: '^(day-note|interaction|record):([A-Za-z0-9_-]+)$', kindGroup: 1, idGroup: 2 },\n resources: {\n 'day-note': { resource: 'day-notes' },\n 'interaction': { resource: 'interactions' },\n 'record': { resource: 'records' },\n },\n } },\n\n // Anonymous lobbies / public pads: explicit opt-out.\n { name: 'PublicLobby', className: 'PublicLobby', from: 'lib/PublicLobby',\n access: 'public' },\n]\n```\n\nThe gate 401s unauthenticated callers, 403s when the firewall hides the row, 404s when the row is missing. Resource references are validated against feature names at compile time. See [PartyServer Rooms → Per-room authorization](/stack/realtime/partyserver-rooms#per-room-authorization-via-access-v012).\n\n---\n\n## v0.11.1 — May 5, 2026\n\n### PartyServer auto-mount is secure by default\n\nThe `/realtime/*` auto-mount now wraps `partyserverMiddleware` in an auth check. Unauthenticated upgrades return 401; the four auth mechanisms (session cookie, JWT bearer, `x-api-key` header, query parameter) all unlock connections. Per-room access remains the `Server` class's responsibility in `onConnect`.\n\n---\n\n## v0.11.0 — May 5, 2026\n\n### OAuth Provider (MCP-ready)\n\nQuickback can act as a standards-compliant OAuth 2.1 + OIDC authorization server via [`@better-auth/oauth-provider`](https://better-auth.com/docs/plugins/oauth-provider). Enable with `plugins: [\"oauthProvider\"]`. The compiler auto-includes Better Auth's `jwt` plugin and the Account SPA gains a `/consent` page for the standard authorization-code flow.\n\nThis replaces Better Auth's deprecated `mcp` plugin and gives every MCP client (Cursor, Claude Desktop, claude.ai connectors, custom tooling) RFC 7591 dynamic client registration plus the discovery documents they need to bootstrap. See [Auth Plugins → OAuth Provider](/stack/auth/plugins#oauth-provider-mcp-ready).\n\n### API keys via query parameter\n\nThe auth middleware now accepts API keys as `?api_key=…` or `?key=…` query parameters. The `x-api-key` header takes precedence when both are sent. Prefer the header whenever the client supports it — query parameters land in access logs and `Referer` headers.\n\n### PartyServer rooms + realtime URL split\n\nThe realtime URL space is reorganized so names match what each primitive does:\n\n- **`/realtime/v1/*` → `/broadcast/v1/*`** — the org-wide Broadcaster moves to its semantically accurate prefix.\n- **`/realtime/<binding>/<room-id>`** — new mount for [PartyServer](/stack/realtime/partyserver-rooms) rooms. Per-room Durable Objects with presence and lifecycle hooks. Auto-mounted whenever a project declares any in-worker DO.\n\n**Breaking** — recompile + redeploy required:\n\n- `REALTIME_URL` env var renamed to `BROADCAST_URL`.\n- SPA helpers `getRealtimeWsUrl()` / `getRealtimeTicketUrl()` renamed to `getBroadcastWsUrl()` / `getBroadcastTicketUrl()`.\n- `appConfig.routes.api.realtime` renamed to `appConfig.routes.api.broadcast`.\n\n`partyserver`, `partysocket`, and `hono-party` are pre-installed in the compiler image; collab projects compile without an extra `npm install` step.\n\n---\n\n## v0.10.20 — May 4, 2026\n\n### In-worker Durable Objects\n\n`bindings.durableObjects[].from` flips a DO binding into in-worker mode and emits the export, the `[[migrations]]` block, and the `CloudflareBindings` type all together:\n\n```ts\ndurableObjects: [{\n name: \"ITEM_STREAM\",\n className: \"ItemStream\",\n from: \"features/loops/lib/ItemStream\",\n}]\n```\n\nDO class files live under `quickback/lib/` or `quickback/features/<feature>/lib/` — both copy verbatim into the generated `src/` tree on every compile. `from` and `scriptName` are mutually exclusive; cross-worker DOs (`scriptName` set) skip the re-export and migration block.\n\n`migrationTag` (default `qb-do-${className}`) is stable across regenerations and must never be removed or renamed once deployed. `useSqlite` defaults to `true`. See [Bindings → Durable Objects](/compiler/config/bindings#durableobjects).\n\n---\n\n## v0.10.18 — May 2, 2026\n\n### `experimentalRemote` — share deployed D1 with `wrangler dev`\n\nPer-binding `experimental_remote = true` lets `wrangler dev` read/write deployed D1 for selected bindings:\n\n```ts\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n splitDatabases: true,\n experimentalRemote: { auth: true, features: false },\n }),\n}\n```\n\nUseful for \"share prod auth in dev, keep feature writes sandboxed.\" Off by default.\n\n### Google OAuth + signup ToS\n\nThe Account SPA wires Google OAuth end-to-end when configured under `auth.config.socialProviders.google.enabled`. The signup flow gains a Terms-of-Service checkbox gate (configurable via the Account SPA branding).\n\n### CLI compile auth gate\n\n`quickback compile` now requires authentication for cloud-compiler runs. Device-flow `?redirect=` parameters are standardized across the login + signup pages so a user clicking \"Create one\" no longer loses their return URL.\n\n---\n\n## v0.10.15–v0.10.17 — May 2, 2026\n\n### CSP auto-config\n\nWhen `security.csp` is set, the compiler widens directives additively based on the project's enabled features:\n\n| Trigger | Auto-added | Directive |\n|---|---|---|\n| `cms: true` OR `account: true` | `'unsafe-inline'`, `https://fonts.googleapis.com` | `styleSrc` |\n| `cms: true` OR `account: true` | `https://fonts.gstatic.com` | `fontSrc` |\n| `csp` set (always) | `@trustedOrigins` | `connectSrc` |\n| Bundled SPA enabled | SPA-baked API origin (`config.domain`, `quickback.{baseDomain}`, `cms.domain`, `account.domain`) | `connectSrc` |\n\nAnything you already wrote stays — auto-config never removes or overrides. Each applied addition is logged to stderr. Opt out with `security: { cspAutoConfig: false }`.\n\nMost projects can write the minimal:\n\n```ts\nsecurity: {\n csp: {\n defaultSrc: ['@self'],\n scriptSrc: ['@self'],\n objectSrc: ['@none'],\n upgradeInsecureRequests: true,\n },\n}\n```\n\n…and the compiler fills in font hosts, trusted origins, and SPA-baked URLs.\n\nWhen a target directive is missing, auto-config scaffolds it from `default-src` baseline rather than widening `default-src` itself — CSP3 fall-back semantics would otherwise leak the addition to every directive that falls back to `default-src`.\n\n---\n\n## v0.10.14 — May 1, 2026\n\n### `auth.jwt` config\n\nThe bearer-token JWT used by the auth fast-path is configurable. Tune `expiresIn` to bound the post-revocation replay window without affecting browser SPAs (which auto-refresh on every authed call):\n\n```ts\nauth: {\n jwt: {\n expiresIn: 30,\n issuer: 'my-api',\n audience: 'partner-svc',\n secretEnv: 'CUSTOM_JWT_SECRET',\n },\n}\n```\n\n### Admin MCP endpoints filtered\n\nBetter Auth admin endpoints (`/admin/list-users`, `/admin/ban-user`, etc.) now carry `x-access: { userRole: ['admin'] }` in the generated OpenAPI spec. The MCP `tools/list` access-filter drops them for non-admin callers.\n\n### Declarative `security` config\n\nEvery security response header (`Content-Security-Policy`, COOP, COEP, CORP, HSTS, `X-Frame-Options`, `Referrer-Policy`, `Permissions-Policy`) is configurable from `quickback.config.ts`. `@`-prefixed sentinels (`@self`, `@none`, `@unsafe-inline`, `@trustedOrigins`, etc.) replace awkward `\"'self'\"` quoting.\n\nThe compiler lints the resolved config for known footguns: `@unsafe-inline` in `script-src`, wildcard sources, missing `default-src`, HSTS preload-list misconfiguration.\n\n### HSTS skipped on localhost\n\nGenerated middleware skips `Strict-Transport-Security` when the request hostname is `localhost`, `127.0.0.1`, or `*.localhost`. Without this gate, `wrangler dev` would pin a developer's browser to HTTPS across every project on that machine.\n\n---\n\n## v0.10.13 — May 1, 2026\n\n### Clickjacking defence on every Worker\n\nEvery Worker emits `Content-Security-Policy: frame-ancestors 'self' <TRUSTED_ORIGINS…>` and `X-Frame-Options: SAMEORIGIN` on every response. The CSP allowlist is sourced from the same `TRUSTED_ORIGINS` constant that gates CORS.\n\n---\n\n## v0.10.11 — May 1, 2026\n\n### MCP `tools/list` is access-filtered\n\nEach MCP tool now carries sanitised access metadata. `tools/list` filters against the caller's `ctx`: unauthenticated callers see only `PUBLIC` tools, authenticated callers see only role-gated tools they pass.\n\n- Wildcard CORS removed from the MCP endpoint.\n- Unauthenticated `GET /mcp` no longer enumerates tool names.\n- Internal flavor text is removed; `annotations.destructiveHint` and `_unsafe` remain — those are the spec-correct signals for clients.\n\n`tools/call` continues to re-enter the Hono app and run every middleware (auth, firewall, access, guards, masking), so hiding a tool from list never weakens the underlying gate.\n\n---\n\n## v0.10.10 — April 29, 2026\n\n### Reserved keys in `access.record` are rejected\n\n`access.record` is a flat field map evaluated as implicit AND between entries — keys must be column names. The compiler now rejects reserved keys (`and`, `or`, `roles`, `userRole`) inside `record` with migration guidance pointing at the working pattern (top-level siblings with their own `record:` blocks).\n\n---\n\n## v0.10.8 — April 29, 2026\n\n### Audit logging on Postgres targets\n\n`audit_events` previously only existed on `cloudflare-d1`. The audit table now lives in a dedicated `audit` schema (`drizzle.pgSchema('audit')`) on Postgres targets. The `hasSecurityAudit` gate accepts D1 or any PG dialect; `auditDatabaseId` remains a D1-only requirement.\n\n### `auditDatabaseId` is a compile-time requirement\n\nProjects with unsafe or `PUBLIC` actions that previously produced a placeholder `database_id = \"local-audit\"` in production now fail at compile time with the exact `wrangler d1 create <project>-audit` command and the config key where the returned ID goes.\n\n### Action input → OpenAPI / MCP\n\n`defineAction({ input: z.object({...}) })` schemas flow into the OpenAPI `requestBody` and the MCP tool's `inputSchema.properties`. Simple `z.object` shapes are extracted at compile time; discriminated unions, refinements, recursive schemas, and bare-identifier references run through Zod's native `z.toJSONSchema()` for full-fidelity output.\n\n### OpenAPI fidelity\n\n- Response schemas emit `required[]` for every non-nullable column.\n- `text(_, { enum: [...] })` columns emit as closed `{ type: \"string\", enum: [...] }`.\n- `id` claims `format: \"uuid\"` only when the project's `generateId` actually produces UUIDs. cuid2 / prefixed / nanoid / serial generators emit plain `{ type: \"string\" }`.\n\n### Minor\n\n- Auto-mask predicate verifies the resolved owner column exists before emitting an `or: 'owner'` clause; falls back to roles-only with a warning otherwise.\n- Generated CRUD errors emit canonical `QuickbackErrorCode` enum values (`DB_NOT_NULL_VIOLATION`, `DB_UNIQUE_VIOLATION`, etc.) so generated SDKs can exhaustively switch on `code`. See [API errors](/compiler/targets/hono-api/using-the-api/errors#database).\n\n---\n\n## DSL: one file per action, multi-table per feature\n\n### One file per action\n\nAction authoring is one file per action under `<feature>/actions/<name>.ts`. The filename is the action name and the URL segment:\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: { applied: [\"screening\"], screening: [\"interview\"], interview: [\"offer\"] },\n },\n async execute({ db, record, input, auditFields, whereTransition }) { /* … */ },\n});\n```\n\n`defineAction` is imported from a generated per-feature helper at `<feature>/.quickback/define-action.ts` — `record`, `input`, and audit fields are typed without manual annotations.\n\n**Discovery rules:**\n- `actions/<name>.ts` binds to the feature's primary table.\n- `actions/<table>/<name>.ts` binds to the sibling table file.\n- Setting `path:` makes the action standalone (custom URL, no record fetch).\n- Tableless features require every action to be standalone.\n\n**Retired** (rejected at load time with migration guidance): `actions.ts` (bundled multi-action file), `_feature.ts`, `handlers/` directory + `handler:` string ref, `defineActions(table, {…})`, colocated `defineActions` inside table files, `standalone: true` flag, `*-actions.ts` / `*.actions.ts` filename patterns.\n\nSee [Actions docs](/compiler/definitions/actions).\n\n### Multi-table actions per feature\n\nOne feature directory can own actions on multiple tables. Three discovery modes:\n\n- **Colocated** (canonical) — `<table>.ts` containing both `defineTable` and `defineActions(<table>, …)`. One file per entity.\n- **`actions.ts`** — single primary-table actions file at feature root.\n- **`actions/<table>.ts`** — per-table action files for strict schema/behavior separation.\n\nPlus a universal `_feature.ts` slot for non-table-bound feature-level actions and shared Zod schemas.\n\nAction names are unique per `(bindTable, name)` pair. Sibling-bound `actions/episodes/publish.ts` and `actions/shows/publish.ts` mount at `/episodes/:id/publish` and `/shows/:id/publish` and compile cleanly.\n\n---\n\n## Firewall: named-scope shape\n\nThe named-scope firewall shape is a co-equal user-facing input alongside the predicate array:\n\n```typescript\nfirewall: { organization: { column: 'tenant_id' } } // named-scope (compact)\nfirewall: { owner: { column: 'account_user_id' } }\nfirewall: { exception: true }\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n] // predicate array (explicit)\n```\n\nPick the form that reads better — named-scope for the common one-line case, predicate array when you need custom `in`-lists or non-scope predicates.\n\n**Auto-detection synonyms.** When `firewall:` is omitted, the compiler scans the schema for an isolation column. The org-scope list accepts `organizationId`, `organisationId`, `orgId`, `organization`, `organisation`, `org` (American + British). User-scope accepts `userId`.\n\n**`ownerId` is a targeted error signal.** When a table carries `ownerId` but no isolation column and no explicit `firewall:`, the compiler raises a specific error — `ownerId` is business-logic ownership, not access control. Use `userId` for access control, declare an explicit `firewall:`, or add a separate isolation column.\n\n---\n\n## v0.10.0 — April 26, 2026\n\n### `q.scope()` — single-declaration tenant scoping\n\n`q.scope(kind)` replaces the three-place pattern (column declaration + firewall predicate + ownership-guard) with one column:\n\n```typescript\ncolumns: {\n organizationId: q.scope('organization'), // → ctx.activeOrgId\n ownerId: q.scope('owner'), // → ctx.userId\n teamId: q.scope('team'), // → ctx.activeTeamId\n}\n```\n\n`q.scope()` columns auto-derive the firewall predicate, register with the guards layer as `systemManaged` (client input rejected), and auto-populate from `ctx` on create / upsert. The systemManaged extension generalises beyond `q.scope()`: any firewall predicate whose `equals` references `ctx.*` registers its `field` automatically.\n\nSee [`q.scope()`](/compiler/definitions/schema#qscope--tenant-scope-columns).\n\n### `masking[col].query.roles` — unified filter / sort / search gate\n\nThe three legacy per-capability flags (`filterable`, `searchable`, `sortable`) are replaced by a single `query.roles` allowlist:\n\n```typescript\nmasking: {\n email: {\n type: 'email',\n show: { roles: ['admin'] },\n query: { roles: ['admin'] }, // defaults to show.roles when omitted\n },\n}\n```\n\nA view's own `query.{filterable,searchable,sortable}` allowlist is the opt-in for higher-privileged roles; the existing intersection validator gates it at compile time.\n\n**Breaking:** `masking[col].filterable / .searchable / .sortable` is rejected at compile time with a migration hint. Replace with `query.roles` (or delete the flags — `query` defaults to `show.roles`).\n\n---\n\n## v0.9.0 — April 25, 2026\n\n### Unified `read:` pipeline\n\nThe read side of every resource has its own block — `read:` — that owns the collection-level `GET /` endpoint, single-record `GET /:id`, and named view projections.\n\n**Breaking changes** (compile-time errors with migration hints):\n\n- `crud.list` → `read.access` (plus `read.pageSize` / `read.maxPageSize`)\n- `crud.get` → `read.access` (single-record GET inherits automatically)\n- Top-level `views: {...}` → `read.views: {...}`\n- `crud.list.fields` / `crud.get.fields` → declare a named view under `read.views` and call `/views/{name}`\n\n### Pre-record access ordering\n\nHandlers on `/:id` run a role-only access check before the firewall query. A caller without a matching role gets 403 before the database is touched. This closes the 404-vs-403 ID-probe channel — an unauthorized caller can no longer distinguish \"row exists in another tenant\" from \"row doesn't exist.\" See [Access evaluation order](/compiler/definitions/access#evaluation-order).\n\n### Transactional batch operations\n\nBatch endpoints expose `failFast` and a `meta.transactional` response field. On tx-supporting providers (postgres, supabase, neon, libsql, better-sqlite3, bun-sqlite), `failFast: true` wraps the per-record loop in `db.transaction(...)` so any failure rolls back the entire batch. On Cloudflare D1 (no `db.transaction`), `failFast: true` stops on the first error but prior writes stay committed.\n\nEmbedding queue messages and realtime broadcasts emit after the transaction commits — rolled-back batches produce no orphan jobs.\n\nSee [Batch Operations → Transactional semantics](/compiler/targets/hono-api/using-the-api/batch-operations#transactional-semantics).\n\n---\n\n## v0.8.7 — April 17, 2026\n\n### Hono CVE bump\n\nHono is bumped to `^4.12.14` across the monorepo, the compiler Docker image's pre-installed deps, and every generator path that emits Hono into compiled projects. Older ranges covered the vulnerable window. Recompile to pick up the fix in your generated project's `package.json`.\n\n### Cloudflare Email Sending in public beta\n\nQuickback defaults to the Workers `send_email` binding for Cloudflare deploys. Cloudflare Email Sending has graduated to public beta — production-ready with zero-config. AWS SES remains a fully supported opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes. See [Email Configuration](/compiler/config#email-configuration).\n\n### Dependency sweep\n\n`wrangler@^4.83.0`, `drizzle-orm@^0.45.2`, `drizzle-kit@^0.31.10`, `zod@^4.3.6`, `@cloudflare/workers-types@^4.20260417.1`.\n\n---\n\n## v0.8.5 — April 15, 2026\n\n### `userRole` access primitive\n\nA new `userRole?: string[]` field in the declarative `Access` config evaluates against `ctx.userRole` (the Better Auth admin-plugin `user.role` column). Distinct from `roles`, which matches `ctx.roles` (org membership).\n\n```typescript\n// Org owner OR platform admin\naccess: { or: [{ roles: ['owner'] }, { userRole: ['admin'] }] }\n\n// Platform admins see SSNs across every org\nmasking: { ssn: { type: 'ssn', show: { userRole: ['admin'] } } }\n```\n\n`userRole` works everywhere `Access` is accepted — CRUD, actions, views, masking, and inside `or` / `and` combinators. See [Access → userRole vs roles](/compiler/definitions/access#userrole-vs-roles).\n\n### CMS admin gate enforced server-side\n\n`cms: { access: \"admin\" }` previously only hid the CMS link in Account UI and rendered an \"Access Denied\" screen inside the SPA. Server-side enforcement now applies at every CMS-facing surface: the SPA shell, `/api/v1/schema`, and `custom_view` CRUD.\n\n### Better Auth 1.5 + `@cloudflare/workers-types` compatibility\n\nGenerated API code typechecks against the new versions. The org-member role-change broadcast hook is emitted via `organizationHooks.afterUpdateMemberRole` (the supported shape after the 1.5 deprecation of `databaseHooks.member.update.after`). `REALTIME_URL` and `ACCESS_TOKEN` are always emitted as optional bindings when the organization plugin is active.\n\n---\n\n## v0.8.4 — April 14, 2026\n\n### `generateId: \"short\"` strategy\n\nA compact ID option for tables where short, shareable codes matter more than collision resistance at scale:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", { generateId: \"short\" }),\n}\n```\n\nGenerates 6-character alphanumeric IDs (e.g. `a3F9xK`) using nanoid's `customAlphabet` with the full 62-char alphabet (`0-9A-Za-z`). Requires the `nanoid` package.\n\n**When to use:** room codes, invite links, share URLs, ephemeral records.\n\n**When not to use:** high-volume tables. 62^6 ≈ 56.8B combinations means ~238K rows before a 50% collision probability. For large tables stick with `\"uuid\"`, `\"cuid\"`, or `\"prefixed\"`. See [Providers → ID Generation Options](/compiler/config/providers#id-generation-options).\n\n---\n\n## v0.8.2 — April 11, 2026\n\n### Catch-all `VITE_QUICKBACK_URL`\n\nA single Quickback origin can be set in place of four separate URL env vars:\n\n```bash\nVITE_QUICKBACK_URL=https://secure.example.com\n```\n\n| Individual var (explicit) | Fallback when unset |\n|---|---|\n| `VITE_QUICKBACK_API_URL` | `${VITE_QUICKBACK_URL}` |\n| `VITE_QUICKBACK_ACCOUNT_URL` | `${VITE_QUICKBACK_URL}/account` |\n| `VITE_QUICKBACK_CMS_URL` | `${VITE_QUICKBACK_URL}/cms` |\n\n`VITE_QUICKBACK_APP_URL` stays independent — it points at the tenant's own frontend. Non-breaking; individual vars take precedence when set. Library users can set `__QUICKBACK_URL__` on `globalThis`. See [Environment Variables](/stack/account-ui/environment-variables).\n\n---\n\n## v0.8.1 — April 9, 2026\n\n### Role hierarchy with `+` suffix\n\nDefine a hierarchy and use `+` to mean \"this role and above\":\n\n```typescript\nauth: { roleHierarchy: ['member', 'admin', 'owner'] }\n\ncrud: {\n list: { access: { roles: [\"member+\"] } }, // member, admin, owner\n create: { access: { roles: [\"admin+\"] } }, // admin, owner\n delete: { access: { roles: [\"owner\"] } }, // owner only\n}\n```\n\nRoles are expanded at compile time. No `+` = exact match. See [Access → Role Hierarchy](/compiler/definitions/access#role-hierarchy).\n\n---\n\n## v0.8.0 — April 9, 2026\n\n### Breaking: VITE URL environment variables namespaced\n\nAll Quickback-generated URL environment variables are namespaced under `VITE_QUICKBACK_*` to avoid collisions with other Vite projects.\n\n| Old | New |\n|-----|-----|\n| `VITE_API_URL` | `VITE_QUICKBACK_API_URL` |\n| `VITE_ACCOUNT_URL` | `VITE_QUICKBACK_ACCOUNT_URL` |\n| `VITE_APP_URL` | `VITE_QUICKBACK_APP_URL` |\n| `VITE_CMS_URL` | `VITE_QUICKBACK_CMS_URL` |\n\nNon-URL variables are unchanged (`VITE_ENABLE_*`, branding vars, `VITE_STRIPE_PUBLISHABLE_KEY`).\n\n**Action required:**\n- Compiled projects: re-run `quickback compile`.\n- Standalone deploys: update `.env`, `.env.production`, and `wrangler.toml` files manually.\n- Library users: `__QUICKBACK_API_URL__` / `__QUICKBACK_APP_URL__` globals are unchanged.\n\n### CMS access control\n\n`cms.access: \"admin\"` enforces access at the CMS level, not just link visibility. Non-admin users (`user.role !== \"admin\"`) see an \"Access Denied\" screen with a sign-out button.\n\n---\n\n## v0.5.11 — February 24, 2026\n\n### Mandatory unsafe action audit trail\n\nStructured `unsafe` config (`unsafe: { reason, adminOnly, crossTenant, targetScope }`). Cross-tenant unsafe actions require Better Auth authentication plus platform admin role (`ctx.userRole === \"admin\"`). Mandatory audit logging on success, denial, and error paths. Cloudflare output includes `AUDIT_DB` wiring, `drizzle.audit.config.ts`, and `db:migrate:audit:*` scripts when unsafe actions are present.\n\nCompile-time raw SQL guard for actions and handlers (`allowRawSql: true` required per action).\n\n### Security contract report artifacts\n\nGenerated security contract artifacts: `reports/security-contracts.report.json`, `reports/security-contracts.report.sig.json`. Config-driven signing controls (`compiler.securityContracts.report.signature.*`). Missing required signing keys fail loudly with explicit remediation.\n\n### Headless Drizzle rename hints\n\n`compiler.migrations.renames` configuration for CI/CD environments where Drizzle's interactive rename prompts block compilation. See [Configuration](/compiler/config).\n\n### Minor\n\n- Email OTP magic links work correctly.\n- Auth is required for all API routes when running locally.\n- Single-file multi-table exports alongside `defineTable()` produce a clear error.\n\n---\n\n## v0.5.8 — February 14, 2026\n\n### Quickback CMS\n\nA schema-driven admin panel that connects to your generated API. The compiler now outputs a JSON schema registry consumed by the CMS at runtime. Firewall error modes (`reveal` for 403 with details, `hide` for opaque 404) are configurable per resource for security-sensitive deployments.\n\n---\n\n## v0.5.7 — February 12, 2026\n\n### Scoped database for actions\n\nActions receive a security-scoped database instead of a raw Drizzle instance. The compiler generates a proxy wrapper that automatically enforces org isolation, owner filtering, and soft-delete visibility — the same protections that CRUD routes have always had.\n\nDuck-typed column detection at runtime:\n\n| Column Detected | SELECT / UPDATE / DELETE | INSERT |\n|---|---|---|\n| `organizationId` | Adds `WHERE organizationId = ?` | Auto-injects `organizationId` from context |\n| `ownerId` | Adds `WHERE ownerId = ?` | Auto-injects `ownerId` from context |\n| `deletedAt` | Adds `WHERE deletedAt IS NULL` | — |\n\nEvery action is secure by default — no manual `WHERE` clauses needed.\n\nActions that intentionally need to bypass security (admin reports, cross-org queries, migrations) can declare `unsafe: true` to receive a raw, unscoped database handle via `rawDb`:\n\n```typescript\ndefineActions(analytics, {\n globalReport: {\n unsafe: true,\n execute: async ({ db, rawDb, ctx, input }) => {\n // db → still scoped (safety net)\n // rawDb → bypasses all security filters\n const allOrgs = await rawDb.select().from(organizations);\n },\n },\n});\n```\n\nWithout `unsafe: true`, `rawDb` is `undefined`. See [Actions](/compiler/definitions/actions).\n\n### Cascading soft delete\n\nSoft-deleting a parent record automatically cascades to child and junction tables within the same feature. The compiler detects foreign key references at build time and generates cascade `UPDATE` statements.\n\nRules:\n- Applies to soft delete only. Hard delete relies on database-level `ON DELETE CASCADE`.\n- Cascades within the same feature only — cross-feature references are not affected.\n- Child tables must have `deletedAt` / `deletedBy` columns (auto-added by the compiler).\n\nSee [Actions API → Cascading Soft Delete](/compiler/targets/hono-api/using-the-api/actions-api#cascading-soft-delete).\n\n### Advanced query parameters\n\nNew capabilities for all list endpoints:\n\n- **Field selection** — `?fields=id,name,status`\n- **Multi-sort** — `?sort=status:asc,createdAt:desc`\n- **Total count** — `?count=true` returns total matching records in `X-Total-Count`\n- **Full-text search** — `?search=keyword` searches across all text columns\n\nSee [Query Parameters](/compiler/targets/hono-api/using-the-api/query-params).\n\n---\n\n## v0.5.5 — February 5, 2026\n\n### OpenAPI spec generation\n\nGenerated APIs include a full OpenAPI specification at `/openapi.json`. Better Auth endpoints are included in the spec.\n\n### Better Auth plugins\n\nPublished `@quickback-dev/better-auth-upgrade-anonymous` (post-passkey email collection flow), `@quickback-dev/better-auth-combo-auth` (combined email + password + OTP), and `@quickback-dev/better-auth-aws-ses` (AWS SES email provider).\n\n### Security headers\n\nGlobal error handler prevents leaking internal error details. Security headers middleware (CSP, HSTS, X-Frame-Options, X-Content-Type-Options). `BETTER_AUTH_SECRET` properly passed to generated config.\n\n---\n\n## v0.5.4 — January 30, 2026\n\n### Account UI\n\nPre-built authentication UI deployed as Cloudflare Workers. Sessions, organizations, passkeys, passwordless, admin panel, API keys. Dual-mode: standalone (degit template) or embedded with Quickback projects.\n\n### Webhook system\n\nInbound webhook endpoints with signature verification. Outbound webhooks via Cloudflare Queues with automatic retries. Configurable per-feature webhook events.\n\n### Realtime & vector search\n\nDurable Objects + WebSocket realtime subscriptions. Vector embeddings via Cloudflare Vectorize. KV and R2 storage integrations.\n\n---\n\n## v0.5.0 — January 2026\n\n### Initial release\n\n- **Quickback Compiler** — TypeScript-first backend compiler.\n- **Four security pillars** — Firewall, Access, Guards, Masking.\n- **`defineTable()`** — schema + security configuration in a single file.\n- **Templates** — Cloudflare Workers, B2B SaaS.\n- **Cloud compiler** — remote compilation via `compiler.quickback.dev`.\n- **CLI** — `quickback create`, `quickback compile`.\n- **Better Auth integration** — organizations, roles, sessions.\n- **Drizzle ORM** — schema-first with automatic migrations.\n- **Cloudflare D1** — split database support (auth + features)."
7
7
  },
8
8
  "compiler/claude-code-skill": {
9
9
  "title": "AI Developer Tools",
@@ -55,7 +55,7 @@ export const DOCS = {
55
55
  },
56
56
  "compiler/config": {
57
57
  "title": "Configuration",
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| `contract` | `{ version?: \"v1\" \\| \"v2\" }` | Public API/auth contract version. Omit for the backward-compatible v1 default; select v2 for `/api/v2/*` and `/auth/v2/*` across generated routes, Better Auth, OpenAPI, MCP, and discovery. |\n| `api` | `object` | Dedicated hostname for the selected feature API contract (`/api/v1/*` or `/api/v2/*`); additive alias — see [Domains](/compiler/config/domains) |\n| `auth` | `object` | App-level auth settings (`roleHierarchy`, `jwt`, delegated `principals`, `loginUrl`/`profileUrl`, `domain`) — see [Access](/compiler/definitions/access#role-hierarchy) and [Delegated principals](#delegated-principals-contract-v2) |\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), Neon `migrations.foreignKeys`, `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## Public contract version\n\nQuickback defaults to the existing v1 HTTP contract. New applications can opt\ninto v2 explicitly:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n contract: { version: \"v2\" },\n providers: cloudflare({}),\n});\n```\n\nThe selection is atomic: feature routes move to `/api/v2/*`, Better Auth moves\nto `/auth/v2/*`, and generated OpenAPI, MCP tool calls, OAuth discovery,\n`llms.txt`, schema/embeddings routes, and dedicated-domain `/v2/*` shortcuts\nuse the same version. When CMS or Account is enabled, Quickback also bakes\nthose paths into the SPA build and injects them at runtime, so CRUD, schema,\nlive-view, and authentication requests use the selected contract. Quickback\ndoes not expose a mixed v1/v2 surface from one compiled Worker. Omitting\n`contract` remains byte-compatible with v1 projects.\n\nV2 also makes action input-schema fidelity a compile gate. The CLI must\nsuccessfully harvest `z.toJSONSchema(action.input)` for every authored action;\npartial or missing harvests fail with the exact action file keys, bundle or\nevaluation phase, and underlying local error. Dependencies are resolved from\nthe generated runtime's `build.outputDir/node_modules` before unrelated\nancestor installs, so an isolated `quickback/` definition tree can use a\nsibling `src/` runtime without a workspace-root symlink. The compiler enforces\nthe same invariant at its shared input boundary, including\n`POST /compile?complete=false`, so validation-only or raw API calls cannot\nbypass it. V1 retains the historical best-effort static-schema fallback.\n\n## Delegated principals (contract v2)\n\n`auth.principals` defines non-account authority such as an event pass or a\nshort-lived event session. It is available only with all three of:\n\n- `contract: { version: \"v2\" }`\n- the Cloudflare runtime\n- Neon with `connectionMode: \"hyperdrive\"`\n\nEach principal type owns an exact Authorization scheme. `Bearer` is reserved\nfor Quickback account authentication, including case variants, and two\nprincipal types cannot share a scheme.\n\n```typescript\nexport default defineConfig({\n name: \"attend-v2\",\n template: \"hono\",\n contract: { version: \"v2\" },\n auth: {\n principals: {\n event_pass: {\n scheme: \"EventPass\",\n authenticate: {\n module: \"./event-pass-proof\",\n export: \"authenticateEventPass\",\n },\n lookup: {\n table: {\n module: \"../features/event-access/event-access\",\n export: \"eventAccess\",\n sqlName: \"event_access\",\n },\n digest: { field: \"digest\", column: \"digest\" },\n actorId: { field: \"personId\", column: \"person_id\" },\n claims: {\n eventId: { field: \"eventId\", column: \"event_id\" },\n personId: { field: \"personId\", column: \"person_id\" },\n },\n status: { field: \"status\", column: \"status\", allow: [\"active\"] },\n },\n },\n event_delegate: {\n scheme: \"EventSession\",\n authenticate: {\n module: \"./event-session-proof\",\n export: \"authenticateEventSession\",\n },\n lookup: {\n table: {\n module: \"../features/event-sessions/event-sessions\",\n export: \"eventSessions\",\n sqlName: \"event_sessions\",\n },\n digest: { field: \"digest\", column: \"digest\" },\n actorId: { field: \"personId\", column: \"person_id\" },\n sessionId: { field: \"id\", column: \"id\" },\n familyId: { field: \"familyId\", column: \"family_id\" },\n claims: {\n eventId: { field: \"eventId\", column: \"event_id\" },\n personId: { field: \"personId\", column: \"person_id\" },\n },\n status: { field: \"status\", column: \"status\", allow: [\"active\"] },\n },\n },\n },\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"neon\", {\n connectionMode: \"hyperdrive\",\n hyperdrive: { id: \"<32-character-hyperdrive-id>\" },\n }),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\nThe `authenticate.module` path is relative to generated\n`src/lib/principal-auth.ts`. Put project proof hooks under `quickback/lib`; the\ncompiler stages them into `src/lib` even if no action imports them. A hook has\none job: prove the presented credential and return its stable digest.\n\n```typescript\n// quickback/lib/event-session-proof.ts\nexport async function authenticateEventSession({ credential, env, request }: {\n credential: string;\n env: Env;\n request: Request;\n}): Promise<{ digest: string } | null> {\n const valid = await verifySignedEventSession(credential, env, request);\n return valid ? { digest: await sha256(credential) } : null;\n}\n```\n\nThe hook receives no `db`, and it must not implement row authorization or\nbusiness behavior. Quickback performs exactly one narrow, unique digest lookup\nunder a lookup-only RLS principal. A digest must be 16–512 non-whitespace\ncharacters; resolved identity strings must be 1–512 characters and serialized\nclaims are limited to 4096 characters. A lookup must resolve exactly one active\nrow or authentication fails.\n\nOn success, actions receive `ctx.principal`:\n\n```typescript\n{\n type: \"event_delegate\",\n actor: { type: \"event_delegate\", id: \"person_123\" },\n session: { id: \"session_123\", familyId: \"family_123\" },\n claims: { eventId: \"event_123\", personId: \"person_123\" },\n}\n```\n\nQuickback never synthesizes `userId`, `activeOrgId`, `activeTeamId`, or\nmembership roles from a delegated credential. Use `principals` in an access\narm to admit it. Values inside one arm are ANDed; sibling `or` arms are ORed:\n\n```typescript\naccess: {\n or: [\n { roles: [\"AUTHENTICATED\"] },\n { principals: [\"event_delegate\"], record: {\n eventId: { equals: \"$ctx.principal.claims.eventId\" },\n } },\n ],\n}\n```\n\nAn Authorization header cannot be combined with `x-api-key` or a Better Auth\nsession cookie. Quickback recognizes only Better Auth's exact session cookie\nnames for this conflict check, so analytics and preference cookies remain\nharmless.\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## Neon Foreign Key Migrations\n\nUse `compiler.migrations.foreignKeys` when a Neon relationship cannot be\nexpressed in one generated Drizzle schema file—for example, a feature table\nthat references a Better Auth table, or a composite integrity relationship\nbetween independently authored feature modules.\n\n```typescript\nexport default defineConfig({\n // ...\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"neon\", { connectionMode: \"hyperdrive\" }),\n auth: defineAuth(\"better-auth\"),\n },\n compiler: {\n migrations: {\n foreignKeys: [\n {\n name: \"person_account_links_user_fk\",\n source: {\n schema: \"app\",\n table: \"person_account_links\",\n columns: [\"user_id\"],\n },\n target: {\n schema: \"auth\",\n table: \"users\",\n columns: [\"id\"],\n },\n onDelete: \"restrict\",\n onUpdate: \"restrict\",\n },\n {\n name: \"event_access_grants_consumed_family_fk\",\n source: {\n schema: \"app\",\n table: \"event_access_grants\",\n columns: [\n \"consumed_by_family_id\",\n \"id\",\n \"organization_id\",\n \"event_id\",\n \"event_person_id\",\n ],\n },\n target: {\n schema: \"app\",\n table: \"event_session_families\",\n columns: [\n \"id\",\n \"source_grant_id\",\n \"organization_id\",\n \"event_id\",\n \"event_person_id\",\n ],\n },\n onDelete: \"restrict\",\n onUpdate: \"restrict\",\n },\n ],\n },\n },\n});\n```\n\nAll identifiers must be lowercase Postgres identifiers of at most 63\ncharacters. Source and target tuples must be nonempty and have equal arity;\ncolumn order is significant. Supported actions are `\"no action\"`,\n`\"restrict\"`, `\"cascade\"`, `\"set null\"`, and `\"set default\"`.\n\nConstraint names and source tuples must be unique in the config. On replay,\nQuickback verifies that an existing same-named constraint has the exact target,\nordered columns, and referential actions. It fails instead of silently\naccepting an ambiguous definition. Existing rows are validated during\nmigration, so clean up orphans before deploying.\n\nThis API is for database integrity, not business behavior. Keep authorization,\nstate transitions, event-pass consumption, and other business rules in the API\naction layer.\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/*` and `/auth/v1/*` for the default contract, or `/api/v2/*` and\n `/auth/v2/*` when `contract.version` is `\"v2\"`\n- `/storage/*` — R2 file storage\n- `/health`, `/openapi.json` — monitoring/discovery\n- `/account/*`, `/cms/*` — bundled SPAs (when enabled)\n- `/broadcast/v1/*` (realtime; `/broadcast/v2/*` under `contract.version: 'v2'`), `/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/{version}/users` | `/api/{version}/users` | `{version}` is the selected `v1` or `v2`; the rewriter prepends `/api` |\n| `https://auth.example.com/{version}/sign-in/email` | `/auth/{version}/sign-in/email` | Same selected version with `/auth` |\n| `https://api.example.com/api/{version}/users` | (unchanged) | Long form also accepted |\n| `https://api.example.com/auth/{version}/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/{version}/users` | feature route | Works for the selected version whether `api.domain` is set or not |\n| `https://quickback.example.com/auth/{version}/sign-in/email` | Better Auth | Works for the selected version whether `auth.domain` is set or not |\n| `https://quickback.example.com/{version}/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- Types the binding with Cloudflare's native `SendEmail` / `EmailSendResult`\n contract (`{ email, name }`, `replyTo`, and `contentId` on Workers). The REST\n helper remains a separate `{ address, name }` / `reply_to` / `content_id`\n contract.\n- Anchors each authentication delivery to `executionCtx.waitUntil(...)`. The\n background promise records a structured generic failure and stays rejected;\n outside a Worker request, the callback returns the observed promise for the\n caller to await. Every Cloudflare Email callback is wired through that shared\n scheduler exactly once, so no auth action can bypass failure observation or\n double-schedule the send. Provider error bodies are never written to\n generated logs.\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| `contract` | `{ version?: \"v1\" \\| \"v2\" }` | Public API/auth contract version. Omit for the backward-compatible v1 default; select v2 for `/api/v2/*` and `/auth/v2/*` across generated routes, Better Auth, OpenAPI, MCP, and discovery. |\n| `api` | `object` | Dedicated hostname for the selected feature API contract (`/api/v1/*` or `/api/v2/*`); additive alias — see [Domains](/compiler/config/domains) |\n| `auth` | `object` | App-level auth settings (`roleHierarchy`, `jwt`, delegated `principals`, `loginUrl`/`profileUrl`, `domain`) — see [Access](/compiler/definitions/access#role-hierarchy) and [Delegated principals](#delegated-principals-contract-v2) |\n| `authz` | `object` | Relationship-based authorization (`relationships`, `roles`, `rules`, `tenants`, `permissions`, `arrows`) — see [Access](/compiler/definitions/access#centrally-defined-access-rules) and [Permissions](/compiler/definitions/permissions). `rules` = named gates (who + `record:` + firewall lanes under one name); `tenants` = named tenant anchors (`{ column, equals }`, referenced as `{ tenant: '<name>' }` in firewalls and `tenant: '<name>'` in auth-view includes). Root `authz` is the GLOBAL vocabulary level — names scoped to one concept belong in that concept's [feature area](/compiler/definitions/feature-areas) (`_area.ts`), and root bodies may reference root-declared names only |\n| `requires` | `string[]` | Capability floor (fail-closed guard). Declare `['feature-areas']` when the project uses `features/**/_area.ts` — an area-unaware CLI/compiler then refuses the compile instead of silently dropping nested features. See [Feature areas](/compiler/definitions/feature-areas#the-capability-floor-requires-feature-areas) |\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), Neon `migrations.foreignKeys`, `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## Public contract version\n\nQuickback defaults to the existing v1 HTTP contract. New applications can opt\ninto v2 explicitly:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n contract: { version: \"v2\" },\n providers: cloudflare({}),\n});\n```\n\nThe selection is atomic: feature routes move to `/api/v2/*`, Better Auth moves\nto `/auth/v2/*`, and generated OpenAPI, MCP tool calls, OAuth discovery,\n`llms.txt`, schema/embeddings routes, and dedicated-domain `/v2/*` shortcuts\nuse the same version. When CMS or Account is enabled, Quickback also bakes\nthose paths into the SPA build and injects them at runtime, so CRUD, schema,\nlive-view, and authentication requests use the selected contract. Quickback\ndoes not expose a mixed v1/v2 surface from one compiled Worker. Omitting\n`contract` remains byte-compatible with v1 projects.\n\nV2 also makes action input-schema fidelity a compile gate. The CLI must\nsuccessfully harvest `z.toJSONSchema(action.input)` for every authored action;\npartial or missing harvests fail with the exact action file keys, bundle or\nevaluation phase, and underlying local error. Dependencies are resolved from\nthe generated runtime's `build.outputDir/node_modules` before unrelated\nancestor installs, so an isolated `quickback/` definition tree can use a\nsibling `src/` runtime without a workspace-root symlink. The compiler enforces\nthe same invariant at its shared input boundary, including\n`POST /compile?complete=false`, so validation-only or raw API calls cannot\nbypass it. V1 retains the historical best-effort static-schema fallback.\n\nThe version selection also moves the event and read surfaces:\n\n| Surface | v1 (pinned) | v2 (flagship) |\n|---|---|---|\n| Realtime data frames (`/broadcast/*`) | raw frames, byte-stable | CloudEvents 1.0 envelopes at DO egress ([realtime](/stack/realtime)) |\n| Outbound webhook signing | Standard Webhooks headers **plus** legacy `X-Webhook-*` | Standard Webhooks **only** |\n| `?include=` FK-graph embedding | not available | available where a resource/view allowlists it |\n| Bare `?fields=` / `fields[<fk>]=` unknown names | silent drop / n/a | 400 on both |\n\nSee [API Contract](/stack/api-contract) for the full v1 → v2 matrix and\nmigration sequencing.\n\n## Delegated principals (contract v2)\n\n`auth.principals` defines non-account authority such as an event pass or a\nshort-lived event session. It is available only with all three of:\n\n- `contract: { version: \"v2\" }`\n- the Cloudflare runtime\n- Neon with `connectionMode: \"hyperdrive\"`\n\nEach principal type owns an exact Authorization scheme. `Bearer` is reserved\nfor Quickback account authentication, including case variants, and two\nprincipal types cannot share a scheme.\n\n```typescript\nexport default defineConfig({\n name: \"attend-v2\",\n template: \"hono\",\n contract: { version: \"v2\" },\n auth: {\n principals: {\n event_pass: {\n scheme: \"EventPass\",\n authenticate: {\n module: \"./event-pass-proof\",\n export: \"authenticateEventPass\",\n },\n lookup: {\n table: {\n module: \"../features/event-access/event-access\",\n export: \"eventAccess\",\n sqlName: \"event_access\",\n },\n digest: { field: \"digest\", column: \"digest\" },\n actorId: { field: \"personId\", column: \"person_id\" },\n claims: {\n eventId: { field: \"eventId\", column: \"event_id\" },\n personId: { field: \"personId\", column: \"person_id\" },\n },\n status: { field: \"status\", column: \"status\", allow: [\"active\"] },\n },\n },\n event_delegate: {\n scheme: \"EventSession\",\n authenticate: {\n module: \"./event-session-proof\",\n export: \"authenticateEventSession\",\n },\n lookup: {\n table: {\n module: \"../features/event-sessions/event-sessions\",\n export: \"eventSessions\",\n sqlName: \"event_sessions\",\n },\n digest: { field: \"digest\", column: \"digest\" },\n actorId: { field: \"personId\", column: \"person_id\" },\n sessionId: { field: \"id\", column: \"id\" },\n familyId: { field: \"familyId\", column: \"family_id\" },\n claims: {\n eventId: { field: \"eventId\", column: \"event_id\" },\n personId: { field: \"personId\", column: \"person_id\" },\n },\n status: { field: \"status\", column: \"status\", allow: [\"active\"] },\n },\n },\n },\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"neon\", {\n connectionMode: \"hyperdrive\",\n hyperdrive: { id: \"<32-character-hyperdrive-id>\" },\n }),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\nThe `authenticate.module` path is relative to generated\n`src/lib/principal-auth.ts`. Put project proof hooks under `quickback/lib`; the\ncompiler stages them into `src/lib` even if no action imports them. A hook has\none job: prove the presented credential and return its stable digest.\n\n```typescript\n// quickback/lib/event-session-proof.ts\nexport async function authenticateEventSession({ credential, env, request }: {\n credential: string;\n env: Env;\n request: Request;\n}): Promise<{ digest: string } | null> {\n const valid = await verifySignedEventSession(credential, env, request);\n return valid ? { digest: await sha256(credential) } : null;\n}\n```\n\nThe hook receives no `db`, and it must not implement row authorization or\nbusiness behavior. Quickback performs exactly one narrow, unique digest lookup\nunder a lookup-only RLS principal. A digest must be 16–512 non-whitespace\ncharacters; resolved identity strings must be 1–512 characters and serialized\nclaims are limited to 4096 characters. A lookup must resolve exactly one active\nrow or authentication fails.\n\nOn success, actions receive `ctx.principal`:\n\n```typescript\n{\n type: \"event_delegate\",\n actor: { type: \"event_delegate\", id: \"person_123\" },\n session: { id: \"session_123\", familyId: \"family_123\" },\n claims: { eventId: \"event_123\", personId: \"person_123\" },\n}\n```\n\nQuickback never synthesizes `userId`, `activeOrgId`, `activeTeamId`, or\nmembership roles from a delegated credential. Use `principals` in an access\narm to admit it. Values inside one arm are ANDed; sibling `or` arms are ORed:\n\n```typescript\naccess: {\n or: [\n { roles: [\"AUTHENTICATED\"] },\n { principals: [\"event_delegate\"], record: {\n eventId: { equals: \"$ctx.principal.claims.eventId\" },\n } },\n ],\n}\n```\n\nAn Authorization header cannot be combined with `x-api-key` or a Better Auth\nsession cookie. Quickback recognizes only Better Auth's exact session cookie\nnames for this conflict check, so analytics and preference cookies remain\nharmless.\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## Neon Foreign Key Migrations\n\nUse `compiler.migrations.foreignKeys` when a Neon relationship cannot be\nexpressed in one generated Drizzle schema file—for example, a feature table\nthat references a Better Auth table, or a composite integrity relationship\nbetween independently authored feature modules.\n\n```typescript\nexport default defineConfig({\n // ...\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"neon\", { connectionMode: \"hyperdrive\" }),\n auth: defineAuth(\"better-auth\"),\n },\n compiler: {\n migrations: {\n foreignKeys: [\n {\n name: \"person_account_links_user_fk\",\n source: {\n schema: \"app\",\n table: \"person_account_links\",\n columns: [\"user_id\"],\n },\n target: {\n schema: \"auth\",\n table: \"users\",\n columns: [\"id\"],\n },\n onDelete: \"restrict\",\n onUpdate: \"restrict\",\n },\n {\n name: \"event_access_grants_consumed_family_fk\",\n source: {\n schema: \"app\",\n table: \"event_access_grants\",\n columns: [\n \"consumed_by_family_id\",\n \"id\",\n \"organization_id\",\n \"event_id\",\n \"event_person_id\",\n ],\n },\n target: {\n schema: \"app\",\n table: \"event_session_families\",\n columns: [\n \"id\",\n \"source_grant_id\",\n \"organization_id\",\n \"event_id\",\n \"event_person_id\",\n ],\n },\n onDelete: \"restrict\",\n onUpdate: \"restrict\",\n },\n ],\n },\n },\n});\n```\n\nAll identifiers must be lowercase Postgres identifiers of at most 63\ncharacters. Source and target tuples must be nonempty and have equal arity;\ncolumn order is significant. Supported actions are `\"no action\"`,\n`\"restrict\"`, `\"cascade\"`, `\"set null\"`, and `\"set default\"`.\n\nConstraint names and source tuples must be unique in the config. On replay,\nQuickback verifies that an existing same-named constraint has the exact target,\nordered columns, and referential actions. It fails instead of silently\naccepting an ambiguous definition. Existing rows are validated during\nmigration, so clean up orphans before deploying.\n\nThis API is for database integrity, not business behavior. Keep authorization,\nstate transitions, event-pass consumption, and other business rules in the API\naction layer.\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/*` and `/auth/v1/*` for the default contract, or `/api/v2/*` and\n `/auth/v2/*` when `contract.version` is `\"v2\"`\n- `/storage/*` — R2 file storage\n- `/health`, `/openapi.json` — monitoring/discovery\n- `/account/*`, `/cms/*` — bundled SPAs (when enabled)\n- `/broadcast/v1/*` (realtime; `/broadcast/v2/*` under `contract.version: 'v2'`), `/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/{version}/users` | `/api/{version}/users` | `{version}` is the selected `v1` or `v2`; the rewriter prepends `/api` |\n| `https://auth.example.com/{version}/sign-in/email` | `/auth/{version}/sign-in/email` | Same selected version with `/auth` |\n| `https://api.example.com/api/{version}/users` | (unchanged) | Long form also accepted |\n| `https://api.example.com/auth/{version}/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/{version}/users` | feature route | Works for the selected version whether `api.domain` is set or not |\n| `https://quickback.example.com/auth/{version}/sign-in/email` | Better Auth | Works for the selected version whether `auth.domain` is set or not |\n| `https://quickback.example.com/{version}/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- Types the binding with Cloudflare's native `SendEmail` / `EmailSendResult`\n contract (`{ email, name }`, `replyTo`, and `contentId` on Workers). The REST\n helper remains a separate `{ address, name }` / `reply_to` / `content_id`\n contract.\n- Anchors each authentication delivery to `executionCtx.waitUntil(...)`. The\n background promise records a structured generic failure and stays rejected;\n outside a Worker request, the callback returns the observed promise for the\n caller to await. Every Cloudflare Email callback is wired through that shared\n scheduler exactly once, so no auth action can bypass failure observation or\n double-schedule the send. Provider error bodies are never written to\n generated logs.\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"
59
59
  },
60
60
  "compiler/config/output": {
61
61
  "title": "Output Structure",
@@ -63,7 +63,7 @@ export const DOCS = {
63
63
  },
64
64
  "compiler/config/providers": {
65
65
  "title": "Providers",
66
- "content": "Providers configure which services your compiled backend targets.\n\n## Runtime Providers\n\nThe Quickback Stack is **Cloudflare-only**. `cloudflare` is the single supported runtime.\n\n```typescript\n\nproviders: {\n runtime: defineRuntime(\"cloudflare\"),\n}\n```\n\n### Runtime Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `compatibilityDate` | `string` | Emits Cloudflare `compatibility_date` in `wrangler.toml`. |\n| `placement.mode` | `\"smart\" \\| \"standard\"` | Emits Cloudflare's `[placement]` block. |\n| `observability.enabled` | `boolean` | Emits top-level Workers Logs persistence under `[observability]`. |\n| `observability.headSamplingRate` | `number` | Top-level Workers Logs sample rate from `0` to `1`. |\n| `observability.logs.enabled` | `boolean` | Emits `[observability.logs]`. |\n| `observability.logs.invocationLogs` | `boolean` | Enables or suppresses invocation logs. |\n| `observability.logs.destinations` | `string[]` | Named log export destinations configured in Cloudflare. |\n| `observability.logs.headSamplingRate` | `number` | Workers Logs sample rate from `0` to `1`. |\n| `observability.logs.persist` | `boolean` | Keeps exported logs in the Cloudflare dashboard. |\n| `observability.traces.enabled` | `boolean` | Emits `[observability.traces]`. |\n| `observability.traces.destinations` | `string[]` | Named trace export destinations configured in Cloudflare. |\n| `observability.traces.headSamplingRate` | `number` | Workers Traces sample rate from `0` to `1`. |\n| `observability.traces.persist` | `boolean` | Keeps exported traces in the Cloudflare dashboard. |\n| `routes` | `{ pattern, custom_domain? }[]` | Custom domain routes for the generated Worker. |\n\n```typescript\nproviders: {\n runtime: defineRuntime(\"cloudflare\", {\n compatibilityDate: \"2026-05-13\",\n placement: { mode: \"smart\" },\n observability: {\n enabled: true,\n logs: {\n enabled: true,\n invocationLogs: false,\n destinations: [\"logs-prod\"],\n headSamplingRate: 0.6,\n },\n traces: {\n enabled: true,\n destinations: [\"otel-prod\"],\n headSamplingRate: 0.05,\n persist: false,\n },\n },\n }),\n}\n```\n\n## Database Providers\n\nTwo databases are supported, both Cloudflare-native:\n\n| Provider | Description |\n|----------|-------------|\n| `cloudflare-d1` | Cloudflare D1 (SQLite at the edge) |\n| `neon` | Neon serverless PostgreSQL (`@neondatabase/serverless` over HTTP) |\n\nOne database provider per app: auth tables and feature tables always share the\nselected database. On `neon`, Better Auth uses its PostgreSQL/Drizzle adapter\nin the same Postgres database as your features; on `cloudflare-d1`, both use\nD1. A per-service map (`database: { auth: ..., features: ... }`) is rejected at\ncompile time — mixed database providers are not supported.\n\n```typescript\n\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n generateId: \"prefixed\", // \"uuid\" | \"cuid\" | \"nanoid\" | \"prefixed\" | \"serial\" | false\n namingConvention: \"snake_case\", // \"camelCase\" | \"snake_case\"\n usePlurals: false, // Auth table names: \"users\" vs \"user\"\n }),\n}\n```\n\n### Database Options\n\nOptions from `splitDatabases` down apply to `cloudflare-d1` only — Neon uses a\nsingle Postgres database with no bindings or split mode (see\n[Neon options](#neon-options) below).\n\n| Option | Type | Default (D1) | Description |\n|--------|------|---------|-------------|\n| `generateId` | `string \\| false` | `\"prefixed\"` | ID generation strategy |\n| `namingConvention` | `string` | `\"snake_case\"` | Column naming convention |\n| `usePlurals` | `boolean` | `false` | Pluralize auth table names (e.g. `user` vs `users`) |\n| `splitDatabases` | `boolean` | `true` | Separate auth and features databases (D1 only) |\n| `authBinding` | `string` | `\"AUTH_DB\"` | Binding name for auth database |\n| `featuresBinding` | `string` | `\"DB\"` | Binding name for features database |\n| `databaseId` | `string` | — | D1 database ID for the features database (used in generated wrangler.toml) |\n| `authDatabaseId` | `string` | — | D1 database ID for the auth database |\n| `featuresDatabaseId` | `string` | — | Explicit features DB ID (falls back to `databaseId`) |\n| `filesDatabaseId` | `string` | — | D1 database ID for the files metadata database |\n| `webhooksDatabaseId` | `string` | — | D1 database ID for the webhooks database |\n| `auditBinding` | `string` | `\"AUDIT_DB\"` | Binding name for the security audit database |\n| `auditDatabaseName` | `string` | `\"{app}-audit\"` | D1 database name for audit events |\n| `auditDatabaseId` | `string` | — | Explicit D1 database ID for audit events |\n| `experimentalRemote` | `{ auth?, features?, audit?, webhooks?, files? }` | `{}` | Per-binding `experimental_remote = true` flag for `wrangler dev` (see [below](#sharing-deployed-d1-in-dev-experimental_remote)) |\n| `realtime` | `boolean \\| { enabled?, wsTicket? }` | `false` | Enables the Broadcaster Durable Object and optional resource-scoped ws-ticket auth (see [below](#realtime-broadcast-config)) |\n| `webhookAdminRoles` | `string[]` | `[\"owner\", \"admin\"]` | Org roles allowed to manage webhook endpoints |\n\n#### Neon Options\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `connectionMode` | `\"auto\" \\| \"http\" \\| \"websocket\" \\| \"hyperdrive\"` | `\"auto\"` | How the generated runtime connects (`hyperdrive` enables interactive Postgres transactions on Workers) |\n| `hyperdrive.id` | `string` | — | Required Cloudflare Hyperdrive configuration ID when `connectionMode: \"hyperdrive\"` |\n| `hyperdrive.localConnectionString` | `string` | — | Optional local-only Postgres connection used by Wrangler dev |\n| `pooled` | `boolean` | `true` | Use the pooled Neon connection string (recommended for Workers) |\n\nThe Worker connects through a single `DATABASE_URL` secret — auth and feature\nqueries share it. See [Neon](/compiler/targets/hono-api/database/neon) for\nconnection modes, RLS, and the migration workflow.\n\n#### Audit Database\n\nCross-tenant `unsafe` actions (see [Actions → Unsafe mode](/compiler/definitions/actions#unsafe-mode)) write mandatory audit events. Those events land in a dedicated D1 database — separate from your features DB — so audit history stays isolated from application data and can't be tampered with through a normal CRUD route.\n\nYou don't need to do anything to enable it — the compiler wires up the binding automatically if your project declares any unsafe action. To override defaults:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n auditBinding: \"MY_AUDIT_DB\", // default: AUDIT_DB\n auditDatabaseName: \"my-app-audit-prod\", // default: {app}-audit\n auditDatabaseId: \"c3b8866b-cc4f-4e51-8382-0af244584d93\",\n }),\n}\n```\n\nThe binding name must match what your Worker reads at runtime. If you don't declare any unsafe actions, no audit DB is provisioned and these options have no effect.\n\n#### Setting Database IDs for Deployment\n\nWhen deploying to production, set your D1 database IDs so the compiler generates a ready-to-deploy `wrangler.toml`:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n authDatabaseId: \"fe6c77c4-2131-40be-a8fc-3649eef2a38c\",\n databaseId: \"bba22981-cb6e-43d6-bf32-4193513c60b1\",\n filesDatabaseId: \"c3b8866b-cc4f-4e51-8382-0af244584d93\",\n }),\n}\n```\n\nIf these are omitted, the compiler uses local-dev placeholders and you'll need to manually edit `wrangler.toml` before deploying.\n\n#### Sharing deployed D1 in dev (`experimental_remote`)\n\nWrangler can read or write the **deployed** D1 for a specific binding while `wrangler dev` runs locally. A common workflow: share the production auth DB in dev so real sessions and users work against the running local Worker, while feature writes stay sandboxed in the local SQLite shadow.\n\nQuickback regenerates `wrangler.toml` on every compile, so flags like `experimental_remote = true` need to live in `quickback.config.ts`:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n authDatabaseId: \"fe6c77c4-2131-40be-a8fc-3649eef2a38c\",\n experimentalRemote: { auth: true },\n }),\n}\n```\n\nKeys map to logical bindings, not the runtime binding string:\n\n| Key | Binding affected |\n|-----|------------------|\n| `auth` | `AUTH_DB` (also applied to the files worker's auth binding) |\n| `features` | `DB` (or the legacy single-DB binding when `splitDatabases: false`) |\n| `audit` | `AUDIT_DB` |\n| `webhooks` | `WEBHOOKS_DB` |\n| `files` | `FILES_DB` (also applied to the files worker) |\n\nOnly `true` flips the flag on; `false` or omitted leaves the binding local. Off by default — only enable against databases you intend to share.\n\n#### Realtime Broadcast Config\n\nSet `realtime: true` to enable the generated Broadcaster Durable Object with the default organization-scoped routing model:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: true,\n }),\n}\n```\n\nFor resource-scoped tickets, use the object form. The mint gate is a discriminated `access` union — exactly one arm:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: {\n wsTicket: {\n access: { authzRole: \"attendee\" }, // or { roles: [\"member+\"] } or { fga: { relation, object } }\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n },\n }),\n}\n```\n\n> The broadcast surface mounts at `/broadcast/v1` by default and `/broadcast/v2` under `contract.version: \"v2\"`.\n\n`wsTicket` tells the compiler how to authorize `/broadcast/v1/ws-ticket` and what scope to stamp into the short-lived websocket ticket:\n\n- `access`: the mint gate — one of `{ roles: [\"member+\"] }` (org-membership roles with hierarchy expansion; also verifies the scope row is in the caller's active org), `{ authzRole: \"attendee\" }` (an authz role declared under `authz.roles` with a direct relationship `{ via: \"...\" }`), or `{ fga: { relation: \"viewer\", object: \"event:{id}\" } }` (an FGA relation on the object derived from the scope row). The legacy `role: \"attendee\"` string is the shorthand for `{ authzRole }`.\n- `requestField`: the JSON body field the client posts to `/broadcast/v1/ws-ticket`\n- `scopeTable`: the parent resource table that defines the broadcast scope key\n\nIn other words: the declared gate proves access, and the `scopeTable` row defines the channel. For an attendee flow, `guests` (or RSVP) would be the relationship evidence and `events` would be the `scopeTable`; see [Realtime](/stack/realtime#enabling-realtime) for the full per-arm semantics.\n\nQuickback keeps Better Auth as the front door, then mints its own 60-second websocket ticket after the authz check succeeds. The generated `createRealtime()` helper and Broadcaster share the same targeting model:\n\n- string target: historical `organizationId` shorthand\n- object target: `{ scopeKey?, organizationId?, userId? }`\n\nSee [Realtime](/stack/realtime) for the client-side connection flow and helper examples.\n\n### ID Generation Options\n\n| Value | Description | Example |\n|-------|-------------|---------|\n| `\"uuid\"` | Server generates UUID | `550e8400-e29b-41d4-a716-446655440000` |\n| `\"cuid\"` | Server generates CUID | `clh2v8k9g0000l508h5gx8j1a` |\n| `\"nanoid\"` | Server generates nanoid (21-char, URL-safe) | `V1StGXR8_Z5jdHi6B-myT` |\n| `\"short\"` | 6-char alphanumeric (nanoid `customAlphabet`) | `a3F9xK` |\n| `\"prefixed\"` | Prefixed ID from table name | `room_abc123` |\n| `\"serial\"` | Database auto-increments | `1`, `2`, `3` |\n| `false` | Client provides ID (enables PUT/upsert) | Any string |\n\n## Auth Providers\n\n| Provider | Description |\n|----------|-------------|\n| `better-auth` | Better Auth with plugins (default) |\n| `external` | External auth via Cloudflare service binding |\n\n```typescript\n\nproviders: {\n auth: defineAuth(\"better-auth\", {\n session: {\n expiresInDays: 7,\n updateAgeInDays: 1,\n },\n rateLimit: {\n enabled: true,\n window: 60,\n max: 100,\n },\n }),\n}\n```\n\n### Better Auth Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `session.expiresInDays` | `number` | Session expiration in days |\n| `session.updateAgeInDays` | `number` | Session refresh interval in days |\n| `rateLimit.enabled` | `boolean` | Enable rate limiting |\n| `rateLimit.window` | `number` | Rate limit window in seconds |\n| `rateLimit.max` | `number` | Max requests per window |\n| `atomicAuthRoutes` | `(\"emailOtpSignIn\")[]` | Runs the exact email-OTP sign-in handler and `before-email-otp-activate.ts` admission hook in one Neon Hyperdrive transaction. Contract v2 only. |\n| `socialProviders` | `object` | Social login providers (`google`, `github`, `discord`) |\n| `debugLogs` | `boolean` | Enable auth debug logging |\n\n### Better Auth Plugins\n\nWhen `features: [\"organizations\"]` is set in your config, the compiler automatically enables organization-related plugins. Additional plugins can be configured:\n\n| Plugin | Description |\n|--------|-------------|\n| `organization` | Multi-tenant organizations |\n| `admin` | Admin panel access |\n| `apiKey` | API key authentication |\n| `anonymous` | Anonymous sessions |\n| `upgradeAnonymous` | Convert anonymous to full accounts |\n| `twoFactor` | Two-factor authentication |\n| `passkey` | WebAuthn passkey login |\n| `magicLink` | Email magic link login |\n| `emailOtp` | Email one-time password |\n| `deviceAuthorization` | Device auth flow (CLI tools) |\n| `jwt` | JWT token support |\n| `openAPI` | OpenAPI spec generation |\n\n`emailOtp` also accepts an options object. Set `expiresIn` to a positive integer\nnumber of seconds to override Better Auth's OTP lifetime. The setting is\ntransport-neutral and is emitted identically for Cloudflare Email and AWS SES:\n\n```typescript\nplugins: { emailOtp: { expiresIn: 1200 } }\n```\n\n## Storage Providers\n\n```typescript\n\nproviders: {\n storage: defineStorage(\"kv\", {\n binding: \"KV_STORE\",\n namespaceId: \"7ed0f824a8c54c388713d9fdf63cd004\",\n }),\n fileStorage: defineFileStorage(\"r2\", {\n binding: \"FILES\",\n maxFileSize: \"10mb\",\n allowedTypes: [\"image/png\", \"image/jpeg\", \"application/pdf\"],\n publicDomain: \"files.example.com\",\n }),\n}\n```\n\n### Storage Types\n\n| Type | Description |\n|------|-------------|\n| `kv` | Key-value storage (Cloudflare KV, Redis) |\n| `r2` | Object storage (Cloudflare R2) |\n| `memory` | In-memory storage (development only) |\n| `redis` | Redis storage |\n\n### File Storage Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `binding` | `string` | R2 bucket binding name |\n| `maxFileSize` | `string` | Maximum file size (e.g. `\"10mb\"`) |\n| `allowedTypes` | `string[]` | Allowed MIME types |\n| `publicDomain` | `string` | Public domain for file URLs |\n| `userScopedBuckets` | `boolean` | Scope files by user |"
66
+ "content": "Providers configure which services your compiled backend targets.\n\n## Runtime Providers\n\nThe Quickback Stack is **Cloudflare-only**. `cloudflare` is the single supported runtime.\n\n```typescript\n\nproviders: {\n runtime: defineRuntime(\"cloudflare\"),\n}\n```\n\n### Runtime Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `compatibilityDate` | `string` | Emits Cloudflare `compatibility_date` in `wrangler.toml`. |\n| `placement.mode` | `\"smart\" \\| \"standard\"` | Emits Cloudflare's `[placement]` block. |\n| `observability.enabled` | `boolean` | Emits top-level Workers Logs persistence under `[observability]`. |\n| `observability.headSamplingRate` | `number` | Top-level Workers Logs sample rate from `0` to `1`. |\n| `observability.logs.enabled` | `boolean` | Emits `[observability.logs]`. |\n| `observability.logs.invocationLogs` | `boolean` | Enables or suppresses invocation logs. |\n| `observability.logs.destinations` | `string[]` | Named log export destinations configured in Cloudflare. |\n| `observability.logs.headSamplingRate` | `number` | Workers Logs sample rate from `0` to `1`. |\n| `observability.logs.persist` | `boolean` | Keeps exported logs in the Cloudflare dashboard. |\n| `observability.traces.enabled` | `boolean` | Emits `[observability.traces]`. |\n| `observability.traces.destinations` | `string[]` | Named trace export destinations configured in Cloudflare. |\n| `observability.traces.headSamplingRate` | `number` | Workers Traces sample rate from `0` to `1`. |\n| `observability.traces.persist` | `boolean` | Keeps exported traces in the Cloudflare dashboard. |\n| `routes` | `{ pattern, custom_domain? }[]` | Custom domain routes for the generated Worker. |\n\n```typescript\nproviders: {\n runtime: defineRuntime(\"cloudflare\", {\n compatibilityDate: \"2026-05-13\",\n placement: { mode: \"smart\" },\n observability: {\n enabled: true,\n logs: {\n enabled: true,\n invocationLogs: false,\n destinations: [\"logs-prod\"],\n headSamplingRate: 0.6,\n },\n traces: {\n enabled: true,\n destinations: [\"otel-prod\"],\n headSamplingRate: 0.05,\n persist: false,\n },\n },\n }),\n}\n```\n\n## Database Providers\n\nTwo databases are supported, both Cloudflare-native:\n\n| Provider | Description |\n|----------|-------------|\n| `cloudflare-d1` | Cloudflare D1 (SQLite at the edge) |\n| `neon` | Neon serverless PostgreSQL (`@neondatabase/serverless` over HTTP) |\n\nOne database provider per app: auth tables and feature tables always share the\nselected database. On `neon`, Better Auth uses its PostgreSQL/Drizzle adapter\nin the same Postgres database as your features; on `cloudflare-d1`, both use\nD1. A per-service map (`database: { auth: ..., features: ... }`) is rejected at\ncompile time — mixed database providers are not supported.\n\n```typescript\n\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n generateId: \"prefixed\", // \"uuid\" | \"cuid\" | \"nanoid\" | \"prefixed\" | \"serial\" | false\n namingConvention: \"snake_case\", // \"camelCase\" | \"snake_case\"\n usePlurals: false, // Auth table names: \"users\" vs \"user\"\n }),\n}\n```\n\n### Database Options\n\nOptions from `splitDatabases` down apply to `cloudflare-d1` only — Neon uses a\nsingle Postgres database with no bindings or split mode (see\n[Neon options](#neon-options) below).\n\n| Option | Type | Default (D1) | Description |\n|--------|------|---------|-------------|\n| `generateId` | `string \\| false` | `\"prefixed\"` | ID generation strategy |\n| `namingConvention` | `string` | `\"snake_case\"` | Column naming convention |\n| `usePlurals` | `boolean` | `false` | Pluralize auth table names (e.g. `user` vs `users`) |\n| `splitDatabases` | `boolean` | `true` | Separate auth and features databases (D1 only) |\n| `authBinding` | `string` | `\"AUTH_DB\"` | Binding name for auth database |\n| `featuresBinding` | `string` | `\"DB\"` | Binding name for features database |\n| `databaseId` | `string` | — | D1 database ID for the features database (used in generated wrangler.toml) |\n| `authDatabaseId` | `string` | — | D1 database ID for the auth database |\n| `featuresDatabaseId` | `string` | — | Explicit features DB ID (falls back to `databaseId`) |\n| `filesDatabaseId` | `string` | — | D1 database ID for the files metadata database |\n| `webhooksDatabaseId` | `string` | — | D1 database ID for the webhooks database |\n| `auditBinding` | `string` | `\"AUDIT_DB\"` | Binding name for the security audit database |\n| `auditDatabaseName` | `string` | `\"{app}-audit\"` | D1 database name for audit events |\n| `auditDatabaseId` | `string` | — | Explicit D1 database ID for audit events |\n| `experimentalRemote` | `{ auth?, features?, audit?, webhooks?, files? }` | `{}` | Per-binding `experimental_remote = true` flag for `wrangler dev` (see [below](#sharing-deployed-d1-in-dev-experimental_remote)) |\n| `realtime` | `boolean \\| { enabled?, wsTicket? }` | `false` | Enables the Broadcaster Durable Object and optional resource-scoped ws-ticket auth (see [below](#realtime-broadcast-config)) |\n| `webhookAdminRoles` | `string[]` | `[\"owner\", \"admin\"]` | Org roles allowed to manage webhook endpoints |\n\n#### Neon Options\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `connectionMode` | `\"auto\" \\| \"http\" \\| \"websocket\" \\| \"hyperdrive\"` | `\"auto\"` | How the generated runtime connects (`hyperdrive` enables interactive Postgres transactions on Workers) |\n| `hyperdrive.id` | `string` | — | Required Cloudflare Hyperdrive configuration ID when `connectionMode: \"hyperdrive\"` |\n| `hyperdrive.localConnectionString` | `string` | — | Optional local-only Postgres connection used by Wrangler dev |\n| `pooled` | `boolean` | `true` | Use the pooled Neon connection string (recommended for Workers) |\n\nThe Worker connects through a single `DATABASE_URL` secret — auth and feature\nqueries share it. See [Neon](/compiler/targets/hono-api/database/neon) for\nconnection modes, RLS, and the migration workflow.\n\n#### Audit Database\n\nCross-tenant `unsafe` actions (see [Actions → Unsafe mode](/compiler/definitions/actions#unsafe-mode)) write mandatory audit events. Those events land in a dedicated D1 database — separate from your features DB — so audit history stays isolated from application data and can't be tampered with through a normal CRUD route.\n\nYou don't need to do anything to enable it — the compiler wires up the binding automatically if your project declares any unsafe action. To override defaults:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n auditBinding: \"MY_AUDIT_DB\", // default: AUDIT_DB\n auditDatabaseName: \"my-app-audit-prod\", // default: {app}-audit\n auditDatabaseId: \"c3b8866b-cc4f-4e51-8382-0af244584d93\",\n }),\n}\n```\n\nThe binding name must match what your Worker reads at runtime. If you don't declare any unsafe actions, no audit DB is provisioned and these options have no effect.\n\n#### Setting Database IDs for Deployment\n\nWhen deploying to production, set your D1 database IDs so the compiler generates a ready-to-deploy `wrangler.toml`:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n authDatabaseId: \"fe6c77c4-2131-40be-a8fc-3649eef2a38c\",\n databaseId: \"bba22981-cb6e-43d6-bf32-4193513c60b1\",\n filesDatabaseId: \"c3b8866b-cc4f-4e51-8382-0af244584d93\",\n }),\n}\n```\n\nIf these are omitted, the compiler uses local-dev placeholders and you'll need to manually edit `wrangler.toml` before deploying.\n\n#### Sharing deployed D1 in dev (`experimental_remote`)\n\nWrangler can read or write the **deployed** D1 for a specific binding while `wrangler dev` runs locally. A common workflow: share the production auth DB in dev so real sessions and users work against the running local Worker, while feature writes stay sandboxed in the local SQLite shadow.\n\nQuickback regenerates `wrangler.toml` on every compile, so flags like `experimental_remote = true` need to live in `quickback.config.ts`:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n authDatabaseId: \"fe6c77c4-2131-40be-a8fc-3649eef2a38c\",\n experimentalRemote: { auth: true },\n }),\n}\n```\n\nKeys map to logical bindings, not the runtime binding string:\n\n| Key | Binding affected |\n|-----|------------------|\n| `auth` | `AUTH_DB` (also applied to the files worker's auth binding) |\n| `features` | `DB` (or the legacy single-DB binding when `splitDatabases: false`) |\n| `audit` | `AUDIT_DB` |\n| `webhooks` | `WEBHOOKS_DB` |\n| `files` | `FILES_DB` (also applied to the files worker) |\n\nOnly `true` flips the flag on; `false` or omitted leaves the binding local. Off by default — only enable against databases you intend to share.\n\n#### Realtime Broadcast Config\n\nSet `realtime: true` to enable the generated Broadcaster Durable Object with the default organization-scoped routing model:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: true,\n }),\n}\n```\n\nFor resource-scoped tickets, use the object form. The mint gate is a discriminated `access` union — exactly one arm:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: {\n wsTicket: {\n access: { authzRole: \"attendee\" }, // or { roles: [\"member+\"] } or { fga: { relation, object } }\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n },\n }),\n}\n```\n\n> The broadcast surface mounts at `/broadcast/v1` by default and `/broadcast/v2` under `contract.version: \"v2\"`.\n\n`wsTicket` tells the compiler how to authorize `/broadcast/v1/ws-ticket` and what scope to stamp into the short-lived websocket ticket:\n\n- `access`: the mint gate — one of `{ roles: [\"member+\"] }` (org-membership roles with hierarchy expansion; also verifies the scope row is in the caller's active org), `{ authzRole: \"attendee\" }` (an authz role declared under `authz.roles` with a direct relationship `{ via: \"...\" }`), or `{ fga: { relation: \"viewer\", object: \"event:{id}\" } }` (an FGA relation on the object derived from the scope row). The legacy `role: \"attendee\"` string is the shorthand for `{ authzRole }`.\n- `requestField`: the JSON body field the client posts to `/broadcast/v1/ws-ticket`\n- `scopeTable`: the parent resource table that defines the broadcast scope key\n\nInstead of `access`, `wsTicket` may name a **namespace** (`namespace: \"eventScope\"`) to\nauthorize through that namespace's full multi-lane `via` — including a namespace declared by\na [feature area](/compiler/definitions/feature-areas)'s `_area.ts` (the one root-config\nsurface allowed to reference an area-declared name; it attaches the area's complete gate and\nis listed in the authz manifest under the owning area). See\n[Namespace-backed tickets](/stack/realtime/durable-objects#namespace-backed-tickets-per-matched-lane).\n\nIn other words: the declared gate proves access, and the `scopeTable` row defines the channel. For an attendee flow, `guests` (or RSVP) would be the relationship evidence and `events` would be the `scopeTable`; see [Realtime](/stack/realtime#enabling-realtime) for the full per-arm semantics.\n\nQuickback keeps Better Auth as the front door, then mints its own 60-second websocket ticket after the authz check succeeds. The generated `createRealtime()` helper and Broadcaster share the same targeting model:\n\n- string target: historical `organizationId` shorthand\n- object target: `{ scopeKey?, organizationId?, userId? }`\n\nSee [Realtime](/stack/realtime) for the client-side connection flow and helper examples.\n\n### ID Generation Options\n\n| Value | Description | Example |\n|-------|-------------|---------|\n| `\"uuid\"` | Server generates UUID | `550e8400-e29b-41d4-a716-446655440000` |\n| `\"cuid\"` | Server generates CUID | `clh2v8k9g0000l508h5gx8j1a` |\n| `\"nanoid\"` | Server generates nanoid (21-char, URL-safe) | `V1StGXR8_Z5jdHi6B-myT` |\n| `\"short\"` | 6-char alphanumeric (nanoid `customAlphabet`) | `a3F9xK` |\n| `\"prefixed\"` | Prefixed ID from table name | `room_abc123` |\n| `\"serial\"` | Database auto-increments | `1`, `2`, `3` |\n| `false` | Client provides ID (enables PUT/upsert) | Any string |\n\n## Auth Providers\n\n| Provider | Description |\n|----------|-------------|\n| `better-auth` | Better Auth with plugins (default) |\n| `external` | External auth via Cloudflare service binding |\n\n```typescript\n\nproviders: {\n auth: defineAuth(\"better-auth\", {\n session: {\n expiresInDays: 7,\n updateAgeInDays: 1,\n },\n rateLimit: {\n enabled: true,\n window: 60,\n max: 100,\n },\n }),\n}\n```\n\n### Better Auth Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `session.expiresInDays` | `number` | Session expiration in days |\n| `session.updateAgeInDays` | `number` | Session refresh interval in days |\n| `rateLimit.enabled` | `boolean` | Enable rate limiting |\n| `rateLimit.window` | `number` | Rate limit window in seconds |\n| `rateLimit.max` | `number` | Max requests per window |\n| `atomicAuthRoutes` | `(\"emailOtpSignIn\")[]` | Runs the exact email-OTP sign-in handler and `before-email-otp-activate.ts` admission hook in one Neon Hyperdrive transaction. Contract v2 only. |\n| `socialProviders` | `object` | Social login providers (`google`, `github`, `discord`) |\n| `debugLogs` | `boolean` | Enable auth debug logging |\n\n### Better Auth Plugins\n\nWhen `features: [\"organizations\"]` is set in your config, the compiler automatically enables organization-related plugins. Additional plugins can be configured:\n\n| Plugin | Description |\n|--------|-------------|\n| `organization` | Multi-tenant organizations |\n| `admin` | Admin panel access |\n| `apiKey` | API key authentication |\n| `anonymous` | Anonymous sessions |\n| `upgradeAnonymous` | Convert anonymous to full accounts |\n| `twoFactor` | Two-factor authentication |\n| `passkey` | WebAuthn passkey login |\n| `magicLink` | Email magic link login |\n| `emailOtp` | Email one-time password |\n| `deviceAuthorization` | Device auth flow (CLI tools) |\n| `jwt` | JWT token support |\n| `openAPI` | OpenAPI spec generation |\n\n`emailOtp` also accepts an options object. Set `expiresIn` to a positive integer\nnumber of seconds to override Better Auth's OTP lifetime. The setting is\ntransport-neutral and is emitted identically for Cloudflare Email and AWS SES:\n\n```typescript\nplugins: { emailOtp: { expiresIn: 1200 } }\n```\n\n## Storage Providers\n\n```typescript\n\nproviders: {\n storage: defineStorage(\"kv\", {\n binding: \"KV_STORE\",\n namespaceId: \"7ed0f824a8c54c388713d9fdf63cd004\",\n }),\n fileStorage: defineFileStorage(\"r2\", {\n binding: \"FILES\",\n maxFileSize: \"10mb\",\n allowedTypes: [\"image/png\", \"image/jpeg\", \"application/pdf\"],\n publicDomain: \"files.example.com\",\n }),\n}\n```\n\n### Storage Types\n\n| Type | Description |\n|------|-------------|\n| `kv` | Key-value storage (Cloudflare KV, Redis) |\n| `r2` | Object storage (Cloudflare R2) |\n| `memory` | In-memory storage (development only) |\n| `redis` | Redis storage |\n\n### File Storage Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `binding` | `string` | R2 bucket binding name |\n| `maxFileSize` | `string` | Maximum file size (e.g. `\"10mb\"`) |\n| `allowedTypes` | `string[]` | Allowed MIME types |\n| `publicDomain` | `string` | Public domain for file URLs |\n| `userScopedBuckets` | `boolean` | Scope files by user |"
67
67
  },
68
68
  "compiler/config/security": {
69
69
  "title": "Security Headers",
@@ -79,11 +79,11 @@ export const DOCS = {
79
79
  },
80
80
  "compiler/definitions/access": {
81
81
  "title": "Access - Role & Condition-Based Access Control",
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`, `SESSION`, `SCOPED`, `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 seven reserved UPPERCASE markers. Six 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` (a full session **or** a scope principal — the wrapper over `SESSION` ∪ `SCOPED`) |\n| `SESSION` | required | none | a full Better Auth session **only** — `ctx.authenticated && !ctx.principal && !ctx.scopePrincipal` |\n| `SCOPED` | required | none | a sessionless scope principal **only** — `ctx.authenticated && ctx.scopePrincipal === 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`?organizationId=` is an account/public addressing surface. A request using a\nconfigured delegated principal cannot use it to acquire account organization\nauthority: the generated route returns `403 CROSS_TENANT_FORBIDDEN` and never\nadds `activeOrgId` or account roles to the delegated `AppContext`. Delegated\nscope continues to come only from the verified principal claims and database\nRLS policy.\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 authenticated caller (the wrapper)\n\nUse `roles: [\"AUTHENTICATED\"]` for endpoints that any logged-in caller 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`AUTHENTICATED` is the **wrapper over two auth flavors** — it admits both a full Better Auth session **and** a sessionless scope principal (a scope-token holder, e.g. an event attendee who isn't an org member; see [Scopes](/compiler/definitions/scopes)). It excludes only *external delegated* principals (`ctx.principal`, admitted via `principals:`). When you need to distinguish the two flavors, use `SESSION` or `SCOPED` below; when either is fine, use `AUTHENTICATED`.\n\n#### `SESSION` — a full session only\n\nUse `roles: [\"SESSION\"]` when a route must admit **only** a full Better Auth session and **not** a sessionless scope principal. This is `AUTHENTICATED` minus scope-token callers.\n\n```typescript\n// Account settings — a real logged-in user, never a scope-token attendee\nread: { access: { roles: [\"SESSION\"] } }\n```\n\n#### `SCOPED` — a scope principal only\n\nUse `roles: [\"SCOPED\"]` for a route that is specifically for **sessionless scope-token callers** (a principal-only surface — e.g. a shared event link or kiosk token with no account). It admits any scope principal regardless of *which* scope; for a **specific** scoped role, use the `scope:<kind>:<role>` form instead (e.g. `scope:event:attendee` — see [Scopes](/compiler/definitions/scopes)).\n\n```typescript\n// Principal-only event surface — a scope token, no account required\nread: { access: { roles: [\"SCOPED\"] } }\n```\n\n> **Firewall coherence:** if an access surface admits a scope caller (`SCOPED` or a `scope:<kind>:<role>` role) but the resource firewall can't filter that caller, the compiler **fails the build** — the caller would reach the handler yet see zero rows (a silent `200 + []`). Give the firewall a way to filter them: a `ctx.scope.<kind>` arm inside an `{ any: [...] }` group (compose org **or** scope — see [Firewall](/compiler/definitions/firewall)), a `via:` relationship, or `firewall: [{ exception: true }]`.\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)"
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`, `SESSION`, `SCOPED`, `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 seven reserved UPPERCASE markers. Six 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` (a full session **or** a scope principal — the wrapper over `SESSION` ∪ `SCOPED`) |\n| `SESSION` | required | none | a full Better Auth session **only** — `ctx.authenticated && !ctx.principal && !ctx.scopePrincipal` |\n| `SCOPED` | required | none | a sessionless scope principal **only** — `ctx.authenticated && ctx.scopePrincipal === true` |\n| `USER` | required | resource firewall **must** scope by `userId` | a real signed-in user — `ctx.authenticated` AND **not** a scope principal (`!ctx.scopePrincipal`) AND (`ctx.userRole` unset OR `=== \"user\"`). A sessionless scope caller does **not** satisfy `USER` (use `SCOPED` / `scope:<kind>:<role>`); `AUTHENTICATED` is the marker that admits both flavors. |\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`?organizationId=` is an account/public addressing surface. A request using a\nconfigured delegated principal cannot use it to acquire account organization\nauthority: the generated route returns `403 CROSS_TENANT_FORBIDDEN` and never\nadds `activeOrgId` or account roles to the delegated `AppContext`. Delegated\nscope continues to come only from the verified principal claims and database\nRLS policy.\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 authenticated caller (the wrapper)\n\nUse `roles: [\"AUTHENTICATED\"]` for endpoints that any logged-in caller 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`AUTHENTICATED` is the **wrapper over two auth flavors** — it admits both a full Better Auth session **and** a sessionless scope principal (a scope-token holder, e.g. an event attendee who isn't an org member; see [Scopes](/compiler/definitions/scopes)). It excludes only *external delegated* principals (`ctx.principal`, admitted via `principals:`). When you need to distinguish the two flavors, use `SESSION` or `SCOPED` below; when either is fine, use `AUTHENTICATED`.\n\n#### `SESSION` — a full session only\n\nUse `roles: [\"SESSION\"]` when a route must admit **only** a full Better Auth session and **not** a sessionless scope principal. This is `AUTHENTICATED` minus scope-token callers.\n\n```typescript\n// Account settings — a real logged-in user, never a scope-token attendee\nread: { access: { roles: [\"SESSION\"] } }\n```\n\n#### `SCOPED` — a scope principal only\n\nUse `roles: [\"SCOPED\"]` for a route that is specifically for **sessionless scope-token callers** (a principal-only surface — e.g. a shared event link or kiosk token with no account). It admits any scope principal regardless of *which* scope; for a **specific** scoped role, use the `scope:<kind>:<role>` form instead (e.g. `scope:event:attendee` — see [Scopes](/compiler/definitions/scopes)).\n\n```typescript\n// Principal-only event surface — a scope token, no account required\nread: { access: { roles: [\"SCOPED\"] } }\n```\n\n> **Firewall coherence:** if an access surface admits a scope caller (`SCOPED` or a `scope:<kind>:<role>` role) but the resource firewall can't filter that caller, the compiler **fails the build** — the caller would reach the handler yet see zero rows (a silent `200 + []`). Give the firewall a way to filter them: a `ctx.scope.<kind>` arm inside an `{ any: [...] }` group (compose org **or** scope — see [Firewall](/compiler/definitions/firewall)), a `via:` relationship, or `firewall: [{ exception: true }]`.\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## Centrally defined access rules\n\nInstead of repeating the same `roles: [...]` expression across every feature, define it **once** in `authz.roles` and reference it by name everywhere. This is the recommended way to manage access as your app grows: one source of truth per rule, changed in one place.\n\nNamed roles (and named gates, tenant anchors, scope kinds) can be declared at **two levels**:\nat root `authz` in `quickback.config.ts` (visible everywhere), or inside a\n[feature area](/compiler/definitions/feature-areas)'s `_area.ts` (visible to that area's\nsubtree only — a feature outside the area referencing the name is a compile error, and root\n`authz` bodies may reference root-declared names only). Declare each name in exactly one\nplace: re-declaring an inherited name is a compile error.\n\n```typescript\n// quickback.config.ts — define ONCE\nexport default defineConfig({\n // ...providers...\n authz: {\n roles: {\n // Compose from BA roles, pseudo-roles, and other named rules:\n staff: { roles: ['admin', 'member'] },\n // Boolean combinators:\n eventStaff: { or: [{ roles: ['staff'] }, { via: 'organizerOf' }] },\n // Relationship-backed (see below):\n attendee: { via: 'attendeeOf' },\n },\n },\n});\n```\n\n```typescript\n// any feature — REFERENCE by bare name\nexport default defineTable(agendaItems, {\n read: { access: { roles: ['eventStaff'] } },\n update: { access: { roles: ['eventStaff'] } },\n});\n\n// actions.ts\ncheckIn: { access: { roles: ['eventStaff', 'attendee'] }, /* ... */ },\n```\n\n### Rule shapes\n\nEach entry in `authz.roles` is one of four shapes:\n\n| Shape | Meaning |\n|---|---|\n| `{ roles: ['admin', 'member'] }` | Composition — matches any of the listed roles (BA, pseudo, or other named rules) |\n| `{ or: [ruleA, ruleB] }` | Matches if **any** sub-rule matches |\n| `{ and: [ruleA, ruleB] }` | Matches only if **all** sub-rules match |\n| `{ via: 'relationshipName' }` | Caller proves a declared relationship — see [Relationship-based authorization](#relationship-based-authorization) below |\n\nRules compose freely — a rule may reference another rule by name (cycles are a compile error).\n\n### Where references resolve\n\nA named rule works in the `roles: [...]` array of every access surface. The compiler expands it at build time:\n\n| Surface | |\n|---|---|\n| `crud.*.access` | ✓ |\n| `read.access` / `read.views.*.access` | ✓ |\n| `masking.<field>.show` | ✓ for role/composite rules; relationship (`via`) rules refused at compile (v1) |\n| `actions.<name>.access` | ✓ |\n| `realtime.requiredRoles` | ✓ — relationship arms fail closed at the WS handshake and are enforced by the row-stream firewall |\n\nNames that **aren't** declared in `authz.roles` — Better Auth roles, pseudo-roles like `AUTHENTICATED` — pass through untouched, so you can mix named rules and raw roles in the same array.\n\n### Beyond roles: named permissions\n\nFor access that traverses the data graph (FK hops, SpiceDB-style permission composition), see [`authz.permissions` + `authz.arrows`](/compiler/definitions/permissions) — the same define-once-reference-by-name model, one level richer than `authz.roles`.\n\n## Named gates (`authz.rules`)\n\n`authz.roles` centralizes the *who*. A **gate** (`authz.rules.<name>`) bundles a full access rule — *who* + an optional row predicate (`record:`) + optional [firewall lanes](/compiler/definitions/firewall#named-gate-references-rule) — under ONE name, declared once:\n\n```typescript\n// quickback.config.ts\nauthz: {\n tenants: { org: { column: 'organizationId', equals: 'ctx.activeOrgId' } },\n rules: {\n // who + record: \"org staff, but only rows still active\"\n activeStaff: {\n who: { roles: ['member', 'admin', 'owner'] },\n record: { status: { equals: 'active' } },\n },\n // who + firewall: an org-OR-event-scope row gate, declared ONCE\n eventRow: {\n who: { roles: ['owner', 'admin', 'member'] },\n firewall: [{ any: [\n { tenant: 'org' },\n { field: 'eventId', equals: 'ctx.scope.event' },\n ] }],\n },\n },\n}\n```\n\n```typescript\n// any feature — the gate name works like a role name\nexport default defineTable(eventLinks, {\n firewall: [{ rule: 'eventRow' }], // firewall stamp\n read: { access: { roles: ['eventRow'] } }, // access stamp\n});\n```\n\n### The two-stamp contract\n\nOne shared name, two independent stamps — **a single reference never applies both**:\n\n- An **access-position reference** (the bare name in any `roles: [...]` array) applies the gate's `who` + `record` arms **only**. It expands exactly like an inline rule: a who-only gate splices as the flat role list; a who+record gate as `{ and: [who, { record }] }`.\n- A **firewall reference** (`firewall: [{ rule: '<name>' }]`) applies the gate's `firewall` lanes **only**, spliced into the resource's top-level AND array. The `who` of a gate referenced only from `firewall:` is **not consulted** — that is the documented contract, not a silent drop. Firewall-who is legitimately *wider* than access-who (e.g. the firewall admits scope-token holders to rows while read access stays staff-only).\n\nBoth directions are enforced fail-closed at compile time:\n\n| You wrote | Compiler says |\n|---|---|\n| Access reference to a firewall-bearing gate, but the resource's `firewall:` doesn't reference it | **Error** — the row lanes would silently not apply |\n| `firewall: [{ rule }]` naming a gate with no `firewall` arm | **Error** — a who/record-only gate would splice zero lanes |\n| A firewall-bearing gate referenced from an **action's** access or from `masking.show` | **Error, unconditional** — no firewall array exists at those sites (nested `show.or` / `show.and` arms included) |\n| A who-less (firewall-only) gate referenced from an access position | **Error** — row lanes can't masquerade as a who-grant |\n| A gate's `record:` field is not a column of the referencing table | **Error, per reference** — a missing field evaluates against `undefined` at runtime (`notEquals`/`notIn` would silently *grant*) |\n| A spliced gate's firewall lane filters on a column the stamped table doesn't have | **Error, per reference** — the lane could never scope rows there |\n\n### Naming rules\n\nRule names share the reference namespace with roles, so the compiler rejects (at declaration time) a rule name that collides with an `authz.roles` entry, a reserved/provider role, **any scoped-role name** (bare sugar like `attendee` or the canonical `scope:<kind>:<role>` spelling), or a name containing `+` or `:` (the `scope:` prefix always means a token-verified scope principal — a colon-named rule could capture references meant for one).\n\nInside `authz.roles` / gate `who` bodies, `+` hierarchy sugar is banned — write the expanded list (`['member', 'admin', 'owner']`), because `+` expansion runs at resource sites only and a `member+` inside a body would silently never match. Roles may not reference rules (the dependency arrow is one-way), and gates never nest.\n\n### Typo safety\n\nA `roles: [...]` name that matches nothing declared is fail-closed at runtime (it never grants) but historically silent. The compiler now emits a warning-level `AUTHZ_UNKNOWN_ROLE_NAME` diagnostic for any name that is not a provider/hierarchy role, pseudo-role, scoped role, or declared role/rule — a typo'd gate name is visible at compile time without breaking projects that use dynamic auth-provider role names. The heuristic runs only for projects that use the authz naming system (any of `authz.roles`, `authz.rules`, or `authz.scopes` declared); projects outside it keep the pre-existing silent-passthrough behavior for dynamic role names.\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. These are the `{ via: '...' }` rule shape from [Centrally defined access rules](#centrally-defined-access-rules) above.\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)"
83
83
  },
84
84
  "compiler/definitions/actions": {
85
85
  "title": "Actions",
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. It infers `record` and Zod `input`, exposes the generated\n> `Services`, types `c` as a Hono request context, binds `whereRecord` and\n> `whereTransition` to the feature table, and preserves the exact value\n> returned by `execute` without imposing an action-output schema. Scoped\n> `db` and interactive `tx` are schema-aware on D1 and Neon Hyperdrive;\n> HTTP/WebSocket Neon keeps its dynamic database escape hatch. `AppContext`\n> also retains its open index for namespace-hydrated fields. Audit fields\n> (`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### Local input-schema harvest\n\nBefore sending a compile request, the CLI loads each action in an isolated\nlocal bundle and converts `action.input` with Zod 4's `z.toJSONSchema`. It does\nnot call `execute`; the hosted compiler never evaluates project code. Under\ncontract v2, every action must produce a schema. A failure names the exact\naction, whether bundling or evaluation failed, and the underlying local error.\nV1 can still fall back to the lower-fidelity static schema parser.\n\nBare imports are resolved from the generated runtime's configured\n`build.outputDir/node_modules` first. If definitions live in `quickback/` and\nthe generated Worker lives in `src/`, install runtime dependencies in `src/`\nas usual; no project-root dependency symlink is required. Shared schema or DTO\nmodules may also declare top-level Drizzle selection objects. Quickback\nreplaces authored table exports with inert proxies during this schema-only\nevaluation, so reading `records.id` to build a projection does not execute\napplication or database logic.\n\nParameterized standalone paths use Hono's `:param` syntax in authored source,\nfor example `path: \"/events/:eventId/check-in\"`. The harvest planner converts\nthose segments to the OpenAPI `{param}` form before applying the schema, so\ncontract-v2 completeness uses the same route key as the emitted OpenAPI and MCP\nsurfaces. The same normalization applies when a record resource path contains\nnamespace parameters.\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\nThe generated OpenAPI document and MCP tools reuse that exact action schema\nin both places: as the single-record request body and as the bulk wrapper's\nnested `input` property. Under contract v2, Quickback considers the action's\nschema harvest complete only after both operations are patched. This also\nholds when the table filename and declared table name use different casing or\nseparators (for example, `event-guests.ts` exporting `event_guests`); the\noperations follow the table's declared resource path.\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### Delegated principals and `databaseAccess`\n\nOn a contract-v2 Cloudflare + Neon Hyperdrive project, an action can admit a\nconfigured delegated principal with `access.principals`:\n\n```typescript\nexport default defineAction({\n description: \"Confirm attendance from an event session\",\n path: \"/attendance/confirm\",\n input: z.object({ response: z.enum([\"yes\", \"no\"]) }),\n access: { principals: [\"event_delegate\"] },\n async execute({ ctx, db, input }) {\n // ctx.principal is guaranteed and narrowed by the generated helper.\n const { eventId, personId } = ctx.principal.claims;\n return confirmAttendance(db, { eventId, personId, response: input.response });\n },\n});\n```\n\nThis is a separate authority lane, not an account impersonation. A delegated\naction context has no `userId`, active organization/team, or membership roles.\nIf access has a `PUBLIC` sibling arm, the generated type includes the anonymous\nlane and code must narrow `ctx.principal` before reading it.\n\nFor an organization- or team-scoped host feature, the standalone route does\nnot run the Better Auth `activeOrgId` / `activeTeamId` precondition before a\nprincipal access tree. Authentication and `evaluateAccessPreRecord` still run;\nthe declared `principals` arm is the authority decision. This avoids turning an\naccount-session field into an accidental prerequisite for delegated callers.\n\nThe generated standalone route reuses that action-specific `execute` context\nafter its runtime access gates. Account, `event_pass`, and `event_delegate`\nactions therefore keep distinct compile-time authority types all the way into\nthe handler. The route also reuses the action's schema-aware scoped `db` type,\nincluding when an unsafe/service-role client is wrapped before the call. If a\nrelationship uses `loads` / `exposeAs`, the loaded row type is\nintersected with the same authority context: a single or shared hydration\ntarget is required, while targets selected by distinct relationship lanes are\noptional and must be narrowed by the handler.\n\nFor tables queried by authored actions, `resource.databaseAccess` adds an\nindependent Postgres RLS policy without adding HTTP surface. It never mounts a\nread/CRUD route and never adds an OpenAPI operation. The action remains the API\nlayer where validation, state transitions, side effects, and business logic\nbelong; `databaseAccess` is only the database's row-level upper bound.\n\n```typescript\nexport default defineTable(attendanceEvidence, {\n // Ordinary account CRUD remains organization-scoped.\n firewall: [\n { field: \"organizationId\", equals: \"ctx.activeOrgId\" },\n ],\n\n // Authored actions can use their caller-scoped db under one of two exact\n // row lanes. Sibling arms OR; fields in each arm AND.\n databaseAccess: {\n select: {\n or: [\n {\n roles: [\"AUTHENTICATED\"],\n record: {\n organizationId: { equals: \"$ctx.activeOrgId\" },\n },\n },\n {\n principals: [\"event_delegate\"],\n record: {\n eventId: { equals: \"$ctx.principal.claims.eventId\" },\n personId: { equals: \"$ctx.principal.claims.personId\" },\n },\n },\n ],\n },\n },\n});\n```\n\n`databaseAccess` supports `select`, `insert`, `update`, and `delete`. Its rule\nlanguage is intentionally smaller than application access: `principals`,\n`roles`, recursive `or`/`and`, and record `equals` against a DB-visible account\nor principal context value. `userRole`, functions, request/body values, and\nother predicate operators are compile errors.\n\nEvery authorization path must contain at least one nonempty record equality.\nA principal-only or role-only leaf is rejected; every `or` arm must be bounded.\nAn `and` group is bounded when at least one child bounds every expansion (for\nexample, a principal child AND an event-id record child). A node cannot mix\nleaf fields with `or`/`and`, because the boolean node is the complete rule.\nThis mandatory shape prevents an action declaration from accidentally granting\nthe delegated principal an entire table.\n\nThe supported equality sources are `ctx.userId`, `ctx.activeOrgId`,\n`ctx.activeTeamId`, `ctx.principal.actor.id`, optional principal session/family\nids, and `ctx.principal.claims.<name>` (with or without a leading `$`). The\nrecord keys are Drizzle/JavaScript table field names; Quickback resolves them\nthrough the table metadata and quotes the exact physical PostgreSQL identifier,\nso a field such as `eventId: text(\"event-id\")` is safe. Unknown fields fail the\ncompile. `ADMIN` and the app-only `INTERNAL` marker are forbidden on this DB\nsurface, while `SYSADMIN` retains its explicit `cms.sysadmin` prerequisite. The\nfeature is rejected outside Cloudflare + Neon Hyperdrive because those targets\ncannot guarantee request-scoped Postgres claims.\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):** `unsafe.enabled` controls app-layer scoped-query\nbypass, while `unsafe.crossTenant` controls database-layer RLS bypass. An\nunsafe action with `crossTenant: false` receives a raw Drizzle handle backed by\nthe request database, so the caller's organization or delegated-principal\nclaims remain active—including inside `db.transaction()`. Its code must still\nprovide every intended scope predicate explicitly.\n\nOnly an action with `crossTenant: true` acquires the dedicated service-role\nhandle (`createServiceDb`). That handle sets the `quickback.service_role`\ntransaction marker instead of caller claims, and generated RLS grants it an\nexplicit per-table bypass policy. The sysadmin guard and mandatory audit log\ntherefore protect the same boundary that receives the RLS bypass. The\naudit-logging contract is otherwise 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\nTransitions grew a v2 surface — guards, timestamp/actor stamps, idempotent\nno-ops, compiler-applied writes with optional `execute`, `undo` pairs, and\ntable-level generated transition actions. See **[Transitions](/compiler/definitions/transitions)**.\n\n## After-commit hooks\n\n> For typed realtime *\"this changed — refresh\"* signals, use [`invalidates`](/stack/realtime/named-invalidations) — it rides this same after-commit model but delivers a versioned, targeted frame to subscribers.\n\nSecondary effects — activity feeds, notification nudges, cache warmers — must\nnever roll back or delay the primary write. Instead of hand-wrapping each leg\nin `try/catch` + `executionCtx.waitUntil`, declare named `afterCommit` hooks:\n\n```typescript\nexport default defineAction({\n // ...\n execute: async ({ db, record, ctx, now }) => {\n await db.update(guests).set({ checkedInAt: now }).where(/* … */);\n return { success: true, checkedInAt: now };\n },\n afterCommit: {\n // Named hooks run after execute returns successfully, in declared order.\n activityFeed: async ({ db, env, record, ctx }, result) => {\n await recordActivity(db, env, { verb: \"guest.checked_in\", /* … */ });\n },\n // blocking: true is awaited before the response (client depends on it).\n issueBadge: { blocking: true, run: async (actx, result) => { /* … */ } },\n },\n});\n```\n\nThe contract:\n\n- Hooks receive `(actx, result)` — the same context `execute` got, plus its\n return value.\n- Each hook is **independently wrapped**: a throw is logged as\n `[<action>] afterCommit:<hook> failed` and never affects the response or\n other hooks.\n- Non-blocking hooks (the default) ride `executionCtx.waitUntil`; blocking\n hooks are awaited before responding.\n- If `execute` throws, no hooks run. A result carrying `dryRun: true` also\n skips them (preview branches never fire side effects).\n- Bulk twins run hooks **once per invocation** with the bulk envelope as\n `result` — per-record fan-out is the hook author's job.\n\nFor effects that need mid-execute data, the context carries an imperative\nescape hatch with the same semantics:\n\n```typescript\nexecute: async ({ db, effects }) => {\n // …\n effects.enqueue(\"cohortRecalc\", () => recalculate(/* … */));\n return { success: true };\n}\n```\n\nEffects enqueued by an `execute` that later throws are dropped. The context\nalso carries `now` — one ISO timestamp per invocation; prefer it over\n`new Date().toISOString()`.\n\n## Realtime emit from actions\n\nTables that lock auto-CRUD but mutate through custom actions no longer need\nhand-written `realtime.insert/update/delete` blocks. Opt the table in:\n\n```typescript\nrealtime: {\n enabled: true,\n access: { roles: [\"member+\"] },\n scopeKeyFrom: \"events:{eventId}\", // sugar for scopeTable + scopeField\n emitFromActions: true, // scoped-db writes auto-emit after commit\n}\n```\n\nWrites to the table through the scoped `db` inside record-bound and bulk\nactions emit frames byte-compatible with auto-CRUD (same envelope, masking,\naudience), after commit, best-effort. For projections, standalone actions, or\ncross-feature targets, declare an action-level `emit:` to get a pre-bound\n`emitCrud(row, oldRow?)` helper. Full details and the capture caveats live in\nthe [realtime docs](/stack/realtime/durable-objects).\n\n## Refs (scoped foreign-key inputs)\n\nThe most common action preamble — load an input id, 404 if missing, assert it\nbelongs to the caller's event/org — becomes declarative:\n\n```typescript\nexport default defineAction({\n input: z.object({ agendaItemId: z.string(), guestId: z.string(), locationId: z.string().optional() }),\n refs: {\n agendaItemId: { table: \"agendaItems\", as: \"agendaItem\",\n matchScope: \"event\", // row.eventId === ctx.event.id\n notFound: { code: \"ITEM_NOT_FOUND\" } }, // status defaults to 404\n guestId: { table: \"guests\", as: \"guest\",\n matchWith: { ref: \"agendaItem\", on: \"eventId\" }, // cross-input parenthood\n mismatch: { code: \"EVENT_MISMATCH\", status: 400 } },\n locationId: { table: \"locations\", as: \"location\", optional: true, matchScope: \"event\" },\n },\n execute: async ({ input, agendaItem, guest, location }) => { /* … */ },\n});\n```\n\n- Loads run **through the scoped db** before `execute` — the org firewall and\n soft-delete filter apply by construction, so a cross-org id 404s with zero\n hand-written tenancy checks. All loads batch into one `Promise.all`.\n- `matchScope: \"<scope>\"` asserts `row.<scope>Id === ctx.<scope>.id` and\n fail-closes (500) if the scope object isn't hydrated. The explicit form\n `{ column, equals: \"ctx.activeOrgId\" }` is also accepted.\n- `matchWith` compares a column against an earlier-declared ref — declaration\n order defines resolution order; forward references are compile errors.\n- Ref keys must exist on the inline `z.object` input with agreeing\n optionality; `as` names can't shadow reserved context keys. Injected rows\n are the **unmasked** DB rows (masking remains a read-projection concern).\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. It infers `record` and Zod `input`, exposes the generated\n> `Services`, types `c` as a Hono request context, binds `whereRecord` and\n> `whereTransition` to the feature table, and preserves the exact value\n> returned by `execute` without imposing an action-output schema. Scoped\n> `db` and interactive `tx` are schema-aware on D1 and Neon Hyperdrive;\n> HTTP/WebSocket Neon keeps its dynamic database escape hatch. `AppContext`\n> also retains its open index for namespace-hydrated fields. Audit fields\n> (`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### Local input-schema harvest\n\nBefore sending a compile request, the CLI loads each action in an isolated\nlocal bundle and converts `action.input` with Zod 4's `z.toJSONSchema`. It does\nnot call `execute`; the hosted compiler never evaluates project code. Under\ncontract v2, every action must produce a schema. A failure names the exact\naction, whether bundling or evaluation failed, and the underlying local error.\nV1 can still fall back to the lower-fidelity static schema parser.\n\nBare imports are resolved from the generated runtime's configured\n`build.outputDir/node_modules` first. If definitions live in `quickback/` and\nthe generated Worker lives in `src/`, install runtime dependencies in `src/`\nas usual; no project-root dependency symlink is required. Shared schema or DTO\nmodules may also declare top-level Drizzle selection objects. Quickback\nreplaces authored table exports with inert proxies during this schema-only\nevaluation, so reading `records.id` to build a projection does not execute\napplication or database logic.\n\nParameterized standalone paths use Hono's `:param` syntax in authored source,\nfor example `path: \"/events/:eventId/check-in\"`. The harvest planner converts\nthose segments to the OpenAPI `{param}` form before applying the schema, so\ncontract-v2 completeness uses the same route key as the emitted OpenAPI and MCP\nsurfaces. The same normalization applies when a record resource path contains\nnamespace parameters.\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| `webhook` | No | Standalone only. Compile-declared inbound signature verification (`standard-webhooks`, `hmac-sha256`, or `aws-sns`) that runs on the raw bytes **before** parse/access — see [Inbound webhooks](/stack/webhooks/inbound) |\n| `idempotency` | No | `'dedupe'` — PUBLIC-action opt-in for the `Idempotency-Key` header with dedupe-only semantics (duplicate ⇒ `409` reference; the cached body is never served to a second caller). Standalone actions with a **static** path only (a `:param` path is a compile error — the allowlist matches literal request paths) and the action's access must admit `PUBLIC`. Authenticated routes accept the header automatically — see [API contract](/stack/api-contract) |\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\nThe generated OpenAPI document and MCP tools reuse that exact action schema\nin both places: as the single-record request body and as the bulk wrapper's\nnested `input` property. Under contract v2, Quickback considers the action's\nschema harvest complete only after both operations are patched. This also\nholds when the table filename and declared table name use different casing or\nseparators (for example, `event-guests.ts` exporting `event_guests`); the\noperations follow the table's declared resource path.\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\nPaths are absolute (`/...`). Inside a [feature area](/compiler/definitions/feature-areas)\nwith a mounted prefix, two more forms apply:\n\n- **Relative** — `path: './tasks/add'` resolves against the area's prefix\n (`/project/:projectId/tasks/add`). Plain descending segments only; `.` / `..` segments are\n rejected at compile time.\n- **Self-gated** — an absolute path *outside* the area's prefix opts the action out of the\n area's admission gate and MUST carry `route: 'self'` (fail-closed; the marker is rejected\n where it would be dead). The action is then gated solely by its own `access:` and listed in\n `quickback/authz-manifest.json`.\n\nAn action's `access:` and `anchor:` may reference vocabulary declared by an ancestor area —\nand never vocabulary of an area the feature is not inside (compile error).\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\nIf the same role expression shows up on more than one action or resource, define it once in `authz.roles` and reference it by name — see [Centrally defined access rules](/compiler/definitions/access#centrally-defined-access-rules).\n\n[Named gates](/compiler/definitions/access#named-gates-authzrules) (`authz.rules`) also work in an action's `roles: [...]` array — a who-only gate expands as its `who`, a who+`record` gate as `{ and: [who, { record }] }` (the record predicate is evaluated against the bound record, exactly like an inline `access.record`). Function-form `access` is opaque to the rewrite and is left untouched.\n\n**A firewall-bearing gate on an action is a compile error.** An action has no firewall array — there is no row query for the gate's lanes to constrain before execution — so the compiler refuses rather than letting the row lanes silently not apply. The escape hatch: split the gate into a who-rule referenced from the action plus a firewall-only gate stamped on the owning resource's `firewall:`.\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### Delegated principals and `databaseAccess`\n\nOn a contract-v2 Cloudflare + Neon Hyperdrive project, an action can admit a\nconfigured delegated principal with `access.principals`:\n\n```typescript\nexport default defineAction({\n description: \"Confirm attendance from an event session\",\n path: \"/attendance/confirm\",\n input: z.object({ response: z.enum([\"yes\", \"no\"]) }),\n access: { principals: [\"event_delegate\"] },\n async execute({ ctx, db, input }) {\n // ctx.principal is guaranteed and narrowed by the generated helper.\n const { eventId, personId } = ctx.principal.claims;\n return confirmAttendance(db, { eventId, personId, response: input.response });\n },\n});\n```\n\nThis is a separate authority lane, not an account impersonation. A delegated\naction context has no `userId`, active organization/team, or membership roles.\nIf access has a `PUBLIC` sibling arm, the generated type includes the anonymous\nlane and code must narrow `ctx.principal` before reading it.\n\nFor an organization- or team-scoped host feature, the standalone route does\nnot run the Better Auth `activeOrgId` / `activeTeamId` precondition before a\nprincipal access tree. Authentication and `evaluateAccessPreRecord` still run;\nthe declared `principals` arm is the authority decision. This avoids turning an\naccount-session field into an accidental prerequisite for delegated callers.\n\nThe generated standalone route reuses that action-specific `execute` context\nafter its runtime access gates. Account, `event_pass`, and `event_delegate`\nactions therefore keep distinct compile-time authority types all the way into\nthe handler. The route also reuses the action's schema-aware scoped `db` type,\nincluding when an unsafe/service-role client is wrapped before the call. If a\nrelationship uses `loads` / `exposeAs`, the loaded row type is\nintersected with the same authority context: a single or shared hydration\ntarget is required, while targets selected by distinct relationship lanes are\noptional and must be narrowed by the handler.\n\nFor tables queried by authored actions, `resource.databaseAccess` adds an\nindependent Postgres RLS policy without adding HTTP surface. It never mounts a\nread/CRUD route and never adds an OpenAPI operation. The action remains the API\nlayer where validation, state transitions, side effects, and business logic\nbelong; `databaseAccess` is only the database's row-level upper bound.\n\n```typescript\nexport default defineTable(attendanceEvidence, {\n // Ordinary account CRUD remains organization-scoped.\n firewall: [\n { field: \"organizationId\", equals: \"ctx.activeOrgId\" },\n ],\n\n // Authored actions can use their caller-scoped db under one of two exact\n // row lanes. Sibling arms OR; fields in each arm AND.\n databaseAccess: {\n select: {\n or: [\n {\n roles: [\"AUTHENTICATED\"],\n record: {\n organizationId: { equals: \"$ctx.activeOrgId\" },\n },\n },\n {\n principals: [\"event_delegate\"],\n record: {\n eventId: { equals: \"$ctx.principal.claims.eventId\" },\n personId: { equals: \"$ctx.principal.claims.personId\" },\n },\n },\n ],\n },\n },\n});\n```\n\n`databaseAccess` supports `select`, `insert`, `update`, and `delete`. Its rule\nlanguage is intentionally smaller than application access: `principals`,\n`roles`, recursive `or`/`and`, and record `equals` against a DB-visible account\nor principal context value. `userRole`, functions, request/body values, and\nother predicate operators are compile errors.\n\nEvery authorization path must contain at least one nonempty record equality.\nA principal-only or role-only leaf is rejected; every `or` arm must be bounded.\nAn `and` group is bounded when at least one child bounds every expansion (for\nexample, a principal child AND an event-id record child). A node cannot mix\nleaf fields with `or`/`and`, because the boolean node is the complete rule.\nThis mandatory shape prevents an action declaration from accidentally granting\nthe delegated principal an entire table.\n\nThe supported equality sources are `ctx.userId`, `ctx.activeOrgId`,\n`ctx.activeTeamId`, `ctx.principal.actor.id`, optional principal session/family\nids, and `ctx.principal.claims.<name>` (with or without a leading `$`). The\nrecord keys are Drizzle/JavaScript table field names; Quickback resolves them\nthrough the table metadata and quotes the exact physical PostgreSQL identifier,\nso a field such as `eventId: text(\"event-id\")` is safe. Unknown fields fail the\ncompile. `ADMIN` and the app-only `INTERNAL` marker are forbidden on this DB\nsurface, while `SYSADMIN` retains its explicit `cms.sysadmin` prerequisite. The\nfeature is rejected outside Cloudflare + Neon Hyperdrive because those targets\ncannot guarantee request-scoped Postgres claims.\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):** `unsafe.enabled` controls app-layer scoped-query\nbypass, while `unsafe.crossTenant` controls database-layer RLS bypass. An\nunsafe action with `crossTenant: false` receives a raw Drizzle handle backed by\nthe request database, so the caller's organization or delegated-principal\nclaims remain active—including inside `db.transaction()`. Its code must still\nprovide every intended scope predicate explicitly.\n\nOnly an action with `crossTenant: true` acquires the dedicated service-role\nhandle (`createServiceDb`). That handle sets the `quickback.service_role`\ntransaction marker instead of caller claims, and generated RLS grants it an\nexplicit per-table bypass policy. The sysadmin guard and mandatory audit log\ntherefore protect the same boundary that receives the RLS bypass. The\naudit-logging contract is otherwise 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\nTransitions grew a v2 surface — guards, timestamp/actor stamps, idempotent\nno-ops, compiler-applied writes with optional `execute`, `undo` pairs, and\ntable-level generated transition actions. See **[Transitions](/compiler/definitions/transitions)**.\n\n## After-commit hooks\n\n> For typed realtime *\"this changed — refresh\"* signals, use [`invalidates`](/stack/realtime/named-invalidations) — it rides this same after-commit model but delivers a versioned, targeted frame to subscribers.\n\nSecondary effects — activity feeds, notification nudges, cache warmers — must\nnever roll back or delay the primary write. Instead of hand-wrapping each leg\nin `try/catch` + `executionCtx.waitUntil`, declare named `afterCommit` hooks:\n\n```typescript\nexport default defineAction({\n // ...\n execute: async ({ db, record, ctx, now }) => {\n await db.update(guests).set({ checkedInAt: now }).where(/* … */);\n return { success: true, checkedInAt: now };\n },\n afterCommit: {\n // Named hooks run after execute returns successfully, in declared order.\n activityFeed: async ({ db, env, record, ctx }, result) => {\n await recordActivity(db, env, { verb: \"guest.checked_in\", /* … */ });\n },\n // blocking: true is awaited before the response (client depends on it).\n issueBadge: { blocking: true, run: async (actx, result) => { /* … */ } },\n },\n});\n```\n\nThe contract:\n\n- Hooks receive `(actx, result)` — the same context `execute` got, plus its\n return value.\n- Each hook is **independently wrapped**: a throw is logged as\n `[<action>] afterCommit:<hook> failed` and never affects the response or\n other hooks.\n- Non-blocking hooks (the default) ride `executionCtx.waitUntil`; blocking\n hooks are awaited before responding.\n- If `execute` throws, no hooks run. A result carrying `dryRun: true` also\n skips them (preview branches never fire side effects).\n- Bulk twins run hooks **once per invocation** with the bulk envelope as\n `result` — per-record fan-out is the hook author's job.\n\nFor effects that need mid-execute data, the context carries an imperative\nescape hatch with the same semantics:\n\n```typescript\nexecute: async ({ db, effects }) => {\n // …\n effects.enqueue(\"cohortRecalc\", () => recalculate(/* … */));\n return { success: true };\n}\n```\n\nEffects enqueued by an `execute` that later throws are dropped. The context\nalso carries `now` — one ISO timestamp per invocation; prefer it over\n`new Date().toISOString()`.\n\n## Realtime emit from actions\n\nTables that lock auto-CRUD but mutate through custom actions no longer need\nhand-written `realtime.insert/update/delete` blocks. Opt the table in:\n\n```typescript\nrealtime: {\n enabled: true,\n access: { roles: [\"member+\"] },\n scopeKeyFrom: \"events:{eventId}\", // sugar for scopeTable + scopeField\n emitFromActions: true, // scoped-db writes auto-emit after commit\n}\n```\n\nWrites to the table through the scoped `db` inside record-bound and bulk\nactions emit frames byte-compatible with auto-CRUD (same envelope, masking,\naudience), after commit, best-effort. For projections, standalone actions, or\ncross-feature targets, declare an action-level `emit:` to get a pre-bound\n`emitCrud(row, oldRow?)` helper. Full details and the capture caveats live in\nthe [realtime docs](/stack/realtime/durable-objects).\n\n## Refs (scoped foreign-key inputs)\n\nThe most common action preamble — load an input id, 404 if missing, assert it\nbelongs to the caller's event/org — becomes declarative:\n\n```typescript\nexport default defineAction({\n input: z.object({ agendaItemId: z.string(), guestId: z.string(), locationId: z.string().optional() }),\n refs: {\n agendaItemId: { table: \"agendaItems\", as: \"agendaItem\",\n matchScope: \"event\", // row.eventId === ctx.event.id\n notFound: { code: \"ITEM_NOT_FOUND\" } }, // status defaults to 404\n guestId: { table: \"guests\", as: \"guest\",\n matchWith: { ref: \"agendaItem\", on: \"eventId\" }, // cross-input parenthood\n mismatch: { code: \"EVENT_MISMATCH\", status: 400 } },\n locationId: { table: \"locations\", as: \"location\", optional: true, matchScope: \"event\" },\n },\n execute: async ({ input, agendaItem, guest, location }) => { /* … */ },\n});\n```\n\n- Loads run **through the scoped db** before `execute` — the org firewall and\n soft-delete filter apply by construction, so a cross-org id 404s with zero\n hand-written tenancy checks. All loads batch into one `Promise.all`.\n- `matchScope: \"<scope>\"` asserts `row.<scope>Id === ctx.<scope>.id` and\n fail-closes (500) if the scope object isn't hydrated. The explicit form\n `{ column, equals: \"ctx.activeOrgId\" }` is also accepted.\n- `matchWith` compares a column against an earlier-declared ref — declaration\n order defines resolution order; forward references are compile errors.\n- Ref keys must exist on the inline `z.object` input with agreeing\n optionality; `as` names can't shadow reserved context keys. Injected rows\n are the **unmasked** DB rows (masking remains a read-projection concern).\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```"
87
87
  },
88
88
  "compiler/definitions/arrows": {
89
89
  "title": "Arrows",
@@ -93,6 +93,10 @@ export const DOCS = {
93
93
  "title": "Bundles",
94
94
  "content": "## Overview\n\nClient bootstrap screens want many small lists in one request. Hand-written\n\"bundle\" endpoints all repeat the same 150 lines: a `Promise.all` of selects\nshaped byte-identically to the CRUD list endpoints they replace, a\n`sections: string[]` subset filter, a copy-pasted SHA-1 ETag +\n`ifNoneMatch → notModified` short-circuit, a `Server-Timing` header, and\nhand-re-derived per-slice masking. `defineBundle` generates all of it.\n\n```typescript\n// features/events/actions/getOverviewBundle.ts\n\nexport default defineBundle({\n path: \"/event/:eventId/overview-bundle\",\n description: \"Console Overview bootstrap\",\n access: { roles: [\"member\", \"admin\"] },\n etag: true, // default true\n serverTiming: \"overview\", // optional\n sections: {\n guests: list(\"guests\", {\n columns: [\"id\", \"status\", \"modifiedAt\", \"createdAt\", \"displayName\"],\n where: { eventId: \"$ctx.event.id\" },\n orderBy: [{ createdAt: \"desc\" }],\n limit: 500,\n }),\n tickets: list(\"supportTickets\", { where: { eventId: \"$ctx.event.id\" }, orderBy: [{ modifiedAt: \"desc\" }], limit: 100 }),\n counts: custom(async ({ db, ctx }) => ({ open: 0 })), // computed slice — author owns masking\n },\n});\n```\n\n## Semantics\n\n- **Generated POST action** with input `{ sections?: string[], ifNoneMatch?: string }`,\n mounted through the standard standalone pipeline — auth, access, org/team\n preconditions, rate limits, OpenAPI, MCP tools, security contracts all\n apply.\n- **`list()` sections run through the scoped db** — the org firewall and\n soft-delete filter apply by construction — and the target table's REAL\n mask function is applied (the same read projection the CRUD list endpoint\n runs), so masked columns are safe to include. Every list slice lands as\n `{ data: rows }` (the per-resource cache-seed contract).\n- **`sections` filter**: omitted/empty = all. An un-wanted list section\n returns `{ data: [] }` (drop-in compatible with existing clients);\n un-wanted `custom` sections are absent.\n- **All sections run in one `Promise.all`.**\n- **ETag**: SHA-1 hex over `{ scopeSeed: <path params>, userId, payload }`.\n An `ifNoneMatch` match returns `{ success: true, etag, notModified: true }`\n with **no sections**. The digest is also exported as `sha1Hex` from\n `lib/etag` so remaining hand-written reads can delete their copies.\n- **`custom()` sections** receive the full action context and are embedded\n verbatim under the section name — the author owns masking there.\n\n## Compile-time validation (fail-closed)\n\n- Unknown section tables error, listing candidates.\n- `columns` / `where` / `orderBy` must name declared columns\n (compiler-injected audit columns like `createdAt`/`modifiedAt` are allowed).\n- `where` values are literals or the strict substitution allowlist\n (`$ctx.userId`, `$ctx.activeOrgId`, `$ctx.<scope>.id`) — always\n parameterized. Anything richer belongs in a `custom()` section.\n- Section names may not shadow the response envelope\n (`success`, `etag`, `notModified`, `sections`).\n- **A bundle must never widen read access**: its `access.roles` must be a\n subset of every list section table's `read.access` roles — a violation is\n a compile error, not a warning."
95
95
  },
96
+ "compiler/definitions/changesets": {
97
+ "title": "Changesets — aggregate writes",
98
+ "content": "A **changeset** writes a parent row and its owned relations — junction\nmemberships, normalized phones/emails, line items — in **one request**,\nreplacing the hand-rolled multi-table action. You declare the one fact the\ncompiler was missing — which relations are **compositions** (owned by this\nroot) vs **references** (independent entities) — and the compiler generates\nthe whole write path.\n\nChangesets are a **contract v2** capability (`contract: { version: \"v2\" }`).\nDeclaring `owns` on a v1-pinned project is a compile error.\n\n## Declaring the boundary — `owns`\n\n```ts title=\"quickback/features/projects/projects.ts\"\nexport default feature(\"projects\", {\n // ...columns, firewall, guards, masking, read...\n create: { access: { roles: [\"admin\", \"owner\"] } },\n update: { access: { roles: [\"admin\", \"owner\"] } },\n\n owns: {\n tasks: {\n table: \"tasks\", // camelCase table name — a defineTable in this project\n fk: \"projectId\", // FK on the CHILD pointing at this root's PK\n refs: { // client-supplied pointers at INDEPENDENT entities\n assigneeId: \"people\",\n reviewerId: \"people\", // nullable refs may be omitted or null\n },\n inherit: [\"organizationId\"], // parent columns copied onto every inserted child\n owns: { // grandchildren — structural nesting, depth-capped\n checklist: { table: \"taskChecklistItems\", fk: \"taskId\", inherit: [\"organizationId\"] },\n },\n },\n },\n});\n```\n\n| Key | Meaning |\n|---|---|\n| `table` | The owned child — **must** be a `defineTable`/`feature()` in the project. String literal, never an identifier. Auth tables can never be owned. |\n| `fk` | The spine: the child column pointing at this root. **Compiler-stamped** on inserts; a client-supplied value is rejected. |\n| `refs` | Columns pointing at independent entities. Client-supplied, **existence-checked inside the caller's tenant** (the referenced table's firewall is ANDed) — on inserts **and** patches. The referenced row is never written through. |\n| `inherit` | Tenant/denorm columns copied verbatim from the (firewall-verified) parent row onto every inserted child. Compiler-stamped; client values rejected. |\n| `owns` | Nested owned relations. Max 3 levels of nesting (the aggregate spans at most 4 tables). |\n\nA child's [`q.stamp`](/compiler/definitions/schema#qstamp--proven-principal-identity-columns) identity columns are a **fourth, disjoint** source, sitting alongside `fk`/`inherit`/`refs`. On a changeset **insert** the engine stamps them from the **caller's proven scope claim** (`ctx.scope.<kind>.<claim>`) — *not* from the parent row — but only when the caller is a scope-only principal; an org-admitted caller keeps their client value (org-firewall-bounded). The contrast is exact: `inherit` copies **tenant** columns from the firewall-verified *parent*, `q.stamp` copies **identity** from the proven *token*. A required claim absent on a scope principal fails the op with **403** — emitted *before* the ref-existence checks, so a claim-less caller cannot probe which rows exist. A `refs` key may not alias a `q.stamp` column (a column is compiler-stamped **or** a client ref, never both). On a changeset **patch** op the stamp column is **immutable** — a client value for it is rejected (400) like any systemManaged column, matching the plain update path. Because the stamp lives inside the changeset handler, a **keyed** (`Idempotency-Key`) replay neither re-writes nor re-stamps; a keyless retry re-writes and re-stamps.\n\n**Owning a relation is not a write grant.** Every changeset op is admitted by\nthe **child table's own crud declaration**: `insert` requires `create:` on the\nchild, `patch` requires `update:`, `delete` requires `delete:` (soft mode only\nin v1) — each with its own `access`. There is no per-relation access override:\naccess is declared exactly once, on the child.\n\n### `routes: false` — changeset admission without a raw route\n\nWidening a child's access for changeset use must not silently open its raw\nCRUD surface. The `create`, `update`, and `delete` op configs accept\n`routes: false` (`upsert`/`put` does not): the access stays declared (it is\nthe changeset admission gate) while the raw HTTP route — and its\nauto-promoted batch variant — is never mounted, documented, or counted in\nthe operations manifest.\n\n```ts title=\"quickback/features/projects/tasks.ts\"\nupdate: { access: { roles: [\"member\", \"admin\", \"owner\"] }, routes: false },\n```\n\n## The wire contract\n\nOne blessed path — **RFC 5789 media-type dispatch** on the routes you already\nhave. No subpath.\n\n- `PATCH /api/v2/<resource>/:id` with\n `Content-Type: application/vnd.quickback.changeset+json` — apply a changeset\n to an existing root. Plain `application/json` keeps the flat-column PATCH.\n- `POST /api/v2/<resource>` with the same media type — create the root and its\n children in one changeset.\n\n```jsonc\n// PATCH /api/v2/projects/prj_1 (Content-Type: application/vnd.quickback.changeset+json)\n{\n \"patch\": { \"name\": \"Renamed\" }, // sparse ROOT patch (optional)\n \"tasks\": {\n \"insert\": [\n {\n \"lid\": \"t1\", // client correlation id\n \"title\": \"Ship it\",\n \"assigneeId\": \"per_9\", // ref — tenant-checked\n \"checklist\": { \"insert\": [{ \"label\": \"QA pass\" }] } // grandchild, FKs onto t1's minted id\n }\n ],\n \"patch\": [{ \"id\": \"tsk_2\", \"state\": \"done\" }],\n \"delete\": [\"tsk_3\"]\n }\n}\n```\n\n```jsonc\n// Response\n{\n \"success\": true,\n \"root\": { \"id\": \"prj_1\", \"name\": \"Renamed\", /* masked through the root's masking */ },\n \"created\": { \"t1\": \"tsk_9a…\", \"/tasks/insert/0/checklist/insert/0\": \"tci_44…\" },\n \"meta\": { \"ops\": 4, \"transactional\": false }\n}\n```\n\n- Inserts/patches apply parent-first (document order); deletes apply\n children-first.\n- `lid` correlates a minted id in `created`; entries without a `lid` key on\n their JSON Pointer. A nested insert's FK comes from its parent op's minted\n id — an unresolvable parent lid is a pointer-carrying **400**, never a\n silent re-parent onto the root.\n- `Prefer: return=minimal` omits `root` from the response. v1 representation\n is **root-row-only** (re-read through the root's masking) — nested aggregate\n reads are the phase-2 `?include=` reader; use [`defineView`\n includes](/compiler/definitions/read) today.\n\n### Headers\n\n| Header | Behavior |\n|---|---|\n| `If-Match` | Optimistic concurrency against the **root revision** — the root's `updatedAt` (or the injected `modifiedAt` audit column). Accepted value forms: `W/\"<revision>\"`, `\"<revision>\"`, or the bare revision value, where `<revision>` is the raw value of the revision column as returned in the root row. **Do not echo `GET /:id`'s `ETag` header into `If-Match`** — that ETag is the contract layer's body-hash ETag, not this revision, and will always **412**. Compared inside the transaction; mismatch → **412**. Every accepted changeset touches the revision. A root with no revision column answers `If-Match` with **428 PRECONDITION_UNSUPPORTED** — never silently ignored; the POST variant always answers 428 (no pre-existing revision to match). |\n| `Idempotency-Key` | The standard write-retry key. Claims are principal-scoped — a replayed key from a different principal is a 422, never a cached-body leak. |\n| `Prefer` | `return=representation` (default) or `return=minimal`. |\n\n### Errors\n\nRFC 9457 `application/problem+json`. The failing op is identified by a JSON\nPointer in the `pointer` extension (`/tasks/insert/0/assigneeId`). On\n**non-transactional providers** the error also carries an `ops` extension\nlisting the outcomes of ops applied before the failure — the honest committed\nprefix. On **transactional providers** the rollback erased every applied op,\nso the error carries **no `ops` extension** (advertising rolled-back ids would\npoint clients at rows that no longer exist). **Outcome entries carry only\n`{ pointer, status, id? }` — never child field values** (v1 deliberately\nwithholds nested child representation, so errors cannot become an\nunmasked-child side channel).\n\n## The security model — \"owning a relation is not a backdoor\"\n\nThe **root op** runs the root table's full single-record gate stack, in order:\nauth → cross-tenant guard → the root's own `update` (PATCH) / `create` (POST)\naccess — **always, including child-only bodies; there is no child-only bypass\nlane** → firewall fetch (reveal → 403 / hide → 404, byte-consistent with the\nplain handler) → `requireSelf` → root body schema + ownership guard + guards.\nThe POST variant runs the root's full create pipeline (org validation, FK\nexistence checks, defaults/computed, ownership stamping).\n\nEvery **child op** then pays:\n\n1. **Admission** — declared relation, declared op kind (unknown keys are 400s).\n2. **The child's own access** — the pre-record role gate runs **before any row\n fetch** (no 404-vs-403 ID probing under the aggregate); `record:`\n predicates are evaluated against the fetched row on patch/delete and\n against the submitted input on insert.\n3. **systemManaged rejection** — client data carrying `fk`, any `inherit`\n column, or an ownership column is **rejected** with the op's pointer, never\n stripped or stamped-over. (The child's *plain-CRUD* guards are unaffected —\n a junction may keep its FK createable for its raw route; the same field in\n a changeset op is rejected because the changeset supplies it structurally.)\n4. **The child's column body schema** — q-authored children pay the same Zod\n types/enums/lengths backstop their plain POST/PATCH enforces (strict,\n guards-aware, with the compiler-stamped columns omitted). Drizzle-authored\n children have no Zod on their plain routes either, so none applies here —\n parity, not an omission.\n5. **The child's guards** — `createable`/`updatable` validation.\n6. **The child's firewall** — every patch/delete WHERE is\n `spine FK = parent id AND child firewall AND id`, same-feature or\n cross-feature alike. Inserts derive tenant columns only from the\n firewall-verified parent row.\n7. **Tenant-scoped `refs` checks** — each non-null ref must exist inside the\n referenced table's firewall, on **inserts and patches alike** (re-pointing\n a ref pays the same check; only columns present in the op's data are\n checked).\n8. **Server-minted child ids** — a client-supplied child primary key on an\n insert is rejected (like the plain POST's strict body schema), unless the\n project is configured for client-provided ids (`generateId: false`).\n\nChild `delete` ops stamp the **fixed `deletedAt`** audit column — exactly what\nthe plain DELETE route stamps (the audit wrapper then auto-stamps\n`deletedBy`). An `isNull` firewall arm on any other column (e.g.\n`archivedAt`) is a read-scoping predicate, never the soft-delete stamp.\n\nCompile-time, fail-closed (everything throws, nothing normalizes silently):\n\n- **Per-arm tenant coverage**: every column arm of the child's *resolved*\n firewall — including **every branch of an `any:` OR** — must be satisfiable\n by `fk`/`inherit`. Covering one arm of an OR is not coverage. This runs over\n the post-expansion firewall, so lanes spliced from\n [`authz.rules`](/compiler/definitions/access#centrally-defined-access-rules)\n gates and `{ tenant }` anchors are checked too.\n- Children firewalled through a **subquery arm** (`via:`, `{ permission }`,\n arrows) cannot be owned in v1 — even when the arm arrives through a gate\n splice.\n- `refs` keys must be **disjoint** from `{fk} ∪ inherit ∪ ownership columns` —\n a column is either compiler-stamped or a client ref, never both (blocks\n ownership-column injection through a ref).\n- **Relationship / FGA access arms are compile errors** on the changeset lane\n — on the root's `update`/`create` access and on every admitted child op's\n access. Those arms are decided by inline route code the changeset engine\n does not emit in v1; rather than silently widen (or silently 403) the gate,\n the compiler refuses. Use roles/record predicates, or keep the write in an\n authored action. (Function-form access is refused for the same reason.)\n- **Envelope-encrypted roots cannot ride the changeset in v1** — the response\n path does not run the decrypt-then-mask prepare helper, so the returned root\n would carry sealed ciphertext. The compiler refuses rather than degrade\n silently. (Sealed-mode columns are unaffected — plain routes return those\n as-is too.)\n- **Relation names `insert`, `patch`, `delete`, and `lid` are rejected** —\n the wire parser reserves those payload keys, so such a relation would be\n silently unreachable on the wire.\n- One aggregate root per table, acyclic graph, bounded depth, declared child\n ops only, soft-delete children only, contract v2 only.\n\n## `afterCommit` — emit a realtime signal after the changeset commits\n\nA changeset that must notify live views declares **`afterCommit`** on the\naggregate root — a declarative broadcast, **not** a hand-rolled\n`try { realtime.* } catch {}` tail. It fires **one aggregate-level CloudEvent**\nstrictly **after** the transaction commits, riding the existing\n[named-invalidation / Broadcaster egress](/stack/realtime/named-invalidations)\n(so it inherits the CloudEvents envelope + AsyncAPI description for free).\n\n```ts title=\"quickback/features/travel/lodging-reservations.ts\"\nexport default defineTable(lodgingReservations, {\n // ...firewall / read / crud ...\n owns: { occupants: { table: \"lodgingReservationGuests\", fk: \"reservationId\",\n inherit: [\"eventId\", \"organizationId\"] } },\n afterCommit: {\n broadcast: {\n travelChanged: {\n event: \"attendRealtime.mobileBundleChanged.travelUpdated\", // registry.event.variant\n delivery: \"thisEvent\", // MUST be in the event's `deliveries` allowlist\n payload: {\n eventId: \"root.eventId\", // a committed root column\n reservationId: \"rootId\", // the root pk\n occupantIds: \"affectedIds\", // ids of child rows touched this changeset\n },\n },\n },\n },\n});\n```\n\n- **One event per aggregate**, not one per touched child. The payload carries\n an **affected-ids / changed-paths** roll-up derived from the applied ops\n (`affectedIds` = child ids, `changedPaths` = JSON pointers) — **ids and\n pointers only, never child field values**.\n- **`delivery` is required and fail-closed.** The audience lives on a named\n [delivery profile](/stack/realtime/named-invalidations); it must appear in the\n referenced event's `deliveries` allowlist. There is **no default selection**,\n so an event permitting a narrow AND a wide room can never silently fan a\n changeset frame to the wider one.\n- **Payload sources:** `root.<col>` (a committed root column), `rootId`,\n `affectedIds`, `changedPaths`. Every payload key the variant declares must be\n mapped; unknown sources / undeclared keys are compile errors.\n- **Best-effort:** a broadcast failure never rolls back the committed changeset\n (`console.warn`, dispatched on `waitUntil`).\n- **Root-row frame:** `afterCommit: { realtime: true }` additionally emits the\n root row (postgres_changes-style) on the table's own `realtime` room. The row\n rides unmasked **with the table's `MASKING_CONFIG`** so the Broadcaster masks\n per-subscriber-role at fanout — the same discipline plain CRUD realtime uses.\n\n### Fail-closed disclosure gates\n\nBecause a broadcast payload is **not** masked at fanout (only the root-row frame\nis), afterCommit fails the build rather than leak:\n\n- A **masked `root.<col>`** may ride a broadcast only to a role-only delivery\n whose roles ⊆ the column's unmask roles (same app-role namespace). A\n **scope-keyed** delivery or an **empty unmask set** (`show: { or: 'owner' }`)\n **always** throws.\n- **`affectedIds` / `rootId` / `changedPaths`** carry firewalled row IDs\n (existence/enumeration). They may ride a scope-keyed delivery (bounded to one\n scope-instance room); a role-only / org-wide delivery throws unless you\n acknowledge with `disclosesChildIds: true`.\n\n### `q.scope` verified vs `q.stamp` proven — the \"stamp then emit\" rule\n\nWhen a changeset [stamps a proven identity](/compiler/definitions/schema#qstamp--proven-principal-identity-columns)\nand then emits it, the two features compose on one write path:\n\n| | `q.scope('<kind>')` | `q.stamp({ fromScope, claim })` |\n|---|---|---|\n| Purpose | tenant isolation column | proven-principal **identity** column |\n| Firewall arm? | **yes** — it is the tenant WHERE | **never** |\n| Verified how? | firewall re-verifies on read/patch/delete | token provenance (un-spoofable) |\n| Phrase | \"**stamp AND verify**\" | \"stamp AND **prove**\" |\n| Safe to broadcast? | to the matching scope-keyed room | **only** to an audience ⊆ the stamping scope kind |\n\nA `q.stamp` identity column (e.g. `guestId`) sourced via `root.<col>` is\n**audience-gated like `affectedIds`** (05×06 integration): the delivery must be\nscope-keyed to the **same scope kind** that stamped it, else the build fails —\nunless you acknowledge with **`disclosesStampedIdentity: true`**. A stamp is\nun-spoofable, not un-*sensitive*: provenance is not audience clearance.\n\n### Idempotency — at-least-once\n\nafterCommit is **at-least-once**, exactly as idempotent as the write it rides.\nA retry carrying the **same `Idempotency-Key`** neither re-writes nor re-emits\n(the middleware returns the cached response before the handler runs). A\n**keyless** retry re-runs the whole handler → re-writes **and** re-emits. Callers\nthat need single-delivery must send an `Idempotency-Key`.\n\n### No-tx: \"row written ⇏ event fired\"\n\nOn a no-tx provider (D1 / neon-http), a mid-changeset failure **throws** before\nthe success path, so **no frames emit** for the partially-applied prefix —\n`meta.transactional: false` is the only guarantee signal. A **fully-successful**\nno-tx changeset **does** emit, still with `transactional: false`. Never assume\n\"row written ⇒ event fired\"; `meta.transactional` is the contract.\n\n> **Deferred out of v1:** embedding reindex on the changeset lane, `notify`\n> (device push — a WS broadcast is not an APNs/web-push delivery), and lifting\n> `afterCommit` onto plain tables/actions. The compiler still **warns** when an\n> `owns` root/child declares `realtime` **without** `afterCommit`, or declares\n> `embeddings`, so a silent asymmetry can't be enabled unknowingly.\n\n## Atomicity — honest, per provider\n\nThe whole changeset runs inside `db.transaction()` when the provider supports\nit; `meta.transactional` reports the actual guarantee (same contract as\n[batch operations](/compiler/targets/hono-api/using-the-api/batch-operations)):\n\n| Provider | transactional | Behavior |\n|---|---|---|\n| postgres / supabase / neon (websocket / hyperdrive) / libsql / better-sqlite3 / bun-sqlite | `true` | One transaction; any op failure rolls back the root op and every child op |\n| cloudflare-d1, neon over http (the Cloudflare default) | `false` | Deterministic parent-first **fail-fast**: the first failure stops the changeset; ops already applied stay committed (a consistent prefix — each was independently authorized) |\n\n## Calling it from authored code\n\nThe engine is exported per root as `apply<Singular>Changeset` — the seam\nauthored actions delegate through when they still need residue logic\n(preconditions, server-side transforms, notifications) around the aggregate\nwrite:\n\n```ts title=\"quickback/features/projects/actions/importBoard.ts\"\n// Action files are compiled into the feature directory, next to the\n// generated module — the relative import resolves at runtime.\n\nexport default defineAction({\n // ...description, input, access...\n execute: async ({ db, ctx, input }) => {\n // precondition / transform residue …\n const result = await applyProjectChangeset(db, ctx, input.projectId, input.changes);\n // notify / respond …\n return result;\n },\n});\n```\n\n**There is no trusted mode.** The auth assertion, cross-tenant guard, and the\nroot's own pre-record access gate are the helper's first statements — an\nauthored action whose action-level access is looser than the root's crud\naccess still pays the root's declared authorization when it delegates. The\nHTTP handler is a thin wrapper over the same helper (parse + Problem-Details\nrendering only).\n\n## Standards mapping\n\n| Changeset concept | Grounded in |\n|---|---|\n| Media-type dispatch on PATCH | RFC 5789 (the media type selects patch semantics) |\n| `lid` correlation + op list | JMAP `/set` creation ids, JSON:API `lid` |\n| Root-revision `If-Match` | JMAP state tokens, RFC 9110 preconditions |\n| Pointer-carrying errors | RFC 9457 Problem Details + RFC 6901 JSON Pointer |\n| Nested relation ops | SCIM PATCH (typed sub-resources) |\n\n## What stays phase 2\n\nFull-document `replace` diff sugar (and its `key:` reconciliation field), the\n`application/json-patch+json` representation, cross-branch `$lid` references,\nnested `Prefer: return=representation`, `?include=` aggregate reads, and\nfind-or-create roots by business key (`conflictTarget`)."
99
+ },
96
100
  "compiler/definitions/concepts": {
97
101
  "title": "Glossary",
98
102
  "content": "Quick reference for terms used across the Quickback documentation.\n\n## Core Concepts\n\n| Term | Definition |\n|------|-----------|\n| **Feature** | A directory in `quickback/features/` containing related tables and actions. Example: a `candidates` feature with `candidates.ts`, `candidate-notes.ts`, and `actions.ts`. |\n| **Resource** | A table with a `defineTable()` default export. Each resource gets its own CRUD API endpoints (`GET`, `POST`, `PATCH`, `DELETE`, plus batch operations). Example: `candidates.ts` with `defineTable()` generates `/api/v1/candidates`. |\n| **Internal Table** | A Drizzle table exported WITHOUT `defineTable()`. Used as supporting data (junction tables, lookup tables) — no API routes generated. |\n| **Definition** | A TypeScript file in `quickback/features/` that defines a table schema and/or security configuration. |\n| **Compilation** | The process of transforming your definitions into production-ready code: routes, middleware, types, and migrations. |\n\n## Security Layers\n\n| Term | Definition |\n|------|-----------|\n| **Firewall** | Row-level data isolation. Automatically adds WHERE clauses (e.g., `WHERE organizationId = ?`) to every query so users only see data they should. |\n| **Access** | CRUD operation permissions. Controls which roles can perform list, get, create, update, and delete operations. |\n| **Guards** | Field-level write protection. Controls which fields can be set on create (`createable`), modified on update (`updatable`), changed only via actions (`protected`), or never changed after creation (`immutable`). |\n| **Masking** | Field-level read protection. Redacts sensitive values (SSN, email, phone) in API responses based on the user's role. |\n| **Views** | Column-level projections. Named subsets of fields (e.g., \"summary\", \"full\") with their own access control. Accessed via `GET /api/v1/{resource}/views/{name}`. |\n\n## Actions\n\n| Term | Definition |\n|------|-----------|\n| **Action** | Custom business logic endpoint beyond CRUD. Defined with `defineActions()` in an `actions.ts` file. |\n| **Record Action** | An action that operates on a specific record (`POST /api/v1/{resource}/:id/{action}`). Receives the record in the handler. Example: `POST /api/v1/applications/:id/advance-stage`. |\n| **Standalone Action** | An action not tied to a specific record (`POST /api/v1/{resource}/{action}`). Used for hiring reports, AI resume screening, bulk candidate imports. |\n| **Scoped DB** | The security-filtered database handle passed to action handlers. Automatically applies firewall, soft-delete, and org isolation. |\n| **Unsafe Mode** | When an action enables `unsafe` (prefer object form), it receives `rawDb` for explicit admin/cross-tenant operations. Cross-tenant mode requires admin role + audit trail. |\n\n## Configuration\n\n| Term | Definition |\n|------|-----------|\n| **`defineTable()`** | The function that combines a Drizzle schema with security configuration. Imported from `@quickback/compiler`. |\n| **`defineActions()`** | The function that defines custom actions for a table. Imported from `@quickback/compiler`. |\n| **`defineConfig()`** | The function that configures your Quickback project (runtime, database, auth providers). Lives in `quickback/quickback.config.ts`. |\n| **Audit Fields** | Auto-injected columns: `createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`, `deletedAt`, `deletedBy`. You don't define these — the compiler adds them. |\n| **Soft Delete** | Default delete behavior. Sets `deletedAt` instead of removing the row. Soft-deleted records are filtered from queries automatically. |\n| **Hard Delete** | Permanent row removal. Configured per-resource with `delete: { mode: \"hard\" }`. |\n\n## Infrastructure\n\n| Term | Definition |\n|------|-----------|\n| **Cloud Compiler** | The remote compilation service at `compiler.quickback.dev`. The CLI sends your definitions and receives generated code back. |\n| **Stack** | The runtime infrastructure (Cloudflare Workers, D1, KV, R2, Better Auth) where your compiled API runs. |\n| **Template** | A pre-configured project starter (`cloudflare`, `bun`, `turso`) created by `quickback create`. |"
@@ -105,9 +109,13 @@ export const DOCS = {
105
109
  "title": "Encryption",
106
110
  "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."
107
111
  },
112
+ "compiler/definitions/feature-areas": {
113
+ "title": "Feature Areas - Hierarchical Authz Grouping",
114
+ "content": "Group related features under one **area** folder. The area's `_area.ts` file declares a route\nprefix, admission lanes, and an authorization vocabulary — relationships, roles, rules, tenant\nanchors, scope kinds — that every feature **inside the folder** inherits by name. Features\noutside the folder cannot reference any of it: the compiler fails the build.\n\n> Naming note: this concept is an **area**. `domain` in Quickback always means a DNS custom\n> domain (see [custom domains](/compiler/config/domains)).\n\n## Why\n\nCross-cutting authz for a concept like a project, an event, or a location used to live in the\nroot `quickback.config.ts` and was wired to its consumers by a path-prefix string across a flat\nfeature list. An area makes the grouping **structural**: the folder *is* the boundary, the\n`_area.ts` *is* the single declaration site, and the compiler enforces that the vocabulary\nnever leaks outside the subtree.\n\n## Layout\n\n```\nquickback/features/\n├── workspace/ ← AREA (has _area.ts)\n│ ├── _area.ts ← defineArea({...})\n│ ├── projects.ts ← the area folder may itself be a feature\n│ ├── project_collaborators.ts\n│ ├── tasks/ ← child feature\n│ │ ├── tasks.ts\n│ │ └── actions/addTask.ts\n│ └── chat/ ← child feature\n│ └── actions/postMessage.ts\n└── billing/ ← flat feature (unchanged)\n```\n\nReserved sub-directories (`actions/`, `handlers/`, `lib/`, `pages/`) are never child features. A directory\n**without** `_area.ts` is a leaf feature — its unreserved subdirectories are not loaded, and a\nsubdirectory containing `defineTable(...)` / `defineAction(...)` **fails the compile** (silent\nroute/table disappearance after a mis-move is the failure mode areas must never introduce).\nFeature leaf names stay globally unique — they key `src/features/<name>/` in the output, so\nmoving a feature into an area changes nothing about its generated identity.\n\n## `_area.ts`\n\n```typescript\n// features/workspace/_area.ts\n\nexport default defineArea({\n // Namespace identity — drives the emitted routes file name and errors.\n name: 'projectScope',\n\n // Inherited route mount + admission gate. Optional: an area with no\n // prefix contributes shared vocabulary only. A prefix REQUIRES at least\n // one `via` lane (a mounted prefix with no gate would be ungated).\n prefix: '/project/:projectId',\n via: ['collaboratorOf', { roles: ['admin', 'owner'] }],\n mintScope: true,\n acceptScope: 'project',\n\n // Area-owned vocabulary — the EXACT same shapes as the root authz blocks.\n relationships: {\n collaboratorOf: {\n from: 'project_collaborators',\n subject: { column: 'collaboratorUserId', equals: 'ctx.userId' },\n resource: { column: 'projectId' },\n where: { status: 'active' },\n loads: 'projects',\n exposeAs: 'project',\n },\n },\n roles: {\n projectStaff: { or: [{ via: 'collaboratorOf' }, { roles: ['admin', 'owner'] }] },\n },\n scopes: {\n project: {\n requestField: 'projectId',\n roles: { collaborator: { via: 'collaboratorOf', subject: 'both' } },\n },\n },\n // Named gates + tenant anchors work too — same shapes as authz.rules /\n // authz.tenants, visible to this subtree only.\n});\n```\n\nA descendant feature references everything by bare name — no imports, no root declaration:\n\n```typescript\n// features/workspace/tasks/actions/addTask.ts\nexport default defineAction({\n path: './tasks/add', // relative → /project/:projectId/tasks/add\n access: { roles: ['projectStaff'] }, // resolves against the area\n // ...\n});\n```\n\n## The visibility contract\n\nAn area's names are visible to **its own subtree only** (the area folder, its features, and\nnested areas). The compiler checks **every** reference channel — access `roles:` arrays\n(including named gates and both spellings of scoped roles: bare aliases and\n`scope:<kind>:<role>`), action `access` and `anchor:`, firewall `via:` arms,\n`ctx.scope.<kind>` accessors, `{ rule }` and `{ tenant }` firewall references, auth-view\n`tenant:` includes, `realtime.requiredRoles`, table-level `namespace.via` lanes, and other\n`_area.ts` nodes. Referencing an area name from outside is always a compile error:\n\n```\nFeature \"billing\" ... references role \"projectStaff\" declared by area \"projectScope\"\n(features/workspace/_area.ts), but this site is not inside that area. ... move the\nreferencing code under the declaring area, or lift the declaration to root authz if it\nis genuinely global.\n```\n\nTwo structural rules keep the fold sound:\n\n- **No overrides (v1).** Re-declaring an inherited name — in any class, including scope kinds,\n scoped-role aliases, and namespace names — is a compile error. Declare each name in exactly\n one place. (`overrides:` marker syntax is reserved for a future release.)\n- **Declaration-site rule.** Root `authz` bodies (roles, rules, tenants, scopes, namespaces)\n may reference **root-declared names only** — a root definition is visible everywhere and\n would launder an area name out of its subtree. An area's bodies may reference root ∪\n ancestors ∪ self.\n\nOne deliberate exception: root-config **namespace-identity wiring** — today exactly\n`realtime.wsTicket.namespace` — may name an area's namespace. It attaches the area's complete\ngate (its full lane set) and constructs no new grant. Such consumers are listed in the\nmanifest under the owning area.\n\n## Containment and the `route: 'self'` marker\n\nThe area's prefix is an audited surface:\n\n- A feature **outside** the area may not declare an action path (or a table-level\n `namespace` prefix) under the area's prefix — compile error.\n- A project-level `authz.namespaces` entry the area does **not** own — root-declared, or\n another area's — may not carve a prefix at or under the area's prefix. Namespace claiming\n is longest-prefix-wins, so such an entry would silently re-gate the area's descendant\n actions with its own `via` lanes — compile error. (A *descendant* feature's table-level\n namespace inside the prefix is legal; the manifest attributes its claimed actions to that\n namespace, not to the area.)\n- A **descendant** action whose absolute path is *outside* the prefix opts out of the area's\n admission gate and is gated solely by its own `access:`. That must be explicit:\n mark the action `route: 'self'`, or the compile fails (a typo'd prefix must never silently\n self-gate). The marker is equally rejected where it is dead — on in-prefix actions and in\n features outside any mounted area. Every self-gated action is listed in the manifest.\n\nRelative paths (`path: './…'`) resolve against the area prefix. Dot segments (`.` / `..`) are\nrejected outright — the resolved route must stay under the prefix.\n\n## Nested areas\n\nAreas nest to arbitrary depth. A nested area may declare additional **vocabulary** freely. A\nnested area may **not** mount its own `prefix` under an ancestor that already mounts one:\nper-level nested admission is *unlinked* (a caller related to child instance S under parent A\nwould be admitted at `/a/A/s/S` even when S belongs to parent B), and Quickback refuses to\ncompile an unlinked gate. Mount one prefix per chain, or keep the nested area\nvocabulary-only.\n\n## The capability floor: `requires: ['feature-areas']`\n\nAn area-tree project **must** declare the marker in `quickback.config.ts`:\n\n```typescript\nexport default defineConfig({\n // ...\n requires: ['feature-areas'],\n});\n```\n\nAny CLI — including one that predates areas — passthrough-executes the config, so the marker\nalways reaches the compiler. A current compiler that sees the marker but no `areas` payload\nrejects the compile with an upgrade message instead of silently compiling a project whose\nnested features an old CLI never loaded (which would otherwise generate destructive\nmigrations). In the other direction, a current CLI refuses output from a compiler that\npredates areas.\n\n## The authz manifest\n\nArea projects emit `quickback/authz-manifest.json` on every compile — the audit inventory the\nflat config can no longer answer from one file: the area tree, every folded name and its\ndeclaring file, per-area member features, `areaGatedActions` vs `selfGatedActions`, and any\nroot-config namespace consumers. Review it in PRs the way you review the security reports;\nthe generated `AGENTS.md` also gains a feature-areas section so coding agents place new\nfeatures correctly.\n\n## What belongs at root\n\nRoot `authz` remains the home for genuinely global vocabulary — names used across areas or by\nflat features. Everything scoped to one concept belongs in that concept's `_area.ts`. When in\ndoubt: if only one folder's features reference it, it belongs in that folder's area."
115
+ },
108
116
  "compiler/definitions/feature": {
109
117
  "title": "feature() — the canonical form",
110
- "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."
118
+ "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\nFeature directories normally sit flat under `features/`. To group several features under one\nauthz concept (a shared route prefix + shared relationships/roles/scopes), put them inside an\n**area** folder carrying `_area.ts` — see [Feature areas](/compiler/definitions/feature-areas).\nReserved sub-directories (`actions/`, `lib/`, `pages/`) are never child features, and a\nsubdirectory of a NON-area feature containing `defineTable(...)`/`defineAction(...)` fails the\ncompile (nested features load only under an area).\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## Composition vs reference — `owns`\n\nA schema-level FK (`references:` / `.references()`) says \"this row points at\nthat row.\" It does **not** say who owns whom. When a set of child rows has no\nlifecycle of its own — junction memberships, normalized phones/emails, line\nitems — declare the composition with `owns` on the root table:\n\n```ts\nexport default feature(\"projects\", {\n // ...\n owns: {\n tasks: { table: \"tasks\", fk: \"projectId\", inherit: [\"organizationId\"] },\n members: { table: \"projectMembers\", fk: \"projectId\", refs: { personId: \"people\" }, inherit: [\"organizationId\"] },\n },\n});\n```\n\nThat single fact generates the whole aggregate write path — one atomic\nchangeset request over the root plus its owned relations, every op paying the\nchild's own firewall/access/guards. Keep plain `references` for pointers at\nindependent entities (those go in the relation's `refs`, existence-checked\nper-tenant). Contract v2 only. Full reference:\n[changesets](/compiler/definitions/changesets) — including the per-op\n`routes: false` knob for widening a child's access for changeset use without\nmounting its raw route.\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."
111
119
  },
112
120
  "compiler/definitions/fga": {
113
121
  "title": "FGA - Relationship-Based Access (Zanzibar)",
@@ -115,19 +123,19 @@ export const DOCS = {
115
123
  },
116
124
  "compiler/definitions/firewall": {
117
125
  "title": "Firewall - Data Isolation",
118
- "content": "The firewall generates WHERE clauses automatically to isolate data by user, organization, or team.\n\n## Basic Usage\n\nThe cleanest pattern is `q.scope()` — declare the tenant column once and the firewall is auto-derived:\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 organizationId: q.scope('organization'), // Auto-derives the firewall\n },\n // No firewall: block needed — auto-derived as\n // [{ field: 'organizationId', equals: 'ctx.activeOrgId' },\n // { field: 'deletedAt', isNull: true }]\n // ... guards, crud, read\n});\n```\n\nIf you need to declare the firewall explicitly, two forms are accepted — pick whichever reads better:\n\n**Named-scope** (compact, default for simple overrides):\n\n```typescript\nfirewall: { organization: { column: 'tenant_id' } }\nfirewall: { owner: { column: 'account_user_id' } }\nfirewall: { exception: true } // opt out of tenant scoping entirely\n```\n\n**Predicate array** (explicit, required for `in`-lists or custom non-scope predicates):\n\n```typescript\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n]\n```\n\nBoth shapes compile to the same canonical predicate array internally — the named-scope object is coerced at parse time. Pick by readability.\n\n## Auto-detected column synonyms\n\nWhen you omit the `firewall:` block entirely, the compiler scans the schema for one of these isolation columns and auto-derives the predicates:\n\n| Scope | Accepted column names |\n|---|---|\n| Organization | `organizationId`, `organisationId`, `orgId`, `organization`, `organisation`, `org` |\n| User | `userId` |\n| Team | `teamId` |\n\n`ownerId` is **not** auto-detected — it's reserved for business-logic ownership (who owns this record), not access control. A table that has only `ownerId` and no isolation column raises a targeted error explaining the distinction; either rename to `userId` if the column controls access, add an isolation column, or specify `firewall:` explicitly.\n\n## Predicate Shape\n\n```typescript\ntype FirewallPredicate =\n | { field: string; equals: string; optional?: boolean; nullable?: true } // column = ctx.* (or literal)\n | { field: string; isNull: true } // column IS NULL\n | { field: string; in: string[] | string; optional?: boolean } // column IN (...)\n | { field: string; via: string } // column IN (relationship subquery)\n | { field?: string; permission: string } // named authz.permissions reference (v0.35+)\n | { all: FirewallPredicate[] } // AND group (v0.35+)\n | { any: FirewallPredicate[] } // OR group (v0.35+)\n | { exception: true }; // opt out of tenant scoping\n\ntype FirewallConfig = ReadonlyArray<FirewallPredicate>;\n\n// Resource top-level (sibling to `firewall:`)\nfirewallErrorMode?: 'reveal' | 'hide';\n```\n\nThe top-level array is AND'd together. `firewallErrorMode` lives at the resource top level — it's a presentation-layer choice (403 vs 404), not a query-shape one.\n\n## Boolean groups: `all` / `any` (v0.35+)\n\nA flat array can only express AND. To grant access through **either** of two independent paths — \"an org member **OR** an event attendee\" — nest an `any` group. The top-level array stays sugar for `all`, so every existing firewall is byte-identical.\n\n```typescript\nfirewall: {\n any: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' }, // org-member grant\n { field: 'eventId', equals: 'ctx.scope.event' }, // attendee grant (token-verified)\n ],\n}\n```\n\nNull-safe scope semantics make this safe (these apply **inside `all`/`any` groups**, opt-in via the new syntax):\n\n- A **scope** arm (`ctx.activeOrgId`, `ctx.activeTeamId`, `ctx.scope.*`) whose claim is **absent never binds `undefined`** (the classic 500 / \"match every row\" trap). In an `any` group an absent arm **drops**; if **every** arm drops, the group denies with `sql\\`1 = 0\\`` (the empty-guard) — never a full-table read. In an `all` group an absent required scope **denies** the group.\n- Mark an arm `{ optional: true }` to **drop-instead-of-deny** when absent inside an `all` group (the teamless rest-of-org slice — `ctx.activeTeamId` is implicitly optional).\n- **Owner** (`ctx.userId`) and **soft-delete** (`isNull deletedAt`) are always present / always AND'd — never relaxed.\n\n`nullable: true` is a separate database-schema opt-in, supported only on an\nowner predicate whose source is exactly `ctx.userId`. It allows the persisted\nowner column to be NULL; NULL rows still do not match the owner arm because SQL\nequality never matches NULL. It does not make the request claim optional.\n\n```typescript\n// (org OR event) AND owner AND not-deleted\nfirewall: {\n all: [\n { any: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', equals: 'ctx.scope.event' },\n ] },\n { field: 'ownerId', equals: 'ctx.userId' },\n ],\n}\n```\n\nThe `ctx.scope.*` arms are how **relationship-derived scopes** (attendees, shuttle drivers, vendors) reach event-scoped rows without org membership — see [Scopes & capability grants](/compiler/definitions/scopes).\n\n## Relationship-based scoping (`via:`)\n\nFor relationship authorization — \"this user can see rows X if they have a confirmed `event_guests` row pointing at X\" — declare the relationship under `authz.relationships` in `quickback.config.ts`, then reference it from `firewall:` with a `via:` predicate:\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests', // table name\n subject: { column: 'userId', equals: 'ctx.userId' }, // caller side\n resource: { column: 'eventId' }, // resource side\n where: { status: 'confirmed' }, // optional row filter\n },\n },\n}\n\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' },\n]\n```\n\nCompiles to:\n\n```sql\nWHERE sessions.organizationId = ?\n AND sessions.eventId IN (\n SELECT eventId FROM event_guests\n WHERE userId = ?\n AND status = 'confirmed'\n AND <event_guests' own firewall — tenant scope + soft-delete>\n )\n```\n\nKey properties:\n\n- **Firewall stays the outermost AND.** A guest of an event in another tenant is still blocked by your tenant predicate. Relationship-based scoping never bypasses tenant isolation.\n- **The relationship table's own firewall is AND'd into the subquery.** Soft-deleting a `event_guests` row revokes access immediately; cross-tenant relationship rows can't grant access.\n- **Anonymous callers fail closed.** `ctx.userId` is null-guarded; the subquery short-circuits to `WHERE 1 = 0` for unauthenticated requests.\n- **The relationship table must be tenant-scoped** (`firewall: { exception: true }` is rejected at compile time on relationship tables).\n\nSee [Access — relationships](/compiler/definitions/access#authz-relationships) for the full `authz.relationships` shape and role-binding patterns.\n\n## Named permissions (`{ permission }`)\n\nA `via:` arm references **one** relationship. When the same grant rule —\n\"organizer **or** confirmed attendee\" — recurs across several resources,\nname it **once** under `authz.permissions` and reference it from any\nfirewall with a `{ permission }` arm. See [Permissions](/compiler/definitions/permissions)\nfor the full DSL.\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: { organizerOf: { /* … */ }, attendeeOf: { /* … */ } },\n permissions: {\n 'event:view': { anyOf: ['organizerOf', 'attendeeOf'] },\n },\n}\n\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', permission: 'event:view' },\n]\n```\n\nThe compiler lowers `{ permission }` to the same `all` / `any` relationship\nsubqueries the expression names — `anyOf` becomes an OR of subqueries,\n`allOf` an AND. `field` is the resource-side column those subqueries\nconstrain (the same column you'd put on a `via:` arm).\n\nA permission referenced from a firewall can also resolve an\n[**arrow**](/compiler/definitions/arrows) — an `{ arrowRef, permission }`\nleaf that traverses a foreign key to inherit authority from a parent object\n(\"org admins of the event's org can see its announcements\", \"anyone who\nadministers an ancestor folder can read this one\"). An arrow leaf lowers to\nan FK-hop subquery (non-recursive) or a bounded `WITH RECURSIVE` CTE\n(self-FK hierarchy), tenant-constrained at every row.\n\n**M1 limit — firewall arms must be SQL-pushable.** A firewall runs as a\nWHERE clause, so a permission referenced from one may only resolve to\nrelationship subqueries. A permission whose expression contains a\n**claim-site leaf** (`{ role }`, `{ scopeRole }`, `{ pseudoRole }`) or a\n`not` is rejected at compile time when referenced from a firewall — those\nshapes are valid in the DSL but reserved for future claim/runtime\nenforcement sites. Use a role gate on `read.access` / `crud.*.access` for\nmembership checks.\n\nThe compile-time analyzer additionally flags a referenced permission that can\nnever be satisfied, an arm shadowed by a broader one, and the SQL / CTE cost\nof each permission — see [Diagnostics](/compiler/definitions/diagnostics).\n\n## Context Sources\n\nWhen `equals` references the request context, use these standard sources:\n\n| Source | Description |\n|--------|-------------|\n| `ctx.userId` | Current authenticated user's ID |\n| `ctx.activeOrgId` | User's active organization ID |\n| `ctx.activeTeamId` | User's active team ID |\n\nThese values are populated by the auth middleware from the user's session. Any predicate where `equals` starts with `ctx.` is treated as server-derived: the column lands in `GUARDS_CONFIG.systemManaged` (clients cannot submit it) and is auto-populated on create / upsert from the context.\n\n## Auto-Derivation\n\nWhen the `firewall:` block is omitted, the compiler scans the schema for known scope columns and synthesises the predicate array:\n\n| Column found | Predicate emitted |\n|--------------|-------------------|\n| `organizationId` / `organisationId` / `orgId` / `organization` / `organisation` / `org` | `{ field: '...', equals: 'ctx.activeOrgId' }` |\n| `userId` | `{ field: 'userId', equals: 'ctx.userId' }` |\n| `teamId` | `{ field: 'teamId', equals: 'ctx.activeTeamId' }` |\n| `deletedAt` (always present via audit injection) | `{ field: 'deletedAt', isNull: true }` — appended automatically whenever the schema carries the column, regardless of which firewall shape you wrote |\n\n`q.scope(kind)` is the canonical way to declare the column — auto-derivation works the same way for plain `q.text().required()` or Drizzle `text(...).notNull()` columns named to match the convention.\n\n**Rules:**\n- Exactly one isolation column → auto-derived.\n- Zero columns AND no PUBLIC route → compile-time error (\"missing isolation column\").\n- Two or more (e.g. `organizationId` + `ownerId`) → compile-time error; declare `firewall:` explicitly.\n\n## What `{ exception: true }` Actually Does\n\n`{ exception: true }` disables **tenant scoping only** — the generated `buildFirewallConditions()` emits no tenant `WHERE` clauses. It does **not** affect:\n\n- **Audit field injection.** `createdAt`, `modifiedAt`, `createdBy`, `modifiedBy`, `deletedAt`, `deletedBy` are always added to every table unless you disable them globally with `compiler.features.auditFields: false`.\n- **Soft-delete filtering.** If the table has a `deletedAt` column (which it does by default, thanks to audit injection), the firewall still emits `isNull(<table>.deletedAt)` so soft-deleted records stay hidden. To opt out of soft-delete filtering on an exception resource, either set `compiler.features.auditFields: false` globally or hand-author a schema without `deletedAt`.\n\nSo `firewall: [{ exception: true }]` on the default configuration returns `isNull(<table>.deletedAt)` from `buildFirewallConditions()` — no tenant filter, soft-delete filter still applied.\n\n## Sysadmin Escape Hatch\n\nWhen `cms: { sysadmin: true }` is set on the project (introduced in v0.15.0), every `buildFirewallConditions()` emits a runtime branch that drops tenant scopes for `ctx.userRole === 'sysadmin'` callers while keeping the soft-delete predicate:\n\n```typescript\n// Generated for an org-scoped table when cms.sysadmin: true\nexport function buildFirewallConditions(ctx: AppContext): SQL | undefined {\n if (ctx.userRole === 'sysadmin') {\n return isNull(invoices.deletedAt); // tenant predicate dropped, soft-delete kept\n }\n return and(\n eq(invoices.organizationId, ctx.activeOrgId!),\n isNull(invoices.deletedAt),\n );\n}\n```\n\nThe escape branch is **only** emitted when:\n\n- `cms.sysadmin: true` is set on the project config\n- The table has at least one tenant-scope predicate (org / owner / team / `via:` relationship). Tables with no tenant scopes already return what a sysadmin would see, so the runtime check would be dead code.\n- The firewall does not declare `{ exception: true }` (no tenant scopes to drop).\n\n**Sysadmin is distinct from appmanager.** `userRole === 'appmanager'` callers still go through the firewall normally — only `userRole === 'sysadmin'` triggers the bypass. Appmanager is the platform control-plane tier, expressed with plain `userRole` checks; sysadmin is the opt-in cross-tenant DB-admin tier. See [CMS Configuration](/compiler/config#cms-configuration).\n\nIf your project doesn't set `cms.sysadmin: true`, the escape branch is never emitted and the role value is functionally inert.\n\n## Common Patterns\n\n```typescript\n// Public/system table - no tenant filtering (soft-delete still applied)\nfirewall: [{ exception: true }]\n\n// Organization-scoped (auto-derived when organizationId is present — block can be omitted)\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n]\n\n// User-owned personal data\nfirewall: [\n { field: 'ownerId', equals: 'ctx.userId' },\n { field: 'deletedAt', isNull: true },\n]\n\n// Multi-tenant + per-team scoping\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'teamId', equals: 'ctx.activeTeamId' },\n { field: 'deletedAt', isNull: true },\n]\n\n// Custom ctx field\nfirewall: [\n { field: 'workspaceId', equals: 'ctx.activeWorkspaceId' },\n]\n\n// Status-gated (literal value, not ctx-derived — does NOT add to systemManaged)\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'status', in: ['active', 'pending'] },\n]\n```\n\n## Error Responses\n\nWhen a record isn't found behind the firewall (wrong org, soft-deleted, or genuinely doesn't exist), the error response depends on `firewallErrorMode`:\n\n### Reveal Mode (Default)\n\nReturns **403** 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\nThis is developer-friendly and helps debug access issues during development.\n\n### Hide Mode\n\nReturns **404** with a generic error:\n\n```json\n{\n \"error\": \"Not found\",\n \"code\": \"NOT_FOUND\"\n}\n```\n\nUse `firewallErrorMode: 'hide'` for security-hardened deployments where you don't want attackers to distinguish between \"record exists but you can't access it\" and \"record doesn't exist\":\n\n```typescript\nexport default defineTable(records, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n firewallErrorMode: 'hide', // Opaque 404s prevent record enumeration\n});\n```\n\n### Foreign-Key Referential Checks\n\nGenerated `POST /` and `POST /batch` handlers validate every foreign-key column against the **target table's** firewall before inserting. If a record references a row that the caller can't see (wrong org, soft-deleted, or non-existent), the request fails with:\n\n```json\n{\n \"error\": \"Referenced jobs row not found\",\n \"code\": \"FK_NOT_FOUND\",\n \"layer\": \"validation\",\n \"field\": \"jobId\"\n}\n```\n\nThis closes a cross-tenant injection vector: even if an attacker knows a foreign tenant's row ID, they cannot attach a child record to it, and they cannot trigger a cross-tenant cascade delete. The check uses the target table's `buildXFirewallConditions(ctx)` helper, so it honors whatever firewall predicates the target declared (organization, owner, team, custom). FKs to tables with `{ exception: true }` get a plain existence check (still verifies the row exists, doesn't tenant-scope it).\n\nThe check runs after guards but before the insert, so it appears as `layer: \"validation\"` in error responses. Status code is `400`, not `404` — returning `404` would leak existence of out-of-scope rows.\n\n### Pre-Record ID-Probe Defense\n\nIndependent of `firewallErrorMode`, generated `/:id` handlers run a\n**role-only access check before** the firewall query (see\n[Access ordering](/compiler/definitions/access#evaluation-order)). A caller\nwithout the right role gets 403 before the database is touched, so they\ncan't distinguish \"row exists out-of-scope\" from \"row doesn't exist\" via\nresponse timing or status differences.\n\n`firewallErrorMode` controls what happens **after** the role check passes\nbut the firewall hides the row — i.e., when an authorized caller asks for\na record in another tenant. Use `'hide'` to make that case indistinguishable\nfrom a non-existent ID.\n\n## Rules\n\n- Every resource MUST have at least one tenant predicate OR `{ exception: true }` OR a PUBLIC route\n- `{ exception: true }` cannot be combined with tenant predicates in the same array\n\n## Why Can't You Mix `{ exception: true }` with Tenant Predicates?\n\nThey represent opposite intentions:\n- `{ exception: true }` = \"Don't generate tenant `WHERE` clauses, data is public/global\"\n- Tenant predicates = \"Generate tenant `WHERE` clauses to isolate data\"\n\nCombining them would be contradictory — you can't both isolate and not isolate. (Note: soft-delete filtering is independent of this decision, see above.)\n\n## Handling \"Some Public, Some Private\" Data\n\nIf you need records that are sometimes public and sometimes scoped, you have two options:\n\n### Option 1: Two Separate Tables\n\nSplit into two tables - one public, one scoped:\n\n```typescript\n// features/job-templates/template-library.ts - Public job templates\nexport default defineTable(templateLibrary, {\n firewall: [{ exception: true }],\n // ...\n});\n\n// features/job-templates/custom-templates.ts - Org's custom job templates\nexport default defineTable(customTemplates, {\n firewall: [{ field: 'ownerId', equals: 'ctx.userId' }],\n // ...\n});\n```\n\n### Option 2: Use Access Control Instead\n\nKeep tenant scope but make access permissive, then control visibility via `access`:\n\n```typescript\n// features/jobs/jobs.ts\nexport default defineTable(jobs, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: {\n // Anyone in the org can list — visibility differences are handled\n // via record-level access conditions on /:id\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n // Use record conditions to allow public jobs OR owned jobs on GET /:id\n // (single-record GET inherits read.access, with optional record-level overrides)\n // ...\n});\n```\n\n### Which to Choose?\n\n| Scenario | Recommendation |\n|----------|----------------|\n| Truly global data (app config, public job templates) | `exception: true` in separate resource |\n| \"Public within org\" but still org-isolated | Ownership scope + permissive access rules |\n| Recruiter can toggle job postings public/private | Ownership scope + `visibility` field + access conditions |"
126
+ "content": "The firewall generates WHERE clauses automatically to isolate data by user, organization, or team.\n\n## Basic Usage\n\nThe cleanest pattern is `q.scope()` — declare the tenant column once and the firewall is auto-derived:\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 organizationId: q.scope('organization'), // Auto-derives the firewall\n },\n // No firewall: block needed — auto-derived as\n // [{ field: 'organizationId', equals: 'ctx.activeOrgId' },\n // { field: 'deletedAt', isNull: true }]\n // ... guards, crud, read\n});\n```\n\nIf you need to declare the firewall explicitly, two forms are accepted — pick whichever reads better:\n\n**Named-scope** (compact, default for simple overrides):\n\n```typescript\nfirewall: { organization: { column: 'tenant_id' } }\nfirewall: { owner: { column: 'account_user_id' } }\nfirewall: { exception: true } // opt out of tenant scoping entirely\n```\n\n**Predicate array** (explicit, required for `in`-lists or custom non-scope predicates):\n\n```typescript\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n]\n```\n\nBoth shapes compile to the same canonical predicate array internally — the named-scope object is coerced at parse time. Pick by readability.\n\n## Auto-detected column synonyms\n\nWhen you omit the `firewall:` block entirely, the compiler scans the schema for one of these isolation columns and auto-derives the predicates:\n\n| Scope | Accepted column names |\n|---|---|\n| Organization | `organizationId`, `organisationId`, `orgId`, `organization`, `organisation`, `org` |\n| User | `userId` |\n| Team | `teamId` |\n\n`ownerId` is **not** auto-detected — it's reserved for business-logic ownership (who owns this record), not access control. A table that has only `ownerId` and no isolation column raises a targeted error explaining the distinction; either rename to `userId` if the column controls access, add an isolation column, or specify `firewall:` explicitly.\n\n## Predicate Shape\n\n```typescript\ntype FirewallPredicate =\n | { field: string; equals: string; optional?: boolean; nullable?: true } // column = ctx.* (or literal)\n | { field: string; isNull: true } // column IS NULL\n | { field: string; in: string[] | string; optional?: boolean } // column IN (...)\n | { field: string; via: string } // column IN (relationship subquery)\n | { field?: string; permission: string } // named authz.permissions reference (v0.35+)\n | { all: FirewallPredicate[] } // AND group (v0.35+)\n | { any: FirewallPredicate[] } // OR group (v0.35+)\n | { exception: true }; // opt out of tenant scoping\n\ntype FirewallConfig = ReadonlyArray<FirewallPredicate>;\n\n// Resource top-level (sibling to `firewall:`)\nfirewallErrorMode?: 'reveal' | 'hide';\n```\n\nThe top-level array is AND'd together. `firewallErrorMode` lives at the resource top level — it's a presentation-layer choice (403 vs 404), not a query-shape one.\n\n## Boolean groups: `all` / `any` (v0.35+)\n\nA flat array can only express AND. To grant access through **either** of two independent paths — \"an org member **OR** an event attendee\" — nest an `any` group. The top-level array stays sugar for `all`, so every existing firewall is byte-identical.\n\n```typescript\nfirewall: {\n any: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' }, // org-member grant\n { field: 'eventId', equals: 'ctx.scope.event' }, // attendee grant (token-verified)\n ],\n}\n```\n\nNull-safe scope semantics make this safe (these apply **inside `all`/`any` groups**, opt-in via the new syntax):\n\n- A **scope** arm (`ctx.activeOrgId`, `ctx.activeTeamId`, `ctx.scope.*`) whose claim is **absent never binds `undefined`** (the classic 500 / \"match every row\" trap). In an `any` group an absent arm **drops**; if **every** arm drops, the group denies with `sql\\`1 = 0\\`` (the empty-guard) — never a full-table read. In an `all` group an absent required scope **denies** the group.\n- Mark an arm `{ optional: true }` to **drop-instead-of-deny** when absent inside an `all` group (the teamless rest-of-org slice — `ctx.activeTeamId` is implicitly optional).\n- **Owner** (`ctx.userId`) and **soft-delete** (`isNull deletedAt`) are always present / always AND'd — never relaxed.\n\n`nullable: true` is a separate database-schema opt-in, supported only on an\nowner predicate whose source is exactly `ctx.userId`. It allows the persisted\nowner column to be NULL; NULL rows still do not match the owner arm because SQL\nequality never matches NULL. It does not make the request claim optional.\n\n```typescript\n// (org OR event) AND owner AND not-deleted\nfirewall: {\n all: [\n { any: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', equals: 'ctx.scope.event' },\n ] },\n { field: 'ownerId', equals: 'ctx.userId' },\n ],\n}\n```\n\nThe `ctx.scope.*` arms are how **relationship-derived scopes** (attendees, shuttle drivers, vendors) reach event-scoped rows without org membership — see [Scopes & capability grants](/compiler/definitions/scopes).\n\n## Relationship-based scoping (`via:`)\n\nFor relationship authorization — \"this user can see rows X if they have a confirmed `event_guests` row pointing at X\" — declare the relationship under `authz.relationships` in `quickback.config.ts`, then reference it from `firewall:` with a `via:` predicate. These relationships (and the named roles/permissions built on them) are defined once, centrally — see [Centrally defined access rules](/compiler/definitions/access#centrally-defined-access-rules).\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests', // table name\n subject: { column: 'userId', equals: 'ctx.userId' }, // caller side\n resource: { column: 'eventId' }, // resource side\n where: { status: 'confirmed' }, // optional row filter\n },\n },\n}\n\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' },\n]\n```\n\nCompiles to:\n\n```sql\nWHERE sessions.organizationId = ?\n AND sessions.eventId IN (\n SELECT eventId FROM event_guests\n WHERE userId = ?\n AND status = 'confirmed'\n AND <event_guests' own firewall — tenant scope + soft-delete>\n )\n```\n\nKey properties:\n\n- **Firewall stays the outermost AND.** A guest of an event in another tenant is still blocked by your tenant predicate. Relationship-based scoping never bypasses tenant isolation.\n- **The relationship table's own firewall is AND'd into the subquery.** Soft-deleting a `event_guests` row revokes access immediately; cross-tenant relationship rows can't grant access.\n- **Anonymous callers fail closed.** `ctx.userId` is null-guarded; the subquery short-circuits to `WHERE 1 = 0` for unauthenticated requests.\n- **The relationship table must be tenant-scoped** (`firewall: { exception: true }` is rejected at compile time on relationship tables).\n\nSee [Access — relationships](/compiler/definitions/access#authz-relationships) for the full `authz.relationships` shape and role-binding patterns.\n\n## Named permissions (`{ permission }`)\n\nA `via:` arm references **one** relationship. When the same grant rule —\n\"organizer **or** confirmed attendee\" — recurs across several resources,\nname it **once** under `authz.permissions` and reference it from any\nfirewall with a `{ permission }` arm. See [Permissions](/compiler/definitions/permissions)\nfor the full DSL.\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: { organizerOf: { /* … */ }, attendeeOf: { /* … */ } },\n permissions: {\n 'event:view': { anyOf: ['organizerOf', 'attendeeOf'] },\n },\n}\n\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', permission: 'event:view' },\n]\n```\n\nThe compiler lowers `{ permission }` to the same `all` / `any` relationship\nsubqueries the expression names — `anyOf` becomes an OR of subqueries,\n`allOf` an AND. `field` is the resource-side column those subqueries\nconstrain (the same column you'd put on a `via:` arm).\n\nA permission referenced from a firewall can also resolve an\n[**arrow**](/compiler/definitions/arrows) — an `{ arrowRef, permission }`\nleaf that traverses a foreign key to inherit authority from a parent object\n(\"org admins of the event's org can see its announcements\", \"anyone who\nadministers an ancestor folder can read this one\"). An arrow leaf lowers to\nan FK-hop subquery (non-recursive) or a bounded `WITH RECURSIVE` CTE\n(self-FK hierarchy), tenant-constrained at every row.\n\n**M1 limit — firewall arms must be SQL-pushable.** A firewall runs as a\nWHERE clause, so a permission referenced from one may only resolve to\nrelationship subqueries. A permission whose expression contains a\n**claim-site leaf** (`{ role }`, `{ scopeRole }`, `{ pseudoRole }`) or a\n`not` is rejected at compile time when referenced from a firewall — those\nshapes are valid in the DSL but reserved for future claim/runtime\nenforcement sites. Use a role gate on `read.access` / `crud.*.access` for\nmembership checks.\n\nThe compile-time analyzer additionally flags a referenced permission that can\nnever be satisfied, an arm shadowed by a broader one, and the SQL / CTE cost\nof each permission — see [Diagnostics](/compiler/definitions/diagnostics).\n\n## Named tenant anchors (`{ tenant }`)\n\nThe tenant predicate `{ field: 'organizationId', equals: 'ctx.activeOrgId' }` tends to be repeated on every table. Declare it **once** as a named anchor and reference it by name:\n\n```typescript\n// quickback.config.ts\nauthz: {\n tenants: {\n org: { column: 'organizationId', equals: 'ctx.activeOrgId' },\n },\n}\n\n// any firewall — top level or inside all/any groups:\nfirewall: [\n { tenant: 'org' }, // → { field: 'organizationId', equals: 'ctx.activeOrgId' }\n { field: 'deletedAt', isNull: true },\n]\n\n// per-site COLUMN override (the claim side is never overridable):\nfirewall: [{ field: 'orgId', tenant: 'org' }]\n```\n\nThe anchor's `equals` must be a **verified ctx claim**: `ctx.activeOrgId` | `ctx.userId` | `ctx.scope.<kind>` | `ctx.scope.<kind>.<subKey>`. `ctx.activeTeamId` (drop-when-absent semantics stay a per-resource decision) and legacy aliases are rejected at declaration time — an anchor can never bind a request-derived value. A `{ tenant }` reference carrying its own `equals` is a compile error (one source of truth); an unknown anchor name is a compile error listing the declared anchors.\n\nExpansion happens at compile time, before rendering — the emitted SQL is byte-identical to writing the predicate inline. Auth-DB read views accept the same anchors as a string: [`tenant: 'org'`](/stack/realtime/live-views#auth-db-includes-source-auth) — with one extra constraint: an anchor referenced from an auth-view include must bind a single-segment session claim (`ctx.<claim>`); scope-principal claims (`ctx.scope.*`) are firewall-lane bindings and are rejected there.\n\n## Named gate references (`{ rule }`)\n\nA [gate](/compiler/definitions/access#named-gates-authzrules) that declares `firewall` lanes can be stamped onto a resource by name:\n\n```typescript\n// quickback.config.ts\nauthz: {\n rules: {\n eventRow: {\n who: { roles: ['owner', 'admin', 'member'] },\n firewall: [{ any: [\n { tenant: 'org' }, // org staff\n { field: 'eventId', equals: 'ctx.scope.event' }, // signed scope claim\n ] }],\n },\n },\n}\n\n// the resource:\nfirewall: [{ rule: 'eventRow' }]\n// composes with the resource's own lanes (top-level AND):\nfirewall: [{ rule: 'eventRow' }, { field: 'kind', equals: 'ctx.scope.event.kind' }]\n```\n\nSemantics — **AND-compose, top-level only, a reference can only narrow**:\n\n- The gate's lanes splice into the resource's **top-level AND array** in place. They never replace the resource's own lanes, and composition can only *narrow* the row set.\n- `{ rule }` is **not** valid inside an `{ all }` / `{ any }` group — a gate's firewall is one-or-more AND lanes, and splicing a multi-lane gate into an `any` group would OR-flatten it, admitting rows in **other tenants** that merely match one lane. This is a type error at authoring time and a compile error at coerce time.\n- A gate's firewall may not contain `{ exception: true }` (a named bundle can never smuggle a firewall opt-out) or another `{ rule }` (gates don't nest — expansion is single-step, so cycles are impossible by construction).\n- A gate with **no** `firewall` arm referenced from `firewall:` is a compile error — a who/record-only gate would silently contribute zero row lanes while the `record:` filter only ever applies at access sites.\n\nThe splice expands before validation and rendering, so the emitted `buildFirewallConditions` helper is byte-identical to writing the lanes inline — same groups, same absent-claim `1 = 0` guards, same `via:` subqueries.\n\n## Context Sources\n\nWhen `equals` references the request context, use these standard sources:\n\n| Source | Description |\n|--------|-------------|\n| `ctx.userId` | Current authenticated user's ID |\n| `ctx.activeOrgId` | User's active organization ID |\n| `ctx.activeTeamId` | User's active team ID |\n\nThese values are populated by the auth middleware from the user's session. Any predicate where `equals` starts with `ctx.` is treated as server-derived: the column lands in `GUARDS_CONFIG.systemManaged` (clients cannot submit it) and is auto-populated on create / upsert from the context.\n\n## Auto-Derivation\n\nWhen the `firewall:` block is omitted, the compiler scans the schema for known scope columns and synthesises the predicate array:\n\n| Column found | Predicate emitted |\n|--------------|-------------------|\n| `organizationId` / `organisationId` / `orgId` / `organization` / `organisation` / `org` | `{ field: '...', equals: 'ctx.activeOrgId' }` |\n| `userId` | `{ field: 'userId', equals: 'ctx.userId' }` |\n| `teamId` | `{ field: 'teamId', equals: 'ctx.activeTeamId' }` |\n| `deletedAt` (always present via audit injection) | `{ field: 'deletedAt', isNull: true }` — appended automatically whenever the schema carries the column, regardless of which firewall shape you wrote |\n\n`q.scope(kind)` is the canonical way to declare the column — auto-derivation works the same way for plain `q.text().required()` or Drizzle `text(...).notNull()` columns named to match the convention.\n\n**Rules:**\n- Exactly one isolation column → auto-derived.\n- Zero columns AND no PUBLIC route → compile-time error (\"missing isolation column\").\n- Two or more (e.g. `organizationId` + `ownerId`) → compile-time error; declare `firewall:` explicitly.\n\n## What `{ exception: true }` Actually Does\n\n`{ exception: true }` disables **tenant scoping only** — the generated `buildFirewallConditions()` emits no tenant `WHERE` clauses. It does **not** affect:\n\n- **Audit field injection.** `createdAt`, `modifiedAt`, `createdBy`, `modifiedBy`, `deletedAt`, `deletedBy` are always added to every table unless you disable them globally with `compiler.features.auditFields: false`.\n- **Soft-delete filtering.** If the table has a `deletedAt` column (which it does by default, thanks to audit injection), the firewall still emits `isNull(<table>.deletedAt)` so soft-deleted records stay hidden. To opt out of soft-delete filtering on an exception resource, either set `compiler.features.auditFields: false` globally or hand-author a schema without `deletedAt`.\n\nSo `firewall: [{ exception: true }]` on the default configuration returns `isNull(<table>.deletedAt)` from `buildFirewallConditions()` — no tenant filter, soft-delete filter still applied.\n\n## Sysadmin Escape Hatch\n\nWhen `cms: { sysadmin: true }` is set on the project (introduced in v0.15.0), every `buildFirewallConditions()` emits a runtime branch that drops tenant scopes for `ctx.userRole === 'sysadmin'` callers while keeping the soft-delete predicate:\n\n```typescript\n// Generated for an org-scoped table when cms.sysadmin: true\nexport function buildFirewallConditions(ctx: AppContext): SQL | undefined {\n if (ctx.userRole === 'sysadmin') {\n return isNull(invoices.deletedAt); // tenant predicate dropped, soft-delete kept\n }\n return and(\n eq(invoices.organizationId, ctx.activeOrgId!),\n isNull(invoices.deletedAt),\n );\n}\n```\n\nThe escape branch is **only** emitted when:\n\n- `cms.sysadmin: true` is set on the project config\n- The table has at least one tenant-scope predicate (org / owner / team / `via:` relationship). Tables with no tenant scopes already return what a sysadmin would see, so the runtime check would be dead code.\n- The firewall does not declare `{ exception: true }` (no tenant scopes to drop).\n\n**Sysadmin is distinct from appmanager.** `userRole === 'appmanager'` callers still go through the firewall normally — only `userRole === 'sysadmin'` triggers the bypass. Appmanager is the platform control-plane tier, expressed with plain `userRole` checks; sysadmin is the opt-in cross-tenant DB-admin tier. See [CMS Configuration](/compiler/config#cms-configuration).\n\nIf your project doesn't set `cms.sysadmin: true`, the escape branch is never emitted and the role value is functionally inert.\n\n## Common Patterns\n\n```typescript\n// Public/system table - no tenant filtering (soft-delete still applied)\nfirewall: [{ exception: true }]\n\n// Organization-scoped (auto-derived when organizationId is present — block can be omitted)\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n]\n\n// User-owned personal data\nfirewall: [\n { field: 'ownerId', equals: 'ctx.userId' },\n { field: 'deletedAt', isNull: true },\n]\n\n// Multi-tenant + per-team scoping\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'teamId', equals: 'ctx.activeTeamId' },\n { field: 'deletedAt', isNull: true },\n]\n\n// Custom ctx field\nfirewall: [\n { field: 'workspaceId', equals: 'ctx.activeWorkspaceId' },\n]\n\n// Status-gated (literal value, not ctx-derived — does NOT add to systemManaged)\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'status', in: ['active', 'pending'] },\n]\n```\n\n## Error Responses\n\nWhen a record isn't found behind the firewall (wrong org, soft-deleted, or genuinely doesn't exist), the error response depends on `firewallErrorMode`:\n\n### Reveal Mode (Default)\n\nReturns **403** 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\nThis is developer-friendly and helps debug access issues during development.\n\n### Hide Mode\n\nReturns **404** with a generic error:\n\n```json\n{\n \"error\": \"Not found\",\n \"code\": \"NOT_FOUND\"\n}\n```\n\nUse `firewallErrorMode: 'hide'` for security-hardened deployments where you don't want attackers to distinguish between \"record exists but you can't access it\" and \"record doesn't exist\":\n\n```typescript\nexport default defineTable(records, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n firewallErrorMode: 'hide', // Opaque 404s prevent record enumeration\n});\n```\n\n### Foreign-Key Referential Checks\n\nGenerated `POST /` and `POST /batch` handlers validate every foreign-key column against the **target table's** firewall before inserting. If a record references a row that the caller can't see (wrong org, soft-deleted, or non-existent), the request fails with:\n\n```json\n{\n \"error\": \"Referenced jobs row not found\",\n \"code\": \"FK_NOT_FOUND\",\n \"layer\": \"validation\",\n \"field\": \"jobId\"\n}\n```\n\nThis closes a cross-tenant injection vector: even if an attacker knows a foreign tenant's row ID, they cannot attach a child record to it, and they cannot trigger a cross-tenant cascade delete. The check uses the target table's `buildXFirewallConditions(ctx)` helper, so it honors whatever firewall predicates the target declared (organization, owner, team, custom). FKs to tables with `{ exception: true }` get a plain existence check (still verifies the row exists, doesn't tenant-scope it).\n\nThe check runs after guards but before the insert, so it appears as `layer: \"validation\"` in error responses. Status code is `400`, not `404` — returning `404` would leak existence of out-of-scope rows.\n\n### Pre-Record ID-Probe Defense\n\nIndependent of `firewallErrorMode`, generated `/:id` handlers run a\n**role-only access check before** the firewall query (see\n[Access ordering](/compiler/definitions/access#evaluation-order)). A caller\nwithout the right role gets 403 before the database is touched, so they\ncan't distinguish \"row exists out-of-scope\" from \"row doesn't exist\" via\nresponse timing or status differences.\n\n`firewallErrorMode` controls what happens **after** the role check passes\nbut the firewall hides the row — i.e., when an authorized caller asks for\na record in another tenant. Use `'hide'` to make that case indistinguishable\nfrom a non-existent ID.\n\n## Rules\n\n- Every resource MUST have at least one tenant predicate OR `{ exception: true }` OR a PUBLIC route\n- `{ exception: true }` cannot be combined with tenant predicates in the same array\n\n## Why Can't You Mix `{ exception: true }` with Tenant Predicates?\n\nThey represent opposite intentions:\n- `{ exception: true }` = \"Don't generate tenant `WHERE` clauses, data is public/global\"\n- Tenant predicates = \"Generate tenant `WHERE` clauses to isolate data\"\n\nCombining them would be contradictory — you can't both isolate and not isolate. (Note: soft-delete filtering is independent of this decision, see above.)\n\n## Handling \"Some Public, Some Private\" Data\n\nIf you need records that are sometimes public and sometimes scoped, you have two options:\n\n### Option 1: Two Separate Tables\n\nSplit into two tables - one public, one scoped:\n\n```typescript\n// features/job-templates/template-library.ts - Public job templates\nexport default defineTable(templateLibrary, {\n firewall: [{ exception: true }],\n // ...\n});\n\n// features/job-templates/custom-templates.ts - Org's custom job templates\nexport default defineTable(customTemplates, {\n firewall: [{ field: 'ownerId', equals: 'ctx.userId' }],\n // ...\n});\n```\n\n### Option 2: Use Access Control Instead\n\nKeep tenant scope but make access permissive, then control visibility via `access`:\n\n```typescript\n// features/jobs/jobs.ts\nexport default defineTable(jobs, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: {\n // Anyone in the org can list — visibility differences are handled\n // via record-level access conditions on /:id\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n // Use record conditions to allow public jobs OR owned jobs on GET /:id\n // (single-record GET inherits read.access, with optional record-level overrides)\n // ...\n});\n```\n\n### Which to Choose?\n\n| Scenario | Recommendation |\n|----------|----------------|\n| Truly global data (app config, public job templates) | `exception: true` in separate resource |\n| \"Public within org\" but still org-isolated | Ownership scope + permissive access rules |\n| Recruiter can toggle job postings public/private | Ownership scope + `visibility` field + access conditions |"
119
127
  },
120
128
  "compiler/definitions/guards": {
121
129
  "title": "Guards - Field Modification Rules",
122
- "content": "Control which fields can be modified in CREATE vs UPDATE operations.\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().default('applied'),\n appliedAt: text('applied_at').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: {\n createable: [\"candidateId\", \"jobId\", \"notes\"],\n updatable: [\"notes\"],\n protected: {\n stage: [\"advance-stage\", \"reject\"],\n },\n immutable: [\"appliedAt\", \"candidateId\", \"jobId\"],\n },\n create: { /* ... */ },\n update: { /* ... */ },\n delete: { /* ... */ },\n});\n```\n\n## Configuration Options\n\n```typescript\nguards: {\n // Fields allowed on CREATE\n createable?: string[];\n\n // Fields allowed on UPDATE/PATCH\n updatable?: string[];\n\n // Fields only modifiable via specific actions\n protected?: Record<string, string[]>;\n\n // Fields set on CREATE, never modified after\n immutable?: string[];\n}\n```\n\n## How It Works\n\n| List | What it controls |\n|------|------------------|\n| `createable` | Fields allowed in create (POST) request body |\n| `updatable` | Fields allowed in update (PATCH) request body |\n| `protected` | Fields blocked from direct writes, only modifiable via named actions |\n| `immutable` | Fields allowed on create, blocked on all updates |\n\n**Combining lists:**\n\n- `createable` + `updatable` - Most fields go in both (can set on create AND modify later)\n- `createable` only - Field is set once, cannot be changed via update\n- `protected` - Don't also list in `createable` or `updatable` (they're mutually exclusive)\n- `immutable` - Don't also list in `updatable` (contradiction)\n\n```typescript\nguards: {\n createable: [\"candidateId\", \"jobId\", \"notes\", \"source\"],\n updatable: [\"notes\"],\n // \"candidateId\", \"jobId\" are only in createable = set once, can't change via update\n protected: {\n stage: [\"advance-stage\", \"reject\"], // NOT in createable/updatable\n },\n immutable: [\"appliedAt\"], // NOT in updatable\n}\n```\n\n**If a field is not listed anywhere, it cannot be set by the client.**\n\n## System-Managed Fields (Always Protected)\n\n`GUARDS_CONFIG.systemManaged` rejects any field in this set from client input — even with `guards: false`. The set always includes the audit fields:\n\n- `createdAt`, `createdBy`\n- `modifiedAt`, `modifiedBy`\n- `deletedAt`, `deletedBy`\n\nIt also extends with **scope columns** — any firewall predicate whose `equals` references `ctx.*` adds its `field` to systemManaged. Most commonly this comes from `q.scope()`:\n\n```typescript\ncolumns: {\n organizationId: q.scope('organization'), // → adds 'organizationId' to systemManaged\n}\n```\n\nThe same applies to a hand-rolled firewall:\n\n```typescript\nfirewall: [\n { field: 'tenantId', equals: 'ctx.activeOrgId' }, // → systemManaged\n { field: 'workspaceId', equals: 'ctx.activeWorkspaceId' }, // → systemManaged\n { field: 'status', equals: 'active' }, // literal, NOT added\n]\n```\n\nThe semantic rule is \"if the firewall says this column's value comes from the request context, the client cannot submit it.\" The value is auto-populated on create / upsert from `ctx`.\n\n## Example\n\n```typescript\nguards: {\n createable: [\"candidateId\", \"jobId\", \"notes\"],\n updatable: [\"notes\"],\n protected: {\n stage: [\"advance-stage\", \"reject\"], // Only these actions can modify stage\n },\n immutable: [\"appliedAt\", \"candidateId\", \"jobId\"],\n}\n```\n\n## Disabling Guards\n\n```typescript\nguards: false // Only system fields protected\n```\n\nWhen `guards: false` is set, all user-defined fields become writable via direct create/update/upsert operations. This is useful for:\n- External sync scenarios where you need full field control\n- Batch upsert operations where field restrictions would be limiting\n- Simple tables where field-level protection isn't needed\n\n## Upsert with External IDs\n\nWhen you disable guards AND use client-provided IDs, you unlock upsert operations. This is designed for **syncing data from external systems**.\n\n### Requirements for Upsert\n\n1. `generateId: false` in database config (client provides IDs)\n2. `guards: false` in resource definition\n\n### How Upsert Works\n\n```\nPUT /resource/:id\n├── Record exists? → UPDATE (replace all fields)\n└── Record missing? → CREATE with provided ID\n```\n\n### Database Config\n\n```typescript\n// quickback.config.ts\nexport default {\n database: {\n generateId: false, // Client provides IDs (enables upsert)\n // Other options: 'uuid' | 'cuid' | 'nanoid' | 'short' | 'prefixed' | 'serial'\n }\n};\n```\n\n### Table Definition\n\n```typescript\n// features/integrations/ats-imports.ts\nexport default defineTable(atsImports, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: false, // Disables field restrictions\n upsert: {\n access: { roles: ['hiring-manager', 'sync-service'] }\n },\n});\n```\n\n## What's Still Protected with guards: false\n\nEven with `guards: false`, system-managed fields are ALWAYS protected. This includes:\n\n- `createdAt`, `createdBy` — set on INSERT only\n- `modifiedAt`, `modifiedBy` — auto-updated\n- `deletedAt`, `deletedBy` — set on soft delete\n- Any column declared via `q.scope()` (or any firewall predicate using `equals: 'ctx.*'`) — auto-populated from request context\n\nSo `guards: false` only opens up user-defined business fields. Tenant scope and audit fields stay locked down regardless.\n\n## Ownership Auto-Population\n\nWhen upsert creates a new record, ownership fields are auto-set from context:\n\n```typescript\n// Client sends: PUT /ats-imports/ext-123 { candidateName: \"Jane Doe\" }\n// Server creates:\n{\n id: \"ext-123\", // Client-provided\n candidateName: \"Jane Doe\", // Client-provided\n organizationId: ctx.activeOrgId, // Auto-set from firewall\n createdAt: now, // Auto-set\n createdBy: ctx.userId, // Auto-set\n modifiedAt: now, // Auto-set\n modifiedBy: ctx.userId, // Auto-set\n}\n```\n\n## Use Cases for Upsert/External IDs\n\n| Use Case | Why upsert? |\n|----------|----------|\n| External API sync | External system controls the ID |\n| Webhook handlers | Events come with their own IDs |\n| Data migration | Preserve IDs from source system |\n| Idempotent updates | Safe to retry (no duplicate creates) |\n| Bulk upsert | Create or update in one operation |\n\n## ID Generation Options\n\n| `generateId` | Upsert Available? | Notes |\n|--------------|----------------|-------|\n| `'uuid'` | No | Server generates UUID |\n| `'cuid'` | No | Server generates CUID |\n| `'nanoid'` | No | Server generates nanoid |\n| `'short'` | No | Server generates 6-char alphanumeric ID (e.g. `a3F9xK`) |\n| `'prefixed'` | No | Server generates prefixed ID (e.g. `room_abc123`) |\n| `'serial'` | No | Database auto-increments |\n| `false` | Yes (if guards: false) | Client provides ID |\n\n## Compile-Time Validation\n\nThe Quickback compiler validates your guards configuration and will error if:\n\n1. **Field in both `createable` and `protected`** - A field cannot be both client-writable on create and action-only\n2. **Field in both `updatable` and `protected`** - A field cannot be both client-writable on update and action-only\n3. **Field in both `updatable` and `immutable`** - Contradictory: immutable fields cannot be updated\n4. **Field in `protected` doesn't exist in schema** - Referenced field must exist in the table\n5. **Field in `createable`/`updatable`/`immutable` doesn't exist in schema** - All referenced fields must exist"
130
+ "content": "Control which fields can be modified in CREATE vs UPDATE operations.\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().default('applied'),\n appliedAt: text('applied_at').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: {\n createable: [\"candidateId\", \"jobId\", \"notes\"],\n updatable: [\"notes\"],\n protected: {\n stage: [\"advance-stage\", \"reject\"],\n },\n immutable: [\"appliedAt\", \"candidateId\", \"jobId\"],\n },\n create: { /* ... */ },\n update: { /* ... */ },\n delete: { /* ... */ },\n});\n```\n\n## Configuration Options\n\n```typescript\nguards: {\n // Fields allowed on CREATE\n createable?: string[];\n\n // Fields allowed on UPDATE/PATCH\n updatable?: string[];\n\n // Fields only modifiable via specific actions\n protected?: Record<string, string[]>;\n\n // Fields set on CREATE, never modified after\n immutable?: string[];\n}\n```\n\n## How It Works\n\n| List | What it controls |\n|------|------------------|\n| `createable` | Fields allowed in create (POST) request body |\n| `updatable` | Fields allowed in update (PATCH) request body |\n| `protected` | Fields blocked from direct writes, only modifiable via named actions |\n| `immutable` | Fields allowed on create, blocked on all updates |\n\n**Combining lists:**\n\n- `createable` + `updatable` - Most fields go in both (can set on create AND modify later)\n- `createable` only - Field is set once, cannot be changed via update\n- `protected` - Don't also list in `createable` or `updatable` (they're mutually exclusive)\n- `immutable` - Don't also list in `updatable` (contradiction)\n\n```typescript\nguards: {\n createable: [\"candidateId\", \"jobId\", \"notes\", \"source\"],\n updatable: [\"notes\"],\n // \"candidateId\", \"jobId\" are only in createable = set once, can't change via update\n protected: {\n stage: [\"advance-stage\", \"reject\"], // NOT in createable/updatable\n },\n immutable: [\"appliedAt\"], // NOT in updatable\n}\n```\n\n**If a field is not listed anywhere, it cannot be set by the client.**\n\n## System-Managed Fields (Always Protected)\n\n`GUARDS_CONFIG.systemManaged` rejects any field in this set from client input — even with `guards: false`. The set always includes the audit fields:\n\n- `createdAt`, `createdBy`\n- `modifiedAt`, `modifiedBy`\n- `deletedAt`, `deletedBy`\n\nIt also extends with **scope columns** — any firewall predicate whose `equals` references `ctx.*` adds its `field` to systemManaged. Most commonly this comes from `q.scope()`:\n\n```typescript\ncolumns: {\n organizationId: q.scope('organization'), // → adds 'organizationId' to systemManaged\n}\n```\n\nThe same applies to a hand-rolled firewall:\n\n```typescript\nfirewall: [\n { field: 'tenantId', equals: 'ctx.activeOrgId' }, // → systemManaged\n { field: 'workspaceId', equals: 'ctx.activeWorkspaceId' }, // → systemManaged\n { field: 'status', equals: 'active' }, // literal, NOT added\n]\n```\n\nThe semantic rule is \"if the firewall says this column's value comes from the request context, the client cannot submit it.\" The value is auto-populated on create / upsert from `ctx`.\n\n### Changeset ops widen the set per-surface\n\nOn [changeset](/compiler/definitions/changesets) ops, an owned child's\nsystemManaged set additionally includes its **spine FK and every `inherit`\ncolumn** — the changeset supplies those structurally (the FK from the parent\nop's id, inherit columns from the firewall-verified parent row), so a\nclient-supplied value is a pointer-carrying `GUARD_SYSTEM_MANAGED` rejection\n(never silently stripped or stamped-over).\n\nThe child's **plain-CRUD guards are unaffected**: a junction that keeps its FK\nin `createable` for its raw `POST` route stays correct — the same field\narriving in a changeset op is rejected because that surface stamps it. Two\nsurfaces, one declared rule each.\n\n## Example\n\n```typescript\nguards: {\n createable: [\"candidateId\", \"jobId\", \"notes\"],\n updatable: [\"notes\"],\n protected: {\n stage: [\"advance-stage\", \"reject\"], // Only these actions can modify stage\n },\n immutable: [\"appliedAt\", \"candidateId\", \"jobId\"],\n}\n```\n\n## Disabling Guards\n\n```typescript\nguards: false // Only system fields protected\n```\n\nWhen `guards: false` is set, all user-defined fields become writable via direct create/update/upsert operations. This is useful for:\n- External sync scenarios where you need full field control\n- Batch upsert operations where field restrictions would be limiting\n- Simple tables where field-level protection isn't needed\n\n## Upsert with External IDs\n\nWhen you disable guards AND use client-provided IDs, you unlock upsert operations. This is designed for **syncing data from external systems**.\n\n### Requirements for Upsert\n\n1. `generateId: false` in database config (client provides IDs)\n2. `guards: false` in resource definition\n\n### How Upsert Works\n\n```\nPUT /resource/:id\n├── Record exists? → UPDATE (replace all fields)\n└── Record missing? → CREATE with provided ID\n```\n\n### Database Config\n\n```typescript\n// quickback.config.ts\nexport default {\n database: {\n generateId: false, // Client provides IDs (enables upsert)\n // Other options: 'uuid' | 'cuid' | 'nanoid' | 'short' | 'prefixed' | 'serial'\n }\n};\n```\n\n### Table Definition\n\n```typescript\n// features/integrations/ats-imports.ts\nexport default defineTable(atsImports, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: false, // Disables field restrictions\n upsert: {\n access: { roles: ['hiring-manager', 'sync-service'] }\n },\n});\n```\n\n## What's Still Protected with guards: false\n\nEven with `guards: false`, system-managed fields are ALWAYS protected. This includes:\n\n- `createdAt`, `createdBy` — set on INSERT only\n- `modifiedAt`, `modifiedBy` — auto-updated\n- `deletedAt`, `deletedBy` — set on soft delete\n- Any column declared via `q.scope()` (or any firewall predicate using `equals: 'ctx.*'`) — auto-populated from request context\n\nSo `guards: false` only opens up user-defined business fields. Tenant scope and audit fields stay locked down regardless.\n\n## Ownership Auto-Population\n\nWhen upsert creates a new record, ownership fields are auto-set from context:\n\n```typescript\n// Client sends: PUT /ats-imports/ext-123 { candidateName: \"Jane Doe\" }\n// Server creates:\n{\n id: \"ext-123\", // Client-provided\n candidateName: \"Jane Doe\", // Client-provided\n organizationId: ctx.activeOrgId, // Auto-set from firewall\n createdAt: now, // Auto-set\n createdBy: ctx.userId, // Auto-set\n modifiedAt: now, // Auto-set\n modifiedBy: ctx.userId, // Auto-set\n}\n```\n\n## Use Cases for Upsert/External IDs\n\n| Use Case | Why upsert? |\n|----------|----------|\n| External API sync | External system controls the ID |\n| Webhook handlers | Events come with their own IDs |\n| Data migration | Preserve IDs from source system |\n| Idempotent updates | Safe to retry (no duplicate creates) |\n| Bulk upsert | Create or update in one operation |\n\n## ID Generation Options\n\n| `generateId` | Upsert Available? | Notes |\n|--------------|----------------|-------|\n| `'uuid'` | No | Server generates UUID |\n| `'cuid'` | No | Server generates CUID |\n| `'nanoid'` | No | Server generates nanoid |\n| `'short'` | No | Server generates 6-char alphanumeric ID (e.g. `a3F9xK`) |\n| `'prefixed'` | No | Server generates prefixed ID (e.g. `room_abc123`) |\n| `'serial'` | No | Database auto-increments |\n| `false` | Yes (if guards: false) | Client provides ID |\n\n## Compile-Time Validation\n\nThe Quickback compiler validates your guards configuration and will error if:\n\n1. **Field in both `createable` and `protected`** - A field cannot be both client-writable on create and action-only\n2. **Field in both `updatable` and `protected`** - A field cannot be both client-writable on update and action-only\n3. **Field in both `updatable` and `immutable`** - Contradictory: immutable fields cannot be updated\n4. **Field in `protected` doesn't exist in schema** - Referenced field must exist in the table\n5. **Field in `createable`/`updatable`/`immutable` doesn't exist in schema** - All referenced fields must exist"
123
131
  },
124
132
  "compiler/definitions": {
125
133
  "title": "Definitions Overview",
126
- "content": "Before diving into specific features, let's understand how Quickback's pieces connect. This page gives you the mental model for everything that follows.\n\n## The Big Picture\n\nQuickback is a **backend compiler**. You write definition files, and Quickback compiles them into a production-ready API.\n\n1. **You write definitions** - Table files with schema and security config using `defineTable`\n2. **Quickback compiles them** - Analyzes your definitions at build time\n3. **You get a production API** - `GET /jobs`, `POST /jobs`, `PATCH /jobs/:id`, `DELETE /jobs/:id`, batch operations, plus custom actions\n\n## File Structure\n\nYour definitions live in a `quickback/features/` folder organized by feature:\n\n```\nmy-app/\n├── quickback/\n│ ├── quickback.config.ts # Compiler configuration\n│ └── features/\n│ └── {feature-name}/\n│ ├── candidates.ts # Table + config (defineTable)\n│ ├── applications.ts # Secondary table + config\n│ ├── interview-scores.ts # Internal table (no routes)\n│ ├── actions.ts # Custom actions (optional)\n│ └── handlers/ # Action handlers (optional)\n│ └── advance-stage.ts\n├── src/ # Generated code (output)\n└── package.json\n```\n\n**Table files** use `defineTable` to combine schema and security config:\n\n```typescript\n// features/candidates/candidates.ts\n\nexport const candidates = sqliteTable(\"candidates\", {\n id: text(\"id\").primaryKey(),\n organizationId: text(\"organization_id\").notNull(),\n name: text(\"name\").notNull(),\n email: text(\"email\").notNull(),\n phone: text(\"phone\"),\n source: text(\"source\"),\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: ['owner', 'hiring-manager', 'recruiter'] } },\n phone: { type: 'phone', show: { roles: ['owner', '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\"] } },\n});\n\nexport type Candidate = typeof candidates.$inferSelect;\n```\n\n**Key points:**\n- Tables with `export default defineTable(...)` → resource routes generated\n- Tables without default export → internal/junction tables (no routes)\n- Route path derived from filename: `applications.ts` → `/api/v1/applications`\n\n## The Five Security Layers\n\nEvery API request passes through five security layers, in order:\n\n```\nRequest → Rate Limit → Firewall → Access → Guards → Masking → Response\n │ │ │ │ │\n │ │ │ │ └── Hide sensitive fields\n │ │ │ └── Block field modifications\n │ │ └── Check roles & conditions\n │ └── Isolate data by owner/org/team\n └── Cap requests per user / op\n```\n\n### 1. Firewall (Data Isolation)\n\nThe firewall controls **which records** a user can see. It automatically adds WHERE clauses to every query based on your schema columns:\n\n| Column in Schema | What happens |\n|------------------|--------------|\n| `organization_id` | Data isolated by organization |\n| `user_id` | Data isolated by user (personal data) |\n\nNo manual configuration needed - Quickback applies smart rules based on your schema.\n\nFor relationship-based row visibility (e.g. \"user can see this event because they have a confirmed `event_guests` row pointing at it\"), declare the relationship under `authz.relationships` and reference it from the firewall with a `via:` predicate. See [Firewall → Relationship-based scoping](/compiler/definitions/firewall#relationship-based-scoping-via).\n\n[Learn more about Firewall →](/compiler/definitions/firewall)\n\n### 2. Access (CRUD Permissions)\n\nAccess controls **which operations** a user can perform. It checks roles and record conditions. Reads (`GET /` and `GET /:id`) live under `read:`; writes live under top-level `create:`, `update:`, `delete:`, and `upsert:`.\n\n```typescript\nread: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n},\ncreate: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\nupdate: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\ndelete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n```\n\n[Learn more about Access →](/compiler/definitions/access)\n\n### 3. Guards (Field Modification Rules)\n\nGuards control **which fields** can be modified in each operation.\n\n| Guard Type | What it means |\n|------------|---------------|\n| `createable` | Fields that can be set when creating |\n| `updatable` | Fields that can be changed when updating |\n| `protected` | Fields that can only be changed via specific actions |\n| `immutable` | Fields that can never be changed after creation |\n\n[Learn more about Guards →](/compiler/definitions/guards)\n\n### 4. Masking (Data Redaction)\n\nMasking hides sensitive fields from users who shouldn't see them.\n\n```typescript\nmasking: {\n email: { type: 'email' }, // Shows: j***@e******.com\n phone: { type: 'phone' }, // Shows: ******4567\n salary: { type: 'redact' }, // Shows: [REDACTED]\n}\n```\n\n[Learn more about Masking →](/compiler/definitions/masking)\n\n### 5. Rate Limiting (Request Caps)\n\nRate limiting caps **how often** an operation can be called, backed by Cloudflare's native Rate Limiting binding — no extra storage, no third-party libraries. Unlike the other four layers, it's applied to **every resource by default** (read `1000/60s`, writes `200/60s`) and runs first, before any data is touched.\n\n```typescript\nrateLimit: {\n delete: { limit: 5, period: 60 }, // tighter than the 200/60s default\n},\n// read / create / update keep shipped defaults\n```\n\nOverride per-op, per-resource, or project-wide; set `false` at any scope to opt out. Limits are keyed by `<resource>:<op>:<userId>` (falling back to client IP for anonymous callers), and over-cap requests get a `429` with `Retry-After`.\n\n[Learn more about Rate Limiting →](/compiler/definitions/rate-limit)\n\n## How They Work Together\n\n**Scenario:** An interviewer requests `GET /candidates/cnd_123`\n\n1. **Rate Limit** checks: Is this user under their `read` cap on `candidates`?\n - Yes → Continue\n - No → 429 Too Many Requests (with `Retry-After`)\n\n2. **Firewall** checks: Is candidate `cnd_123` in the user's organization?\n - Yes → Continue\n - No → 404 Not Found (as if it doesn't exist)\n\n3. **Access** checks: Can interviewers perform GET?\n - Yes → Continue\n - No → 403 Forbidden\n\n4. **Guards** don't apply to GET (they're for writes)\n\n5. **Masking** applies: User is an `interviewer`, not `recruiter` or `hiring-manager`\n - Email: `jane@company.com` → `j***@c******.com`\n - Phone: `555-123-4567` → `******4567`\n\n6. **Response** sent with masked data\n\n## Locked Down by Default\n\nQuickback is **secure by default**. Nothing is accessible until you explicitly allow it.\n\n| Layer | Default | What you must do |\n|-------|---------|------------------|\n| Firewall | AUTO | Auto-detects from `organization_id`/`user_id` columns. Only configure for exceptions. |\n| Access | DENIED | Explicitly define `access` rules with roles |\n| Guards | LOCKED | Explicitly list `createable`, `updatable` fields |\n| Rate Limit | ON | Applied to every resource (read 1000/60s, write 200/60s). Override or set `false` to opt out. |\n| Actions | BLOCKED | Explicitly define `access` for each action |\n\n**You must deliberately open each door.** This prevents accidental data exposure.\n\n## Other Resource Options\n\nBeyond the five security layers, `defineTable` accepts a handful of declarative hints that shape the generated API and the CMS without touching your security posture.\n\n| Option | What it does | Full reference |\n|---|---|---|\n| `views` | Named column projections — `GET /resource/views/{name}` returns a subset of columns under its own access rule. | [Views](/compiler/definitions/views) |\n| `references` | Explicit FK target table for columns that don't follow the \"Id\"-stripped convention (e.g. `vendorId → contact`). | [CMS Schema Registry](/stack/cms/schema-registry) |\n| `displayColumn` | Column to use as the human-readable label in FK resolutions and CMS list views (auto-detected as `name`/`title`/`label` if not set). | [CMS Table Views](/stack/cms/table-views) |\n| `defaultSort` | Default sort order for CMS list rendering (`{ field, order: \"asc\" \\| \"desc\" }`). | [CMS Table Views](/stack/cms/table-views) |\n| `inputHints` | Per-column CMS input type: `select`, `richtext`, `textarea`, `lookup`, `currency`, etc. Pure CMS hint, no runtime effect. | [CMS Record Layouts](/stack/cms/record-layouts) |\n| `layouts` | Named record-page layouts — group fields into sections (collapsed, multi-column). Falls back to auto-grouping if unset. | [CMS Record Layouts](/stack/cms/record-layouts) |\n| `embeddings` | Auto-generate vector embeddings for specified fields on insert/update. | [Stack → Embeddings](/stack/vector/using-embeddings) |\n| `realtime` | Per-table broadcast config (`enabled`, `onInsert`, `onUpdate`, `onDelete`, `requiredRoles`, `fields`). | [Stack → Realtime](/stack/realtime/using-realtime) |\n| `path` | Override the route base path (defaults to feature name). | — |\n\nAll options are optional — omit them and Quickback uses sensible defaults (auto-detected display column, auto-grouped layout, no embeddings, no realtime).\n\n## Next Steps\n\n1. [Database Schema](/compiler/definitions/schema) — Define your tables\n2. [Firewall](/compiler/definitions/firewall) — Set up data isolation\n3. [Access](/compiler/definitions/access) — Configure read and write permissions\n4. [Guards](/compiler/definitions/guards) — Control field modifications\n5. [Masking](/compiler/definitions/masking) — Hide sensitive data\n6. [Rate Limit](/compiler/definitions/rate-limit) — Per-operation request caps\n7. [Views](/compiler/definitions/views) — Column-level security\n8. [Validation](/compiler/definitions/validation) — Field validation rules\n9. [Actions](/compiler/definitions/actions) — Add custom business logic"
134
+ "content": "Before diving into specific features, let's understand how Quickback's pieces connect. This page gives you the mental model for everything that follows.\n\n## The Big Picture\n\nQuickback is a **backend compiler**. You write definition files, and Quickback compiles them into a production-ready API.\n\n1. **You write definitions** - Table files with schema and security config using `defineTable`\n2. **Quickback compiles them** - Analyzes your definitions at build time\n3. **You get a production API** - `GET /jobs`, `POST /jobs`, `PATCH /jobs/:id`, `DELETE /jobs/:id`, batch operations, plus custom actions\n\n## File Structure\n\nYour definitions live in a `quickback/features/` folder organized by feature:\n\n```\nmy-app/\n├── quickback/\n│ ├── quickback.config.ts # Compiler configuration\n│ └── features/\n│ └── {feature-name}/\n│ ├── candidates.ts # Table + config (defineTable)\n│ ├── applications.ts # Secondary table + config\n│ ├── interview-scores.ts # Internal table (no routes)\n│ ├── actions/ # Custom actions — one file per action\n│ │ └── advance-stage.ts\n│ ├── lib/ # Feature-local helpers (optional)\n│ └── pages/ # CMS page definitions (optional)\n├── src/ # Generated code (output)\n└── package.json\n```\n\n`actions/`, `handlers/`, `lib/`, and `pages/` are the **reserved** sub-directories of a\nfeature — nothing else inside a feature folder is loaded, and a stray subdirectory that\ncontains `defineTable(...)` / `defineAction(...)` files fails the compile (files silently\ndisappearing after a mis-move is the failure mode this guards against).\n\nFeatures can also be grouped into **areas**: a folder carrying an `_area.ts`\n(`export default defineArea({...})`) declares a route prefix + admission gate and a shared\nauthz vocabulary, and every unreserved child directory becomes a child feature (nesting to\narbitrary depth):\n\n```\nquickback/features/\n├── workspace/ # AREA (has _area.ts)\n│ ├── _area.ts # defineArea({...}) — prefix, via lanes, vocabulary\n│ ├── projects.ts # the area folder may itself be a feature\n│ └── tasks/ # child feature\n│ ├── tasks.ts\n│ └── actions/addTask.ts\n└── billing/ # flat feature (unchanged)\n```\n\nArea projects must declare `requires: ['feature-areas']` in `quickback.config.ts`.\nSee [Feature areas](/compiler/definitions/feature-areas) for the full model.\n\n**Table files** use `defineTable` to combine schema and security config:\n\n```typescript\n// features/candidates/candidates.ts\n\nexport const candidates = sqliteTable(\"candidates\", {\n id: text(\"id\").primaryKey(),\n organizationId: text(\"organization_id\").notNull(),\n name: text(\"name\").notNull(),\n email: text(\"email\").notNull(),\n phone: text(\"phone\"),\n source: text(\"source\"),\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: ['owner', 'hiring-manager', 'recruiter'] } },\n phone: { type: 'phone', show: { roles: ['owner', '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\"] } },\n});\n\nexport type Candidate = typeof candidates.$inferSelect;\n```\n\n**Key points:**\n- Tables with `export default defineTable(...)` → resource routes generated\n- Tables without default export → internal/junction tables (no routes)\n- Route path derived from filename: `applications.ts` → `/api/v1/applications`\n\n## The Five Security Layers\n\nEvery API request passes through five security layers, in order:\n\n```\nRequest → Rate Limit → Firewall → Access → Guards → Masking → Response\n │ │ │ │ │\n │ │ │ │ └── Hide sensitive fields\n │ │ │ └── Block field modifications\n │ │ └── Check roles & conditions\n │ └── Isolate data by owner/org/team\n └── Cap requests per user / op\n```\n\n### 1. Firewall (Data Isolation)\n\nThe firewall controls **which records** a user can see. It automatically adds WHERE clauses to every query based on your schema columns:\n\n| Column in Schema | What happens |\n|------------------|--------------|\n| `organization_id` | Data isolated by organization |\n| `user_id` | Data isolated by user (personal data) |\n\nNo manual configuration needed - Quickback applies smart rules based on your schema.\n\nFor relationship-based row visibility (e.g. \"user can see this event because they have a confirmed `event_guests` row pointing at it\"), declare the relationship under `authz.relationships` and reference it from the firewall with a `via:` predicate. See [Firewall → Relationship-based scoping](/compiler/definitions/firewall#relationship-based-scoping-via).\n\n[Learn more about Firewall →](/compiler/definitions/firewall)\n\n### 2. Access (CRUD Permissions)\n\nAccess controls **which operations** a user can perform. It checks roles and record conditions. Reads (`GET /` and `GET /:id`) live under `read:`; writes live under top-level `create:`, `update:`, `delete:`, and `upsert:`.\n\n```typescript\nread: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n},\ncreate: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\nupdate: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\ndelete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n```\n\n[Learn more about Access →](/compiler/definitions/access)\n\n### 3. Guards (Field Modification Rules)\n\nGuards control **which fields** can be modified in each operation.\n\n| Guard Type | What it means |\n|------------|---------------|\n| `createable` | Fields that can be set when creating |\n| `updatable` | Fields that can be changed when updating |\n| `protected` | Fields that can only be changed via specific actions |\n| `immutable` | Fields that can never be changed after creation |\n\n[Learn more about Guards →](/compiler/definitions/guards)\n\n### 4. Masking (Data Redaction)\n\nMasking hides sensitive fields from users who shouldn't see them.\n\n```typescript\nmasking: {\n email: { type: 'email' }, // Shows: j***@e******.com\n phone: { type: 'phone' }, // Shows: ******4567\n salary: { type: 'redact' }, // Shows: [REDACTED]\n}\n```\n\n[Learn more about Masking →](/compiler/definitions/masking)\n\n### 5. Rate Limiting (Request Caps)\n\nRate limiting caps **how often** an operation can be called, backed by Cloudflare's native Rate Limiting binding — no extra storage, no third-party libraries. Unlike the other four layers, it's applied to **every resource by default** (read `1000/60s`, writes `200/60s`) and runs first, before any data is touched.\n\n```typescript\nrateLimit: {\n delete: { limit: 5, period: 60 }, // tighter than the 200/60s default\n},\n// read / create / update keep shipped defaults\n```\n\nOverride per-op, per-resource, or project-wide; set `false` at any scope to opt out. Limits are keyed by `<resource>:<op>:<userId>` (falling back to client IP for anonymous callers), and over-cap requests get a `429` with `Retry-After`.\n\n[Learn more about Rate Limiting →](/compiler/definitions/rate-limit)\n\n## How They Work Together\n\n**Scenario:** An interviewer requests `GET /candidates/cnd_123`\n\n1. **Rate Limit** checks: Is this user under their `read` cap on `candidates`?\n - Yes → Continue\n - No → 429 Too Many Requests (with `Retry-After`)\n\n2. **Firewall** checks: Is candidate `cnd_123` in the user's organization?\n - Yes → Continue\n - No → 404 Not Found (as if it doesn't exist)\n\n3. **Access** checks: Can interviewers perform GET?\n - Yes → Continue\n - No → 403 Forbidden\n\n4. **Guards** don't apply to GET (they're for writes)\n\n5. **Masking** applies: User is an `interviewer`, not `recruiter` or `hiring-manager`\n - Email: `jane@company.com` → `j***@c******.com`\n - Phone: `555-123-4567` → `******4567`\n\n6. **Response** sent with masked data\n\n## Locked Down by Default\n\nQuickback is **secure by default**. Nothing is accessible until you explicitly allow it.\n\n| Layer | Default | What you must do |\n|-------|---------|------------------|\n| Firewall | AUTO | Auto-detects from `organization_id`/`user_id` columns. Only configure for exceptions. |\n| Access | DENIED | Explicitly define `access` rules with roles |\n| Guards | LOCKED | Explicitly list `createable`, `updatable` fields |\n| Rate Limit | ON | Applied to every resource (read 1000/60s, write 200/60s). Override or set `false` to opt out. |\n| Actions | BLOCKED | Explicitly define `access` for each action |\n\n**You must deliberately open each door.** This prevents accidental data exposure.\n\n## Other Resource Options\n\nBeyond the five security layers, `defineTable` accepts a handful of declarative hints that shape the generated API and the CMS without touching your security posture.\n\n| Option | What it does | Full reference |\n|---|---|---|\n| `views` | Named column projections — `GET /resource/views/{name}` returns a subset of columns under its own access rule. | [Views](/compiler/definitions/views) |\n| `references` | Explicit FK target table for columns that don't follow the \"Id\"-stripped convention (e.g. `vendorId → contact`). | [CMS Schema Registry](/stack/cms/schema-registry) |\n| `displayColumn` | Column to use as the human-readable label in FK resolutions and CMS list views (auto-detected as `name`/`title`/`label` if not set). | [CMS Table Views](/stack/cms/table-views) |\n| `defaultSort` | Default sort order for CMS list rendering (`{ field, order: \"asc\" \\| \"desc\" }`). | [CMS Table Views](/stack/cms/table-views) |\n| `inputHints` | Per-column CMS input type: `select`, `richtext`, `textarea`, `lookup`, `currency`, etc. Pure CMS hint, no runtime effect. | [CMS Record Layouts](/stack/cms/record-layouts) |\n| `layouts` | Named record-page layouts — group fields into sections (collapsed, multi-column). Falls back to auto-grouping if unset. | [CMS Record Layouts](/stack/cms/record-layouts) |\n| `embeddings` | Auto-generate vector embeddings for specified fields on insert/update. | [Stack → Embeddings](/stack/vector/using-embeddings) |\n| `realtime` | Per-table broadcast config (`enabled`, `onInsert`, `onUpdate`, `onDelete`, `requiredRoles`, `fields`). | [Stack → Realtime](/stack/realtime/using-realtime) |\n| `path` | Override the route base path (defaults to feature name). | — |\n\nAll options are optional — omit them and Quickback uses sensible defaults (auto-detected display column, auto-grouped layout, no embeddings, no realtime).\n\n## Next Steps\n\n1. [Database Schema](/compiler/definitions/schema) — Define your tables\n2. [Firewall](/compiler/definitions/firewall) — Set up data isolation\n3. [Access](/compiler/definitions/access) — Configure read and write permissions\n4. [Guards](/compiler/definitions/guards) — Control field modifications\n5. [Masking](/compiler/definitions/masking) — Hide sensitive data\n6. [Rate Limit](/compiler/definitions/rate-limit) — Per-operation request caps\n7. [Views](/compiler/definitions/views) — Column-level security\n8. [Validation](/compiler/definitions/validation) — Field validation rules\n9. [Actions](/compiler/definitions/actions) — Add custom business logic"
127
135
  },
128
136
  "compiler/definitions/masking": {
129
137
  "title": "Masking - Field Redaction",
130
- "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](/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```"
138
+ "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### Named gates in masking\n\n[Named gates](/compiler/definitions/access#named-gates-authzrules) (`authz.rules`) follow the same discipline in `show:`:\n\n- A **who-only** gate expands like a named role (its flat role list; the owner-gated flat-role constraint above applies).\n- A gate carrying a **`record:`** predicate is a **compile error** — masking cannot evaluate record conditions, so the record dimension would be silently dropped.\n- A gate carrying **firewall lanes** is a **compile error** — masking has no firewall array to satisfy, so the gate's row lanes would silently not apply. Reference a who-only rule (or inline the roles) in `show:`, and stamp the firewall gate on the resource's `firewall:` instead.\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](/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```"
131
139
  },
132
140
  "compiler/definitions/permissions": {
133
141
  "title": "Permissions",
@@ -139,15 +147,15 @@ export const DOCS = {
139
147
  },
140
148
  "compiler/definitions/read": {
141
149
  "title": "Read - Unified Read Pipeline",
142
- "content": "The `read` block owns the read side of every resource: the collection-level\n`GET /` endpoint, single-record `GET /:id`, and named view projections. It\nreplaces the legacy `crud.list` and `crud.get` shapes — those are rejected\nat compile time in DSL v2.\n\n## Basic Usage\n\n```typescript\n// features/customers/customers.ts\n\nexport const customers = sqliteTable('customers', {\n id: text('id').primaryKey(),\n name: text('name').notNull(),\n email: text('email').notNull(),\n ssn: text('ssn'),\n status: text('status').notNull(),\n organizationId: text('organization_id').notNull(),\n});\n\nexport default defineTable(customers, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n masking: {\n ssn: { type: 'ssn', show: { roles: ['admin'] } },\n },\n read: {\n access: { roles: ['member', 'admin'] },\n views: {\n summary: {\n fields: ['id', 'name', 'status'],\n access: { roles: ['member', 'admin'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'ssn', 'status'],\n access: { roles: ['admin'] },\n },\n },\n },\n create: { access: { roles: ['admin'] } },\n update: { access: { roles: ['admin'] } },\n delete: { access: { roles: ['admin'] }, mode: 'soft' },\n});\n```\n\n## What `read` Owns\n\n| Endpoint | Gate |\n|----------|------|\n| `GET /api/v1/{resource}` | `read.access` |\n| `GET /api/v1/{resource}/:id` | `read.access` |\n| `GET /api/v1/{resource}/views/{name}` | `read.views[name].access` (falls back to `read.access`) |\n\nSingle-record `GET /:id` inherits `read.access` automatically — there's no\nseparate `read.get` block. If you need different access for single records,\nuse record-level conditions on `read.access`:\n\n```typescript\nread: {\n access: {\n or: [\n { roles: ['admin'] },\n { roles: ['member'], record: { ownerId: { equals: '$ctx.userId' } } },\n ],\n },\n}\n```\n\n## Configuration Options\n\n```typescript\ninterface ReadConfig {\n // Role/condition gate for collection reads, single-record reads, and the\n // default view fallback.\n access?: Access;\n\n // Optional read-side firewall override. If omitted, the resource-level\n // `firewall` block is used (the common case).\n firewall?: FirewallConfig;\n\n // Pagination defaults for collection reads.\n pageSize?: number; // Default page size (default: 50)\n maxPageSize?: number; // Hard cap (default: 100)\n\n // Named field projections. Each view has its own access and field list.\n views?: {\n [viewName: string]: ViewConfig;\n };\n}\n\ninterface ViewConfig {\n fields: string[]; // Columns returned by this view\n access?: Access; // Per-view access (falls back to read.access)\n pageSize?: number;\n maxPageSize?: number;\n}\n```\n\n## Access Ordering on `/:id`\n\nSingle-record `GET /:id` evaluates checks in this order to close the\n404-vs-403 ID-probe channel:\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\nAn unauthorized caller without a matching role gets 403 from step 2 before\nthe database is touched, so they can't distinguish \"row exists in another\ntenant\" from \"row doesn't exist.\" A caller with the right role but the wrong\ntenant gets the firewall's configured response (403 by default; see\n[`firewallErrorMode: 'hide'`](/compiler/definitions/firewall) for an opaque\n404 instead).\n\nFunction-form access is opaque to the pre-check (it always passes there) and\nis fully evaluated post-record, so `access: async (ctx, record) => ...`\nstill works as before.\n\n## Views Under `read.views`\n\nViews are named field projections — Column Level Security. They live under\n`read.views` (not at the resource top level). See\n[Views](/compiler/definitions/views) for the full feature reference.\n\n```typescript\nread: {\n access: { roles: ['member', 'admin'] },\n views: {\n public: {\n fields: ['id', 'title', 'status'],\n access: { roles: ['PUBLIC'] },\n },\n internal: {\n fields: ['id', 'title', 'status', 'salaryMin', 'salaryMax'],\n access: { roles: ['admin'] },\n },\n },\n}\n```\n\nNamed views are emitted at dedicated path routes:\n\n- `GET /api/v1/jobs/views/internal`\n- If `read.defaultView` is set, bare `GET /api/v1/jobs` resolves to that view.\n\n## Migrating from `crud.list` / `crud.get`\n\nDSL v2 rejects both at compile time. The migration is mechanical:\n\n| Before (DSL v1) | After (DSL v2) |\n|---|---|\n| `crud.list.access` | `read.access` |\n| `crud.list.pageSize` | `read.pageSize` |\n| `crud.list.maxPageSize` | `read.maxPageSize` |\n| `crud.list.fields: [...]` | Move to a named view under `read.views` |\n| `crud.get.access` | `read.access` (or record-level conditions) |\n| `crud.get.fields: [...]` | Move to a named view; clients call `/views/{name}` |\n| Top-level `views: {...}` | `read.views: {...}` |\n\nExample before/after:\n\n```typescript\n// Before — DSL v1\ncrud: {\n list: {\n access: { roles: ['member'] },\n pageSize: 25,\n },\n get: {\n access: { roles: ['member'] },\n fields: ['id', 'name', 'status'], // per-field projection\n },\n create: { access: { roles: ['admin'] } },\n}\n\n// After — DSL v2\nread: {\n access: { roles: ['member'] },\n pageSize: 25,\n views: {\n summary: {\n fields: ['id', 'name', 'status'],\n access: { roles: ['member'] },\n },\n },\n}\ncreate: { access: { roles: ['admin'] } }\n```\n\nClients that previously hit `GET /:id` to retrieve only summary fields now\nmove that projection to a named collection view such as\n`GET /api/v1/jobs/views/summary`. Single-record `GET /:id` always returns the\nfull masked record.\n\n## Read-Only Resources\n\nA resource that exposes only reads is valid with no write-operation blocks at all:\n\n```typescript\nexport default defineTable(balanceSnapshots, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: { access: { roles: ['member', 'admin'] } },\n // no create/update/delete/upsert — no writes\n});\n```\n\n## See Also\n\n- [Views](/compiler/definitions/views) — Full reference for named projections\n- [Access](/compiler/definitions/access) — Roles, record conditions, and combinators\n- [Firewall](/compiler/definitions/firewall) — Tenant scoping and `firewallErrorMode`\n- [Views API](/compiler/targets/hono-api/using-the-api/views-api) — Calling views from clients"
150
+ "content": "The `read` block owns the read side of every resource: the collection-level\n`GET /` endpoint, single-record `GET /:id`, and named view projections. It\nreplaces the legacy `crud.list` and `crud.get` shapes — those are rejected\nat compile time in DSL v2.\n\n## Basic Usage\n\n```typescript\n// features/customers/customers.ts\n\nexport const customers = sqliteTable('customers', {\n id: text('id').primaryKey(),\n name: text('name').notNull(),\n email: text('email').notNull(),\n ssn: text('ssn'),\n status: text('status').notNull(),\n organizationId: text('organization_id').notNull(),\n});\n\nexport default defineTable(customers, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n masking: {\n ssn: { type: 'ssn', show: { roles: ['admin'] } },\n },\n read: {\n access: { roles: ['member', 'admin'] },\n views: {\n summary: {\n fields: ['id', 'name', 'status'],\n access: { roles: ['member', 'admin'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'ssn', 'status'],\n access: { roles: ['admin'] },\n },\n },\n },\n create: { access: { roles: ['admin'] } },\n update: { access: { roles: ['admin'] } },\n delete: { access: { roles: ['admin'] }, mode: 'soft' },\n});\n```\n\n## What `read` Owns\n\n| Endpoint | Gate |\n|----------|------|\n| `GET /api/v1/{resource}` | `read.access` |\n| `GET /api/v1/{resource}/:id` | `read.access` |\n| `GET /api/v1/{resource}/views/{name}` | `read.views[name].access` (falls back to `read.access`) |\n\nEach `access` block takes a `roles: [...]` array. When the same role expression recurs across reads/views/CRUD, define it once in `authz.roles` and reference it by name — see [Centrally defined access rules](/compiler/definitions/access#centrally-defined-access-rules).\n\nSingle-record `GET /:id` inherits `read.access` automatically — there's no\nseparate `read.get` block. If you need different access for single records,\nuse record-level conditions on `read.access`:\n\n```typescript\nread: {\n access: {\n or: [\n { roles: ['admin'] },\n { roles: ['member'], record: { ownerId: { equals: '$ctx.userId' } } },\n ],\n },\n}\n```\n\n## Configuration Options\n\n```typescript\ninterface ReadConfig {\n // Role/condition gate for collection reads, single-record reads, and the\n // default view fallback.\n access?: Access;\n\n // Optional read-side firewall override. If omitted, the resource-level\n // `firewall` block is used (the common case).\n firewall?: FirewallConfig;\n\n // Pagination defaults for collection reads.\n pageSize?: number; // Default page size (default: 50)\n maxPageSize?: number; // Hard cap (default: 100)\n\n // Named field projections. Each view has its own access and field list.\n views?: {\n [viewName: string]: ViewConfig;\n };\n}\n\ninterface ViewConfig {\n fields: string[]; // Columns returned by this view\n access?: Access; // Per-view access (falls back to read.access)\n pageSize?: number;\n maxPageSize?: number;\n}\n```\n\n## Access Ordering on `/:id`\n\nSingle-record `GET /:id` evaluates checks in this order to close the\n404-vs-403 ID-probe channel:\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\nAn unauthorized caller without a matching role gets 403 from step 2 before\nthe database is touched, so they can't distinguish \"row exists in another\ntenant\" from \"row doesn't exist.\" A caller with the right role but the wrong\ntenant gets the firewall's configured response (403 by default; see\n[`firewallErrorMode: 'hide'`](/compiler/definitions/firewall) for an opaque\n404 instead).\n\nFunction-form access is opaque to the pre-check (it always passes there) and\nis fully evaluated post-record, so `access: async (ctx, record) => ...`\nstill works as before.\n\n## Views Under `read.views`\n\nViews are named field projections — Column Level Security. They live under\n`read.views` (not at the resource top level). See\n[Views](/compiler/definitions/views) for the full feature reference.\n\n```typescript\nread: {\n access: { roles: ['member', 'admin'] },\n views: {\n public: {\n fields: ['id', 'title', 'status'],\n access: { roles: ['PUBLIC'] },\n },\n internal: {\n fields: ['id', 'title', 'status', 'salaryMin', 'salaryMax'],\n access: { roles: ['admin'] },\n },\n },\n}\n```\n\nNamed views are emitted at dedicated path routes:\n\n- `GET /api/v1/jobs/views/internal`\n- If `read.defaultView` is set, bare `GET /api/v1/jobs` resolves to that view.\n\n## Migrating from `crud.list` / `crud.get`\n\nDSL v2 rejects both at compile time. The migration is mechanical:\n\n| Before (DSL v1) | After (DSL v2) |\n|---|---|\n| `crud.list.access` | `read.access` |\n| `crud.list.pageSize` | `read.pageSize` |\n| `crud.list.maxPageSize` | `read.maxPageSize` |\n| `crud.list.fields: [...]` | Move to a named view under `read.views` |\n| `crud.get.access` | `read.access` (or record-level conditions) |\n| `crud.get.fields: [...]` | Move to a named view; clients call `/views/{name}` |\n| Top-level `views: {...}` | `read.views: {...}` |\n\nExample before/after:\n\n```typescript\n// Before — DSL v1\ncrud: {\n list: {\n access: { roles: ['member'] },\n pageSize: 25,\n },\n get: {\n access: { roles: ['member'] },\n fields: ['id', 'name', 'status'], // per-field projection\n },\n create: { access: { roles: ['admin'] } },\n}\n\n// After — DSL v2\nread: {\n access: { roles: ['member'] },\n pageSize: 25,\n views: {\n summary: {\n fields: ['id', 'name', 'status'],\n access: { roles: ['member'] },\n },\n },\n}\ncreate: { access: { roles: ['admin'] } }\n```\n\nClients that previously hit `GET /:id` to retrieve only summary fields now\nmove that projection to a named collection view such as\n`GET /api/v1/jobs/views/summary`. Single-record `GET /:id` always returns the\nfull masked record.\n\n## Read-Only Resources\n\nA resource that exposes only reads is valid with no write-operation blocks at all:\n\n```typescript\nexport default defineTable(balanceSnapshots, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: { access: { roles: ['member', 'admin'] } },\n // no create/update/delete/upsert — no writes\n});\n```\n\n## Aggregate Reads\n\nReading a parent **with** its owned relations is served today by `defineView`\nincludes (reverse-FK embedding with per-included-table firewall + masking) and\ncontract-v2 `?include=` on FK columns. The aggregate-changeset write surface\n([changesets](/compiler/definitions/changesets)) deliberately returns the\n**root row only** in v1 — a nested aggregate representation is the phase-2\nreader and will land on `?include=` over the `owns` graph, not on the write\nresponse.\n\n## See Also\n\n- [Views](/compiler/definitions/views) — Full reference for named projections\n- [Changesets](/compiler/definitions/changesets) — Atomic writes over the `owns` graph\n- [Access](/compiler/definitions/access) — Roles, record conditions, and combinators\n- [Firewall](/compiler/definitions/firewall) — Tenant scoping and `firewallErrorMode`\n- [Views API](/compiler/targets/hono-api/using-the-api/views-api) — Calling views from clients"
143
151
  },
144
152
  "compiler/definitions/schema": {
145
153
  "title": "Database Schema",
146
- "content": "There is **one way to write a feature**: `feature()` — one file, one export, the table and its security contract in a single call. See [feature()](/compiler/definitions/feature) for the full reference.\n\nTwo lower-level forms exist for specific situations, not as alternatives to choose between — both compile to exactly the same runtime, and `feature()` itself is sugar over the first:\n\n- **`q.table()` + `defineTable()`** — the two-export form `feature()` expands into. Reach for it only when another file needs to import the table identifier directly (e.g. an action file referencing the table before the default export).\n- **Drizzle `sqliteTable()` / `pgTable()` + `defineTable()`** — interop for bringing an existing Drizzle schema forward, or for dialect-specific column options.\n\nIf you're starting fresh — or you're an agent defining a user's features — use `feature()` for every table.\n\n## feature() — the one-call form (default)\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport default feature('jobs', {\n columns: {\n id: q.id(),\n title: q.text().required(),\n department: q.text().required(),\n status: q.text().default('draft').required(), // \"draft\" | \"open\" | \"closed\"\n salaryMin: q.int().optional(),\n salaryMax: q.int().optional(),\n organizationId: q.scope('organization'),\n },\n // firewall block omitted — q.scope('organization') triggers auto-derivation\n // of [{ field: 'organizationId', equals: 'ctx.activeOrgId' }, { field: 'deletedAt', isNull: true }].\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\nType inference still works — `typeof import('./jobs').default.$infer` gives you the row type. In action files, `import jobs from './jobs'` gives you the same typed handle you'd get from `q.table()`, so `defineActions(jobs, { … })` accepts it unchanged.\n\n## q.table() + defineTable() — the expanded form\n\nThis is what `feature()` compiles into. Write it by hand only when another file needs the table identifier as a named export.\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport const jobs = q.table('jobs', {\n id: q.id(),\n title: q.text().required(),\n department: q.text().required(),\n status: q.text().default('draft').required(),\n salaryMin: q.int().optional(),\n salaryMax: q.int().optional(),\n organizationId: q.scope('organization'),\n});\n\nexport default defineTable(jobs, {\n guards: { /* ... */ },\n read: { /* ... */ },\n create: { /* ... */ },\n update: { /* ... */ },\n delete: { /* ... */ },\n});\n\nexport type Job = typeof jobs.$infer;\n```\n\nProduces byte-identical output to the `feature()` form above — the compiler expands `feature()` to exactly this shape internally. Use whichever reads better for the file you're writing.\n\nA few mechanics to know:\n\n- **Column names** default to snake_case of the JS key — `organizationId` ↔ `organization_id`, `salaryMin` ↔ `salary_min`. Pass a positional argument to override: `q.text('custom_name')`.\n- **`q.id()`** emits `text('id').primaryKey()` with a provider-driven app-layer default.\n- **`.required()` / `.optional()`** control NOT NULL. Chain before or after `.default(x)`.\n- **References:** `q.text().required().references(() => other.id, { onDelete: 'cascade' })`.\n- **Indexes:** column-level `.index()` or table-level `indexes` / `unique` as a third arg to `q.table(name, cols, { indexes, unique })`. With `feature()`, pass `indexes` and `unique` as top-level keys alongside `columns` — the sugar forwards them into the same `q.table` opts.\n\n### Column Types\n\n| Builder | Drizzle equivalent | Zod type |\n|---------|---------------------|----------|\n| `q.text()` | `text(...)` | `z.string()` |\n| `q.url()` | `text(...)` | `z.string().url()` |\n| `q.int()` | `integer(...)` | `z.number().int()` |\n| `q.bool()` | `boolean(...)` | `z.boolean()` |\n| `q.uuid()` | `uuid(...)` | `z.string().uuid()` |\n| `q.timestamp()` | `timestamp(...)` (converted to SQLite `text` on sqlite targets) | `z.coerce.date()` |\n| `q.json()` | `jsonb(...)` | `z.unknown()` (or the type you pass in) |\n| `q.enum(['a','b'])` | `text(..., { enum: [...] })` | `z.enum([...])` |\n| `q.id()` | `text('id').primaryKey()` | `z.string()` |\n| `q.scope(kind)` | `text(...).notNull()` | `z.string()` |\n\n`q.text()` and `q.url()` accept either a SQL-name string or an options object — `q.text({ sqlName: 'org_id', maxLength: 80 })`. `maxLength` adds `z.string().max(n)` at the validation edge; the SQL column stays `text` (D1 ignores `VARCHAR(n)` length anyway).\n\n`q.url()` is `q.text()` plus `z.string().url()` at the validation edge, so `javascript:` / `data:` URIs and free-form strings are rejected before they ever land in storage or get rendered in the CMS.\n\n`q.id()` emits a plain text primary key. Actual ID assignment at insert time is driven by the provider's `generateId` setting. This keeps q's output decoupled from any specific ID library.\n\nFor `generateId: \"cuid\"`, there is one important nuance: import-capable runtime\npaths can emit real `createId()` usage, but compiler-managed schema\nauto-injection may keep the same `createId()` call site and back it with a\nfile-local `crypto.randomUUID()` polyfill so schema-generation sandboxes do not\ndepend on project `node_modules`.\n\n### q.scope() — tenant scope columns\n\n`q.scope(kind)` is the canonical way to declare a column that holds a tenant-scope value (org / owner / team). It compiles to `text(...).notNull()` like a regular required text column, plus metadata that the compiler reads to:\n\n1. **Auto-derive the firewall predicate** — `q.scope('organization')` produces `[{ field: 'organizationId', equals: 'ctx.activeOrgId' }]` so you can omit the explicit `firewall:` block. (If `deletedAt` is present — and it is whenever the resource uses soft delete, which is the default — the `isNull(deletedAt)` predicate is appended automatically.)\n2. **Reject the column from client input** — scope fields land in `GUARDS_CONFIG.systemManaged` alongside the audit fields, so `POST { organizationId: 'org_other' }` returns 400 even if guards aren't otherwise configured.\n3. **Auto-populate on create / upsert** — the value is taken from the request context, not the request body.\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\nOverride the context source for non-default sources:\n\n```typescript\nownerId: q.scope('owner', { source: 'ctx.userId' }),\n```\n\n`q.scope()` is preferred over `q.text().required()` for tenant columns. Auto-detection on column names (`organizationId`, `userId`, etc.) still works as a fallback for projects bringing forward Drizzle schemas, but the explicit `q.scope()` form locks in the semantics in the source.\n\n### Naming Convention\n\nBy default, `q` picks the SQL column name from the JS key using the target database's conventional casing. Both `cloudflare-d1` and `neon` default to **`snake_case`** (`organizationId` → `organization_id`).\n\nYou can override for any project by setting `namingConvention` on the database provider config:\n\n```ts\n// quickback/quickback.config.ts\nexport default {\n providers: {\n database: {\n name: 'cloudflare-d1',\n config: {\n namingConvention: 'camelCase', // keep JS-style names in the SQL\n },\n },\n },\n};\n```\n\nFor one-off overrides on a specific column, pass an explicit name as the positional argument:\n\n```ts\norganizationId: q.scope('organization', { sqlName: 'org_id' }), // SQL name: 'org_id'\n```\n\n## Drizzle interop\n\nIf you have an existing Drizzle schema you're bringing forward — or need a dialect-specific column option `q` doesn't expose — use `pgTable` / `sqliteTable` / `mysqlTable` directly:\n\n| Target Database | Import From | Table Function |\n|-----------------|-------------|----------------|\n| Cloudflare D1, Turso, SQLite | `drizzle-orm/sqlite-core` | `sqliteTable` |\n| Supabase, Neon, PostgreSQL | `drizzle-orm/pg-core` | `pgTable` |\n| PlanetScale, MySQL | `drizzle-orm/mysql-core` | `mysqlTable` |\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport const jobs = sqliteTable('jobs', {\n id: text('id').primaryKey(),\n organizationId: text('organization_id').notNull(),\n title: text('title').notNull(),\n department: text('department').notNull(),\n status: text('status').notNull(),\n salaryMin: integer('salary_min'),\n salaryMax: integer('salary_max'),\n});\n\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 create: { /* ... */ },\n update: { /* ... */ },\n delete: { /* ... */ },\n});\n\nexport type Job = typeof jobs.$inferSelect;\n```\n\nWhen using Drizzle (rather than `q.scope()`), declare the firewall as a predicate array. Auto-detection still works on column names (`organizationId`, `ownerId`, `teamId`) so you can omit `firewall:` entirely if exactly one isolation column is present.\n\n### When Drizzle interop is the right call\n\nDefault to `feature()`. Drop to Drizzle only when:\n\n- You already have Drizzle schemas to bring forward\n- You need a Drizzle-specific column option not yet in `q` (e.g., `decimal`, `varchar` with length, dialect-specific types)\n\nFeatures in the same project may mix freely — Quickback dispatches per feature — so one interop table doesn't force the rest of the project off `feature()`.\n\nOne dialect rule: interop files **without** a `defineTable(...)` default export (internal child tables) are not dialect-translated — author them in the target database's dialect. On Postgres providers (Neon, Supabase), a `sqliteTable` interop source without `defineTable` is a compile-time error; write it with `pgTable` from `drizzle-orm/pg-core` instead. Sources **with** `defineTable(...)` keep compiling across dialects automatically.\n\n### Drizzle Column Types\n\nDrizzle supports all standard SQL column types:\n\n| Type | Drizzle Function | Example |\n|------|------------------|---------|\n| String | `text()`, `varchar()` | `text('name')` |\n| Integer | `integer()`, `bigint()` | `integer('count')` |\n| Boolean | `boolean()` | `boolean('is_active')` |\n| Timestamp | `timestamp()` | `timestamp('created_at')` |\n| JSON | `json()`, `jsonb()` | `jsonb('metadata')` |\n| UUID | `uuid()` | `uuid('id')` |\n| Decimal | `decimal()`, `numeric()` | `decimal('price', { precision: 10, scale: 2 })` |\n\n### Drizzle Column Modifiers\n\n```typescript\n// Required field\nname: text('name').notNull()\n\n// Default value\nisActive: boolean('is_active').default(true)\n\n// Primary key\nid: text('id').primaryKey()\n\n// Unique constraint\nemail: text('email').unique()\n\n// Default to current timestamp\ncreatedAt: timestamp('created_at').defaultNow()\n```\n\n## File Organization\n\nOrganize your tables by feature. Each feature directory contains table files:\n\n```\nquickback/\n├── quickback.config.ts\n└── features/\n ├── jobs/\n │ ├── jobs.ts # Main table + config\n │ ├── applications.ts # Related table + config\n │ └── actions.ts # Custom actions\n ├── candidates/\n │ ├── candidates.ts # Table + config\n │ └── candidate-notes.ts # Related table\n └── organizations/\n └── organizations.ts\n```\n\n**Key points:**\n- Tables with `export default defineTable(...)` get resource routes generated\n- Tables without a default export are internal (no routes, used for joins/relations)\n- Route paths are derived from filenames: `applications.ts` → `/api/v1/applications`\n\n### defineTable vs defineResource\n\n- **`defineTable`** — The standard function for defining tables with generated API routes\n- **`defineResource`** — Deprecated and scheduled for removal. Still compiles with a warning; do not write new code with it — migrate to `feature()` (or `defineTable`).\n\n```typescript\n// Preferred:\nexport default defineTable(jobs, { /* config */ });\n```\n\n## 1 Resource = 1 Security Boundary\n\nEach `defineTable()` call defines a complete, self-contained security boundary. The security config you write — firewall, access, guards, and masking — is compiled into a single resource file that wraps all generated routes for that table.\n\nThis is a deliberate design choice. Mixing two resources with different security rules in one configuration would create ambiguity about which firewall, access, or masking rules apply to which table. By keeping it 1:1, there's never any question.\n\n| Scenario | What to do |\n|----------|------------|\n| Table needs its own API routes + security | Own file with `defineTable()` |\n| Table is internal/supporting (no direct API) | Extra `.ts` file in the parent feature directory, no `defineTable()` |\n\nA supporting table without `defineTable()` is useful when it's accessed internally — by action handlers, joins, or background jobs — but should never be directly exposed as its own API endpoint.\n\n## Internal Tables (No Routes)\n\nFor junction tables or internal data structures that shouldn't have API routes, simply omit the `defineTable` export. Add a `// @quickback-internal` marker so the compiler skips the \"no defineTable found\" warning:\n\n```typescript\n// quickback/features/jobs/interview-scores.ts\n\n// @quickback-internal — child table, no routes intentionally.\n\nexport const interviewScores = sqliteTable('interview_scores', {\n applicationId: text('application_id').notNull(),\n interviewerId: text('interviewer_id').notNull(),\n score: integer('score'),\n organizationId: text('organization_id').notNull(), // Scope junction tables for cascade soft-deletes\n});\n\n// No default export = no routes generated\n```\n\nThese internal tables still participate in the database schema and migrations — they just don't get API routes or security configuration. Without the `@quickback-internal` marker the compiler emits a warning per table, since the missing `defineTable` is more often a bug than a deliberate choice.\n\nThe compiler automatically injects the four **[audit fields](#audit-fields)** (`createdAt`/`createdBy`/`modifiedAt`/`modifiedBy`), the soft-delete pair (`deletedAt`/`deletedBy`, when soft delete is enabled), and **`organizationId`** into child/junction tables when the parent feature is org-scoped. This ensures cascade soft deletes and scoped queries work correctly without manual column definitions.\n\n## Audit Fields\n\nQuickback adds four audit columns to **every table** (including child/junction tables without `defineTable`) — never declare them in your schemas:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `createdAt` | timestamp | Set on insert |\n| `createdBy` | text | Actor that performed the insert (`ctx.userId`) |\n| `modifiedAt` | timestamp | Set on every insert and update |\n| `modifiedBy` | text | Actor that performed the latest insert/update (`ctx.userId`) |\n\nAudit fields are a separate concept from soft-delete (`deletedAt`/`deletedBy`) — they're always present, regardless of delete mode. See [Soft-Delete Fields](#soft-delete-fields) below.\n\nOpt out of audit injection entirely with `compiler.features.auditFields: false` in `quickback.config.ts`. (You almost never want to.)\n\n### How auto-injection works (two layers)\n\n\"Auto-injection\" covers two distinct steps. Conflating them is the most common source of confusion:\n\n1. **Schema injection (compile-time)** — the compiler adds the four columns to every Drizzle table. Idempotent: if you've authored a column with the same name yourself, the compiler leaves yours alone.\n2. **Runtime injection (per-write)** — a Proxy around the request-context `db` (`createAuditDb`, generated to `src/lib/audit-wrapper.ts`) intercepts `.insert(...).values(...)` and `.update(...).set(...)` and writes the audit columns from `ctx.userId` and the actual write moment.\n\nThe runtime layer **hard-stamps** every audit field on every write. Caller-supplied values for `createdAt`/`createdBy`/`modifiedAt`/`modifiedBy` are silently overwritten. This is intentional: the audit log can never be forged by a crafted request body or by a client echoing a row back into a PATCH.\n\n```ts\n// In a custom action handler — caller cannot fake audit attribution\nawait db.insert(records).values({\n id: createId(),\n status: 'active',\n createdBy: 'admin', // ← ignored; wrapper writes ctx.userId\n modifiedAt: '1999-01-01', // ← ignored; wrapper writes \"now\"\n});\n```\n\nWhat the caller is responsible for: `id` (the framework doesn't mint ids for you) and the domain fields.\n\nWhat the caller does *not* need to set: any of the four audit fields, ever.\n\n### Actors: who shows up in `createdBy` / `modifiedBy`\n\nThe wrapper writes whatever string is in `ctx.userId`. For user-driven requests this is the authenticated user's id — set by auth middleware before the handler runs. For non-user-driven entry points (inbound webhooks, cron, queue workers), you mint a synthetic actor id at the boundary so the audit log preserves provenance.\n\n**Inherit before you mint.** If a real user's request triggers cascades, hooks, or enqueues background jobs, every downstream write should carry that user's id — not a synthetic one. The cascade is part of the user's action. Only mint when there is genuinely no upstream user.\n\nWhen you do mint, use a single namespace and a stable convention:\n\n| Boundary | Actor id |\n|----------|----------|\n| Inbound webhook | `system:webhook-<provider>` (e.g. `system:webhook-stripe`) |\n| Scheduled / cron | `system:cron-<job>` (e.g. `system:cron-cleanup-stale`) |\n| Queue worker | `system:queue-<queue>` (e.g. `system:queue-embeddings-retry`) |\n| Quickback platform-internal write with no user upstream | `system:quickback` |\n| Out-of-band operator script | `system:script-<name>` |\n\nThe `system:` prefix marks \"not a real user\" — readable by anyone joining the audit columns to `users`, and cheap to filter on. Don't use `tenant:admin` or `quickback:admin`: those imply a human role nobody is actually playing. The tenant context is already on the row (in `organizationId`); the actor id is purely about *source*.\n\n### Failure mode: missing `ctx.userId`\n\nIf a write reaches the wrapper without a `ctx.userId`, the wrapper throws:\n\n```\naudit-wrapper: insert reached without ctx.userId.\nIf this is an intentional system-side write, use the unwrapped db directly.\n```\n\nTwo paths to fix it, depending on intent:\n\n- **Mint a synthetic actor** (preferred — preserves attribution) — populate `ctx.userId` with one of the conventions above before calling into your handler.\n- **Bypass the wrapper entirely** — use the unwrapped `createDb` instead of the request-context `db`. Use this only for migrations, schema repair, or backfill scripts where you genuinely don't want any audit attribution. The audit columns will fall back to DB defaults (`createdAt`/`modifiedAt` populate from `defaultNow()`; `createdBy`/`modifiedBy` end up `NULL`).\n\n### Disabling Audit Fields\n\nTo disable automatic audit fields for your project:\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n // ...\n compiler: {\n features: {\n auditFields: false, // Disable for entire project\n }\n }\n});\n```\n\nThis turns off both layers — schema injection and the runtime wrapper.\n\n## Soft-Delete Fields\n\n`deletedAt` and `deletedBy` are **not** audit fields. They're a separate, per-table mechanism for soft delete:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `deletedAt` | timestamp | Set when the record is soft-deleted |\n| `deletedBy` | text | Actor that performed the soft delete (`ctx.userId`) |\n\nThe compiler injects them only when the resource uses soft delete — i.e. when neither `delete.mode` nor `delete.batch.mode` is explicitly `'hard'`. Soft is the default, so most tables get the columns. Tables with both delete paths set to `'hard'` skip them entirely, which also drops the `isNull(deletedAt)` predicate from the firewall WHERE clause.\n\n```typescript\n// soft delete (default) — table gets deletedAt + deletedBy\ndelete: {}\n\n// hard delete — no deletedAt/deletedBy columns, no soft-delete predicate\ndelete: { mode: 'hard', batch: { mode: 'hard' } }\n```\n\n### Caller contract\n\nIn custom-action handlers, **passing `deletedAt` in `.set({})` is the signal** that this update is a soft delete. Any value works — the wrapper detects the field and overwrites both `deletedAt` and `deletedBy` with `now` and `ctx.userId`:\n\n```ts\nawait db.update(records)\n .set({ deletedAt: new Date() }) // signal — value is overwritten\n .where(eq(records.id, id));\n```\n\nYou don't set `deletedBy` yourself; the wrapper pairs it with the `deletedAt` signal.\n\n### Protected system fields\n\nThe audit and soft-delete columns are always protected from client input, even with `guards: false`:\n\n- `id` (when `generateId` is not `false`)\n- `createdAt`, `createdBy` *(audit — always present)*\n- `modifiedAt`, `modifiedBy` *(audit — always present)*\n- `deletedAt`, `deletedBy` *(soft-delete — present when delete mode allows soft)*\n\nProtection is enforced by the runtime wrapper — even if a request body passes one of these, it gets overwritten before the SQL is built.\n\n## Auto-Indexes\n\nThe compiler injects performance-critical indexes you'd otherwise have to author by hand. The pass runs after audit-field injection (so `deletedAt` is present) and is idempotent — if you already declared a matching index it's left alone.\n\n| Trigger | Index | Why |\n|---------|-------|-----|\n| Tenant column (`organizationId` / `organisationId` / `userId`) + `deletedAt` | Composite `(<isolation_col>, deletedAt)` | Every list query filters by isolation AND `deletedAt IS NULL` — a composite index lets D1/SQLite prune both predicates in one btree walk. |\n| Any FK column (`.references(() => other.id)`) | Single-column `(<fk_col>)` | SQLite/D1 don't auto-index FK columns, and the generated FK existence checks read by id on the parent. |\n| Any column that appears in a view's `read.query.sortable` allowlist (or `defaultSort`) | Single-column `(<col>)` | Sort scans go through an index instead of a full-table scan. |\n\nIndexes are emitted into the table's Drizzle extras callback (`(t) => ({ ... })`) and named `<table>_<col>_idx` (or `<table>_<col1>_<col2>_idx` for the composite). The `index` import is added to your schema's `drizzle-orm/<dialect>-core` import line if it isn't already there.\n\nYou can opt out of any auto-injected index by declaring your own with the same name or column set — the injector treats both as already-present and skips.\n\n## Ownership Fields\n\nFor the firewall to work, declare a tenant-scope column. With `q.scope()` (recommended), the compiler auto-derives the firewall predicate, marks the column as system-managed, and auto-populates it on create:\n\n```typescript\n// q DSL (recommended)\norganizationId: q.scope('organization') // → ctx.activeOrgId\nownerId: q.scope('owner') // → ctx.userId\nteamId: q.scope('team') // → ctx.activeTeamId\n```\n\nWhen using Drizzle directly, declare a regular column. Auto-detection picks it up by name; `q.scope()` semantics (systemManaged, auto-populate) still apply because they're keyed off the firewall predicate, not the column DSL:\n\n```typescript\n// Drizzle interop\norganizationId: text('organization_id').notNull()\nownerId: text('owner_id').notNull()\nteamId: text('team_id').notNull()\n```\n\n## Display Column\n\nWhen a table has foreign key columns (e.g., `departmentId` referencing `departments`), Quickback can automatically resolve the human-readable label in GET and LIST responses. This eliminates the need for frontend lookup calls.\n\n### Auto-Detection\n\nQuickback auto-detects the display column by checking for common column names in this order:\n\n`name` → `title` → `label` → `headline` → `subject` → `code` → `displayName` → `fullName` → `description`\n\nIf your `departments` table has a `name` column, it's automatically used as the display column. No config needed.\n\n### Explicit Override\n\nOverride the auto-detected column with `displayColumn`:\n\n```typescript\nexport default defineTable(interviewStages, {\n displayColumn: 'label', // Use 'label' instead of auto-detected 'name'\n read: { access: { roles: [\"hiring-manager\", \"recruiter\"] } },\n});\n```\n\n### Default Sort\n\nSet a default sort order for the CMS table list view with `defaultSort`:\n\n```typescript\nexport default defineTable(podcastEpisodes, {\n defaultSort: { field: \"createdAt\", order: \"desc\" },\n firewall: [{ exception: true }],\n read: { access: { roles: [\"PUBLIC\"] } },\n});\n```\n\nThe CMS applies this sort when the table first loads. Users can still click column headers to change the sort order.\n\n### How Labels Appear in Responses\n\nFor any FK column ending in `Id`, the API adds a `_label` field with the resolved display value:\n\n```json\n{\n \"id\": \"job_abc\",\n \"title\": \"Senior Engineer\",\n \"departmentId\": \"dept_xyz\",\n \"department_label\": \"Engineering\",\n \"locationId\": \"loc_123\",\n \"location_label\": \"San Francisco\"\n}\n```\n\nThe pattern is `{columnWithoutId}_label`. The frontend can find all labels with:\n\n```typescript\nObject.keys(record).filter(k => k.endsWith('_label'))\n```\n\nLabel resolution works within the same feature (tables in the same feature directory). System columns (`organizationId`, `createdBy`, `modifiedBy`) are never resolved.\n\nFor LIST endpoints, labels are batch-resolved efficiently — one query per FK column, not per record.\n\n## References\n\nWhen your FK columns don't match the target table name by convention (e.g., `vendorId` actually points to the `contact` table), declare explicit references so the CMS and schema registry know the correct target:\n\n```typescript\nexport default defineTable(applications, {\n references: {\n candidateId: \"candidate\",\n jobId: \"job\",\n referredById: \"candidate\",\n },\n // ... firewall, guards, crud\n});\n```\n\nEach key is a column name ending in `Id`, and the value is the camelCase table name it references. These mappings flow into the schema registry as `fkTarget` on each column, enabling the CMS to render typeahead/lookup inputs that search the correct table.\n\nConvention-based matching (strip `Id` suffix, look for a matching table) still works for simple cases like `projectId` → `project`. Use `references` only for columns where the convention doesn't match.\n\n## Input Hints\n\nControl how the CMS renders form inputs for specific columns. By default the CMS infers input types from the column's SQL type — `inputHints` lets you override that:\n\n```typescript\nexport default defineTable(jobs, {\n inputHints: {\n status: \"select\",\n department: \"select\",\n salaryMin: \"currency\",\n salaryMax: \"currency\",\n description: \"richtext\",\n },\n // ... firewall, guards, crud\n});\n```\n\n### Available Hint Values\n\n| Hint | Renders As |\n|------|-----------|\n| `richtext` | Rich text editor (tiptap) — bold, italic, headings, lists, links. Stores HTML. Lazy-loaded in edit mode, rendered as formatted HTML in view mode. |\n| `select` | Dropdown select (single value) |\n| `multi-select` | Multi-value select |\n| `radio` | Radio button group |\n| `checkbox` | Checkbox toggle |\n| `textarea` | Multi-line text input |\n| `lookup` | FK typeahead search |\n| `hidden` | Hidden from forms |\n| `color` | Color picker |\n| `date` | Date picker |\n| `datetime` | Date + time picker |\n| `time` | Time picker |\n| `currency` | Currency input with formatting |\n\nInput hints are emitted in the schema registry as `inputHints` on the table metadata, and the CMS reads them to render the appropriate form controls.\n\n### Rich Text Example\n\nFor fields that contain HTML content (e.g., blog posts, descriptions from RSS feeds), use `\"richtext\"`:\n\n```typescript\nexport default defineTable(podcastEpisodes, {\n inputHints: { description: \"richtext\" },\n // ...\n});\n```\n\nThe CMS will:\n- **View mode**: Render the HTML with proper formatting (headings, lists, links, etc.)\n- **Edit mode**: Load a tiptap rich text editor with a toolbar (bold, italic, H2, H3, bullet/ordered lists, links, code, undo/redo)\n- **Storage**: HTML strings — no format conversion needed, compatible with external HTML content\n\n## Relations (Optional)\n\nDrizzle supports defining relations for type-safe joins:\n\n```typescript\n\nexport const jobsRelations = relations(jobs, ({ one, many }) => ({\n organization: one(organizations, {\n fields: [jobs.organizationId],\n references: [organizations.id],\n }),\n applications: many(applications),\n}));\n```\n\nDrizzle `relations(...)` describe application-side joins; they do not always\ncreate a database foreign-key constraint. On Neon, use\n[`compiler.migrations.foreignKeys`](/compiler/config#neon-foreign-key-migrations)\nfor fully qualified cross-schema or composite constraints that cannot be\ndeclared alongside a table. The ordered source and target column tuples must\nhave equal arity, and the referenced target tuple must have a matching unique\nor primary-key constraint before the foreign key migration runs.\n\nUse these constraints for relational integrity only. Authorization, pass\nconsumption, state transitions, and other business logic belong in the API\naction layer.\n\n## Database Configuration\n\nConfigure database options in your Quickback config:\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n name: 'my-app',\n providers: {\n database: defineDatabase('cloudflare-d1', {\n generateId: 'prefixed', // 'uuid' | 'cuid' | 'nanoid' | 'short' | 'prefixed' | 'serial' | false\n namingConvention: 'snake_case', // 'camelCase' | 'snake_case'\n usePlurals: false, // Auth table names: 'users' vs 'user'\n }),\n },\n compiler: {\n features: {\n auditFields: true, // Auto-manage audit timestamps\n }\n }\n});\n```\n\n## Choosing Your Dialect\n\nUse the Drizzle dialect that matches your database provider:\n\n### SQLite (Cloudflare D1)\n\n```typescript\n\nexport const jobs = sqliteTable('jobs', {\n id: text('id').primaryKey(),\n title: text('title').notNull(),\n metadata: text('metadata', { mode: 'json' }), // JSON stored as text\n isOpen: integer('is_open', { mode: 'boolean' }).default(false),\n organizationId: text('organization_id').notNull(),\n});\n```\n\n### PostgreSQL (Neon)\n\n```typescript\n\nexport const jobs = pgTable('jobs', {\n id: serial('id').primaryKey(),\n title: text('title').notNull(),\n metadata: jsonb('metadata'), // Native JSONB\n isOpen: boolean('is_open').default(false),\n organizationId: text('organization_id').notNull(),\n});\n```\n\n### Key Differences\n\n| Feature | SQLite | PostgreSQL |\n|---------|--------|------------|\n| Boolean | `integer({ mode: 'boolean' })` | `boolean()` |\n| JSON | `text({ mode: 'json' })` | `jsonb()` or `json()` |\n| Auto-increment | `integer().primaryKey()` | `serial()` |\n| UUID | `text()` | `uuid()` |\n\n## Next Steps\n\n- [Configure the firewall](/compiler/definitions/firewall) for data isolation\n- [Set up access control](/compiler/definitions/access) for read and write operations\n- [Define guards](/compiler/definitions/guards) for field modification rules\n- [Add custom actions](/compiler/definitions/actions) for business logic"
154
+ "content": "There is **one way to write a feature**: `feature()` — one file, one export, the table and its security contract in a single call. See [feature()](/compiler/definitions/feature) for the full reference.\n\nTwo lower-level forms exist for specific situations, not as alternatives to choose between — both compile to exactly the same runtime, and `feature()` itself is sugar over the first:\n\n- **`q.table()` + `defineTable()`** — the two-export form `feature()` expands into. Reach for it only when another file needs to import the table identifier directly (e.g. an action file referencing the table before the default export).\n- **Drizzle `sqliteTable()` / `pgTable()` + `defineTable()`** — interop for bringing an existing Drizzle schema forward, or for dialect-specific column options.\n\nIf you're starting fresh — or you're an agent defining a user's features — use `feature()` for every table.\n\n## feature() — the one-call form (default)\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport default feature('jobs', {\n columns: {\n id: q.id(),\n title: q.text().required(),\n department: q.text().required(),\n status: q.text().default('draft').required(), // \"draft\" | \"open\" | \"closed\"\n salaryMin: q.int().optional(),\n salaryMax: q.int().optional(),\n organizationId: q.scope('organization'),\n },\n // firewall block omitted — q.scope('organization') triggers auto-derivation\n // of [{ field: 'organizationId', equals: 'ctx.activeOrgId' }, { field: 'deletedAt', isNull: true }].\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\nType inference still works — `typeof import('./jobs').default.$infer` gives you the row type. In action files, `import jobs from './jobs'` gives you the same typed handle you'd get from `q.table()`, so `defineActions(jobs, { … })` accepts it unchanged.\n\n## q.table() + defineTable() — the expanded form\n\nThis is what `feature()` compiles into. Write it by hand only when another file needs the table identifier as a named export.\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport const jobs = q.table('jobs', {\n id: q.id(),\n title: q.text().required(),\n department: q.text().required(),\n status: q.text().default('draft').required(),\n salaryMin: q.int().optional(),\n salaryMax: q.int().optional(),\n organizationId: q.scope('organization'),\n});\n\nexport default defineTable(jobs, {\n guards: { /* ... */ },\n read: { /* ... */ },\n create: { /* ... */ },\n update: { /* ... */ },\n delete: { /* ... */ },\n});\n\nexport type Job = typeof jobs.$infer;\n```\n\nProduces byte-identical output to the `feature()` form above — the compiler expands `feature()` to exactly this shape internally. Use whichever reads better for the file you're writing.\n\nA few mechanics to know:\n\n- **Column names** default to snake_case of the JS key — `organizationId` ↔ `organization_id`, `salaryMin` ↔ `salary_min`. Pass a positional argument to override: `q.text('custom_name')`.\n- **`q.id()`** emits `text('id').primaryKey()` with a provider-driven app-layer default.\n- **`.required()` / `.optional()`** control NOT NULL. Chain before or after `.default(x)`.\n- **References:** `q.text().required().references(() => other.id, { onDelete: 'cascade' })`. An FK declares a *pointer*, not ownership — when the child rows are a **composition** of one root (junctions, phones/emails, line items), also declare [`owns`](/compiler/definitions/changesets) on the root to generate the atomic aggregate write path.\n- **Indexes:** column-level `.index()` or table-level `indexes` / `unique` as a third arg to `q.table(name, cols, { indexes, unique })`. With `feature()`, pass `indexes` and `unique` as top-level keys alongside `columns` — the sugar forwards them into the same `q.table` opts.\n\n### Column Types\n\n| Builder | Drizzle equivalent | Zod type |\n|---------|---------------------|----------|\n| `q.text()` | `text(...)` | `z.string()` |\n| `q.url()` | `text(...)` | `z.string().url()` |\n| `q.int()` | `integer(...)` | `z.number().int()` |\n| `q.bool()` | `boolean(...)` | `z.boolean()` |\n| `q.uuid()` | `uuid(...)` | `z.string().uuid()` |\n| `q.timestamp()` | `timestamp(...)` (converted to SQLite `text` on sqlite targets) | `z.coerce.date()` |\n| `q.json()` | `jsonb(...)` | `z.unknown()` (or the type you pass in) |\n| `q.enum(['a','b'])` | `text(..., { enum: [...] })` | `z.enum([...])` |\n| `q.id()` | `text('id').primaryKey()` | `z.string()` |\n| `q.scope(kind)` | `text(...).notNull()` | `z.string()` |\n| `q.stamp({ fromScope, claim })` | `text(...).notNull()` (nullable with `optional: true`) | `z.string().optional()` |\n\n`q.text()` and `q.url()` accept either a SQL-name string or an options object — `q.text({ sqlName: 'org_id', maxLength: 80 })`. `maxLength` adds `z.string().max(n)` at the validation edge; the SQL column stays `text` (D1 ignores `VARCHAR(n)` length anyway).\n\n`q.url()` is `q.text()` plus `z.string().url()` at the validation edge, so `javascript:` / `data:` URIs and free-form strings are rejected before they ever land in storage or get rendered in the CMS.\n\n`q.id()` emits a plain text primary key. Actual ID assignment at insert time is driven by the provider's `generateId` setting. This keeps q's output decoupled from any specific ID library.\n\nFor `generateId: \"cuid\"`, there is one important nuance: import-capable runtime\npaths can emit real `createId()` usage, but compiler-managed schema\nauto-injection may keep the same `createId()` call site and back it with a\nfile-local `crypto.randomUUID()` polyfill so schema-generation sandboxes do not\ndepend on project `node_modules`.\n\n### q.scope() — tenant scope columns\n\n`q.scope(kind)` is the canonical way to declare a column that holds a tenant-scope value (org / owner / team). It compiles to `text(...).notNull()` like a regular required text column, plus metadata that the compiler reads to:\n\n1. **Auto-derive the firewall predicate** — `q.scope('organization')` produces `[{ field: 'organizationId', equals: 'ctx.activeOrgId' }]` so you can omit the explicit `firewall:` block. (If `deletedAt` is present — and it is whenever the resource uses soft delete, which is the default — the `isNull(deletedAt)` predicate is appended automatically.)\n2. **Reject the column from client input** — scope fields land in `GUARDS_CONFIG.systemManaged` alongside the audit fields, so `POST { organizationId: 'org_other' }` returns 400 even if guards aren't otherwise configured.\n3. **Auto-populate on create / upsert** — the value is taken from the request context, not the request body.\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\nOverride the context source for non-default sources:\n\n```typescript\nownerId: q.scope('owner', { source: 'ctx.userId' }),\n```\n\n`q.scope()` is preferred over `q.text().required()` for tenant columns. Auto-detection on column names (`organizationId`, `userId`, etc.) still works as a fallback for projects bringing forward Drizzle schemas, but the explicit `q.scope()` form locks in the semantics in the source.\n\n### q.stamp() — proven-principal identity columns\n\n`q.stamp({ fromScope, claim })` server-stamps a column from a **proven** scope claim — the caller's own identity within a relationship they were cryptographically proven to hold (e.g. an event attendee's own guest id). It is the identity sibling of `q.scope`:\n\n| | `q.scope('<kind>')` | `q.stamp({ fromScope, claim })` |\n|---|---|---|\n| **Purpose** | tenant isolation column | proven-principal **identity** column |\n| **Value** | `ctx.scope.<kind>.id` / `activeOrgId` / `userId` | `ctx.scope.<kind>.<claim>` (`id` \\| `subjectId` \\| a scalar sub-key) |\n| **Firewall arm?** | **yes** — it is the tenant `WHERE` | **never** — identity is not a tenant scope |\n| **Guarantee** | \"stamp **and verify**\" (firewall re-checks on read/patch/delete) | \"stamp **and prove**\" (un-spoofable by token provenance) |\n\n```typescript\ncolumns: {\n eventId: q.scope('event'), // tenant firewall column\n authorId: q.stamp({ fromScope: 'event', claim: 'subjectId' }), // proven identity — un-spoofable\n}\n```\n\n**Runtime precedence — the org/admin hierarchy takes priority.** The stamp fires **only when the caller is admitted as a scope-only principal** (a scope-token holder, `ctx.scopePrincipal === true`): the column is force-stamped from the proven claim and any client-sent value is ignored. A caller admitted via the **org role hierarchy** (member / admin / owner) writes the column through the **org path** — a normal client-settable value, bounded by the org firewall (this is legitimate org-admin capability over their own org's rows). So a table whose `create` admits *both* org roles and a scope role needs **no split**: each identity writes the column the way its principal allows. The invariant that always holds is that a scope-only principal can never set a scope-stamped column to anything but its proven token.\n\n**Fail-closed.** If a scope-only caller reaches the write without the required claim (`ctx.scope.<kind>.<claim>` absent) the write is refused with **403** *before* the insert — never a `NULL` identity row — for nullable stamp columns too. A `q.stamp` column may not also be a firewall arm, live on an `exception: true` table, or be sourced from a set-valued sub-key; each is a compile error.\n\n`optional: true` makes the DDL column nullable (an org caller may then omit it); it does **not** relax the scope-principal 403.\n\n**Set-on-insert, immutable thereafter.** A `q.stamp` column is a **create-time identity** — it is never re-derived on update. On every update-shaped write (`PATCH`, `PUT`, batch update, upsert, and a changeset root/child patch) the column is **systemManaged**: a client value for it is **rejected** (400), regardless of your `guards.updatable` list. Re-keying a proven identity is not an operation. (The force-stamp and the org-writable-on-create allowance apply to the create path only.)\n\n**A non-nullable stamp on the org path must be supplied by the caller.** The force-stamp fires for scope-only principals; an org-admitted caller writes the column as normal client input. So a `NOT NULL` `q.stamp` column (the default) that an org caller *omits* lands on the database `NOT NULL` constraint (a deterministic field-named 400), not a NULL row. Add the column to `guards.createable` so org callers can supply it, or mark it `optional: true` if an org-created row may legitimately have no identity.\n\n**The scope-only lane needs a scope-reachable write.** The force-stamp only runs once the scope-only principal actually *reaches* the insert. A table with a **hard organization firewall arm** (an `organizationId` sourced from `ctx.activeOrgId`) emits an `ORG_REQUIRED` gate that denies a sessionless scope principal (who has no active org) *before* the stamp — so on such tables the stamp serves the **org-admitted** caller, and the scope-only principal writes these rows as a **changeset child** that *inherits* `organizationId` from a firewall-verified parent. For a plain create/batch by a scope-only principal, firewall the table on the **scope** arm only (e.g. `firewall: { any: [{ field: 'eventId', equals: 'ctx.scope.event' }] }`, no org column) so no `ORG_REQUIRED` gate is emitted.\n\n**Idempotency (at-least-once).** The stamp rides inside the write, so it inherits the endpoint's replay semantics: a **keyed** replay (a repeated `Idempotency-Key` whose handler is skipped) neither re-writes nor re-stamps; a **keyless** retry re-writes and therefore re-stamps from the caller's then-current proven claim.\n\n### Naming Convention\n\nBy default, `q` picks the SQL column name from the JS key using the target database's conventional casing. Both `cloudflare-d1` and `neon` default to **`snake_case`** (`organizationId` → `organization_id`).\n\nYou can override for any project by setting `namingConvention` on the database provider config:\n\n```ts\n// quickback/quickback.config.ts\nexport default {\n providers: {\n database: {\n name: 'cloudflare-d1',\n config: {\n namingConvention: 'camelCase', // keep JS-style names in the SQL\n },\n },\n },\n};\n```\n\nFor one-off overrides on a specific column, pass an explicit name as the positional argument:\n\n```ts\norganizationId: q.scope('organization', { sqlName: 'org_id' }), // SQL name: 'org_id'\n```\n\n## Drizzle interop\n\nIf you have an existing Drizzle schema you're bringing forward — or need a dialect-specific column option `q` doesn't expose — use `pgTable` / `sqliteTable` / `mysqlTable` directly:\n\n| Target Database | Import From | Table Function |\n|-----------------|-------------|----------------|\n| Cloudflare D1, Turso, SQLite | `drizzle-orm/sqlite-core` | `sqliteTable` |\n| Supabase, Neon, PostgreSQL | `drizzle-orm/pg-core` | `pgTable` |\n| PlanetScale, MySQL | `drizzle-orm/mysql-core` | `mysqlTable` |\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport const jobs = sqliteTable('jobs', {\n id: text('id').primaryKey(),\n organizationId: text('organization_id').notNull(),\n title: text('title').notNull(),\n department: text('department').notNull(),\n status: text('status').notNull(),\n salaryMin: integer('salary_min'),\n salaryMax: integer('salary_max'),\n});\n\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 create: { /* ... */ },\n update: { /* ... */ },\n delete: { /* ... */ },\n});\n\nexport type Job = typeof jobs.$inferSelect;\n```\n\nWhen using Drizzle (rather than `q.scope()`), declare the firewall as a predicate array. Auto-detection still works on column names (`organizationId`, `ownerId`, `teamId`) so you can omit `firewall:` entirely if exactly one isolation column is present.\n\n### When Drizzle interop is the right call\n\nDefault to `feature()`. Drop to Drizzle only when:\n\n- You already have Drizzle schemas to bring forward\n- You need a Drizzle-specific column option not yet in `q` (e.g., `decimal`, `varchar` with length, dialect-specific types)\n\nFeatures in the same project may mix freely — Quickback dispatches per feature — so one interop table doesn't force the rest of the project off `feature()`.\n\nOne dialect rule: interop files **without** a `defineTable(...)` default export (internal child tables) are not dialect-translated — author them in the target database's dialect. On Postgres providers (Neon, Supabase), a `sqliteTable` interop source without `defineTable` is a compile-time error; write it with `pgTable` from `drizzle-orm/pg-core` instead. Sources **with** `defineTable(...)` keep compiling across dialects automatically.\n\n### Drizzle Column Types\n\nDrizzle supports all standard SQL column types:\n\n| Type | Drizzle Function | Example |\n|------|------------------|---------|\n| String | `text()`, `varchar()` | `text('name')` |\n| Integer | `integer()`, `bigint()` | `integer('count')` |\n| Boolean | `boolean()` | `boolean('is_active')` |\n| Timestamp | `timestamp()` | `timestamp('created_at')` |\n| JSON | `json()`, `jsonb()` | `jsonb('metadata')` |\n| UUID | `uuid()` | `uuid('id')` |\n| Decimal | `decimal()`, `numeric()` | `decimal('price', { precision: 10, scale: 2 })` |\n\n### Drizzle Column Modifiers\n\n```typescript\n// Required field\nname: text('name').notNull()\n\n// Default value\nisActive: boolean('is_active').default(true)\n\n// Primary key\nid: text('id').primaryKey()\n\n// Unique constraint\nemail: text('email').unique()\n\n// Default to current timestamp\ncreatedAt: timestamp('created_at').defaultNow()\n```\n\n## File Organization\n\nOrganize your tables by feature. Each feature directory contains table files:\n\n```\nquickback/\n├── quickback.config.ts\n└── features/\n ├── jobs/\n │ ├── jobs.ts # Main table + config\n │ ├── applications.ts # Related table + config\n │ └── actions.ts # Custom actions\n ├── candidates/\n │ ├── candidates.ts # Table + config\n │ └── candidate-notes.ts # Related table\n └── organizations/\n └── organizations.ts\n```\n\n**Key points:**\n- Tables with `export default defineTable(...)` get resource routes generated\n- Tables without a default export are internal (no routes, used for joins/relations)\n- Route paths are derived from filenames: `applications.ts` → `/api/v1/applications`\n\n### defineTable vs defineResource\n\n- **`defineTable`** — The standard function for defining tables with generated API routes\n- **`defineResource`** — Deprecated and scheduled for removal. Still compiles with a warning; do not write new code with it — migrate to `feature()` (or `defineTable`).\n\n```typescript\n// Preferred:\nexport default defineTable(jobs, { /* config */ });\n```\n\n## 1 Resource = 1 Security Boundary\n\nEach `defineTable()` call defines a complete, self-contained security boundary. The security config you write — firewall, access, guards, and masking — is compiled into a single resource file that wraps all generated routes for that table.\n\nThis is a deliberate design choice. Mixing two resources with different security rules in one configuration would create ambiguity about which firewall, access, or masking rules apply to which table. By keeping it 1:1, there's never any question.\n\n| Scenario | What to do |\n|----------|------------|\n| Table needs its own API routes + security | Own file with `defineTable()` |\n| Table is internal/supporting (no direct API) | Extra `.ts` file in the parent feature directory, no `defineTable()` |\n\nA supporting table without `defineTable()` is useful when it's accessed internally — by action handlers, joins, or background jobs — but should never be directly exposed as its own API endpoint.\n\n## Internal Tables (No Routes)\n\nFor junction tables or internal data structures that shouldn't have API routes, simply omit the `defineTable` export. Add a `// @quickback-internal` marker so the compiler skips the \"no defineTable found\" warning:\n\n```typescript\n// quickback/features/jobs/interview-scores.ts\n\n// @quickback-internal — child table, no routes intentionally.\n\nexport const interviewScores = sqliteTable('interview_scores', {\n applicationId: text('application_id').notNull(),\n interviewerId: text('interviewer_id').notNull(),\n score: integer('score'),\n organizationId: text('organization_id').notNull(), // Scope junction tables for cascade soft-deletes\n});\n\n// No default export = no routes generated\n```\n\nThese internal tables still participate in the database schema and migrations — they just don't get API routes or security configuration. Without the `@quickback-internal` marker the compiler emits a warning per table, since the missing `defineTable` is more often a bug than a deliberate choice.\n\nThe compiler automatically injects the four **[audit fields](#audit-fields)** (`createdAt`/`createdBy`/`modifiedAt`/`modifiedBy`), the soft-delete pair (`deletedAt`/`deletedBy`, when soft delete is enabled), and **`organizationId`** into child/junction tables when the parent feature is org-scoped. This ensures cascade soft deletes and scoped queries work correctly without manual column definitions.\n\n## Audit Fields\n\nQuickback adds four audit columns to **every table** (including child/junction tables without `defineTable`) — never declare them in your schemas:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `createdAt` | timestamp | Set on insert |\n| `createdBy` | text | Actor that performed the insert (`ctx.userId`) |\n| `modifiedAt` | timestamp | Set on every insert and update |\n| `modifiedBy` | text | Actor that performed the latest insert/update (`ctx.userId`) |\n\nAudit fields are a separate concept from soft-delete (`deletedAt`/`deletedBy`) — they're always present, regardless of delete mode. See [Soft-Delete Fields](#soft-delete-fields) below.\n\nOpt out of audit injection entirely with `compiler.features.auditFields: false` in `quickback.config.ts`. (You almost never want to.)\n\n### How auto-injection works (two layers)\n\n\"Auto-injection\" covers two distinct steps. Conflating them is the most common source of confusion:\n\n1. **Schema injection (compile-time)** — the compiler adds the four columns to every Drizzle table. Idempotent: if you've authored a column with the same name yourself, the compiler leaves yours alone.\n2. **Runtime injection (per-write)** — a Proxy around the request-context `db` (`createAuditDb`, generated to `src/lib/audit-wrapper.ts`) intercepts `.insert(...).values(...)` and `.update(...).set(...)` and writes the audit columns from `ctx.userId` and the actual write moment.\n\nThe runtime layer **hard-stamps** every audit field on every write. Caller-supplied values for `createdAt`/`createdBy`/`modifiedAt`/`modifiedBy` are silently overwritten. This is intentional: the audit log can never be forged by a crafted request body or by a client echoing a row back into a PATCH.\n\n```ts\n// In a custom action handler — caller cannot fake audit attribution\nawait db.insert(records).values({\n id: createId(),\n status: 'active',\n createdBy: 'admin', // ← ignored; wrapper writes ctx.userId\n modifiedAt: '1999-01-01', // ← ignored; wrapper writes \"now\"\n});\n```\n\nWhat the caller is responsible for: `id` (the framework doesn't mint ids for you) and the domain fields.\n\nWhat the caller does *not* need to set: any of the four audit fields, ever.\n\n### Actors: who shows up in `createdBy` / `modifiedBy`\n\nThe wrapper writes whatever string is in `ctx.userId`. For user-driven requests this is the authenticated user's id — set by auth middleware before the handler runs. For non-user-driven entry points (inbound webhooks, cron, queue workers), you mint a synthetic actor id at the boundary so the audit log preserves provenance.\n\n**Inherit before you mint.** If a real user's request triggers cascades, hooks, or enqueues background jobs, every downstream write should carry that user's id — not a synthetic one. The cascade is part of the user's action. Only mint when there is genuinely no upstream user.\n\nWhen you do mint, use a single namespace and a stable convention:\n\n| Boundary | Actor id |\n|----------|----------|\n| Inbound webhook | `system:webhook-<provider>` (e.g. `system:webhook-stripe`) |\n| Scheduled / cron | `system:cron-<job>` (e.g. `system:cron-cleanup-stale`) |\n| Queue worker | `system:queue-<queue>` (e.g. `system:queue-embeddings-retry`) |\n| Quickback platform-internal write with no user upstream | `system:quickback` |\n| Out-of-band operator script | `system:script-<name>` |\n\nThe `system:` prefix marks \"not a real user\" — readable by anyone joining the audit columns to `users`, and cheap to filter on. Don't use `tenant:admin` or `quickback:admin`: those imply a human role nobody is actually playing. The tenant context is already on the row (in `organizationId`); the actor id is purely about *source*.\n\n### Failure mode: missing `ctx.userId`\n\nIf a write reaches the wrapper without a `ctx.userId`, the wrapper throws:\n\n```\naudit-wrapper: insert reached without ctx.userId.\nIf this is an intentional system-side write, use the unwrapped db directly.\n```\n\nTwo paths to fix it, depending on intent:\n\n- **Mint a synthetic actor** (preferred — preserves attribution) — populate `ctx.userId` with one of the conventions above before calling into your handler.\n- **Bypass the wrapper entirely** — use the unwrapped `createDb` instead of the request-context `db`. Use this only for migrations, schema repair, or backfill scripts where you genuinely don't want any audit attribution. The audit columns will fall back to DB defaults (`createdAt`/`modifiedAt` populate from `defaultNow()`; `createdBy`/`modifiedBy` end up `NULL`).\n\n### Disabling Audit Fields\n\nTo disable automatic audit fields for your project:\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n // ...\n compiler: {\n features: {\n auditFields: false, // Disable for entire project\n }\n }\n});\n```\n\nThis turns off both layers — schema injection and the runtime wrapper.\n\n## Soft-Delete Fields\n\n`deletedAt` and `deletedBy` are **not** audit fields. They're a separate, per-table mechanism for soft delete:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `deletedAt` | timestamp | Set when the record is soft-deleted |\n| `deletedBy` | text | Actor that performed the soft delete (`ctx.userId`) |\n\nThe compiler injects them only when the resource uses soft delete — i.e. when neither `delete.mode` nor `delete.batch.mode` is explicitly `'hard'`. Soft is the default, so most tables get the columns. Tables with both delete paths set to `'hard'` skip them entirely, which also drops the `isNull(deletedAt)` predicate from the firewall WHERE clause.\n\n```typescript\n// soft delete (default) — table gets deletedAt + deletedBy\ndelete: {}\n\n// hard delete — no deletedAt/deletedBy columns, no soft-delete predicate\ndelete: { mode: 'hard', batch: { mode: 'hard' } }\n```\n\n### Caller contract\n\nIn custom-action handlers, **passing `deletedAt` in `.set({})` is the signal** that this update is a soft delete. Any value works — the wrapper detects the field and overwrites both `deletedAt` and `deletedBy` with `now` and `ctx.userId`:\n\n```ts\nawait db.update(records)\n .set({ deletedAt: new Date() }) // signal — value is overwritten\n .where(eq(records.id, id));\n```\n\nYou don't set `deletedBy` yourself; the wrapper pairs it with the `deletedAt` signal.\n\n### Protected system fields\n\nThe audit and soft-delete columns are always protected from client input, even with `guards: false`:\n\n- `id` (when `generateId` is not `false`)\n- `createdAt`, `createdBy` *(audit — always present)*\n- `modifiedAt`, `modifiedBy` *(audit — always present)*\n- `deletedAt`, `deletedBy` *(soft-delete — present when delete mode allows soft)*\n\nProtection is enforced by the runtime wrapper — even if a request body passes one of these, it gets overwritten before the SQL is built.\n\n## Auto-Indexes\n\nThe compiler injects performance-critical indexes you'd otherwise have to author by hand. The pass runs after audit-field injection (so `deletedAt` is present) and is idempotent — if you already declared a matching index it's left alone.\n\n| Trigger | Index | Why |\n|---------|-------|-----|\n| Tenant column (`organizationId` / `organisationId` / `userId`) + `deletedAt` | Composite `(<isolation_col>, deletedAt)` | Every list query filters by isolation AND `deletedAt IS NULL` — a composite index lets D1/SQLite prune both predicates in one btree walk. |\n| Any FK column (`.references(() => other.id)`) | Single-column `(<fk_col>)` | SQLite/D1 don't auto-index FK columns, and the generated FK existence checks read by id on the parent. |\n| Any column that appears in a view's `read.query.sortable` allowlist (or `defaultSort`) | Single-column `(<col>)` | Sort scans go through an index instead of a full-table scan. |\n\nIndexes are emitted into the table's Drizzle extras callback (`(t) => ({ ... })`) and named `<table>_<col>_idx` (or `<table>_<col1>_<col2>_idx` for the composite). The `index` import is added to your schema's `drizzle-orm/<dialect>-core` import line if it isn't already there.\n\nYou can opt out of any auto-injected index by declaring your own with the same name or column set — the injector treats both as already-present and skips.\n\n## Ownership Fields\n\nFor the firewall to work, declare a tenant-scope column. With `q.scope()` (recommended), the compiler auto-derives the firewall predicate, marks the column as system-managed, and auto-populates it on create:\n\n```typescript\n// q DSL (recommended)\norganizationId: q.scope('organization') // → ctx.activeOrgId\nownerId: q.scope('owner') // → ctx.userId\nteamId: q.scope('team') // → ctx.activeTeamId\n```\n\nWhen using Drizzle directly, declare a regular column. Auto-detection picks it up by name; `q.scope()` semantics (systemManaged, auto-populate) still apply because they're keyed off the firewall predicate, not the column DSL:\n\n```typescript\n// Drizzle interop\norganizationId: text('organization_id').notNull()\nownerId: text('owner_id').notNull()\nteamId: text('team_id').notNull()\n```\n\nThose three are **tenant** auto-stamps (org / owner / team). To auto-stamp a **proven-principal identity** column instead — the caller's own id within a relationship, not a tenant key — use [`q.stamp()`](#qstamp--proven-principal-identity-columns). It sources from `ctx.scope.<kind>.<claim>` for scope-only principals and, unlike the tenant stamps, is never a firewall arm.\n\n## Display Column\n\nWhen a table has foreign key columns (e.g., `departmentId` referencing `departments`), Quickback can automatically resolve the human-readable label in GET and LIST responses. This eliminates the need for frontend lookup calls.\n\n### Auto-Detection\n\nQuickback auto-detects the display column by checking for common column names in this order:\n\n`name` → `title` → `label` → `headline` → `subject` → `code` → `displayName` → `fullName` → `description`\n\nIf your `departments` table has a `name` column, it's automatically used as the display column. No config needed.\n\n### Explicit Override\n\nOverride the auto-detected column with `displayColumn`:\n\n```typescript\nexport default defineTable(interviewStages, {\n displayColumn: 'label', // Use 'label' instead of auto-detected 'name'\n read: { access: { roles: [\"hiring-manager\", \"recruiter\"] } },\n});\n```\n\n### Default Sort\n\nSet a default sort order for the CMS table list view with `defaultSort`:\n\n```typescript\nexport default defineTable(podcastEpisodes, {\n defaultSort: { field: \"createdAt\", order: \"desc\" },\n firewall: [{ exception: true }],\n read: { access: { roles: [\"PUBLIC\"] } },\n});\n```\n\nThe CMS applies this sort when the table first loads. Users can still click column headers to change the sort order.\n\n### How Labels Appear in Responses\n\nFor any FK column ending in `Id`, the API adds a `_label` field with the resolved display value:\n\n```json\n{\n \"id\": \"job_abc\",\n \"title\": \"Senior Engineer\",\n \"departmentId\": \"dept_xyz\",\n \"department_label\": \"Engineering\",\n \"locationId\": \"loc_123\",\n \"location_label\": \"San Francisco\"\n}\n```\n\nThe pattern is `{columnWithoutId}_label`. The frontend can find all labels with:\n\n```typescript\nObject.keys(record).filter(k => k.endsWith('_label'))\n```\n\nLabel resolution works within the same feature (tables in the same feature directory). System columns (`organizationId`, `createdBy`, `modifiedBy`) are never resolved.\n\nFor LIST endpoints, labels are batch-resolved efficiently — one query per FK column, not per record.\n\n## References\n\nWhen your FK columns don't match the target table name by convention (e.g., `vendorId` actually points to the `contact` table), declare explicit references so the CMS and schema registry know the correct target:\n\n```typescript\nexport default defineTable(applications, {\n references: {\n candidateId: \"candidate\",\n jobId: \"job\",\n referredById: \"candidate\",\n },\n // ... firewall, guards, crud\n});\n```\n\nEach key is a column name ending in `Id`, and the value is the camelCase table name it references. These mappings flow into the schema registry as `fkTarget` on each column, enabling the CMS to render typeahead/lookup inputs that search the correct table.\n\nConvention-based matching (strip `Id` suffix, look for a matching table) still works for simple cases like `projectId` → `project`. Use `references` only for columns where the convention doesn't match.\n\n## Input Hints\n\nControl how the CMS renders form inputs for specific columns. By default the CMS infers input types from the column's SQL type — `inputHints` lets you override that:\n\n```typescript\nexport default defineTable(jobs, {\n inputHints: {\n status: \"select\",\n department: \"select\",\n salaryMin: \"currency\",\n salaryMax: \"currency\",\n description: \"richtext\",\n },\n // ... firewall, guards, crud\n});\n```\n\n### Available Hint Values\n\n| Hint | Renders As |\n|------|-----------|\n| `richtext` | Rich text editor (tiptap) — bold, italic, headings, lists, links. Stores HTML. Lazy-loaded in edit mode, rendered as formatted HTML in view mode. |\n| `select` | Dropdown select (single value) |\n| `multi-select` | Multi-value select |\n| `radio` | Radio button group |\n| `checkbox` | Checkbox toggle |\n| `textarea` | Multi-line text input |\n| `lookup` | FK typeahead search |\n| `hidden` | Hidden from forms |\n| `color` | Color picker |\n| `date` | Date picker |\n| `datetime` | Date + time picker |\n| `time` | Time picker |\n| `currency` | Currency input with formatting |\n\nInput hints are emitted in the schema registry as `inputHints` on the table metadata, and the CMS reads them to render the appropriate form controls.\n\n### Rich Text Example\n\nFor fields that contain HTML content (e.g., blog posts, descriptions from RSS feeds), use `\"richtext\"`:\n\n```typescript\nexport default defineTable(podcastEpisodes, {\n inputHints: { description: \"richtext\" },\n // ...\n});\n```\n\nThe CMS will:\n- **View mode**: Render the HTML with proper formatting (headings, lists, links, etc.)\n- **Edit mode**: Load a tiptap rich text editor with a toolbar (bold, italic, H2, H3, bullet/ordered lists, links, code, undo/redo)\n- **Storage**: HTML strings — no format conversion needed, compatible with external HTML content\n\n## Relations (Optional)\n\nDrizzle supports defining relations for type-safe joins:\n\n```typescript\n\nexport const jobsRelations = relations(jobs, ({ one, many }) => ({\n organization: one(organizations, {\n fields: [jobs.organizationId],\n references: [organizations.id],\n }),\n applications: many(applications),\n}));\n```\n\nDrizzle `relations(...)` describe application-side joins; they do not always\ncreate a database foreign-key constraint. On Neon, use\n[`compiler.migrations.foreignKeys`](/compiler/config#neon-foreign-key-migrations)\nfor fully qualified cross-schema or composite constraints that cannot be\ndeclared alongside a table. The ordered source and target column tuples must\nhave equal arity, and the referenced target tuple must have a matching unique\nor primary-key constraint before the foreign key migration runs.\n\nUse these constraints for relational integrity only. Authorization, pass\nconsumption, state transitions, and other business logic belong in the API\naction layer.\n\n## Database Configuration\n\nConfigure database options in your Quickback config:\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n name: 'my-app',\n providers: {\n database: defineDatabase('cloudflare-d1', {\n generateId: 'prefixed', // 'uuid' | 'cuid' | 'nanoid' | 'short' | 'prefixed' | 'serial' | false\n namingConvention: 'snake_case', // 'camelCase' | 'snake_case'\n usePlurals: false, // Auth table names: 'users' vs 'user'\n }),\n },\n compiler: {\n features: {\n auditFields: true, // Auto-manage audit timestamps\n }\n }\n});\n```\n\n## Choosing Your Dialect\n\nUse the Drizzle dialect that matches your database provider:\n\n### SQLite (Cloudflare D1)\n\n```typescript\n\nexport const jobs = sqliteTable('jobs', {\n id: text('id').primaryKey(),\n title: text('title').notNull(),\n metadata: text('metadata', { mode: 'json' }), // JSON stored as text\n isOpen: integer('is_open', { mode: 'boolean' }).default(false),\n organizationId: text('organization_id').notNull(),\n});\n```\n\n### PostgreSQL (Neon)\n\n```typescript\n\nexport const jobs = pgTable('jobs', {\n id: serial('id').primaryKey(),\n title: text('title').notNull(),\n metadata: jsonb('metadata'), // Native JSONB\n isOpen: boolean('is_open').default(false),\n organizationId: text('organization_id').notNull(),\n});\n```\n\n### Key Differences\n\n| Feature | SQLite | PostgreSQL |\n|---------|--------|------------|\n| Boolean | `integer({ mode: 'boolean' })` | `boolean()` |\n| JSON | `text({ mode: 'json' })` | `jsonb()` or `json()` |\n| Auto-increment | `integer().primaryKey()` | `serial()` |\n| UUID | `text()` | `uuid()` |\n\n## Next Steps\n\n- [Configure the firewall](/compiler/definitions/firewall) for data isolation\n- [Set up access control](/compiler/definitions/access) for read and write operations\n- [Define guards](/compiler/definitions/guards) for field modification rules\n- [Add custom actions](/compiler/definitions/actions) for business logic"
147
155
  },
148
156
  "compiler/definitions/scopes": {
149
157
  "title": "Scopes & Capability Grants",
150
- "content": "Org membership answers *\"which tenant is this caller in?\"* Scopes answer a different question: *\"this caller isn't an org member, but they're a **confirmed attendee of event E** — let them see exactly E's rows, as exactly the role they hold, and nothing else.\"*\n\nA **scope** is a tenant axis whose value is established by a **relationship you prove once** (at `POST /scope/v1/enter`) and then carry in a signed JWT claim — verified cryptographically on every later request with **no database round-trip**. It's the REST/JWT twin of the realtime ws-ticket.\n\n## When to use it\n\nReach for a scope when a principal must touch a bounded slice of an instance **without being an org member**:\n\n- **Event attendee** — reads their event's announcements / sessions, not the org.\n- **Shuttle driver** — sees only the passengers on *their* bus (a row slice), can DM them.\n- **F&B vendor** — reads dietary *counts*, zero attendee rows.\n- **Visiting nurse / carrier / contractor** — one patient's meds, one carrier's shipments.\n\nEach is *event-scoped* but a **distinct least-privilege role**. Org members are unaffected — they keep their normal tenant access.\n\nMost scope principals are signed-in users who prove a relationship at [`/scope/v1/enter`](#2-enter-the-scope). But some have **no account at all** — an attendee who arrives by email + invite code, a kiosk/handout code, a partner token. For those, an action proves the principal its own way and [`ctx.mintScope`](#sessionless-scope-mint--ctxmintscope) mints the same scope, no Better Auth user required.\n\n## The model\n\n### 1. Declare relationships + scopes\n\nA scope **kind** (`event`) declares named **roles**, each conferred by a relationship whose `from` row carries the role (and optionally a **sub-key** for row slicing):\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: { from: 'guests', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { status: 'confirmed' } },\n organizerOf: { from: 'staff', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { role: 'organizer' } },\n shuttleDriverOf: { from: 'staff', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { role: 'shuttleDriver' } },\n },\n scopes: {\n event: {\n requestField: 'eventId', // the body field the client sends to /enter\n roles: {\n attendee: { via: 'attendeeOf' },\n organizer: { via: 'organizerOf' },\n shuttleDriver: { via: 'shuttleDriverOf', subKeys: ['shuttleId'] }, // row-slice sub-key\n },\n },\n },\n}\n```\n\n### 2. Enter the scope\n\n```http\nPOST /scope/v1/enter (session OR existing JWT auth)\n{ \"eventId\": \"evt_123\" }\n```\n\nThe server probes **every declared role** for the proposed instance (one DB touch), and mints the proven roles + sub-keys into a signed JWT `scope` claim, returned via the `set-auth-token` header and the body:\n\n```jsonc\n// a shuttle driver who is also a confirmed guest\n\"scope\": { \"event\": { \"id\": \"evt_123\", \"roles\": [\"attendee\", \"shuttleDriver\"], \"shuttleId\": \"shA\" } }\n```\n\nThe client sends that JWT as `Authorization: Bearer …` on subsequent requests. The auth middleware verifies the signature and sets `ctx.scope` — **no DB**. The claim is carried forward on every authed call (rolling refresh) for up to **15 minutes from the last actual relationship proof** — the mint stamps a proof timestamp (`sct`) that the refresh carries forward verbatim and checks against the carry-forward cap. Past the cap the refresh stops, the token expires within one TTL, and the client re-proves via `enter` (or any namespace route that mints) to restart the window.\n\n> **Invariant:** the client only *proposes* the instance id (from the URL). The server proves membership before signing. No client-asserted scope is ever trusted.\n\n### 3. Gate the pillars\n\nScoped roles are referenced everywhere a pillar takes a role as the namespaced identifier **`scope:<kind>:<role>`**:\n\n```typescript\n// features/guests/guests.ts — the manifest, row-sliced + PII-masked\nexport default feature('guests', {\n columns: { /* … eventId, shuttleId, email, … */ },\n // org staff see the whole event; a shuttle driver sees only their bus\n firewall: {\n any: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { all: [\n { field: 'eventId', equals: 'ctx.scope.event' },\n { field: 'shuttleId', equals: 'ctx.scope.event.shuttleId' }, // sub-key row slice\n ] },\n ],\n },\n masking: {\n email: { type: 'email', show: { roles: ['admin', 'scope:event:organizer'] } }, // hidden from the driver\n },\n read: {\n views: {\n manifest: {\n fields: ['id', 'nameAtInvite', 'shuttleId', 'pickupLocation'],\n access: { roles: ['admin', 'scope:event:organizer', 'scope:event:shuttleDriver'] },\n },\n },\n },\n});\n```\n\n| Pillar | How it reads the scoped role |\n|--------|------------------------------|\n| **Firewall** (rows) | `all`/`any` arms keyed on `ctx.scope.<kind>` (+ sub-keys) — see [Firewall](/compiler/definitions/firewall) |\n| **Access** (verbs/views) | `access.roles: ['scope:event:shuttleDriver']` on CRUD, actions, and views |\n| **Masking** (fields) | `masking.<col>.show.roles` includes / excludes `scope:event:<role>` |\n\n## The org / scope split (security)\n\n**Scoped roles never merge into `ctx.roles`.** A `scope:*` identifier matches **only** the verified scope claim (`ctx.scope.<kind>.roles`); a bare org role (`admin`, `member`) matches **only** `ctx.roles`. The compiler enforces the split so an externally-provisioned `shuttleDriver` can **never** satisfy an `admin` gate by string coincidence, and a tampered scope claim can't impersonate an org role. This is the precondition for admitting limited outside users at all.\n\n## Sub-keys (row slicing)\n\nA role's `subKeys` name columns on the relationship's `from` row that are projected into the claim. A firewall arm then slices on them:\n\n```typescript\n{ field: 'shuttleId', equals: 'ctx.scope.event.shuttleId' }\n```\n\nBecause sub-key arms compose with `all`, an **absent** sub-key denies (`sql\\`1 = 0\\``) rather than widening — a driver can never see *all* shuttles by simply lacking the claim. The scope accessor is always emitted null-safe (`ctx.scope?.event?.shuttleId`), so an org caller who never entered the scope hits a clean deny, not a 500.\n\n### Set-valued sub-keys\n\nA driver may cover **more than one** bus. Append a `[]` marker to the\nsub-key name to project **every** matched `from` row's value into the claim\nas a `string[]`:\n\n```typescript\nroles: {\n shuttleDriver: { via: 'shuttleDriverOf', subKeys: ['shuttleId[]'] }, // set-valued\n}\n```\n\nThe `[]` is a marker only — it's stripped from the column name (the\nrelationship's `from` row still reads `shuttleId`). At `/scope/v1/enter` the\nproven rows union their values, so the claim carries an array:\n\n```jsonc\n\"scope\": { \"event\": { \"id\": \"evt_123\", \"roles\": [\"shuttleDriver\"], \"shuttleId\": [\"shA\", \"shC\"] } }\n```\n\nThe matching firewall arm — written exactly as for the scalar case\n(`{ field: 'shuttleId', equals: 'ctx.scope.event.shuttleId' }`) — is\n**rewritten by the compiler** to an `inArray` row-slice:\n\n```sql\nWHERE shuttle_id IN (ctx.scope?.event?.shuttleId ?? [])\n```\n\nThe `?? []` default makes an absent claim lower to `inArray(col, [])` — a\nclean DENY, never a malformed SQL fragment or a 500. A scalar sub-key (no\n`[]` marker) is untouched and keeps lowering to `eq`. You write the same\n`equals` arm either way; declaring `shuttleId[]` vs `shuttleId` in the scope\nrole is the only switch.\n\n## Auto-stamping the scope column on insert (`q.scope`)\n\n`q.scope('organization')` auto-stamps the tenant column on write, the same\nway `q.scope('owner')` stamps `ownerId`. A relationship-derived kind works\nidentically: `q.scope('event')` auto-stamps the column from the **verified\nscope claim** (`ctx.scope.event.id`) on insert — no need to pass `eventId`\nin the request body:\n\n```typescript\nexport const eventNotes = q.table('event_notes', {\n id: q.id(),\n eventId: q.scope('event'), // INSERT autofill from ctx.scope.event.id\n body: q.text().required(),\n organizationId: q.scope('organization'), // INSERT autofill from ctx.activeOrgId\n});\n```\n\nThe stamp is **insert-only** and null-safe — the generated CREATE handler\nwrites `eventId: ctx.scope?.event?.id`, so it never binds `undefined`. It\ndoes **not** add a read-time `WHERE` filter (that's the firewall's job; a\nread scoped to `eventId = ctx.scope.event.id` would be wrong here). Infra\nkinds map to their session fields (`organization` → `ctx.activeOrgId`,\n`owner` → `ctx.userId`, `team` → `ctx.activeTeamId`); any other kind maps to\n`ctx.scope.<kind>.id`.\n\n## Namespace scope-claim refresh\n\nA scope is normally minted at `POST /scope/v1/enter`. When you also mount a\n[namespace](/compiler/definitions/access#namespace-mounts-hoisted-relationship-middleware)\nthat gates `/event/:eventId/*` on the **same** relationship, the namespace\nresolver can refresh `ctx.scope.<kind>` in memory for the duration of that\nrequest — so an attendee hitting `/event/evt_123/announce` gets\n`ctx.scope.event = { id: 'evt_123', roles: ['attendee'] }` without a separate\n`enter` round-trip. The refresh runs **after** the gate (the gate proves the\nrelationship; the refresh stamps the proven role from the path param).\n\nThis is a strictly-guarded convenience, and it stamps **per matched lane**. The\nresolver records which `via:` lane opened the gate (first-match-wins) and stamps\n**only that lane's** scope role — an attendee who matched `attendeeOf` gets\n`roles: ['attendee']`; an organizer who matched `organizerOf` gets\n`roles: ['organizer']`. A caller can never receive a role they didn't prove this\nrequest.\n\n- **Relationship lanes** each confer their own scope role, stamped only when that exact lane matched — so a **multi-lane `via:`** (e.g. `via: ['attendeeOf', 'organizerOf']`) refreshes the matched lane's role, not an ambiguous union.\n- A **bulk-grant lane** (`{ roles: [...] }` or `{ team: true }`) confers **no** scope role — it opens the gate via the caller's org role *without* proving any relationship, so there is nothing to stamp (stamping one would forge it). The gate still passes; the caller is simply authorized by their org role.\n\nThe refresh described so far is in-memory and single-request. To also hand the\ncaller a **persisted** scope token, opt the namespace into `mintScope` — see\nbelow.\n\n### Gotcha: a namespace only emits its resolver when it claims a standalone action\n\nThis is the single most common surprise (it has tripped up a customer): **a\nnamespace emits its resolver — and therefore the scope refresh and the\n[`mintScope`](#mintscope-mint-the-scope-token-from-the-namespace-resolver)\nmint — only when at least one STANDALONE action's `path:` falls under the\nnamespace prefix.**\n\nA standalone action declares its own `path:` (e.g.\n`path: '/event/:eventId/home'`), so the compiler can match it against the\nnamespace prefix and hoist it into the synthetic namespace routes file.\n**Record-based actions are different** — they mount under their resource's CRUD\nroutes (`/api/v1/guests/:id/checkin`), which live *outside* the\n`/event/:eventId` prefix. They never match the prefix, so they never get\nclaimed.\n\nA namespace that contains **only** record-based actions is therefore **inert**:\nnothing matches the prefix, no synthetic routes file is emitted, and so there\nis **no resolver, no scope refresh, and no mint** — even though the namespace\nis declared and validates cleanly. The middleware you expected to gate\n`/event/:eventId/*` simply isn't there.\n\nThe fix is to give the namespace at least one standalone action under the\nprefix. In `q-events`, `eventHome` exists precisely for this — a standalone\n`GET /event/:eventId/home` that pulls the resolver (and the §5.3 mint) into\nexistence:\n\n```typescript\n// features/events/actions/eventHome.ts\nexport default defineAction({\n path: '/event/:eventId/home', // ← standalone path UNDER the namespace prefix\n method: 'GET',\n input: z.object({}),\n access: { roles: ['scope:event:attendee', 'scope:event:organizer', 'manager+'] },\n async execute({ db, ctx, c }) { /* … */ },\n});\n```\n\nWith that action present, the `eventScope` resolver is emitted, runs the\n`attendeeOf` probe once per `/event/:eventId/*` request, stamps\n`ctx.scope.event`, and (because the namespace sets `mintScope: true`) mints the\nscope token. Without a standalone action under the prefix, none of that fires.\n\n## `mintScope` — mint the scope token from the namespace resolver\n\nA scope is normally minted by an explicit `POST /scope/v1/enter` round-trip.\nSetting **`mintScope: true`** on a namespace folds that mint into the\nnamespace resolver: on a successful relationship probe the resolver MINTS a\npersisted scope JWT and returns it via the `set-auth-token` header — so a\nnative client hitting `/event/:eventId/*` gets a scope token **without ever\ncalling `/scope/v1/enter`**.\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'linkedUserId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'guests',\n exposeAs: 'guest',\n },\n },\n namespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: ['attendeeOf'], // one or more lanes — mints the matched lane's role\n mintScope: true, // ← fold the scope-token mint into the resolver\n },\n },\n}\n```\n\nA confirmed attendee then hits the standalone action under the prefix:\n\n```http\nGET /api/v1/event/evt_123/home\nAuthorization: Bearer <existing-jwt>\n\n200 OK\nset-auth-token: <new-scoped-jwt> ← carries scope.event.roles = [\"attendee\"]\n```\n\nThe client stores the `set-auth-token` value and sends it as the bearer on\nevery subsequent `/event/:eventId/*` request. The JWT carries\n`scope.event = { id: 'evt_123', roles: ['attendee'] }`, so the scoped-role\naccess checks (`scope:event:attendee`) pass with no DB touch and no second\n`enter` call.\n\n`mintScope` is **opt-in per namespace** and defaults to `false`. With it off,\nthe resolver does the in-memory `ctx.scope.<kind>` refresh only (the section\nabove); subsequent requests must still call `/scope/v1/enter` for a persisted\ntoken.\n\n### Per-matched-lane minting (forging safety)\n\nThe mint stamps the scope role of **whichever lane matched**, gated on the\nfirst-match-wins probe — the *same* per-lane discipline as the in-memory stamp,\napplied here with higher stakes: a minted token **persists for its whole TTL**,\nso it can only ever carry the role the caller actually proved this request.\n\n- A **multi-lane `via:`** (e.g. `via: ['attendeeOf', 'organizerOf']`) mints the matched lane's role — `attendeeOf` → `scope.event.roles = ['attendee']`, `organizerOf` → `['organizer']`. The resolver records which lane opened the gate, so there is no ambiguity.\n- A **bulk-grant lane** (`{ roles: [...] }` or `{ team: true }`) mints **no** scope role — it opens the gate via the caller's org role without proving a relationship. The gate passes; the caller carries their org role, not a minted scope role.\n\n> The realtime [ws-ticket](/stack/realtime/durable-objects#namespace-backed-tickets-per-matched-lane) can authorize through this same namespace `via:`, issuing a per-matched-lane WebSocket ticket — so the socket gate and the REST gate stay identical.\n\nIn every suppressed case the gate still authorizes the request; only the mint\n(and the in-memory refresh) are skipped, and those callers obtain a scope\ntoken through `/scope/v1/enter` as usual. Flipping `mintScope: true` can never\nforge a scope role — the guard, not the flag, is the gate.\n\n### TTL and best-effort semantics\n\n- **TTL is the scope-token TTL** — `auth.jwt.expiresIn` (default 180s), **clamped to a hard ≤180s ceiling** at every signing site that emits a scope claim: both proven mints (`/scope/v1/enter`, the namespace resolver) *and* the middleware's rolling refresh. A longer-lived scope token would widen the post-revocation replay window past the spec bound, so the clamp is non-negotiable — an `auth.jwt.expiresIn` above the ceiling applies to plain tokens but never survives into a scope-bearing one.\n- **The mint is gated by the same proven-relationship guard as the in-memory stamp.** It runs *after* the gate has granted access, reading the instance id from the proven path param (`:eventId`) — never from request input — so the minted `scope:<kind>:<role>` is backed by exactly the proof `/scope/v1/enter` requires. The token is **byte-identical** to one `/scope/v1/enter` would produce: same shared mint helper, same carry-forward of any *other* verified scope kinds already on the incoming token (the freshly-proven kind takes precedence; siblings survive the re-mint).\n- **The mint is best-effort.** A mint failure (e.g. a missing signing secret) **never fails the request** — the in-memory stamp already authorized it; the caller simply doesn't receive a refreshed token on that response and can fall back to `/scope/v1/enter`.\n\n## `acceptScope` — accept an incoming scope claim as proof of entry\n\n`mintScope` is the resolver *minting* a scope claim after a `ctx.userId` lane\nmatches. **`acceptScope: '<kind>'` is the inverse: it lets the same resolver\n*accept* an already-minted `ctx.scope.<kind>` claim as its own proof** — so one\n`/event/:eventId/*` handler serves **both** the Better-Auth user (userId\nrelationship probe) **and** the sessionless scope principal (verified scope\nJWT, no account). It's the exact fast-path the realtime\n[ws-ticket](/stack/realtime/durable-objects) already has, ported to REST.\n\nWithout it, every scope-principal-facing namespaced action needs a **parallel\nPUBLIC twin** (a separate handler with a hand-rolled `requireScope` check and\nraw DB writes that bypass scoped-db) — double the surface, and \"someone forgot\nthe twin\" becomes a standing bug class. `acceptScope` retires the twin.\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n inspectorOf: {\n from: 'site_inspectors',\n subject: { column: 'inspectorUserId', equals: 'ctx.userId' },\n resource: { column: 'locationId' },\n where: { status: 'active' },\n loads: 'locations',\n exposeAs: 'location',\n },\n },\n scopes: {\n location: {\n requestField: 'locationId',\n roles: {\n // supplied-reachable: a signed-in user AND a sessionless principal\n // converge on ONE scope:location:inspector.\n inspector: { via: 'inspectorOf', subKeys: ['inspectorId'], subject: 'both' },\n },\n },\n },\n namespaces: {\n locationScope: {\n prefix: '/location/:locationId',\n via: ['inspectorOf'],\n acceptScope: 'location', // ← honor an incoming ctx.scope.location claim\n // mintScope: true, // ← compose freely: a userId caller also re-mints\n },\n },\n}\n```\n\nA sessionless principal that already minted a token (via\n[`ctx.mintScope`](#sessionless-scope-mint--ctxmintscope) or `/scope/v1/enter`)\nthen hits the namespaced action directly, no second round-trip:\n\n```http\nGET /api/v1/location/loc_42/summary\nAuthorization: Bearer <scope-only-jwt carrying scope.location = { id: 'loc_42', roles: ['inspector'] }>\n\n200 OK\n```\n\nThe resolver reads `ctx.scope.location`, confirms its `id` equals the `:locationId`\nparam, sees the `inspector` role a supplied-reachable lane confers, and admits\nthe request — no `ctx.userId`, no DB relationship probe. `ctx.location` is\nhydrated through its own firewall exactly as it is for the userId caller.\n\n### Two locks (both required, fail-closed)\n\n`acceptScope` is **named-string only** — always the explicit kind, never a bare\n`true` (there's no inference from the `:param`). Default absent → the resolver\n**never** admits a scope principal (unchanged behavior). Beyond naming the kind,\nthe compiler enforces a second lock:\n\n1. **`acceptScope: '<kind>'`** opts *this namespace's* REST surface in, **and**\n2. at least one relationship lane of the namespace confers a `<kind>` role\n declared **`subject: 'supplied' | 'both'`** (supplied-reachable).\n\nA `subject: 'user'` role can be *minted* or *refreshed* by the namespace but can\n**never be accepted** from a token — a user-only role must be proven by a live\n`ctx.userId` probe. If `acceptScope` names a kind whose every conferring lane is\n`subject: 'user'`, the **compiler errors** rather than emit a dead fast-path.\nThe compiler also checks the kind is declared and its `requestField` equals the\nprefix's first `:param`.\n\n### Forging safety\n\nA scope principal can't use `acceptScope` to reach anything its token doesn't\nalready authorize:\n\n- **The claim is verified, not asserted** — `ctx.scope` is populated only from a\n JWT the auth middleware verified; the action can't write it.\n- **Named kind, not any-kind** — the fast-path reads `ctx.scope['<kind>']` for\n the declared kind (stricter than the ws-ticket's any-key loop); a colliding\n foreign-kind id can't open the gate.\n- **Instance pinned twice** — `entry.id === :param` in the gate, *and*\n `eq(loads.pk, :param)` in hydration. The principal enters exactly the instance\n its claim proved.\n- **Role → lane is exact and supplied-restricted** — each accept arm is one\n `(role, lane)` pair with `subject !== 'user'`; an `inspector` claim matches\n `inspectorOf`, never a sibling lane.\n- **No new enforcement surface** — firewall, masking, `access` arms, and\n scoped-db all read the same `ctx.scope` / `ctx.activeOrgId` they read for a\n userId caller. New proof source, zero new enforcement surface.\n\nThe tenant (`ctx.activeOrgId`) is sourced from the pinned-loaded resource\n(`ctx.<exposeAs>.organizationId`) — parity with the userId caller, not a new\ngrant. Fine-grained \"own rows only\" stays the resource author's job via a\nfirewall arm on `ctx.scope.<kind>.subjectId`, the **same** arm that already\nserves the userId principal.\n\n### Writes: audit fields for a userless principal\n\nA scope principal has no `ctx.userId`, so the scoped-db **audit wrapper** — which\nstamps `created_by` / `modified_by` — can't record a user. Rather than force a\nparallel raw-`db` write path (which would re-scatter the exact duplication\n`acceptScope` removes), the wrapper stamps the principal's synthetic, audit-only\nid — the token's `sub`, `scope:<kind>:<subjectId>` — into those columns:\n\n```ts\n// A verified scope principal's write, through the normal scoped db:\nawait db.insert(vendorCheckins).values({ eventId, note });\n// → created_by = modified_by = \"scope:event:guest_abc123\"\n```\n\nThe `scope:` prefix self-describes the actor (which kind, which subject), so no\nseparate \"actor type\" column is needed. This is the write-side companion to the\nread fast-path: **one handler body serves both a Better-Auth user and the\nsessionless principal, on reads and writes alike.**\n\nIt stays **fail-closed**: the relaxation fires *only* for `ctx.scopePrincipal\n=== true`. A write that reaches the wrapper with no `userId` and no scope\nprincipal (genuine auth-context loss) still throws — the audit layer never\nsilently logs an unauthenticated write. For a real system-side write outside any\nrequest, use the unwrapped `db` (`createDb`) directly, as before.\n\n## Sessionless scope mint — `ctx.mintScope`\n\n`POST /scope/v1/enter` and the namespace resolver both prove the relationship by\n**`ctx.userId`** — so they require a Better Auth account. But a legitimate\nprincipal often has none: an **event attendee who arrives by email + invite\ncode**, holding an opaque session token you validate yourself, who must never\nget a global account. The shape is general — magic links, kiosk/handout codes,\npartner-issued API keys, expiring share links that need row-level scope.\n\nFor these, prove the relationship **your own way** inside an action, then ask\nQuickback to mint a disciplined scope token from the row you proved.\n\n### 1. Opt the role into supplied-subject proof\n\nAdd `subject` to the scope role (default `'user'`):\n\n```typescript\nauthz: {\n scopes: {\n event: {\n requestField: 'eventId',\n roles: {\n // 'both' → the SAME scope:event:attendee for a logged-in user\n // (via /enter) AND a sessionless invite-holder (via ctx.mintScope).\n attendee: { via: 'attendeeOf', subKeys: ['guestId'], subject: 'both' },\n },\n },\n },\n}\n```\n\n- **`'user'`** (default) — `/scope/v1/enter` only, proven by `subject.column = ctx.userId`. Unchanged.\n- **`'supplied'`** — sessionless only. `ctx.mintScope` mints it; `/enter` won't (there's no user to probe).\n- **`'both'`** — either path. A user-attendee and a sessionless invite-attendee converge on **one** `scope:event:attendee` — one firewall arm, one masking rule, both principals.\n\nThis opt-in is the single fail-closed switch: without `'supplied'` or `'both'`, no relationship is mintable by a supplied id.\n\n### 2. Mint from the proven row\n\n`ctx.mintScope` is hydrated on `ctx` in **any action** when a `subject:\n'supplied' | 'both'` role is declared (including **PUBLIC** actions — the\ncanonical caller has no token yet). The action proves the principal however it\nlikes, then hands Quickback **only the conferring row's primary key**:\n\n```typescript\n// features/events/actions/enterEvent.ts\nexport default defineAction({\n path: '/enter-event',\n method: 'POST',\n input: z.object({ code: z.string() }),\n access: { roles: ['PUBLIC'] }, // unauthenticated entry\n async execute({ ctx, input }) {\n const guestRowId = await validateInviteCode(ctx, input.code); // YOUR proof, YOUR table\n const { token } = await ctx.mintScope({ via: 'attendeeOf', subject: guestRowId });\n return { token }; // client sends it as `Authorization: Bearer …` thereafter\n },\n});\n```\n\nYou assert **nothing** about the scope. Quickback re-reads the `attendeeOf` row\nby primary key and takes the role, the resource id (`eventId`), the sub-keys,\nand the subject id **off that row** — so a buggy or hostile action can't forge\n`organizer`, can't pick a different event, and can't widen the slice. The only\nthing delegated to you is *which row* — exactly the opaque-credential check that\nhas to be custom code.\n\n| What you supply | What Quickback reads off the row |\n|---|---|\n| `via` (a declared `supplied`/`both` relationship) + `subject` (the `from`-row PK you proved) | the role, `id` (resource), sub-keys, and `subjectId` — none caller-asserted |\n\nThe `where:` filter runs on the mint probe exactly as at `/enter` — a cancelled\nor pending row confers nothing, so flipping a guest's `status` revokes them\nwithin one mint cycle (**≤180s**). Re-prove by calling `ctx.mintScope` again\n(your own refresh endpoint does exactly that). The by-PK probe does **not** apply\nthe relationship's tenant firewall (a sessionless principal has no\n`activeOrgId` yet — the proven row *is* what establishes scope), but matching by\nprimary key + the `where:` filter keeps it bounded and fail-closed.\n\n### 3. The scope-only token\n\n`ctx.mintScope` signs a **scope-only** JWT — it carries the `scope` claim and\nnothing else. There is **no user identity**: the auth middleware builds a context\nwith **`ctx.userId` undefined**, so every user-, org-, and owner-gated path\n**fails closed automatically** (an owner firewall compares against `undefined`\n→ matches nothing; org-role gates see empty `ctx.roles`). `AUTHENTICATED`\n**admits** a scope principal past the auth gate — it's the wrapper over session\n*and* scope callers (see [Access → Pseudo-roles](/compiler/definitions/access),\nwhere `SESSION` and `SCOPED` distinguish the two) — but a user/org/owner\n**firewall** then filters it to **zero rows** (no `ctx.userId`, no `ctx.activeOrgId`),\nso it reaches nothing it shouldn't. `USER` is likewise gate-permissive but\nfirewall-excluded: it mandates a `userId` scope the principal can't satisfy. To\nserve a scope principal actual rows, use `scope:<kind>:<role>` gates +\n`ctx.scope.<kind>` firewall arms (or `SCOPED` to admit any scope-token caller as\na tier).\n\nEverything downstream — REST firewall, masking, scoped-role access, the realtime\nws-ticket — then treats the sessionless attendee **identically** to a\nuser-proven one. There is no new enforcement surface; the principal is just\n`scope:event:attendee`.\n\n### `subjectId` — scoping to the person, not just the instance\n\nA user-proven scope scopes self-data (an attendee's travel, dietary, todos) by\n`ctx.userId`. A sessionless attendee has no `ctx.userId`, so the **proven\nsubject's identity rides in the claim** as a reserved **`subjectId`** — the\nconferring row's primary key:\n\n```jsonc\n\"scope\": { \"event\": { \"id\": \"evt_123\", \"roles\": [\"attendee\"], \"subjectId\": \"gst_42\" } }\n```\n\nScope self-data on it with one firewall arm:\n\n```typescript\n{ field: 'guestId', equals: 'ctx.scope.event.subjectId' }\n```\n\n`subjectId` is populated on **both** proof paths — `/scope/v1/enter` projects\nthe matched row's PK too — so the arm above is **one arm that serves both** a\nlogged-in attendee and a sessionless one. (It is distinct from\n`ctx.scope.event.id`, which is the *instance* — the event.)\n\n### Realtime\n\nA scope-only token authorizes the realtime\n[ws-ticket](/stack/realtime/durable-objects) directly off its proven\n`ctx.scope` claim — no `ctx.userId` re-probe. The sessionless attendee joins the\nsame per-event rooms (and per-attendee rooms keyed on `subjectId`) as a\nuser-attendee, carrying the same scope role on the ticket. So the REST gate and\nthe socket gate stay identical for accountless principals too.\n\n## Revocation & TTL\n\nThe scope claim is trusted between proofs — it is never re-checked against the database while it rides. Two bounds keep that window finite:\n\n- **The TTL** (default 180s, `auth.jwt.expiresIn`, clamped ≤180s on scope-bearing tokens) bounds an *idle* client: a token that stops being used dies within one TTL.\n- **The carry-forward cap** (15 minutes) bounds an *active* client: the rolling refresh re-signs the claim on every authed call, but only while the claim's proof timestamp (`sct`, stamped exclusively by the proven mint sites) is younger than the cap. Past it the refresh refuses, the token expires, and the next `enter` (or namespace-route mint) re-probes the relationship — which won't re-mint a revoked role.\n\nSo removing a guest/staff row takes effect within **cap + one TTL** for a client that keeps polling, and within one TTL once it goes idle. Two ways to tighten that:\n\n- **`auth.jwt.revocationCheck: 'kv'`** (v0.45+, Cloudflare runtime) — sub-TTL revocation: updating or deleting a conferring relationship row stamps a revocation timestamp in KV, and the bearer fast-path rejects a carried scope claim whose proof (`sct`) predates it. See [auth config](/compiler/config/auth).\n- **`via` arms** — for tables where any caching is too wide, gate with a `via` arm instead of a bare `ctx.scope.<kind>` arm: `via` emits a live subquery against the relationship table on every request, immune to a stale claim entirely.\n\n## Reference\n\n```typescript\n// AppContext (generated lib/types.ts)\nctx.scope?: Record<string, { id: string; roles?: string[]; subjectId?: string; [subKey: string]: string | string[] | undefined }>;\n\n// authz.scopes.<kind>\n{\n requestField: string; // body field carrying the instance id\n roles: Record<string, {\n via: string;\n subKeys?: string[]; // 'col' → eq, 'col[]' → inArray\n subject?: 'user' | 'supplied' | 'both'; // who selects the conferring row (default 'user')\n }>;\n}\n\n// ctx.mintScope — present in actions when a `subject: 'supplied' | 'both'` role is declared\nctx.mintScope(opts: { via: string; subject: string; setAuthToken?: boolean }):\n Promise<{ token: string; scope: { id: string; roles: string[]; subjectId?: string } }>;\n```\n\n- `requestField` must equal every role-relationship's `resource.column`.\n- Each relationship's `from` table must exist and ship a generated firewall (it can't be `exception`).\n- A `subKeys` entry ending in `[]` is **set-valued** (lowers to `inArray`, minted as `string[]`); without the marker it's scalar (`eq`, minted as `string`).\n- `subject` defaults to `'user'`. `'supplied'`/`'both'` enable [`ctx.mintScope`](#sessionless-scope-mint--ctxmintscope) (sessionless mint); `'supplied'` is **not** mintable via `/scope/v1/enter`.\n- `ctx.mintScope({ via, subject })` mints a **scope-only** token (no user identity, `ctx.userId` undefined) from the `from`-row whose PK is `subject` — reading the role, resource id, sub-keys, and `subjectId` off that row.\n- `subjectId` is the conferring row's primary key, populated on **both** proof paths — scope self-data on `ctx.scope.<kind>.subjectId`.\n- `q.scope('<kind>')` auto-stamps the column from `ctx.scope.<kind>.id` on insert.\n- Generated route: `POST /scope/v1/enter` (mounted only when `authz.scopes` is declared)."
158
+ "content": "Org membership answers *\"which tenant is this caller in?\"* Scopes answer a different question: *\"this caller isn't an org member, but they're a **confirmed attendee of event E** — let them see exactly E's rows, as exactly the role they hold, and nothing else.\"*\n\nA **scope** is a tenant axis whose value is established by a **relationship you prove once** (at `POST /scope/v1/enter`) and then carry in a signed JWT claim — verified cryptographically on every later request with **no database round-trip**. It's the REST/JWT twin of the realtime ws-ticket.\n\n## When to use it\n\nReach for a scope when a principal must touch a bounded slice of an instance **without being an org member**:\n\n- **Event attendee** — reads their event's announcements / sessions, not the org.\n- **Shuttle driver** — sees only the passengers on *their* bus (a row slice), can DM them.\n- **F&B vendor** — reads dietary *counts*, zero attendee rows.\n- **Visiting nurse / carrier / contractor** — one patient's meds, one carrier's shipments.\n\nEach is *event-scoped* but a **distinct least-privilege role**. Org members are unaffected — they keep their normal tenant access.\n\nMost scope principals are signed-in users who prove a relationship at [`/scope/v1/enter`](#2-enter-the-scope). But some have **no account at all** — an attendee who arrives by email + invite code, a kiosk/handout code, a partner token. For those, an action proves the principal its own way and [`ctx.mintScope`](#sessionless-scope-mint--ctxmintscope) mints the same scope, no Better Auth user required.\n\n## The model\n\n### 1. Declare relationships + scopes\n\nA scope **kind** (`event`) declares named **roles**, each conferred by a relationship whose `from` row carries the role (and optionally a **sub-key** for row slicing).\n\nScope kinds declare at root `authz` (visible everywhere) or inside a\n[feature area](/compiler/definitions/feature-areas)'s `_area.ts` — then the kind, its bare\nrole aliases, the canonical `scope:<kind>:<role>` spellings, and `ctx.scope.<kind>` accessors\nare all visible to that area's subtree only (any outside reference is a compile error):\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: { from: 'guests', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { status: 'confirmed' } },\n organizerOf: { from: 'staff', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { role: 'organizer' } },\n shuttleDriverOf: { from: 'staff', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { role: 'shuttleDriver' } },\n },\n scopes: {\n event: {\n requestField: 'eventId', // the body field the client sends to /enter\n roles: {\n attendee: { via: 'attendeeOf' },\n organizer: { via: 'organizerOf' },\n shuttleDriver: { via: 'shuttleDriverOf', subKeys: ['shuttleId'] }, // row-slice sub-key\n },\n },\n },\n}\n```\n\n### 2. Enter the scope\n\n```http\nPOST /scope/v1/enter (session OR existing JWT auth)\n{ \"eventId\": \"evt_123\" }\n```\n\nThe server probes **every declared role** for the proposed instance (one DB touch), and mints the proven roles + sub-keys into a signed JWT `scope` claim, returned via the `set-auth-token` header and the body:\n\n```jsonc\n// a shuttle driver who is also a confirmed guest\n\"scope\": { \"event\": { \"id\": \"evt_123\", \"roles\": [\"attendee\", \"shuttleDriver\"], \"shuttleId\": \"shA\" } }\n```\n\nThe client sends that JWT as `Authorization: Bearer …` on subsequent requests. The auth middleware verifies the signature and sets `ctx.scope` — **no DB**. The claim is carried forward on every authed call (rolling refresh) for up to **15 minutes from the last actual relationship proof** — the mint stamps a proof timestamp (`sct`) that the refresh carries forward verbatim and checks against the carry-forward cap. Past the cap the refresh stops, the token expires within one TTL, and the client re-proves via `enter` (or any namespace route that mints) to restart the window.\n\n> **Invariant:** the client only *proposes* the instance id (from the URL). The server proves membership before signing. No client-asserted scope is ever trusted.\n\n### 3. Gate the pillars\n\nScoped roles are referenced everywhere a pillar takes a role as the namespaced identifier **`scope:<kind>:<role>`**:\n\n```typescript\n// features/guests/guests.ts — the manifest, row-sliced + PII-masked\nexport default feature('guests', {\n columns: { /* … eventId, shuttleId, email, … */ },\n // org staff see the whole event; a shuttle driver sees only their bus\n firewall: {\n any: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { all: [\n { field: 'eventId', equals: 'ctx.scope.event' },\n { field: 'shuttleId', equals: 'ctx.scope.event.shuttleId' }, // sub-key row slice\n ] },\n ],\n },\n masking: {\n email: { type: 'email', show: { roles: ['admin', 'scope:event:organizer'] } }, // hidden from the driver\n },\n read: {\n views: {\n manifest: {\n fields: ['id', 'nameAtInvite', 'shuttleId', 'pickupLocation'],\n access: { roles: ['admin', 'scope:event:organizer', 'scope:event:shuttleDriver'] },\n },\n },\n },\n});\n```\n\n| Pillar | How it reads the scoped role |\n|--------|------------------------------|\n| **Firewall** (rows) | `all`/`any` arms keyed on `ctx.scope.<kind>` (+ sub-keys) — see [Firewall](/compiler/definitions/firewall) |\n| **Access** (verbs/views) | `access.roles: ['scope:event:shuttleDriver']` on CRUD, actions, and views |\n| **Masking** (fields) | `masking.<col>.show.roles` includes / excludes `scope:event:<role>` |\n\n## The org / scope split (security)\n\n**Scoped roles never merge into `ctx.roles`.** A `scope:*` identifier matches **only** the verified scope claim (`ctx.scope.<kind>.roles`); a bare org role (`admin`, `member`) matches **only** `ctx.roles`. The compiler enforces the split so an externally-provisioned `shuttleDriver` can **never** satisfy an `admin` gate by string coincidence, and a tampered scope claim can't impersonate an org role. This is the precondition for admitting limited outside users at all.\n\n## Sub-keys (row slicing)\n\nA role's `subKeys` name columns on the relationship's `from` row that are projected into the claim. A firewall arm then slices on them:\n\n```typescript\n{ field: 'shuttleId', equals: 'ctx.scope.event.shuttleId' }\n```\n\nBecause sub-key arms compose with `all`, an **absent** sub-key denies (`sql\\`1 = 0\\``) rather than widening — a driver can never see *all* shuttles by simply lacking the claim. The scope accessor is always emitted null-safe (`ctx.scope?.event?.shuttleId`), so an org caller who never entered the scope hits a clean deny, not a 500.\n\n### Set-valued sub-keys\n\nA driver may cover **more than one** bus. Append a `[]` marker to the\nsub-key name to project **every** matched `from` row's value into the claim\nas a `string[]`:\n\n```typescript\nroles: {\n shuttleDriver: { via: 'shuttleDriverOf', subKeys: ['shuttleId[]'] }, // set-valued\n}\n```\n\nThe `[]` is a marker only — it's stripped from the column name (the\nrelationship's `from` row still reads `shuttleId`). At `/scope/v1/enter` the\nproven rows union their values, so the claim carries an array:\n\n```jsonc\n\"scope\": { \"event\": { \"id\": \"evt_123\", \"roles\": [\"shuttleDriver\"], \"shuttleId\": [\"shA\", \"shC\"] } }\n```\n\nThe matching firewall arm — written exactly as for the scalar case\n(`{ field: 'shuttleId', equals: 'ctx.scope.event.shuttleId' }`) — is\n**rewritten by the compiler** to an `inArray` row-slice:\n\n```sql\nWHERE shuttle_id IN (ctx.scope?.event?.shuttleId ?? [])\n```\n\nThe `?? []` default makes an absent claim lower to `inArray(col, [])` — a\nclean DENY, never a malformed SQL fragment or a 500. A scalar sub-key (no\n`[]` marker) is untouched and keeps lowering to `eq`. You write the same\n`equals` arm either way; declaring `shuttleId[]` vs `shuttleId` in the scope\nrole is the only switch.\n\n## Auto-stamping the scope column on insert (`q.scope`)\n\n`q.scope('organization')` auto-stamps the tenant column on write, the same\nway `q.scope('owner')` stamps `ownerId`. A relationship-derived kind works\nidentically: `q.scope('event')` auto-stamps the column from the **verified\nscope claim** (`ctx.scope.event.id`) on insert — no need to pass `eventId`\nin the request body:\n\n```typescript\nexport const eventNotes = q.table('event_notes', {\n id: q.id(),\n eventId: q.scope('event'), // INSERT autofill from ctx.scope.event.id\n body: q.text().required(),\n organizationId: q.scope('organization'), // INSERT autofill from ctx.activeOrgId\n});\n```\n\nThe stamp is **insert-only** and null-safe — the generated CREATE handler\nwrites `eventId: ctx.scope?.event?.id`, so it never binds `undefined`. It\ndoes **not** add a read-time `WHERE` filter (that's the firewall's job; a\nread scoped to `eventId = ctx.scope.event.id` would be wrong here). Infra\nkinds map to their session fields (`organization` → `ctx.activeOrgId`,\n`owner` → `ctx.userId`, `team` → `ctx.activeTeamId`); any other kind maps to\n`ctx.scope.<kind>.id`.\n\n### Stamping a proven *identity* claim (`q.stamp`)\n\n`q.scope('event')` stamps the **tenant** id (`ctx.scope.event.id`). To stamp a\ndifferent **proven claim** off the same verified scope — the caller's own\n`subjectId` (the conferring row's PK) or a scalar sub-key — use\n[`q.stamp`](/compiler/definitions/schema#qstamp--proven-principal-identity-columns):\n\n```typescript\nauthorId: q.stamp({ fromScope: 'event', claim: 'subjectId' }),\n```\n\nEvery proven scope carries `id`, `subjectId`, and any projected sub-keys; a\n`q.stamp` column reads one of those. Unlike `q.scope` it is **never** a firewall\narm (identity is not a tenant scope), and it force-stamps **only** for scope-only\nprincipals — an org member/admin/owner writes it via the org path. A scope-only\ncaller missing the claim gets a fail-closed **403**, never a `NULL` row.\n\n## Namespace scope-claim refresh\n\nA scope is normally minted at `POST /scope/v1/enter`. When you also mount a\n[namespace](/compiler/definitions/access#namespace-mounts-hoisted-relationship-middleware)\nthat gates `/event/:eventId/*` on the **same** relationship, the namespace\nresolver can refresh `ctx.scope.<kind>` in memory for the duration of that\nrequest — so an attendee hitting `/event/evt_123/announce` gets\n`ctx.scope.event = { id: 'evt_123', roles: ['attendee'] }` without a separate\n`enter` round-trip. The refresh runs **after** the gate (the gate proves the\nrelationship; the refresh stamps the proven role from the path param).\n\nThis is a strictly-guarded convenience, and it stamps **per matched lane**. The\nresolver records which `via:` lane opened the gate (first-match-wins) and stamps\n**only that lane's** scope role — an attendee who matched `attendeeOf` gets\n`roles: ['attendee']`; an organizer who matched `organizerOf` gets\n`roles: ['organizer']`. A caller can never receive a role they didn't prove this\nrequest.\n\n- **Relationship lanes** each confer their own scope role, stamped only when that exact lane matched — so a **multi-lane `via:`** (e.g. `via: ['attendeeOf', 'organizerOf']`) refreshes the matched lane's role, not an ambiguous union.\n- A **bulk-grant lane** (`{ roles: [...] }` or `{ team: true }`) confers **no** scope role — it opens the gate via the caller's org role *without* proving any relationship, so there is nothing to stamp (stamping one would forge it). The gate still passes; the caller is simply authorized by their org role.\n\nThe refresh described so far is in-memory and single-request. To also hand the\ncaller a **persisted** scope token, opt the namespace into `mintScope` — see\nbelow.\n\n### Gotcha: a namespace only emits its resolver when it claims a standalone action\n\nThis is the single most common surprise (it has tripped up a customer): **a\nnamespace emits its resolver — and therefore the scope refresh and the\n[`mintScope`](#mintscope-mint-the-scope-token-from-the-namespace-resolver)\nmint — only when at least one STANDALONE action's `path:` falls under the\nnamespace prefix.**\n\nA standalone action declares its own `path:` (e.g.\n`path: '/event/:eventId/home'`), so the compiler can match it against the\nnamespace prefix and hoist it into the synthetic namespace routes file.\n**Record-based actions are different** — they mount under their resource's CRUD\nroutes (`/api/v1/guests/:id/checkin`), which live *outside* the\n`/event/:eventId` prefix. They never match the prefix, so they never get\nclaimed.\n\nA namespace that contains **only** record-based actions is therefore **inert**:\nnothing matches the prefix, no synthetic routes file is emitted, and so there\nis **no resolver, no scope refresh, and no mint** — even though the namespace\nis declared and validates cleanly. The middleware you expected to gate\n`/event/:eventId/*` simply isn't there.\n\nThe fix is to give the namespace at least one standalone action under the\nprefix. In `q-events`, `eventHome` exists precisely for this — a standalone\n`GET /event/:eventId/home` that pulls the resolver (and the §5.3 mint) into\nexistence:\n\n```typescript\n// features/events/actions/eventHome.ts\nexport default defineAction({\n path: '/event/:eventId/home', // ← standalone path UNDER the namespace prefix\n method: 'GET',\n input: z.object({}),\n access: { roles: ['scope:event:attendee', 'scope:event:organizer', 'manager+'] },\n async execute({ db, ctx, c }) { /* … */ },\n});\n```\n\nWith that action present, the `eventScope` resolver is emitted, runs the\n`attendeeOf` probe once per `/event/:eventId/*` request, stamps\n`ctx.scope.event`, and (because the namespace sets `mintScope: true`) mints the\nscope token. Without a standalone action under the prefix, none of that fires.\n\n## `mintScope` — mint the scope token from the namespace resolver\n\nA scope is normally minted by an explicit `POST /scope/v1/enter` round-trip.\nSetting **`mintScope: true`** on a namespace folds that mint into the\nnamespace resolver: on a successful relationship probe the resolver MINTS a\npersisted scope JWT and returns it via the `set-auth-token` header — so a\nnative client hitting `/event/:eventId/*` gets a scope token **without ever\ncalling `/scope/v1/enter`**.\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'linkedUserId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'guests',\n exposeAs: 'guest',\n },\n },\n namespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: ['attendeeOf'], // one or more lanes — mints the matched lane's role\n mintScope: true, // ← fold the scope-token mint into the resolver\n },\n },\n}\n```\n\nA confirmed attendee then hits the standalone action under the prefix:\n\n```http\nGET /api/v1/event/evt_123/home\nAuthorization: Bearer <existing-jwt>\n\n200 OK\nset-auth-token: <new-scoped-jwt> ← carries scope.event.roles = [\"attendee\"]\n```\n\nThe client stores the `set-auth-token` value and sends it as the bearer on\nevery subsequent `/event/:eventId/*` request. The JWT carries\n`scope.event = { id: 'evt_123', roles: ['attendee'] }`, so the scoped-role\naccess checks (`scope:event:attendee`) pass with no DB touch and no second\n`enter` call.\n\n`mintScope` is **opt-in per namespace** and defaults to `false`. With it off,\nthe resolver does the in-memory `ctx.scope.<kind>` refresh only (the section\nabove); subsequent requests must still call `/scope/v1/enter` for a persisted\ntoken.\n\n### Per-matched-lane minting (forging safety)\n\nThe mint stamps the scope role of **whichever lane matched**, gated on the\nfirst-match-wins probe — the *same* per-lane discipline as the in-memory stamp,\napplied here with higher stakes: a minted token **persists for its whole TTL**,\nso it can only ever carry the role the caller actually proved this request.\n\n- A **multi-lane `via:`** (e.g. `via: ['attendeeOf', 'organizerOf']`) mints the matched lane's role — `attendeeOf` → `scope.event.roles = ['attendee']`, `organizerOf` → `['organizer']`. The resolver records which lane opened the gate, so there is no ambiguity.\n- A **bulk-grant lane** (`{ roles: [...] }` or `{ team: true }`) mints **no** scope role — it opens the gate via the caller's org role without proving a relationship. The gate passes; the caller carries their org role, not a minted scope role.\n\n> The realtime [ws-ticket](/stack/realtime/durable-objects#namespace-backed-tickets-per-matched-lane) can authorize through this same namespace `via:`, issuing a per-matched-lane WebSocket ticket — so the socket gate and the REST gate stay identical.\n\nIn every suppressed case the gate still authorizes the request; only the mint\n(and the in-memory refresh) are skipped, and those callers obtain a scope\ntoken through `/scope/v1/enter` as usual. Flipping `mintScope: true` can never\nforge a scope role — the guard, not the flag, is the gate.\n\n### TTL and best-effort semantics\n\n- **TTL is the scope-token TTL** — `auth.jwt.expiresIn` (default 180s), **clamped to a hard ≤180s ceiling** at every signing site that emits a scope claim: both proven mints (`/scope/v1/enter`, the namespace resolver) *and* the middleware's rolling refresh. A longer-lived scope token would widen the post-revocation replay window past the spec bound, so the clamp is non-negotiable — an `auth.jwt.expiresIn` above the ceiling applies to plain tokens but never survives into a scope-bearing one.\n- **The mint is gated by the same proven-relationship guard as the in-memory stamp.** It runs *after* the gate has granted access, reading the instance id from the proven path param (`:eventId`) — never from request input — so the minted `scope:<kind>:<role>` is backed by exactly the proof `/scope/v1/enter` requires. The token is **byte-identical** to one `/scope/v1/enter` would produce: same shared mint helper, same carry-forward of any *other* verified scope kinds already on the incoming token (the freshly-proven kind takes precedence; siblings survive the re-mint).\n- **The mint is best-effort.** A mint failure (e.g. a missing signing secret) **never fails the request** — the in-memory stamp already authorized it; the caller simply doesn't receive a refreshed token on that response and can fall back to `/scope/v1/enter`.\n\n## `acceptScope` — accept an incoming scope claim as proof of entry\n\n`mintScope` is the resolver *minting* a scope claim after a `ctx.userId` lane\nmatches. **`acceptScope: '<kind>'` is the inverse: it lets the same resolver\n*accept* an already-minted `ctx.scope.<kind>` claim as its own proof** — so one\n`/event/:eventId/*` handler serves **both** the Better-Auth user (userId\nrelationship probe) **and** the sessionless scope principal (verified scope\nJWT, no account). It's the exact fast-path the realtime\n[ws-ticket](/stack/realtime/durable-objects) already has, ported to REST.\n\nWithout it, every scope-principal-facing namespaced action needs a **parallel\nPUBLIC twin** (a separate handler with a hand-rolled `requireScope` check and\nraw DB writes that bypass scoped-db) — double the surface, and \"someone forgot\nthe twin\" becomes a standing bug class. `acceptScope` retires the twin.\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n inspectorOf: {\n from: 'site_inspectors',\n subject: { column: 'inspectorUserId', equals: 'ctx.userId' },\n resource: { column: 'locationId' },\n where: { status: 'active' },\n loads: 'locations',\n exposeAs: 'location',\n },\n },\n scopes: {\n location: {\n requestField: 'locationId',\n roles: {\n // supplied-reachable: a signed-in user AND a sessionless principal\n // converge on ONE scope:location:inspector.\n inspector: { via: 'inspectorOf', subKeys: ['inspectorId'], subject: 'both' },\n },\n },\n },\n namespaces: {\n locationScope: {\n prefix: '/location/:locationId',\n via: ['inspectorOf'],\n acceptScope: 'location', // ← honor an incoming ctx.scope.location claim\n // mintScope: true, // ← compose freely: a userId caller also re-mints\n },\n },\n}\n```\n\nA sessionless principal that already minted a token (via\n[`ctx.mintScope`](#sessionless-scope-mint--ctxmintscope) or `/scope/v1/enter`)\nthen hits the namespaced action directly, no second round-trip:\n\n```http\nGET /api/v1/location/loc_42/summary\nAuthorization: Bearer <scope-only-jwt carrying scope.location = { id: 'loc_42', roles: ['inspector'] }>\n\n200 OK\n```\n\nThe resolver reads `ctx.scope.location`, confirms its `id` equals the `:locationId`\nparam, sees the `inspector` role a supplied-reachable lane confers, and admits\nthe request — no `ctx.userId`, no DB relationship probe. `ctx.location` is\nhydrated through its own firewall exactly as it is for the userId caller.\n\n### Two locks (both required, fail-closed)\n\n`acceptScope` is **named-string only** — always the explicit kind, never a bare\n`true` (there's no inference from the `:param`). Default absent → the resolver\n**never** admits a scope principal (unchanged behavior). Beyond naming the kind,\nthe compiler enforces a second lock:\n\n1. **`acceptScope: '<kind>'`** opts *this namespace's* REST surface in, **and**\n2. at least one relationship lane of the namespace confers a `<kind>` role\n declared **`subject: 'supplied' | 'both'`** (supplied-reachable).\n\nA `subject: 'user'` role can be *minted* or *refreshed* by the namespace but can\n**never be accepted** from a token — a user-only role must be proven by a live\n`ctx.userId` probe. If `acceptScope` names a kind whose every conferring lane is\n`subject: 'user'`, the **compiler errors** rather than emit a dead fast-path.\nThe compiler also checks the kind is declared and its `requestField` equals the\nprefix's first `:param`.\n\n### Forging safety\n\nA scope principal can't use `acceptScope` to reach anything its token doesn't\nalready authorize:\n\n- **The claim is verified, not asserted** — `ctx.scope` is populated only from a\n JWT the auth middleware verified; the action can't write it.\n- **Named kind, not any-kind** — the fast-path reads `ctx.scope['<kind>']` for\n the declared kind (stricter than the ws-ticket's any-key loop); a colliding\n foreign-kind id can't open the gate.\n- **Instance pinned twice** — `entry.id === :param` in the gate, *and*\n `eq(loads.pk, :param)` in hydration. The principal enters exactly the instance\n its claim proved.\n- **Role → lane is exact and supplied-restricted** — each accept arm is one\n `(role, lane)` pair with `subject !== 'user'`; an `inspector` claim matches\n `inspectorOf`, never a sibling lane.\n- **No new enforcement surface** — firewall, masking, `access` arms, and\n scoped-db all read the same `ctx.scope` / `ctx.activeOrgId` they read for a\n userId caller. New proof source, zero new enforcement surface.\n\nThe tenant (`ctx.activeOrgId`) is sourced from the pinned-loaded resource\n(`ctx.<exposeAs>.organizationId`) — parity with the userId caller, not a new\ngrant. Fine-grained \"own rows only\" stays the resource author's job via a\nfirewall arm on `ctx.scope.<kind>.subjectId`, the **same** arm that already\nserves the userId principal.\n\n### Writes: audit fields for a userless principal\n\nA scope principal has no `ctx.userId`, so the scoped-db **audit wrapper** — which\nstamps `created_by` / `modified_by` — can't record a user. Rather than force a\nparallel raw-`db` write path (which would re-scatter the exact duplication\n`acceptScope` removes), the wrapper stamps the principal's synthetic, audit-only\nid — the token's `sub`, `scope:<kind>:<subjectId>` — into those columns:\n\n```ts\n// A verified scope principal's write, through the normal scoped db:\nawait db.insert(vendorCheckins).values({ eventId, note });\n// → created_by = modified_by = \"scope:event:guest_abc123\"\n```\n\nThe `scope:` prefix self-describes the actor (which kind, which subject), so no\nseparate \"actor type\" column is needed. This is the write-side companion to the\nread fast-path: **one handler body serves both a Better-Auth user and the\nsessionless principal, on reads and writes alike.**\n\nIt stays **fail-closed**: the relaxation fires *only* for `ctx.scopePrincipal\n=== true`. A write that reaches the wrapper with no `userId` and no scope\nprincipal (genuine auth-context loss) still throws — the audit layer never\nsilently logs an unauthenticated write. For a real system-side write outside any\nrequest, use the unwrapped `db` (`createDb`) directly, as before.\n\n## Sessionless scope mint — `ctx.mintScope`\n\n`POST /scope/v1/enter` and the namespace resolver both prove the relationship by\n**`ctx.userId`** — so they require a Better Auth account. But a legitimate\nprincipal often has none: an **event attendee who arrives by email + invite\ncode**, holding an opaque session token you validate yourself, who must never\nget a global account. The shape is general — magic links, kiosk/handout codes,\npartner-issued API keys, expiring share links that need row-level scope.\n\nFor these, prove the relationship **your own way** inside an action, then ask\nQuickback to mint a disciplined scope token from the row you proved.\n\n### 1. Opt the role into supplied-subject proof\n\nAdd `subject` to the scope role (default `'user'`):\n\n```typescript\nauthz: {\n scopes: {\n event: {\n requestField: 'eventId',\n roles: {\n // 'both' → the SAME scope:event:attendee for a logged-in user\n // (via /enter) AND a sessionless invite-holder (via ctx.mintScope).\n attendee: { via: 'attendeeOf', subKeys: ['guestId'], subject: 'both' },\n },\n },\n },\n}\n```\n\n- **`'user'`** (default) — `/scope/v1/enter` only, proven by `subject.column = ctx.userId`. Unchanged.\n- **`'supplied'`** — sessionless only. `ctx.mintScope` mints it; `/enter` won't (there's no user to probe).\n- **`'both'`** — either path. A user-attendee and a sessionless invite-attendee converge on **one** `scope:event:attendee` — one firewall arm, one masking rule, both principals.\n\nThis opt-in is the single fail-closed switch: without `'supplied'` or `'both'`, no relationship is mintable by a supplied id.\n\n### 2. Mint from the proven row\n\n`ctx.mintScope` is hydrated on `ctx` in **any action** when a `subject:\n'supplied' | 'both'` role is declared (including **PUBLIC** actions — the\ncanonical caller has no token yet). The action proves the principal however it\nlikes, then hands Quickback **only the conferring row's primary key**:\n\n```typescript\n// features/events/actions/enterEvent.ts\nexport default defineAction({\n path: '/enter-event',\n method: 'POST',\n input: z.object({ code: z.string() }),\n access: { roles: ['PUBLIC'] }, // unauthenticated entry\n async execute({ ctx, input }) {\n const guestRowId = await validateInviteCode(ctx, input.code); // YOUR proof, YOUR table\n const { token } = await ctx.mintScope({ via: 'attendeeOf', subject: guestRowId });\n return { token }; // client sends it as `Authorization: Bearer …` thereafter\n },\n});\n```\n\nYou assert **nothing** about the scope. Quickback re-reads the `attendeeOf` row\nby primary key and takes the role, the resource id (`eventId`), the sub-keys,\nand the subject id **off that row** — so a buggy or hostile action can't forge\n`organizer`, can't pick a different event, and can't widen the slice. The only\nthing delegated to you is *which row* — exactly the opaque-credential check that\nhas to be custom code.\n\n| What you supply | What Quickback reads off the row |\n|---|---|\n| `via` (a declared `supplied`/`both` relationship) + `subject` (the `from`-row PK you proved) | the role, `id` (resource), sub-keys, and `subjectId` — none caller-asserted |\n\nThe `where:` filter runs on the mint probe exactly as at `/enter` — a cancelled\nor pending row confers nothing, so flipping a guest's `status` revokes them\nwithin one mint cycle (**≤180s**). Re-prove by calling `ctx.mintScope` again\n(your own refresh endpoint does exactly that). The by-PK probe does **not** apply\nthe relationship's tenant firewall (a sessionless principal has no\n`activeOrgId` yet — the proven row *is* what establishes scope), but matching by\nprimary key + the `where:` filter keeps it bounded and fail-closed.\n\n### 3. The scope-only token\n\n`ctx.mintScope` signs a **scope-only** JWT — it carries the `scope` claim and\nnothing else. There is **no user identity**: the auth middleware builds a context\nwith **`ctx.userId` undefined**, so every user-, org-, and owner-gated path\n**fails closed automatically** (an owner firewall compares against `undefined`\n→ matches nothing; org-role gates see empty `ctx.roles`). `AUTHENTICATED`\n**admits** a scope principal past the auth gate — it's the wrapper over session\n*and* scope callers (see [Access → Pseudo-roles](/compiler/definitions/access),\nwhere `SESSION` and `SCOPED` distinguish the two) — but a user/org/owner\n**firewall** then filters it to **zero rows** (no `ctx.userId`, no `ctx.activeOrgId`),\nso it reaches nothing it shouldn't. `USER` is likewise gate-permissive but\nfirewall-excluded: it mandates a `userId` scope the principal can't satisfy. To\nserve a scope principal actual rows, use `scope:<kind>:<role>` gates +\n`ctx.scope.<kind>` firewall arms (or `SCOPED` to admit any scope-token caller as\na tier).\n\nEverything downstream — REST firewall, masking, scoped-role access, the realtime\nws-ticket — then treats the sessionless attendee **identically** to a\nuser-proven one. There is no new enforcement surface; the principal is just\n`scope:event:attendee`.\n\n### `subjectId` — scoping to the person, not just the instance\n\nA user-proven scope scopes self-data (an attendee's travel, dietary, todos) by\n`ctx.userId`. A sessionless attendee has no `ctx.userId`, so the **proven\nsubject's identity rides in the claim** as a reserved **`subjectId`** — the\nconferring row's primary key:\n\n```jsonc\n\"scope\": { \"event\": { \"id\": \"evt_123\", \"roles\": [\"attendee\"], \"subjectId\": \"gst_42\" } }\n```\n\nScope self-data on it with one firewall arm:\n\n```typescript\n{ field: 'guestId', equals: 'ctx.scope.event.subjectId' }\n```\n\n`subjectId` is populated on **both** proof paths — `/scope/v1/enter` projects\nthe matched row's PK too — so the arm above is **one arm that serves both** a\nlogged-in attendee and a sessionless one. (It is distinct from\n`ctx.scope.event.id`, which is the *instance* — the event.)\n\n### Realtime\n\nA scope-only token authorizes the realtime\n[ws-ticket](/stack/realtime/durable-objects) directly off its proven\n`ctx.scope` claim — no `ctx.userId` re-probe. The sessionless attendee joins the\nsame per-event rooms (and per-attendee rooms keyed on `subjectId`) as a\nuser-attendee, carrying the same scope role on the ticket. So the REST gate and\nthe socket gate stay identical for accountless principals too.\n\n## Revocation & TTL\n\nThe scope claim is trusted between proofs — it is never re-checked against the database while it rides. Two bounds keep that window finite:\n\n- **The TTL** (default 180s, `auth.jwt.expiresIn`, clamped ≤180s on scope-bearing tokens) bounds an *idle* client: a token that stops being used dies within one TTL.\n- **The carry-forward cap** (15 minutes) bounds an *active* client: the rolling refresh re-signs the claim on every authed call, but only while the claim's proof timestamp (`sct`, stamped exclusively by the proven mint sites) is younger than the cap. Past it the refresh refuses, the token expires, and the next `enter` (or namespace-route mint) re-probes the relationship — which won't re-mint a revoked role.\n\nSo removing a guest/staff row takes effect within **cap + one TTL** for a client that keeps polling, and within one TTL once it goes idle. Two ways to tighten that:\n\n- **`auth.jwt.revocationCheck: 'kv'`** (v0.45+, Cloudflare runtime) — sub-TTL revocation: updating or deleting a conferring relationship row stamps a revocation timestamp in KV, and the bearer fast-path rejects a carried scope claim whose proof (`sct`) predates it. See [auth config](/compiler/config/auth).\n- **`via` arms** — for tables where any caching is too wide, gate with a `via` arm instead of a bare `ctx.scope.<kind>` arm: `via` emits a live subquery against the relationship table on every request, immune to a stale claim entirely.\n\n## Reference\n\n```typescript\n// AppContext (generated lib/types.ts)\nctx.scope?: Record<string, { id: string; roles?: string[]; subjectId?: string; [subKey: string]: string | string[] | undefined }>;\n\n// authz.scopes.<kind>\n{\n requestField: string; // body field carrying the instance id\n roles: Record<string, {\n via: string;\n subKeys?: string[]; // 'col' → eq, 'col[]' → inArray\n subject?: 'user' | 'supplied' | 'both'; // who selects the conferring row (default 'user')\n }>;\n}\n\n// ctx.mintScope — present in actions when a `subject: 'supplied' | 'both'` role is declared\nctx.mintScope(opts: { via: string; subject: string; setAuthToken?: boolean }):\n Promise<{ token: string; scope: { id: string; roles: string[]; subjectId?: string } }>;\n```\n\n- `requestField` must equal every role-relationship's `resource.column`.\n- Each relationship's `from` table must exist and ship a generated firewall (it can't be `exception`).\n- A `subKeys` entry ending in `[]` is **set-valued** (lowers to `inArray`, minted as `string[]`); without the marker it's scalar (`eq`, minted as `string`).\n- `subject` defaults to `'user'`. `'supplied'`/`'both'` enable [`ctx.mintScope`](#sessionless-scope-mint--ctxmintscope) (sessionless mint); `'supplied'` is **not** mintable via `/scope/v1/enter`.\n- `ctx.mintScope({ via, subject })` mints a **scope-only** token (no user identity, `ctx.userId` undefined) from the `from`-row whose PK is `subject` — reading the role, resource id, sub-keys, and `subjectId` off that row.\n- `subjectId` is the conferring row's primary key, populated on **both** proof paths — scope self-data on `ctx.scope.<kind>.subjectId`.\n- `q.scope('<kind>')` auto-stamps the column from `ctx.scope.<kind>.id` on insert.\n- Generated route: `POST /scope/v1/enter` (mounted only when `authz.scopes` is declared)."
151
159
  },
152
160
  "compiler/definitions/sealed-protocol": {
153
161
  "title": "Sealed protocol (qbseal:1)",
@@ -239,7 +247,7 @@ export const DOCS = {
239
247
  },
240
248
  "compiler/targets/hono-api/using-the-api/batch-operations": {
241
249
  "title": "Batch Operations",
242
- "content": "Batch operations let you create, update, upsert, or delete multiple records in a single request. They are **auto-enabled** when the corresponding write operation exists in your definition.\n\n## Available Endpoints\n\n| Endpoint | Method | Auto-enabled When |\n|----------|--------|-------------------|\n| `/{resource}/batch` | `POST` | `create` exists |\n| `/{resource}/batch` | `PATCH` | `update` exists |\n| `/{resource}/batch` | `DELETE` | `delete` exists |\n| `/{resource}/batch` | `PUT` | `upsert` exists |\n\nTo disable a batch operation, set it to `false` in your definition:\n\n```typescript\ncreate: {\n access: { roles: ['hiring-manager'] },\n batch: false, // Disable batch create\n}\n```\n\n## Batch Create\n\n```\nPOST /api/v1/{resource}/batch\n```\n\n### Request\n\n```json\n{\n \"records\": [\n { \"candidateId\": \"cand_101\", \"jobId\": \"job_201\", \"stage\": \"applied\", \"notes\": \"Strong frontend background\" },\n { \"candidateId\": \"cand_101\", \"jobId\": \"job_202\", \"stage\": \"applied\", \"notes\": \"Also interested in backend role\" },\n { \"candidateId\": \"cand_102\", \"jobId\": \"job_201\", \"stage\": \"applied\", \"notes\": \"Referred by employee\" }\n ],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\n### Response (201 or 207)\n\n```json\n{\n \"success\": [\n { \"id\": \"app_abc1\", \"candidateId\": \"cand_101\", \"jobId\": \"job_201\", \"stage\": \"applied\", \"createdAt\": \"2025-01-15T10:00:00Z\" },\n { \"id\": \"app_abc3\", \"candidateId\": \"cand_102\", \"jobId\": \"job_201\", \"stage\": \"applied\", \"createdAt\": \"2025-01-15T10:00:00Z\" }\n ],\n \"errors\": [\n {\n \"index\": 1,\n \"record\": { \"candidateId\": \"cand_101\", \"jobId\": \"job_202\", \"stage\": \"applied\", \"notes\": \"Also interested in backend role\" },\n \"error\": {\n \"error\": \"Database insert failed\",\n \"layer\": \"validation\",\n \"code\": \"INSERT_FAILED\",\n \"details\": { \"reason\": \"UNIQUE constraint failed: applications.candidateId, applications.jobId\" }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"failFast\": false,\n \"transactional\": true\n }\n}\n```\n\n- **201** — All records created successfully\n- **207** — Partial success (some errors, some successes)\n\n`POST /batch` uses a single bulk `INSERT`, so `meta.transactional` is `true` on every provider — the database guarantees the insert is atomic regardless of the `failFast` flag.\n\nFields applied automatically to each record:\n- ID generation (UUID, prefixed, etc.)\n- Ownership fields (`organizationId`, `ownerId`, `createdBy`)\n- Audit fields (`createdAt`, `modifiedAt`)\n- Default values and computed fields\n\n## Batch Update\n\n```\nPATCH /api/v1/{resource}/batch\n```\n\nEvery record **must include an `id` field**.\n\n### Request\n\n```json\n{\n \"records\": [\n { \"id\": \"app_abc1\", \"notes\": \"Passed phone screen, schedule onsite\" },\n { \"id\": \"app_abc2\", \"notes\": \"Moved to technical interview round\" },\n { \"id\": \"app_xyz9\", \"notes\": \"Hiring manager approved offer\" }\n ],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\n### Response (200 or 207)\n\n```json\n{\n \"success\": [\n { \"id\": \"app_abc1\", \"notes\": \"Passed phone screen, schedule onsite\", \"modifiedAt\": \"2025-01-15T11:00:00Z\" },\n { \"id\": \"app_abc2\", \"notes\": \"Moved to technical interview round\", \"modifiedAt\": \"2025-01-15T11:00:00Z\" }\n ],\n \"errors\": [\n {\n \"index\": 2,\n \"record\": { \"id\": \"app_xyz9\", \"notes\": \"Hiring manager approved offer\" },\n \"error\": {\n \"error\": \"Not found\",\n \"layer\": \"firewall\",\n \"code\": \"NOT_FOUND\",\n \"details\": { \"id\": \"app_xyz9\" }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"failFast\": false,\n \"transactional\": false\n }\n}\n```\n\nRecords that don't exist or aren't accessible through the firewall return a `NOT_FOUND` error. Guard rules (immutable, protected, not-updatable fields) are checked per record.\n\n### Missing IDs\n\nIf any records are missing the `id` field, the entire request is rejected:\n\n```json\n{\n \"error\": \"Records missing required ID field\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_MISSING_IDS\",\n \"details\": { \"indices\": [0, 2] },\n \"hint\": \"All records must include an ID field for batch update.\"\n}\n```\n\n## Batch Delete\n\n```\nDELETE /api/v1/{resource}/batch\n```\n\n### Request\n\n```json\n{\n \"ids\": [\"app_abc1\", \"app_abc2\", \"app_abc3\"],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\nNote: Batch delete uses an `ids` array (not `records`).\n\n### Response (200 or 207)\n\n**Soft delete** (default):\n\n```json\n{\n \"success\": [\n { \"id\": \"app_abc1\", \"candidateId\": \"cand_101\", \"deletedAt\": \"2025-01-15T12:00:00Z\" },\n { \"id\": \"app_abc2\", \"candidateId\": \"cand_103\", \"deletedAt\": \"2025-01-15T12:00:00Z\" }\n ],\n \"errors\": [],\n \"meta\": {\n \"total\": 2,\n \"succeeded\": 2,\n \"failed\": 0,\n \"failFast\": false,\n \"transactional\": true\n }\n}\n```\n\n`DELETE /batch` issues a single bulk `UPDATE … WHERE id IN (...)` (soft delete) or `DELETE … WHERE id IN (...)` (hard delete), so `meta.transactional` is `true` on every provider regardless of `failFast`.\n\n**Hard delete**: Returns objects with only the `id` field (record data is deleted).\n\n## Batch Upsert\n\n```\nPUT /api/v1/{resource}/batch\n```\n\nInserts new records or updates existing ones. Every record must include an `id` field.\n\n**Note:** Batch upsert is only available when `generateId` is set to `false` (user-provided IDs) in your configuration.\n\n### Request\n\n```json\n{\n \"records\": [\n { \"id\": \"app_001\", \"candidateId\": \"cand_101\", \"jobId\": \"job_201\", \"stage\": \"screening\", \"notes\": \"Updated after phone screen\" },\n { \"id\": \"app_002\", \"candidateId\": \"cand_104\", \"jobId\": \"job_203\", \"stage\": \"applied\", \"notes\": \"New application from referral\" }\n ],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\n### Response (201 or 207)\n\nThe compiler checks which IDs already exist and splits the batch into creates and updates. Create records get ownership and default fields; update records get only `modifiedAt`. Under `failFast: true`, both the bulk insert and the per-record updates run inside the same transaction — a failed update rolls back the inserts too on tx-supporting providers.\n\n## Fail-Fast Mode\n\nBy default, batch operations use **partial success** mode — each record is processed independently, and failures don't affect other records.\n\nSet `\"failFast\": true` to stop on the first error:\n\n```json\n{\n \"records\": [...],\n \"options\": {\n \"failFast\": true\n }\n}\n```\n\n### Fail-Fast Failure Response (400)\n\n```json\n{\n \"error\": \"Batch failed at index 1\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_FAILFAST_STOPPED\",\n \"details\": {\n \"failedAt\": 1,\n \"reason\": \"Database insert failed\",\n \"errorDetails\": { \"reason\": \"UNIQUE constraint failed\" }\n }\n}\n```\n\n## Transactional Semantics\n\nThe behavior of `failFast: true` depends on whether your database provider —\nand, for Neon, its **connection mode** — supports interactive transactions.\nThe response's `meta.transactional` flag tells you which guarantee you\nactually got — inspect it in clients that care about rollback.\n\nNeon is transactional **only over websocket** (`connectionMode: 'websocket'`,\nthe default on Node/Bun runtimes). Over HTTP — the default on Cloudflare\nWorkers — the `drizzle-orm/neon-http` driver has no `db.transaction()` (it\nthrows at runtime), so Neon-over-HTTP batches behave exactly like D1:\nfail-fast per-record loop, `meta.transactional: false`.\n\n### Per-Provider Matrix\n\n| Endpoint | Provider | `failFast` | `meta.transactional` | Behavior |\n|----------|----------|-----------|----------------------|----------|\n| `PATCH /batch` (update) | tx-supporting (postgres, neon over websocket) | `true` | `true` | `db.transaction()` wraps the per-record loop. Any failure rolls back ALL writes in the batch. |\n| `PATCH /batch` (update) | (any) | `false` | `false` | Per-record loop, partial success. Each record commits independently. |\n| `PATCH /batch` (update) | cloudflare-d1, neon over http (Cloudflare default) | `true` | `false` | Fail-fast loop without rollback — the driver has no `db.transaction`. Records before the failure stay committed. |\n| `PUT /batch` (upsert) | tx-supporting (postgres, neon over websocket) | `true` | `true` | Bulk insert + per-record update share one transaction. Any failure rolls back both. |\n| `PUT /batch` (upsert) | cloudflare-d1, neon over http (Cloudflare default) | `true` | `false` | Bulk insert commits; per-record update loop is fail-fast without rollback. |\n| `POST /batch` (create) | (any) | (any) | `true` | Single bulk `INSERT` — atomic at the DB level. |\n| `DELETE /batch` | (any) | (any) | `true` | Single bulk `UPDATE` (soft) or `DELETE` (hard) — atomic at the DB level. |\n\n### Reading `meta.transactional` in clients\n\n```typescript\nconst res = await fetch('/api/v1/jobs/batch', {\n method: 'PATCH',\n body: JSON.stringify({ records, options: { failFast: true } }),\n});\nconst body = await res.json();\n\nif (!body.meta.transactional && body.errors.length > 0) {\n // Some records succeeded before the failure and remain committed.\n // Compensate via the success array if needed.\n}\n```\n\n### Embeddings and Realtime\n\nWhen a resource has `embeddings` or `realtime` configured, queue messages\nand broadcasts are emitted **after** the transaction commits. A\nrolled-back batch produces no orphan embedding jobs.\n\n## Batch Size Limit\n\nThe default maximum batch size is **100 records**. Requests exceeding the limit are rejected:\n\n```json\n{\n \"error\": \"Batch size limit exceeded\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_SIZE_EXCEEDED\",\n \"details\": { \"max\": 100, \"actual\": 250 },\n \"hint\": \"Maximum 100 records allowed per batch. Split into multiple requests.\"\n}\n```\n\n## Configuration\n\nBatch operations inherit access control from their corresponding write operation. You can override per-batch settings:\n\n```typescript\nexport default defineTable(applications, {\n create: {\n access: { roles: ['hiring-manager', 'recruiter'] },\n batch: {\n access: { roles: ['hiring-manager'] }, // More restrictive than single create\n maxBatchSize: 50, // Default: 100\n allowFailFast: true, // Default: true\n },\n },\n update: {\n access: { roles: ['hiring-manager', 'recruiter'] },\n batch: {\n maxBatchSize: 100,\n allowFailFast: true,\n },\n },\n delete: {\n access: { roles: ['hiring-manager'] },\n mode: 'soft',\n batch: {\n access: { roles: ['hiring-manager'] },\n maxBatchSize: 100,\n allowFailFast: true,\n },\n },\n\n // Disable only batch upsert\n upsert: {\n access: { roles: ['hiring-manager'] },\n batch: false,\n },\n});\n```\n\n## Security\n\nAll security pillars apply to batch operations:\n\n1. **Authentication** — Required for all batch endpoints (401 if missing)\n2. **Firewall** — Applied per-record for update/delete/upsert (not applicable to create)\n3. **Access** — Role-based check using the batch operation's access config\n4. **Guards** — Per-record validation (createable/updatable/immutable fields)\n5. **Masking** — Applied to all records in the success array before response\n\n## See Also\n\n- [CRUD Endpoints](/compiler/targets/hono-api/using-the-api/crud) — Single-record operations\n- [Error Responses](/compiler/targets/hono-api/using-the-api/errors) — Error format reference\n- [Guards](/compiler/definitions/guards) — Field-level write protection"
250
+ "content": "Batch operations let you create, update, upsert, or delete multiple records in a single request. They are **auto-enabled** when the corresponding write operation exists in your definition.\n\n## Available Endpoints\n\n| Endpoint | Method | Auto-enabled When |\n|----------|--------|-------------------|\n| `/{resource}/batch` | `POST` | `create` exists |\n| `/{resource}/batch` | `PATCH` | `update` exists |\n| `/{resource}/batch` | `DELETE` | `delete` exists |\n| `/{resource}/batch` | `PUT` | `upsert` exists |\n\nTo disable a batch operation, set it to `false` in your definition:\n\n```typescript\ncreate: {\n access: { roles: ['hiring-manager'] },\n batch: false, // Disable batch create\n}\n```\n\n## Batch Create\n\n```\nPOST /api/v1/{resource}/batch\n```\n\n### Request\n\n```json\n{\n \"records\": [\n { \"candidateId\": \"cand_101\", \"jobId\": \"job_201\", \"stage\": \"applied\", \"notes\": \"Strong frontend background\" },\n { \"candidateId\": \"cand_101\", \"jobId\": \"job_202\", \"stage\": \"applied\", \"notes\": \"Also interested in backend role\" },\n { \"candidateId\": \"cand_102\", \"jobId\": \"job_201\", \"stage\": \"applied\", \"notes\": \"Referred by employee\" }\n ],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\n### Response (201 or 207)\n\n```json\n{\n \"success\": [\n { \"id\": \"app_abc1\", \"candidateId\": \"cand_101\", \"jobId\": \"job_201\", \"stage\": \"applied\", \"createdAt\": \"2025-01-15T10:00:00Z\" },\n { \"id\": \"app_abc3\", \"candidateId\": \"cand_102\", \"jobId\": \"job_201\", \"stage\": \"applied\", \"createdAt\": \"2025-01-15T10:00:00Z\" }\n ],\n \"errors\": [\n {\n \"index\": 1,\n \"record\": { \"candidateId\": \"cand_101\", \"jobId\": \"job_202\", \"stage\": \"applied\", \"notes\": \"Also interested in backend role\" },\n \"error\": {\n \"error\": \"Database insert failed\",\n \"layer\": \"validation\",\n \"code\": \"INSERT_FAILED\",\n \"details\": { \"reason\": \"UNIQUE constraint failed: applications.candidateId, applications.jobId\" }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"failFast\": false,\n \"transactional\": true\n }\n}\n```\n\n- **201** — All records created successfully\n- **207** — Partial success (some errors, some successes)\n\n`POST /batch` uses a single bulk `INSERT`, so `meta.transactional` is `true` on every provider — the database guarantees the insert is atomic regardless of the `failFast` flag.\n\nFields applied automatically to each record:\n- ID generation (UUID, prefixed, etc.)\n- Ownership fields (`organizationId`, `ownerId`, `createdBy`)\n- Audit fields (`createdAt`, `modifiedAt`)\n- Default values and computed fields\n\n## Batch Update\n\n```\nPATCH /api/v1/{resource}/batch\n```\n\nEvery record **must include an `id` field**.\n\n### Request\n\n```json\n{\n \"records\": [\n { \"id\": \"app_abc1\", \"notes\": \"Passed phone screen, schedule onsite\" },\n { \"id\": \"app_abc2\", \"notes\": \"Moved to technical interview round\" },\n { \"id\": \"app_xyz9\", \"notes\": \"Hiring manager approved offer\" }\n ],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\n### Response (200 or 207)\n\n```json\n{\n \"success\": [\n { \"id\": \"app_abc1\", \"notes\": \"Passed phone screen, schedule onsite\", \"modifiedAt\": \"2025-01-15T11:00:00Z\" },\n { \"id\": \"app_abc2\", \"notes\": \"Moved to technical interview round\", \"modifiedAt\": \"2025-01-15T11:00:00Z\" }\n ],\n \"errors\": [\n {\n \"index\": 2,\n \"record\": { \"id\": \"app_xyz9\", \"notes\": \"Hiring manager approved offer\" },\n \"error\": {\n \"error\": \"Not found\",\n \"layer\": \"firewall\",\n \"code\": \"NOT_FOUND\",\n \"details\": { \"id\": \"app_xyz9\" }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"failFast\": false,\n \"transactional\": false\n }\n}\n```\n\nRecords that don't exist or aren't accessible through the firewall return a `NOT_FOUND` error. Guard rules (immutable, protected, not-updatable fields) are checked per record.\n\n### Missing IDs\n\nIf any records are missing the `id` field, the entire request is rejected:\n\n```json\n{\n \"error\": \"Records missing required ID field\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_MISSING_IDS\",\n \"details\": { \"indices\": [0, 2] },\n \"hint\": \"All records must include an ID field for batch update.\"\n}\n```\n\n## Batch Delete\n\n```\nDELETE /api/v1/{resource}/batch\n```\n\n### Request\n\n```json\n{\n \"ids\": [\"app_abc1\", \"app_abc2\", \"app_abc3\"],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\nNote: Batch delete uses an `ids` array (not `records`).\n\n### Response (200 or 207)\n\n**Soft delete** (default):\n\n```json\n{\n \"success\": [\n { \"id\": \"app_abc1\", \"candidateId\": \"cand_101\", \"deletedAt\": \"2025-01-15T12:00:00Z\" },\n { \"id\": \"app_abc2\", \"candidateId\": \"cand_103\", \"deletedAt\": \"2025-01-15T12:00:00Z\" }\n ],\n \"errors\": [],\n \"meta\": {\n \"total\": 2,\n \"succeeded\": 2,\n \"failed\": 0,\n \"failFast\": false,\n \"transactional\": true\n }\n}\n```\n\n`DELETE /batch` issues a single bulk `UPDATE … WHERE id IN (...)` (soft delete) or `DELETE … WHERE id IN (...)` (hard delete), so `meta.transactional` is `true` on every provider regardless of `failFast`.\n\n**Hard delete**: Returns objects with only the `id` field (record data is deleted).\n\n## Batch Upsert\n\n```\nPUT /api/v1/{resource}/batch\n```\n\nInserts new records or updates existing ones. Every record must include an `id` field.\n\n**Note:** Batch upsert is only available when `generateId` is set to `false` (user-provided IDs) in your configuration.\n\n### Request\n\n```json\n{\n \"records\": [\n { \"id\": \"app_001\", \"candidateId\": \"cand_101\", \"jobId\": \"job_201\", \"stage\": \"screening\", \"notes\": \"Updated after phone screen\" },\n { \"id\": \"app_002\", \"candidateId\": \"cand_104\", \"jobId\": \"job_203\", \"stage\": \"applied\", \"notes\": \"New application from referral\" }\n ],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\n### Response (201 or 207)\n\nThe compiler checks which IDs already exist and splits the batch into creates and updates. Create records get ownership and default fields; update records get only `modifiedAt`. Under `failFast: true`, both the bulk insert and the per-record updates run inside the same transaction — a failed update rolls back the inserts too on tx-supporting providers.\n\n## Fail-Fast Mode\n\nBy default, batch operations use **partial success** mode — each record is processed independently, and failures don't affect other records.\n\nSet `\"failFast\": true` to stop on the first error:\n\n```json\n{\n \"records\": [...],\n \"options\": {\n \"failFast\": true\n }\n}\n```\n\n### Fail-Fast Failure Response (400)\n\n```json\n{\n \"error\": \"Batch failed at index 1\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_FAILFAST_STOPPED\",\n \"details\": {\n \"failedAt\": 1,\n \"reason\": \"Database insert failed\",\n \"errorDetails\": { \"reason\": \"UNIQUE constraint failed\" }\n }\n}\n```\n\n## Transactional Semantics\n\nThe behavior of `failFast: true` depends on whether your database provider —\nand, for Neon, its **connection mode** — supports interactive transactions.\nThe response's `meta.transactional` flag tells you which guarantee you\nactually got — inspect it in clients that care about rollback.\n\nNeon is transactional **only over websocket** (`connectionMode: 'websocket'`,\nthe default on Node/Bun runtimes). Over HTTP — the default on Cloudflare\nWorkers — the `drizzle-orm/neon-http` driver has no `db.transaction()` (it\nthrows at runtime), so Neon-over-HTTP batches behave exactly like D1:\nfail-fast per-record loop, `meta.transactional: false`.\n\n### Per-Provider Matrix\n\n| Endpoint | Provider | `failFast` | `meta.transactional` | Behavior |\n|----------|----------|-----------|----------------------|----------|\n| `PATCH /batch` (update) | tx-supporting (postgres, neon over websocket) | `true` | `true` | `db.transaction()` wraps the per-record loop. Any failure rolls back ALL writes in the batch. |\n| `PATCH /batch` (update) | (any) | `false` | `false` | Per-record loop, partial success. Each record commits independently. |\n| `PATCH /batch` (update) | cloudflare-d1, neon over http (Cloudflare default) | `true` | `false` | Fail-fast loop without rollback — the driver has no `db.transaction`. Records before the failure stay committed. |\n| `PUT /batch` (upsert) | tx-supporting (postgres, neon over websocket) | `true` | `true` | Bulk insert + per-record update share one transaction. Any failure rolls back both. |\n| `PUT /batch` (upsert) | cloudflare-d1, neon over http (Cloudflare default) | `true` | `false` | Bulk insert commits; per-record update loop is fail-fast without rollback. |\n| `POST /batch` (create) | (any) | (any) | `true` | Single bulk `INSERT` — atomic at the DB level. |\n| `DELETE /batch` | (any) | (any) | `true` | Single bulk `UPDATE` (soft) or `DELETE` (hard) — atomic at the DB level. |\n| [Changeset](/compiler/definitions/changesets) (`application/vnd.quickback.changeset+json`, contract v2) | tx-supporting (postgres, neon over websocket/hyperdrive) | n/a | `true` | Root op + every child op share one transaction; any op failure rolls back the whole changeset. |\n| [Changeset](/compiler/definitions/changesets) | cloudflare-d1, neon over http (Cloudflare default) | n/a | `false` | Deterministic parent-first fail-fast — the first op failure stops the changeset; already-applied ops stay committed (a consistent, independently-authorized prefix). |\n\n### Reading `meta.transactional` in clients\n\n```typescript\nconst res = await fetch('/api/v1/jobs/batch', {\n method: 'PATCH',\n body: JSON.stringify({ records, options: { failFast: true } }),\n});\nconst body = await res.json();\n\nif (!body.meta.transactional && body.errors.length > 0) {\n // Some records succeeded before the failure and remain committed.\n // Compensate via the success array if needed.\n}\n```\n\n### Embeddings and Realtime\n\nWhen a resource has `embeddings` or `realtime` configured, queue messages\nand broadcasts are emitted **after** the transaction commits. A\nrolled-back batch produces no orphan embedding jobs.\n\n## Batch Size Limit\n\nThe default maximum batch size is **100 records**. Requests exceeding the limit are rejected:\n\n```json\n{\n \"error\": \"Batch size limit exceeded\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_SIZE_EXCEEDED\",\n \"details\": { \"max\": 100, \"actual\": 250 },\n \"hint\": \"Maximum 100 records allowed per batch. Split into multiple requests.\"\n}\n```\n\n## Configuration\n\nBatch operations inherit access control from their corresponding write operation. You can override per-batch settings:\n\n```typescript\nexport default defineTable(applications, {\n create: {\n access: { roles: ['hiring-manager', 'recruiter'] },\n batch: {\n access: { roles: ['hiring-manager'] }, // More restrictive than single create\n maxBatchSize: 50, // Default: 100\n allowFailFast: true, // Default: true\n },\n },\n update: {\n access: { roles: ['hiring-manager', 'recruiter'] },\n batch: {\n maxBatchSize: 100,\n allowFailFast: true,\n },\n },\n delete: {\n access: { roles: ['hiring-manager'] },\n mode: 'soft',\n batch: {\n access: { roles: ['hiring-manager'] },\n maxBatchSize: 100,\n allowFailFast: true,\n },\n },\n\n // Disable only batch upsert\n upsert: {\n access: { roles: ['hiring-manager'] },\n batch: false,\n },\n});\n```\n\n## Security\n\nAll security pillars apply to batch operations:\n\n1. **Authentication** — Required for all batch endpoints (401 if missing)\n2. **Firewall** — Applied per-record for update/delete/upsert (not applicable to create)\n3. **Access** — Role-based check using the batch operation's access config\n4. **Guards** — Per-record validation (createable/updatable/immutable fields)\n5. **Masking** — Applied to all records in the success array before response\n\n## See Also\n\n- [CRUD Endpoints](/compiler/targets/hono-api/using-the-api/crud) — Single-record operations\n- [Error Responses](/compiler/targets/hono-api/using-the-api/errors) — Error format reference\n- [Guards](/compiler/definitions/guards) — Field-level write protection"
243
251
  },
244
252
  "compiler/targets/hono-api/using-the-api/caching": {
245
253
  "title": "Caching & ETags",
@@ -251,7 +259,7 @@ export const DOCS = {
251
259
  },
252
260
  "compiler/targets/hono-api/using-the-api/errors": {
253
261
  "title": "Errors",
254
- "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 production body is generic: it carries\nonly the error class name in `details.name` (so callers can branch on\ne.g. `TypeError` vs a fetch timeout) — never the underlying message,\ncause, or stack frames. The raw error is always logged server-side.\n\n```json\n{\n \"error\": \"Action execution failed\",\n \"layer\": \"action\",\n \"code\": \"ACTION_EXECUTION_FAILED\",\n \"details\": {\n \"name\": \"TypeError\"\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`. Same contract: the production\nbody is generic, and the full error (message, cause chain, stack) is\nlogged via `console.error` keyed by the `requestId` in the body — so\nthe response → log correlation is one grep.\n\n```json\n{\n \"error\": \"Internal error\",\n \"layer\": \"database\",\n \"code\": \"INTERNAL_ERROR\",\n \"details\": { \"operation\": \"request handling\" },\n \"hint\": \"Operation \\\"request handling\\\" failed unexpectedly. Check server logs for details.\",\n \"request\": {\n \"method\": \"GET\",\n \"url\": \"/api/v1/jobs\",\n \"requestId\": \"0c4f2c9e-...\"\n }\n}\n```\n\n### Exposing error details in dev / staging\n\nBy default nothing derived from the thrown error reaches the response\nbody — messages, cause chains, and stack frames can carry SQL, file\npaths, or secrets, so they stay server-side. To get verbose bodies\nwhile developing or staging, set `EXPOSE_ERROR_STACK=1` on the worker\n(`wrangler.toml` `[vars]`, or `wrangler secret put`):\n\n```toml\n[vars]\nEXPOSE_ERROR_STACK = \"1\"\n```\n\nWhen set, the global 500 and `ACTION_EXECUTION_FAILED` bodies forward\nthe underlying error message plus `details.cause` (cause-chain\nmessage), `details.frames` (top three stack frames with absolute paths\nsanitized to basename + line number), and `details.stack` (the full\nunsanitized stack trace). Leave it unset in production."
262
+ "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| `409` | Conflict | Unique constraint hit, or a duplicate [`Idempotency-Key`](/stack/api-contract#idempotency-key) still in flight |\n| `412` | Precondition Failed | [Changeset](/compiler/definitions/changesets) `If-Match` revision mismatch |\n| `422` | Unprocessable | `Idempotency-Key` reused with a different request or principal |\n| `428` | Precondition Required | `If-Match` sent where no revision exists (root without `updatedAt`, or the POST changeset variant) |\n| `429` | Too Many Requests | Rate limit exceeded |\n| `500` | Internal Error | Uncaught throw — generic body, full error server-side |\n\n## Error Response Format — RFC 9457 Problem Details\n\nEvery top-level error response is an\n[RFC 9457](https://www.rfc-editor.org/rfc/rfc9457) Problem Details document,\nserved as `application/problem+json` (see\n[API Contract](/stack/api-contract)).\nQuickback's contextual fields (`code`, `layer`, `details`, `hint`, `request`)\nsurvive as 9457 **extension members**, so clients that switch on `code` keep\nworking. Every structured error also carries a `request` block with the HTTP\nmethod, URL, request ID, and a redacted+truncated copy of the request body —\nenough to triage or hand the response to an LLM agent without grepping logs:\n\n```json\n{\n \"type\": \"https://quickback.dev/problems/access-role-required\",\n \"title\": \"Access role required\",\n \"status\": 403,\n \"detail\": \"Insufficient permissions\",\n \"instance\": \"/api/v1/candidates/cnd_01H.../advance\",\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| `type` | string | Problem type URI — `https://quickback.dev/problems/<code-in-kebab-case>` |\n| `title` | string | Human-stable summary derived from the code |\n| `status` | number | The HTTP status, repeated in the body |\n| `detail` | string | Human-readable error message (optional) |\n| `instance` | string | Request path (optional) |\n| `layer` | string | Extension — security layer that rejected the request |\n| `code` | string | Extension — machine-readable error code (the full enum ships in `openapi.json` as `Problem.code`) |\n| `details` | object | Extension — layer-specific context (optional) |\n| `pointer` | string | Extension — first offending field for validation failures, e.g. `/stage` (optional) |\n| `hint` | string | Extension — actionable guidance for resolution (optional) |\n| `request` | object | Extension — 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\nThe per-layer examples below are abbreviated to `detail` plus each layer's\nextension members — every real response also carries `type`, `title`,\n`status`, and (where derivable) `instance`.\n\n## Errors by Security Layer\n\n### Authentication (401)\n\nMissing or invalid authentication tokens.\n\n```json\n{\n \"detail\": \"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 \"detail\": \"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 \"detail\": \"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 \"detail\": \"Field cannot be set during creation\",\n \"layer\": \"guards\",\n \"code\": \"GUARD_FIELD_NOT_CREATEABLE\",\n \"details\": {\n \"fields\": [\"stage\"]\n },\n \"pointer\": \"/stage\",\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 \"detail\": \"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\nA 207 body is a **success envelope** (plain `application/json`, not\n`application/problem+json`) — the per-record `error` objects embedded in it\nkeep the internal flat shape (`error` message field, `layer`, `code`,\n`details`, `hint`):\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 \"detail\": \"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 production body is generic: it carries\nonly the error class name in `details.name` (so callers can branch on\ne.g. `TypeError` vs a fetch timeout) — never the underlying message,\ncause, or stack frames. The raw error is always logged server-side.\n\n```json\n{\n \"detail\": \"Action execution failed\",\n \"layer\": \"action\",\n \"code\": \"ACTION_EXECUTION_FAILED\",\n \"details\": {\n \"name\": \"TypeError\"\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`. Same contract: the production\nbody is generic, and the full error (message, cause chain, stack) is\nlogged via `console.error` keyed by the `requestId` in the body — so\nthe response → log correlation is one grep.\n\n```json\n{\n \"detail\": \"Internal error\",\n \"layer\": \"database\",\n \"code\": \"INTERNAL_ERROR\",\n \"details\": { \"operation\": \"request handling\" },\n \"hint\": \"Operation \\\"request handling\\\" failed unexpectedly. Check server logs for details.\",\n \"request\": {\n \"method\": \"GET\",\n \"url\": \"/api/v1/jobs\",\n \"requestId\": \"0c4f2c9e-...\"\n }\n}\n```\n\n### Exposing error details in dev / staging\n\nBy default nothing derived from the thrown error reaches the response\nbody — messages, cause chains, and stack frames can carry SQL, file\npaths, or secrets, so they stay server-side. To get verbose bodies\nwhile developing or staging, set `EXPOSE_ERROR_STACK=1` on the worker\n(`wrangler.toml` `[vars]`, or `wrangler secret put`):\n\n```toml\n[vars]\nEXPOSE_ERROR_STACK = \"1\"\n```\n\nWhen set, the global 500 and `ACTION_EXECUTION_FAILED` bodies forward\nthe underlying error message plus `details.cause` (cause-chain\nmessage), `details.frames` (top three stack frames with absolute paths\nsanitized to basename + line number), and `details.stack` (the full\nunsanitized stack trace). Leave it unset in production."
255
263
  },
256
264
  "compiler/targets/hono-api/using-the-api": {
257
265
  "title": "Using the API",
@@ -263,7 +271,7 @@ export const DOCS = {
263
271
  },
264
272
  "compiler/targets/hono-api/using-the-api/query-params": {
265
273
  "title": "Query Parameters",
266
- "content": "The generated API supports filtering, pagination, sorting, field selection, search, and total count via query parameters on `GET` list endpoints.\n\n## Filter Operators\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### Examples\n\n```bash\n# Filter by status\nGET /api/v1/jobs?status=open\n\n# Range query\nGET /api/v1/jobs?salaryMin.gte=100000&salaryMax.lte=200000\n\n# Pattern matching\nGET /api/v1/jobs?title.like=Engineer\n\n# Multiple values\nGET /api/v1/jobs?department.in=Engineering,Design,Product\n```\n\n## Pagination\n\n| Parameter | Default | Description |\n|-----------|---------|-------------|\n| `limit` | `50` | Number of records to return (min: 1, max: 100) |\n| `offset` | `0` | Number of records to skip |\n\n```bash\nGET /api/v1/jobs?limit=25&offset=50\n```\n\nThe default `limit` can be configured per-resource in your `read` definition:\n\n```typescript\nread: {\n access: { roles: [\"recruiter\"] },\n pageSize: 25, // Default limit\n maxPageSize: 100, // Maximum allowed limit\n},\n```\n\n### Response Shape\n\n```json\n{\n \"data\": [ /* records */ ],\n \"pagination\": {\n \"limit\": 25,\n \"offset\": 50,\n \"count\": 12\n }\n}\n```\n\n- `count` — number of records returned on this page\n- `total` — total matching records across all pages (only when `?total=true`, see below)\n\n## Sorting\n\nSort by one or more fields. Use the `-` prefix for descending order.\n\n### Multi-Sort (Recommended)\n\n```bash\n# Sort by status ascending, then createdAt descending\nGET /api/v1/jobs?sort=status,-createdAt\n\n# Single field descending\nGET /api/v1/jobs?sort=-createdAt\n\n# Multiple fields\nGET /api/v1/jobs?sort=department,-salaryMax,title\n```\n\n| Prefix | Direction |\n|--------|-----------|\n| (none) | Ascending |\n| `-` | Descending |\n\n### Legacy Format\n\nThe original `sort` + `order` format is still supported for backwards compatibility:\n\n```bash\nGET /api/v1/jobs?sort=title&order=asc\n```\n\n| Parameter | Values | Default | Description |\n|-----------|--------|---------|-------------|\n| `sort` | Any column name | `createdAt` | Field to sort by |\n| `order` | `asc`, `desc` | `desc` | Sort direction |\n\nWhen the multi-sort format is detected (comma or `-` prefix), the `order` parameter is ignored.\n\n## Field Selection\n\nSelect which columns to return using `?fields=`. Available on LIST and GET routes (not Views — they define their own field set).\n\n```bash\n# Return only id, title, and status\nGET /api/v1/jobs?fields=id,title,status\n\n# Combine with other query params\nGET /api/v1/jobs?fields=id,title,status&status=open&sort=-createdAt\n\n# Single record\nGET /api/v1/jobs/job_123?fields=id,title,salaryMin,salaryMax\n```\n\nAll columns are available including system columns (`id`, `organizationId`, `createdAt`, `modifiedAt`, etc.). Invalid field names are silently ignored. If no valid fields are provided, all columns are returned.\n\n**Security**: Masking still applies to selected fields. Requesting `?fields=ssn` will return the masked value, not the raw data.\n\n## Total Count\n\nGet the total number of matching records across all pages by adding `?total=true`. Available on LIST and VIEW routes.\n\n```bash\nGET /api/v1/jobs?status=open&total=true\n```\n\n```json\n{\n \"data\": [ /* 25 records */ ],\n \"pagination\": {\n \"limit\": 25,\n \"offset\": 0,\n \"count\": 25,\n \"total\": 142\n }\n}\n```\n\nThis is opt-in because it runs an additional `COUNT(*)` query. Only use it when you need the total (e.g., for pagination UI).\n\n## Search\n\nFull-text search across all text columns using `?search=`. Available on LIST and VIEW routes.\n\n```bash\n# Search across all text fields\nGET /api/v1/jobs?search=engineer\n\n# Combine with filters\nGET /api/v1/jobs?search=engineer&status=open\n```\n\nThe search generates an OR'd `LIKE` condition across all `text()` columns in your schema:\n\n```sql\nWHERE (title LIKE '%engineer%' OR department LIKE '%engineer%')\n```\n\nOnly columns defined with `text()` in your Drizzle schema are searchable. Non-text columns (integers, timestamps, UUIDs, blobs) are automatically excluded.\n\n## Complete Example\n\nCombine all query parameters together:\n\n```bash\nGET /api/v1/jobs?fields=id,title,status,salaryMin&status=open&salaryMin.gte=100000&search=engineer&sort=salaryMin,-createdAt&limit=10&offset=20&total=true\n```\n\nThis request:\n1. **Selects** only `id`, `title`, `status`, `salaryMin` fields\n2. **Filters** to open jobs with salaryMin >= 100000\n3. **Searches** text columns for \"engineer\"\n4. **Sorts** by salaryMin ascending, then createdAt descending\n5. **Paginates** with 10 results starting at offset 20\n6. **Counts** total matching records\n\n## Parameter Summary\n\n| Parameter | Applies To | Description |\n|-----------|-----------|-------------|\n| `limit` | LIST, VIEW | Page size (default: 50, max: 100) |\n| `offset` | LIST, VIEW | Skip N records |\n| `sort` | LIST, VIEW | Sort fields (comma-separated, `-` prefix for desc) |\n| `order` | LIST, VIEW | Legacy sort direction (`asc` or `desc`) |\n| `fields` | LIST, GET | Comma-separated column names to return |\n| `total` | LIST, VIEW | Set to `true` to include total count |\n| `search` | LIST, VIEW | Search text across all text columns |\n| `field=value` | LIST, VIEW | Filter by exact match |\n| `field.op=value` | LIST, VIEW | Filter with operator (gt, gte, lt, lte, ne, like, in) |"
274
+ "content": "The generated API supports filtering, pagination, sorting, field selection, search, and total count via query parameters on `GET` list endpoints.\n\n## Filter Operators\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### Examples\n\n```bash\n# Filter by status\nGET /api/v1/jobs?status=open\n\n# Range query\nGET /api/v1/jobs?salaryMin.gte=100000&salaryMax.lte=200000\n\n# Pattern matching\nGET /api/v1/jobs?title.like=Engineer\n\n# Multiple values\nGET /api/v1/jobs?department.in=Engineering,Design,Product\n```\n\n## Pagination\n\n| Parameter | Default | Description |\n|-----------|---------|-------------|\n| `limit` | `50` | Number of records to return (min: 1, max: 100) |\n| `offset` | `0` | Number of records to skip |\n\n```bash\nGET /api/v1/jobs?limit=25&offset=50\n```\n\nThe default `limit` can be configured per-resource in your `read` definition:\n\n```typescript\nread: {\n access: { roles: [\"recruiter\"] },\n pageSize: 25, // Default limit\n maxPageSize: 100, // Maximum allowed limit\n},\n```\n\n### Response Shape\n\n```json\n{\n \"data\": [ /* records */ ],\n \"pagination\": {\n \"limit\": 25,\n \"offset\": 50,\n \"count\": 12\n }\n}\n```\n\n- `count` — number of records returned on this page\n- `total` — total matching records across all pages (only when `?total=true`, see below)\n\n## Sorting\n\nSort by one or more fields. Use the `-` prefix for descending order.\n\n### Multi-Sort (Recommended)\n\n```bash\n# Sort by status ascending, then createdAt descending\nGET /api/v1/jobs?sort=status,-createdAt\n\n# Single field descending\nGET /api/v1/jobs?sort=-createdAt\n\n# Multiple fields\nGET /api/v1/jobs?sort=department,-salaryMax,title\n```\n\n| Prefix | Direction |\n|--------|-----------|\n| (none) | Ascending |\n| `-` | Descending |\n\n### Legacy Format\n\nThe original `sort` + `order` format is still supported for backwards compatibility:\n\n```bash\nGET /api/v1/jobs?sort=title&order=asc\n```\n\n| Parameter | Values | Default | Description |\n|-----------|--------|---------|-------------|\n| `sort` | Any column name | `createdAt` | Field to sort by |\n| `order` | `asc`, `desc` | `desc` | Sort direction |\n\nWhen the multi-sort format is detected (comma or `-` prefix), the `order` parameter is ignored.\n\n## Field Selection\n\nSelect which columns to return using `?fields=`. Available on LIST and GET routes (not Views — they define their own field set).\n\n```bash\n# Return only id, title, and status\nGET /api/v1/jobs?fields=id,title,status\n\n# Combine with other query params\nGET /api/v1/jobs?fields=id,title,status&status=open&sort=-createdAt\n\n# Single record\nGET /api/v1/jobs/job_123?fields=id,title,salaryMin,salaryMax\n```\n\nAll columns are available including system columns (`id`, `organizationId`, `createdAt`, `modifiedAt`, etc.). Invalid field names are silently ignored. If no valid fields are provided, all columns are returned.\n\n**Security**: Masking still applies to selected fields. Requesting `?fields=ssn` will return the masked value, not the raw data.\n\n## Total Count\n\nGet the total number of matching records across all pages by adding `?total=true`. Available on LIST and VIEW routes.\n\n```bash\nGET /api/v1/jobs?status=open&total=true\n```\n\n```json\n{\n \"data\": [ /* 25 records */ ],\n \"pagination\": {\n \"limit\": 25,\n \"offset\": 0,\n \"count\": 25,\n \"total\": 142\n }\n}\n```\n\nThis is opt-in because it runs an additional `COUNT(*)` query. Only use it when you need the total (e.g., for pagination UI).\n\n## Search\n\nFull-text search across all text columns using `?search=`. Available on LIST and VIEW routes.\n\n```bash\n# Search across all text fields\nGET /api/v1/jobs?search=engineer\n\n# Combine with filters\nGET /api/v1/jobs?search=engineer&status=open\n```\n\nThe search generates an OR'd `LIKE` condition across all `text()` columns in your schema:\n\n```sql\nWHERE (title LIKE '%engineer%' OR department LIKE '%engineer%')\n```\n\nOnly columns defined with `text()` in your Drizzle schema are searchable. Non-text columns (integers, timestamps, UUIDs, blobs) are automatically excluded.\n\n## Complete Example\n\nCombine all query parameters together:\n\n```bash\nGET /api/v1/jobs?fields=id,title,status,salaryMin&status=open&salaryMin.gte=100000&search=engineer&sort=salaryMin,-createdAt&limit=10&offset=20&total=true\n```\n\nThis request:\n1. **Selects** only `id`, `title`, `status`, `salaryMin` fields\n2. **Filters** to open jobs with salaryMin >= 100000\n3. **Searches** text columns for \"engineer\"\n4. **Sorts** by salaryMin ascending, then createdAt descending\n5. **Paginates** with 10 results starting at offset 20\n6. **Counts** total matching records\n\n## Parameter Summary\n\n| Parameter | Applies To | Description |\n|-----------|-----------|-------------|\n| `limit` | LIST, VIEW | Page size (default: 50, max: 100) |\n| `offset` | LIST, VIEW | Skip N records |\n| `sort` | LIST, VIEW | Sort fields (comma-separated, `-` prefix for desc) |\n| `order` | LIST, VIEW | Legacy sort direction (`asc` or `desc`) |\n| `fields` | LIST, GET | Comma-separated column names to return |\n| `total` | LIST, VIEW | Set to `true` to include total count |\n| `search` | LIST, VIEW | Search text across all text columns |\n| `field=value` | LIST, VIEW | Filter by exact match |\n| `field.op=value` | LIST, VIEW | Filter with operator (gt, gte, lt, lte, ne, like, in) |\n| `starting_after` | LIST, VIEW | Opaque keyset cursor — rows strictly after the boundary |\n| `ending_before` | LIST, VIEW | Opaque keyset cursor — rows strictly before the boundary |\n| `include` | LIST, VIEW, GET | FK-graph embedding (contract v2, allowlisted — see below) |\n| `fields[<fk>]` | LIST, VIEW, GET | Sparse fields for an embedded include target (contract v2) |\n\n## Include & Sparse Fields (contract v2)\n\nOn the v2 contract a resource can allowlist FK columns for **FK-graph\nembedding**, collapsing client-side N+1 fetches:\n\n```ts title=\"quickback/features/orders/order-items.ts\"\nexport default feature(\"orderItems\", {\n columns: {\n id: q.id(),\n orderId: q.text().required().references(() => orders.id),\n organizationId: q.scope(\"organization\"),\n },\n read: {\n access: { roles: [\"member\", \"admin\"] },\n include: [\"orderId\"], // FK columns eligible for ?include=\n },\n});\n```\n\n```bash\nGET /api/v2/order-items?include=orderId&fields[orderId]=id,total\n```\n\n```json\n{\n \"data\": [ { \"id\": \"oi_1\", \"orderId\": \"ord_9\" } ],\n \"included\": { \"orderId\": { \"ord_9\": { \"id\": \"ord_9\", \"total\": 129 } } }\n}\n```\n\nEmbedded rows land in a **top-level `included` map** keyed by FK column, then\nby target primary key — row objects are never mutated.\n\n**Security semantics (all enforced, fail-closed):**\n\n- An embedded read **is a read of the target resource**: the target's own\n `read.access` is checked before any fetch (403 on failure, never silent\n omission), the child query runs under the target's tenant firewall on the\n caller's own database handle, and embedded rows pass through the target's\n masking before attachment.\n- Targets whose `read.access` is **record-aware** (function access, `record:`\n conditions, `relationship` or `fga` arms) are refused **at compile time** —\n embedding them would skip their post-fetch record checks.\n- A tenant-scoped target with no resolvable firewall clause is a compile\n error; a global reference table must opt out explicitly with\n `firewall: { exception: true }`. Even then, the child fetch still calls\n the target's own firewall helper — for a soft-deleting reference table\n that helper is the soft-delete predicate, so an embed never serves rows\n the target's own routes refuse.\n- `?include=` on a resource (or view) without an allowlist is a **400**.\n Explicit views declare their own `include: [...]` — nothing is expandable\n undeclared. Depth is exactly 1. A view that declares `include` must keep\n each listed FK column in its `fields` projection (compile error\n otherwise — the embedded lookup pivots on that column).\n\n**Strict fields on v2:** unknown names in bare `?fields=` and in\n`fields[<fk>]=` are rejected with a 400 Problem. (Pinned v1 keeps its\nhistorical silent-drop for bare `?fields=`.) A `?fields=` projection that\ndrops the FK column of a requested `?include=` is also a **400** —\n`include=orderId requires \"orderId\" in ?fields=` — never a silently-empty\n`included` slot."
267
275
  },
268
276
  "compiler/targets/hono-api/using-the-api/views-api": {
269
277
  "title": "Views API",
@@ -337,6 +345,10 @@ export const DOCS = {
337
345
  "title": "With Quickback",
338
346
  "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"
339
347
  },
348
+ "stack/api-contract": {
349
+ "title": "API Contract",
350
+ "content": "Every generated API speaks one public HTTP contract, selected once per project:\n\n```ts title=\"quickback/quickback.config.ts\"\nexport default defineConfig({\n // Omitted = v1 (the pinned compatibility mode for already-deployed clients).\n contract: { version: \"v2\" },\n // ...\n});\n```\n\n**v2 is the flagship contract.** Everything new lands on v2; projects pinned to\nv1 keep today's byte-stable wire and receive no new contract features until\nthey migrate.\n\n## Response envelope\n\nCollection reads return a flat envelope; single reads return the resource\nobject itself:\n\n```json\n{\n \"data\": [ { \"id\": \"po_1\", \"vendorId\": \"ven_1\", \"status\": \"open\" } ],\n \"pagination\": { \"count\": 1, \"page\": 1, \"pageSize\": 50, \"hasMore\": false,\n \"nextCursor\": \"…\", \"prevCursor\": null },\n \"included\": { \"vendorId\": { \"ven_1\": { \"id\": \"ven_1\", \"name\": \"Acme\" } } }\n}\n```\n\n`included` appears only when the request carried `?include=` (contract v2 —\nsee [query params](/compiler/targets/hono-api/using-the-api/query-params)).\n\n## Errors — RFC 9457 Problem Details\n\nEvery error response is `application/problem+json`:\n\n```json\n{\n \"type\": \"https://quickback.dev/problems/access-role-required\",\n \"title\": \"Access role required\",\n \"status\": 403,\n \"detail\": \"Access denied\",\n \"instance\": \"/api/v2/purchase-orders\",\n \"code\": \"ACCESS_ROLE_REQUIRED\",\n \"layer\": \"access\"\n}\n```\n\nThe internal fields (`code`, `layer`, `details`, `hint`, `request`) survive as\nextension members, so clients that switch on `code` keep working. The full\ncode catalog ships in `openapi.json` as the `Problem.code` enum.\n\n## Cursor pagination\n\nList endpoints accept an opaque keyset cursor alongside classic\n`?limit=`/`?offset=`:\n\n| Param | Meaning |\n|---|---|\n| `?starting_after=<cursor>` | rows strictly after the boundary (forward) |\n| `?ending_before=<cursor>` | rows strictly before the boundary (backward) |\n| `?total=true` | opt into a counted total |\n\n`pagination.nextCursor` / `prevCursor` carry the boundaries. Cursors are\nopaque — never parse them.\n\n## Idempotency-Key\n\nAny `POST`/`PATCH`/`PUT`/`DELETE` may carry an `Idempotency-Key` header (a\ncaller-generated UUID, ≤ 255 chars) to make the write safe to retry:\n\n- First request **claims** the key (the claim is the concurrency lock) and\n caches the response.\n- A retry with the same key replays the cached response byte-identically with\n `Idempotency-Replayed: true`.\n- A concurrent duplicate gets `409 IDEMPOTENCY_IN_PROGRESS`.\n- Reusing a key for a *different* request (method/path) is a\n `422 IDEMPOTENCY_KEY_REUSED`.\n- Keys expire after **24 hours** (Stripe semantics); 5xx and `Set-Cookie`\n responses release the lock instead of caching.\n\n**Claims are bound to the calling principal.** A replay from a different\nprincipal — another user, another scope subject, a delegated machine\nprincipal, or a legacy row with no principal — is refused with a `422`\nProblem: the cached response body is **never served to a foreign\nprincipal**, and nothing beyond the `422` itself leaks. The comparison runs\nbefore the stale-claim takeover, so a foreign caller can neither read nor\noverwrite your claim.\n\n**Unauthenticated requests carrying the header are rejected (400)** — an\nanonymous caller has no principal to bind the claim to. A PUBLIC standalone\naction may opt in explicitly:\n\n```ts title=\"quickback/features/orders/actions/submitForm.ts\"\nexport default defineAction({\n path: \"/orders/submit-form\",\n method: \"POST\",\n access: { roles: [\"PUBLIC\"] },\n idempotency: \"dedupe\", // dedupe-only: duplicate ⇒ 409 reference,\n // the cached body is NEVER served to a second caller\n // ...\n});\n```\n\n## Contract version matrix\n\nFlipping `contract.version` moves the **entire** contract at once — plan the\nclient migration as one move:\n\n| Surface | v1 (pinned) | v2 (flagship) |\n|---|---|---|\n| API base | `/api/v1` | `/api/v2` |\n| Auth base | `/auth/v1` | `/auth/v2` |\n| Realtime base | `/broadcast/v1` | `/broadcast/v2` |\n| Quickback HMAC-JWT lane | on by default | only with explicit `auth.jwt` |\n| Realtime data frames | raw (byte-stable) | CloudEvents 1.0 envelopes ([realtime](/stack/realtime)) |\n| Outbound webhook signing | Standard Webhooks **+** legacy `X-Webhook-*` | Standard Webhooks **only** |\n| `?include=` FK embedding | not available | available where allowlisted |\n| Aggregate changesets (`application/vnd.quickback.changeset+json` on PATCH/POST, [`owns`](/compiler/definitions/changesets)) | not available | available where `owns` is declared |\n| Bare `?fields=` unknown names | silently dropped | **400** |\n| `fields[<fk>]=` unknown names | n/a | **400** |\n| Action input schemas | best-effort static parse | complete client-side harvest **required** |\n\nSequencing a migration: ship clients that speak the v2 paths, CloudEvents\nframes, and session-first auth (or declare `auth.jwt`); confirm webhook\nconsumers validate the `webhook-*` headers; then flip the switch. Until then\nv1 stays byte-identical.\n\n## Machine-readable contract\n\n- `GET /openapi.json` — OpenAPI 3.1: Problem responses, cursor params,\n `Idempotency-Key` on every write op, per-resource `include` params.\n- `GET /asyncapi.json` — AsyncAPI 3.0: the realtime channel + named\n invalidation events + outbound webhook messages. Served under the **same**\n auth gating as `/openapi.json` (`openapi.publish`)."
351
+ },
340
352
  "stack/auth/api-keys": {
341
353
  "title": "API Keys",
342
354
  "content": "API keys provide programmatic access for CI/CD pipelines, scripts, and server-to-server communication.\n\n## Creating API Keys\n\nCreate API keys from your [Quickback account](https://account.quickback.dev/profile). Each key is scoped to your organization.\n\n## Usage\n\n```bash\nQUICKBACK_API_KEY=your_api_key quickback compile\n```\n\nAPI keys are validated by the same `/internal/validate` endpoint as session tokens. See [Authentication](/compiler/cloud-compiler/authentication) for details."
@@ -447,15 +459,15 @@ export const DOCS = {
447
459
  },
448
460
  "stack/realtime/durable-objects": {
449
461
  "title": "Realtime",
450
- "content": "Quickback can generate realtime notification helpers for broadcasting changes to connected clients. This enables live updates via WebSocket using Cloudflare Durable Objects.\n\nThe targeting model is shared across ws tickets, websocket attachment, and server-side broadcasts:\n\n- string target: historical `organizationId` shorthand\n- object target: `{ scopeKey?, organizationId?, userId? }`\n\nThat means the same mental model drives both `createRealtime()` and the generated Broadcaster filter path.\n\n## Enabling Realtime\n\nAdd `realtime` configuration to individual table definitions:\n\n```typescript\n// features/applications/applications.ts\n\nexport const applications = sqliteTable(\"applications\", {\n id: text(\"id\").primaryKey(),\n candidateId: text(\"candidate_id\").notNull(),\n jobId: text(\"job_id\").notNull(),\n stage: text(\"stage\").notNull(),\n organizationId: text(\"organization_id\").notNull(),\n});\n\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n realtime: {\n enabled: true, // Enable realtime broadcasts for this table\n onInsert: true, // Broadcast on INSERT (default: true)\n onUpdate: true, // Broadcast on UPDATE (default: true)\n onDelete: true, // Broadcast on DELETE (default: true)\n access: { roles: [\"recruiter\", \"hiring-manager\"] }, // Audience — MANDATORY, fail-closed\n fields: [\"id\", \"candidateId\", \"stage\"], // Fields to include (optional)\n scopeKeyFrom: \"events:{eventId}\", // Sugar for scopeTable + scopeField (optional)\n emitFromActions: true, // Custom-action writes auto-emit after commit (optional)\n },\n // ... guards, crud\n});\n```\n\n`scopeKeyFrom` routes broadcasts to a resource lane instead of the default\norg room — the template form (`\"events:{eventId}\"`) names the prefix and the\nrow column in one string; a bare column name inherits the prefix from\n`scopeTable` (or the project-level ws-ticket default). `emitFromActions`\nextends the same broadcasts to writes made through the scoped `db` inside\ncustom record-bound and bulk actions — see the boundary table below. It\ntriggers the same mandatory-audience check auto-CRUD broadcasts have.\n\nWhen any table has realtime enabled, the compiler generates `src/lib/realtime.ts` with helper functions for sending notifications.\n\nAt the project level, `providers.database.config.realtime` can stay boolean or become object-shaped when you need resource-scoped tickets. The mint gate accepts three authorization vocabularies via the discriminated `access` form — pick exactly one arm:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: {\n wsTicket: {\n access: { authzRole: \"attendee\" }, // authz relationship role (legacy shorthand: role: \"attendee\")\n // access: { roles: [\"member+\"] }, // org-membership roles — verifies the org role AND that the\n // // scope row is in the caller's ACTIVE org (org column required)\n // access: { fga: { relation: \"viewer\", object: \"event:{id}\" } }, // FGA relation on the scope row —\n // // same evaluator + object template as read-path access:{ fga }\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n },\n }),\n}\n```\n\nThat tells `/broadcast/v1/ws-ticket` (the broadcast surface tracks `contract.version`, so `/broadcast/v2/ws-ticket` on contract-v2 projects) to authenticate with Better Auth, run the declared gate against `body.eventId`, and mint a short-lived ticket scoped to the resolved `events:<id>` lane. See [Realtime → Enabling Realtime](/stack/realtime#enabling-realtime) for the full per-arm semantics; all three forms fail closed at compile time (ambiguous names living in two vocabularies, missing `auth.roleHierarchy` for `+`, missing `authz.fga`, unknown FGA type/relation, missing organization column, non-tenant-scoped `scopeTable`).\n\n### Namespace-backed tickets (per-matched-lane)\n\nThe single-`role` form above authorizes the ticket through **one** relationship.\nWhen the room is gated by an [authz namespace](/compiler/definitions/scopes#mintscope-mint-the-scope-token-from-the-namespace-resolver)\nwith a **multi-lane `via:`** — e.g. an event reachable by attendees, organizers,\ncontractors, *and* org admins — point the ticket at the namespace instead, and it\nauthorizes through the namespace's full `via` (per-matched-lane):\n\n```typescript\nrealtime: {\n wsTicket: {\n namespace: \"eventScope\", // authorize via this namespace's full multi-lane `via`\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n},\n```\n\n`/broadcast/v1/ws-ticket` now runs the **same first-match-wins gate** the\nnamespace uses, and issues the ticket for whichever lane matched:\n\n| Caller matched via | Ticket role |\n|---|---|\n| `attendeeOf` (relationship lane) | `attendee` |\n| `organizerOf` | `organizer` |\n| `contractorOf` | `contractor` |\n| `{ roles: [\"admin\",\"owner\"] }` (bulk lane) | the caller's **org/membership roles** — no scope role |\n\nThis closes the gap where the single-`role` form denied (`403`) an org admin who\ncould legitimately reach the room through the bulk lane but isn't a confirmed\nattendee — their realtime socket now opens.\n\n## When auto-broadcast fires (and when you call it manually)\n\nQuickback emits auto-broadcasts in **only one place**: the generated CRUD route handlers (`POST /` create, `PATCH /:id` update, `DELETE /:id` delete) for resources that **explicitly declare** a `realtime.enabled` block. The project-level `dbConfig.realtime` switch wires the *transport* (Broadcaster DO + ws-ticket route) but does **not** auto-enable broadcasting on any resource — broadcasting is opt-in per resource, like CRUD. Those handlers wrap each successful write with a `realtime.insert / update / delete` call before responding.\n\nAuto-broadcasts carry the table's declared gates: the `realtime.access.roles`\naudience (or the deprecated `requiredRoles` alias) becomes the broadcast's\n`targetRoles` (with role-hierarchy `+` expanded and UPPERCASE pseudo-roles like\n`PUBLIC`/`USER` evaluated at fanout exactly as REST evaluates them), and the\ntable's effective masking config —\ndeclared plus auto-detected sensitive columns — is applied per subscriber\nrole at fanout, matching what the HTTP routes mask. A `type: 'custom'` mask\nfunction can't be replicated by the Broadcaster, so those columns broadcast\nas `[REDACTED]` (fail closed). Tables that declare neither broadcast openly,\nas before.\n\nEverywhere else — action handlers, queue consumers, scheduled jobs, custom Hono routes — you broadcast manually **unless the table opts in to action emission** (see below). In action handlers on realtime-enabled projects, Quickback injects a typed `realtime` helper directly into `execute(...)`; outside actions you still call `createRealtime(env)` yourself.\n\n| Mutation site | Auto-broadcast? | Why |\n|---|---|---|\n| Generated CRUD route (`POST /`, `PATCH /:id`, `DELETE /:id`) | Yes | The compiler emits the call after the write returns. |\n| Generated batch route (`/batch/...`) | Yes | Same pattern, emitted per record. |\n| `db.insert/update/delete` inside a record-bound action, table declares `realtime.emitFromActions: true` | Yes — after commit | The scoped db records each write into a per-request capture collector (recording only — it never calls the transport itself); the route emits identical auto-CRUD frames after `execute` succeeds, via the after-commit effects machinery. |\n| `db.insert/update/delete` inside an action handler (no `emitFromActions`) | No — manual | Scoped-db stays a query-shape wrapper (firewall + soft-delete WHERE injection) with no broadcast side-effects. |\n| `unsafeDb` writes in actions (or any custom route) | No — manual | `unsafeDb` is the un-wrapped escape hatch — invisible to capture too. |\n| Queue consumers, cron jobs, webhook handlers | No — manual | These run outside the CRUD path entirely. |\n\nThe rule of thumb: opt the table into `realtime: { emitFromActions: true }` (or give the action an `emit:` block for the pre-bound `emitCrud(row, oldRow?)` helper) and the frames take care of themselves; otherwise, if your code calls `db.insert(...)` directly, you also call `realtime.insert(...)` directly on the next line.\n\nTwo capture caveats: inserts that skip `.returning()` emit the values as written (DB-default columns absent), and updates/deletes cost one extra pre-select on the same WHERE — it replaces the hand-written read every manual emit needed anyway. Capture covers the feature's own table on record-bound and bulk routes; standalone actions and cross-feature writes use `emit:`/`emitCrud` or the raw `realtime.*` API.\n\n## Generated Helper\n\nAction handlers on realtime-enabled projects receive a typed `realtime` param. The underlying `createRealtime()` factory still powers it and remains the API to use from queues, cron jobs, and other non-action code:\n\n```typescript\nexport const execute: ActionExecutor = async ({ db, ctx, input, realtime }) => {\n // After creating a record\n await realtime.insert('applications', newApplication, ctx.activeOrgId!);\n\n // After updating a record\n await realtime.update('applications', newApplication, oldApplication, ctx.activeOrgId!);\n\n // After deleting a record\n await realtime.delete('applications', { id: applicationId }, ctx.activeOrgId!);\n\n return { success: true };\n};\n```\n\n`env` is also typed in action handlers, so custom bindings like R2, D1, Queues, Durable Objects, and auth env vars no longer need `(env as any)` casts.\n\nFor explicit targeting, pass an object instead of the historical org string:\n\n```typescript\nawait realtime.broadcast(\"event-page-updated\", payload, {\n scopeKey: `events:${input.eventId}`,\n});\n\nawait realtime.broadcast(\"dm\", payload, {\n userId: recipientId,\n});\n```\n\n## Event Format\n\nQuickback broadcasts events in a structured JSON format for easy client-side handling.\n\n### Insert Event\n\n```typescript\nawait realtime.insert('applications', {\n id: 'app_123',\n candidateId: 'cnd_456',\n stage: 'applied'\n}, ctx.activeOrgId!);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"INSERT\",\n \"schema\": \"public\",\n \"new\": {\n \"id\": \"app_123\",\n \"candidateId\": \"cnd_456\",\n \"stage\": \"applied\"\n },\n \"old\": null\n}\n```\n\n### Update Event\n\n```typescript\nawait realtime.update('applications',\n { id: 'app_123', stage: 'interview' }, // new\n { id: 'app_123', stage: 'screening' }, // old\n ctx.activeOrgId!\n);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"UPDATE\",\n \"schema\": \"public\",\n \"new\": { \"id\": \"app_123\", \"stage\": \"interview\" },\n \"old\": { \"id\": \"app_123\", \"stage\": \"screening\" }\n}\n```\n\n### Delete Event\n\n```typescript\nawait realtime.delete('applications',\n { id: 'app_123' },\n ctx.activeOrgId!\n);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"DELETE\",\n \"schema\": \"public\",\n \"new\": null,\n \"old\": { \"id\": \"app_123\" }\n}\n```\n\n## Custom Broadcasts\n\nFor arbitrary events that don't map to CRUD operations:\n\n```typescript\nawait realtime.broadcast('screening-complete', {\n applicationId: 'app_123',\n candidateId: 'cnd_456',\n stage: 'interview'\n}, ctx.activeOrgId!, {\n targetRoles: ['AUTHENTICATED'],\n});\n```\n\n**Every send needs an audience.** Delivery is fail-closed: a broadcast whose\n`targetRoles` is omitted or empty reaches **nobody**. \"Everyone in the room\" is\nspelled explicitly — `targetRoles: ['AUTHENTICATED']` (any authenticated\nsubscriber) or `['PUBLIC']`.\n\nBroadcasts:\n```json\n{\n \"type\": \"broadcast\",\n \"event\": \"screening-complete\",\n \"payload\": {\n \"applicationId\": \"app_123\",\n \"candidateId\": \"cnd_456\",\n \"stage\": \"interview\"\n }\n}\n```\n\n## User-Specific Broadcasts\n\nTarget a specific user instead of the entire organization:\n\n```typescript\n// Only this user receives the notification\nawait realtime.insert('notifications', newNotification, ctx.activeOrgId!, {\n userId: ctx.userId,\n targetRoles: ['AUTHENTICATED'],\n});\n\n// Notify a hiring manager of a new application\nawait realtime.broadcast('application-received', {\n applicationId: 'app_123',\n jobId: 'job_789'\n}, ctx.activeOrgId!, {\n userId: hiringManagerId,\n targetRoles: ['AUTHENTICATED'],\n});\n```\n\n`userId` targeting matches the **socket identity** — the Better Auth user id, or\nthe synthetic `scope:<subjectId>` principal for sessionless scope connections. If\nthe same person can connect through either door, prefer\n[identity-tag targeting](#identity-tag-targeting) — one send reaches both.\n\n## Role-Based Filtering\n\nLimit which roles receive a broadcast using `targetRoles`:\n\n```typescript\n// Only hiring managers and recruiters receive this broadcast\nawait realtime.insert('applications', application, ctx.activeOrgId!, {\n targetRoles: ['hiring-manager', 'recruiter']\n});\n\n// Interviewers only see applications assigned to them\nawait realtime.update('applications', newRecord, oldRecord, ctx.activeOrgId!, {\n targetRoles: ['hiring-manager']\n});\n```\n\n**Fail-closed (v0.48+):** an omitted or empty `targetRoles` delivers to\n**nobody** — there is no implicit \"everyone\" fallback. To reach every\nauthenticated subscriber in the scope, say so explicitly with\n`targetRoles: ['AUTHENTICATED']`. UPPERCASE pseudo-roles (`PUBLIC`,\n`AUTHENTICATED`, `USER`, `SYSADMIN`) are evaluated exactly as the REST access\nevaluator does.\n\n> **Migrating from pre-0.48:** custom `realtime.broadcast(...)` /\n> `realtime.insert(...)` calls that omitted `targetRoles` used to fan out to\n> everyone; they now silently deliver to nobody. Audit every manual send and add\n> an explicit audience.\n\n## Identity-Tag Targeting\n\nEvery connection carries **identity tags**, proven at ticket mint and signed\ninto the ticket (never client-supplied):\n\n- `user:<userId>` — every Better Auth caller\n- `scope:<kind>:<subjectId>` — when a scope subject is proven, on **either**\n door: a sessionless scope principal's verified claim, or a Better Auth caller\n whose matched relationship lane maps to a scope kind with\n `subject: 'supplied' | 'both'`. Both doors stamp the **identical** tag (the\n subject row's id), which is the point.\n\nTarget them with `targetTags`:\n\n```typescript\n// ONE send reaches this guest whether they're connected via their Better Auth\n// session or a sessionless scope link — no per-identity double-send.\nawait realtime.broadcast('chat.frame', payload, { scopeKey }, {\n targetTags: [`scope:guest:${guestId}`],\n targetRoles: ['AUTHENTICATED'],\n});\n\n// Reach a person under either identity explicitly (deduped per socket):\nawait realtime.broadcast('rsvp.updated', payload, { scopeKey }, {\n targetTags: [`scope:guest:${guestId}`, `user:${linkedUserId}`],\n targetRoles: ['AUTHENTICATED'],\n});\n```\n\nSemantics:\n\n- Delivery is the **deduplicated union** of the runtime's indexed tag lookup\n (`getWebSockets(tag)`) — no attachment scan, and a dual-identity socket\n matches once.\n- `targetTags` **replaces the `userId` identity arm** when present; the\n scope/org bind and the `targetRoles` audience still apply on top.\n- **Fail-closed:** `targetTags: []` delivers to nobody.\n- Tags are **immutable** for a socket's lifetime (a Workers hibernation-tag\n constraint) — an identity change requires a reconnect.\n- Limits: at most 10 tags per connection, 256 characters per tag. The mint\n rejects violations; it never truncates.\n\n## Authorization Lease\n\nThe 60-second ws-ticket is verified once, at upgrade — but Durable Object\nhibernation keeps sockets alive indefinitely. Without a lease, a ban, member\nremoval, or subject revocation (say, an organizer cancelling a guest) would\nnever affect an already-connected socket. The lease closes that gap:\n\n- At upgrade, the connection stores `authExpiresAt = ticket.iat + lease`\n (default **15 minutes**).\n- The fan-out **skips expired connections** — they receive nothing — and closes\n them with code **4401** so the client knows to re-ticket rather than blindly\n reconnect. Inbound messages (even pings) are enforced the same way.\n- Renewal happens at mint: `POST /broadcast/v1/ws-ticket` re-runs the full\n authorization gate (session validity, revocation checks, relationship /\n scope-claim probes), so a revoked principal simply can't obtain a renewal\n ticket. Revocation propagates within one lease period with no polling.\n\nConfigure it on the realtime transport:\n\n```typescript\nproviders: {\n database: {\n config: {\n realtime: {\n enabled: true,\n lease: '15m', // default; also '900s', '1h', or a number of seconds\n // lease: false // disable (discouraged — reopens the revocation gap)\n },\n },\n },\n}\n```\n\nThe lease must be at least 60 seconds (the handshake-ticket TTL).\n\n### In-place renewal (`reauth`)\n\nInstead of reconnecting every lease period, a client can renew in place: mint a\nfresh ticket and send it over the open socket.\n\n```typescript\n// On a timer comfortably inside the lease (e.g. every 10 min for a 15m lease):\nconst { wsTicket } = await mintTicket(); // POST /broadcast/v1/ws-ticket\nws.send(JSON.stringify({ type: 'reauth', ticket: wsTicket }));\n\nws.onmessage = (event) => {\n const msg = JSON.parse(event.data);\n if (msg.type === 'reauth_ok') {\n scheduleNextRenewal(msg.authExpiresAt); // lease extended, roles refreshed\n }\n if (msg.type === 'error' && msg.code === 'REAUTH_FAILED') {\n // Ticket invalid/expired — mint a fresh one and retry before the lease lapses.\n }\n};\n\nws.onclose = (event) => {\n if (event.code === 4401) {\n // Lease expired or identity drift: mint a fresh ticket and reconnect.\n reconnectWithFreshTicket();\n }\n};\n```\n\nRenewal is **strict**: the fresh ticket must carry the same `userId`,\n`scopeKey`/`organizationId`, and the **exact same tag set** as the live socket\n(tags are immutable). A renewal that matches extends the lease and refreshes\n`role`/`roles` in place — live permission changes without socket churn. One\nthat doesn't closes the socket with 4401: reconnect fresh.\n\nClients that never send `reauth` still work — their socket is closed with 4401\nonce per lease and normal reconnect logic (with a fresh ticket) re-runs the\nfull gate. The lease is the server-side invariant either way.\n\n## Per-Role Field Masking\n\nApply different field masking based on the subscriber's role using `maskingConfig`:\n\n```typescript\nawait realtime.insert('candidates', newCandidate, ctx.activeOrgId!, {\n maskingConfig: {\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n email: { type: 'email', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n resumeUrl: { type: 'redact', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n },\n});\n```\n\n**How masking works:**\n- Each subscriber receives a payload masked according to their role\n- Roles in the `show.roles` array see unmasked values\n- All other roles see the masked version\n- Masking is pre-computed per-role (O(roles) not O(subscribers))\n\n**Available mask types:**\n| Type | Example Output |\n|------|----------------|\n| `email` | `j***@y*********.com` |\n| `phone` | `******4567` |\n| `ssn` | `*****6789` |\n| `creditCard` | `**** **** **** 1111` |\n| `name` | `J***` |\n| `redact` | `[REDACTED]` |\n\n### Owner-Based Masking\n\nShow unmasked data to the record owner:\n\n```typescript\nmaskingConfig: {\n phone: {\n type: 'phone',\n show: { roles: ['hiring-manager'], or: 'owner' } // Hiring manager OR owner sees unmasked\n },\n}\n```\n\n## Client-Side Subscription\n\n### WebSocket Authentication\n\nQuickback uses **ticket-based authentication** for WebSocket connections. The client first obtains a short-lived ticket from the main API, then connects with it as a URL parameter. The Broadcaster verifies the ticket cryptographically at upgrade time — no HTTP round-trip needed.\n\n```typescript\n// 1. Get a ws-ticket from your API (requires session auth)\nconst response = await fetch('/broadcast/v1/ws-ticket', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${sessionToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ eventId: 'evt_123' }),\n});\nconst { wsTicket } = await response.json();\n\n// 2. Connect with ticket as URL param\nconst ws = new WebSocket(\n `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}`\n);\n\nws.onopen = () => {\n console.log('Connected and authenticated!');\n // No auth message needed — pre-authenticated at upgrade\n};\n```\n\nTickets expire after 60 seconds, so fetch a fresh one before each connection or reconnection.\n\n### Handling Messages\n\n```typescript\nws.onmessage = (event) => {\n const msg = JSON.parse(event.data);\n\n // Handle CRUD events\n if (msg.type === 'postgres_changes') {\n const { table, eventType, new: newRecord, old: oldRecord } = msg;\n\n if (eventType === 'INSERT') {\n addRecord(table, newRecord);\n } else if (eventType === 'UPDATE') {\n updateRecord(table, newRecord);\n } else if (eventType === 'DELETE') {\n removeRecord(table, oldRecord.id);\n }\n }\n\n // Handle custom broadcasts\n if (msg.type === 'broadcast') {\n const { event, payload } = msg;\n\n if (event === 'screening-complete') {\n refreshApplication(payload.applicationId);\n } else if (event === 'interview-scheduled') {\n showInterviewNotification(payload.applicationId);\n }\n }\n};\n```\n\n## Environment\n\nNo additional environment variables are needed for realtime. The Broadcaster DO runs inline in your main worker and uses `BETTER_AUTH_SECRET` (already required for auth) to sign and verify WebSocket tickets.\n\n| Variable | Description |\n|----------|-------------|\n| `BETTER_AUTH_SECRET` | Signs/verifies WebSocket tickets (already set for auth) |\n\nThe `BROADCASTER` binding is a `DurableObjectNamespace` — the compiler generates this in your `wrangler.toml` automatically:\n\n```toml\n[[durable_objects.bindings]]\nname = \"BROADCASTER\"\nclass_name = \"Broadcaster\"\n\n[[migrations]]\ntag = \"v1\"\nnew_classes = [\"Broadcaster\"]\n```\n\n## Architecture\n\n```\n 1. POST /ws-ticket\n┌───────────────────────────────────────────────┐ ┌─────────────────┐\n│ Quickback Worker │ ◄──│ Browser Client │\n│ │ ──►│ │\n│ ┌──────────┐ DO binding ┌────────────────┐ │ └───────┬─────────┘\n│ │ Hono API │ ───────────► │ Broadcaster DO │ │ │\n│ └──────────┘ (in-process)└───────┬────────┘ │ 2. WS ?ws_ticket=...\n│ │ │ │\n└────────────────────────────────────┼──────────┘ │\n │◄──────────────────────┘\n WebSocket (verified at upgrade)\n```\n\n1. **Client gets a ticket** — `POST /broadcast/v1/ws-ticket` on the main API (session-authenticated). Returns a 60-second HMAC-signed ticket.\n2. **Client connects** — Opens WebSocket with `?ws_ticket=<ticket>`. The Durable Object verifies the ticket cryptographically at upgrade and attaches the socket to the ticket's `scopeKey`, `organizationId`, or `userId`.\n3. **API broadcasts** — After CRUD ops, or from custom handlers, the API calls the Broadcaster DO directly via its binding (in-process, no network hop) using the same target model.\n\n## Best Practices\n\n### Broadcast After Commit\n\nAlways broadcast after the database operation succeeds:\n\n```typescript\n// Good - broadcast after successful insert\nconst [newApp] = await db.insert(applications).values(data).returning();\nawait realtime.insert('applications', newApp, ctx.activeOrgId!);\n\n// Bad - don't broadcast before confirming success\nawait realtime.insert('applications', data, ctx.activeOrgId!);\nawait db.insert(applications).values(data); // Could fail!\n```\n\n### Minimal Payloads\n\nOnly include necessary data in broadcasts:\n\n```typescript\n// Good - minimal payload\nawait realtime.update('applications',\n { id: record.id, stage: 'interview' },\n { id: record.id, stage: 'screening' },\n ctx.activeOrgId!\n);\n\n// Avoid - sending entire record with large content\nawait realtime.update('applications', fullRecord, oldRecord, ctx.activeOrgId!);\n```\n\n### Use Broadcasts for Complex Events\n\nFor events that don't map cleanly to CRUD:\n\n```typescript\n// Hiring pipeline stage completed\nawait realtime.broadcast('pipeline-stage-complete', {\n applicationId: application.id,\n stages: ['applied', 'screening', 'interview'],\n currentStage: 'offer',\n candidateId: application.candidateId\n}, ctx.activeOrgId!);\n```\n\n## Custom Event Namespaces\n\nFor complex applications with many custom events, you can define typed event namespaces using `defineRealtime`. This generates strongly-typed helper methods for your custom events.\n\n### Defining Event Namespaces\n\nCreate a file in `services/realtime/`:\n\n```typescript\n// services/realtime/screening.ts\n\nexport default defineRealtime({\n name: 'screening',\n events: ['started', 'progress', 'completed', 'failed'],\n description: 'Candidate screening pipeline events',\n});\n```\n\n### Generated Helper Methods\n\nAfter compilation, the `createRealtime()` helper includes your custom namespace:\n\n```typescript\n\nexport const execute: ActionExecutor = async ({ ctx, input }) => {\n const realtime = createRealtime(ctx.env);\n\n // Type-safe custom event methods\n await realtime.screening.started({\n applicationId: input.applicationId,\n }, ctx.activeOrgId!);\n\n // Progress updates\n await realtime.screening.progress({\n applicationId: input.applicationId,\n percent: 50,\n step: 'background-check',\n }, ctx.activeOrgId!);\n\n // Completion\n await realtime.screening.completed({\n applicationId: input.applicationId,\n result: 'passed',\n duration: 1234,\n }, ctx.activeOrgId!);\n\n return { success: true };\n};\n```\n\n### Event Format\n\nCustom namespace events use the `broadcast` type with namespaced event names:\n\n```json\n{\n \"type\": \"broadcast\",\n \"event\": \"screening:started\",\n \"payload\": {\n \"applicationId\": \"app_123\"\n }\n}\n```\n\n### Multiple Namespaces\n\nDefine multiple namespaces for different parts of your application:\n\n```typescript\n// services/realtime/notifications.ts\nexport default defineRealtime({\n name: 'notifications',\n events: ['interview-reminder', 'offer-update', 'application-received'],\n description: 'Recruitment notification events',\n});\n\n// services/realtime/presence.ts\nexport default defineRealtime({\n name: 'presence',\n events: ['joined', 'left', 'reviewing', 'idle'],\n description: 'Who is reviewing which candidate',\n});\n```\n\nUsage:\n```typescript\nconst realtime = createRealtime(ctx.env);\n\n// Notification events\nawait realtime.notifications['interview-reminder']({ ... }, ctx.activeOrgId!);\n\n// Presence events — who's reviewing which candidate\nawait realtime.presence.reviewing({ userId: ctx.userId, candidateId: 'cnd_456' }, ctx.activeOrgId!);\n```\n\n### Namespace vs Generic Broadcast\n\n| Use Case | Approach |\n|----------|----------|\n| One-off custom event | `realtime.broadcast('event-name', payload, orgId)` |\n| Repeated event patterns | `defineRealtime` namespace |\n| Type-safe events | `defineRealtime` namespace |\n| Event discovery | `defineRealtime` (appears in generated types) |"
462
+ "content": "Quickback can generate realtime notification helpers for broadcasting changes to connected clients. This enables live updates via WebSocket using Cloudflare Durable Objects.\n\nThe targeting model is shared across ws tickets, websocket attachment, and server-side broadcasts:\n\n- string target: historical `organizationId` shorthand\n- object target: `{ scopeKey?, organizationId?, userId? }`\n\nThat means the same mental model drives both `createRealtime()` and the generated Broadcaster filter path.\n\n## Enabling Realtime\n\nAdd `realtime` configuration to individual table definitions:\n\n```typescript\n// features/applications/applications.ts\n\nexport const applications = sqliteTable(\"applications\", {\n id: text(\"id\").primaryKey(),\n candidateId: text(\"candidate_id\").notNull(),\n jobId: text(\"job_id\").notNull(),\n stage: text(\"stage\").notNull(),\n organizationId: text(\"organization_id\").notNull(),\n});\n\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n realtime: {\n enabled: true, // Enable realtime broadcasts for this table\n onInsert: true, // Broadcast on INSERT (default: true)\n onUpdate: true, // Broadcast on UPDATE (default: true)\n onDelete: true, // Broadcast on DELETE (default: true)\n access: { roles: [\"recruiter\", \"hiring-manager\"] }, // Audience — MANDATORY, fail-closed\n fields: [\"id\", \"candidateId\", \"stage\"], // Fields to include (optional)\n scopeKeyFrom: \"events:{eventId}\", // Sugar for scopeTable + scopeField (optional)\n emitFromActions: true, // Custom-action writes auto-emit after commit (optional)\n },\n // ... guards, crud\n});\n```\n\n`scopeKeyFrom` routes broadcasts to a resource lane instead of the default\norg room — the template form (`\"events:{eventId}\"`) names the prefix and the\nrow column in one string; a bare column name inherits the prefix from\n`scopeTable` (or the project-level ws-ticket default). `emitFromActions`\nextends the same broadcasts to writes made through the scoped `db` inside\ncustom record-bound and bulk actions — see the boundary table below. It\ntriggers the same mandatory-audience check auto-CRUD broadcasts have.\n\nWhen any table has realtime enabled, the compiler generates `src/lib/realtime.ts` with helper functions for sending notifications.\n\nAt the project level, `providers.database.config.realtime` can stay boolean or become object-shaped when you need resource-scoped tickets. The mint gate accepts three authorization vocabularies via the discriminated `access` form — pick exactly one arm:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: {\n wsTicket: {\n access: { authzRole: \"attendee\" }, // authz relationship role (legacy shorthand: role: \"attendee\")\n // access: { roles: [\"member+\"] }, // org-membership roles — verifies the org role AND that the\n // // scope row is in the caller's ACTIVE org (org column required)\n // access: { fga: { relation: \"viewer\", object: \"event:{id}\" } }, // FGA relation on the scope row —\n // // same evaluator + object template as read-path access:{ fga }\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n },\n }),\n}\n```\n\nThat tells `/broadcast/v1/ws-ticket` (the broadcast surface tracks `contract.version`, so `/broadcast/v2/ws-ticket` on contract-v2 projects) to authenticate with Better Auth, run the declared gate against `body.eventId`, and mint a short-lived ticket scoped to the resolved `events:<id>` lane. See [Realtime → Enabling Realtime](/stack/realtime#enabling-realtime) for the full per-arm semantics; all three forms fail closed at compile time (ambiguous names living in two vocabularies, missing `auth.roleHierarchy` for `+`, missing `authz.fga`, unknown FGA type/relation, missing organization column, non-tenant-scoped `scopeTable`).\n\n### Namespace-backed tickets (per-matched-lane)\n\nThe single-`role` form above authorizes the ticket through **one** relationship.\nWhen the room is gated by an [authz namespace](/compiler/definitions/scopes#mintscope-mint-the-scope-token-from-the-namespace-resolver)\nwith a **multi-lane `via:`** — e.g. an event reachable by attendees, organizers,\ncontractors, *and* org admins — point the ticket at the namespace instead, and it\nauthorizes through the namespace's full `via` (per-matched-lane):\n\n```typescript\nrealtime: {\n wsTicket: {\n namespace: \"eventScope\", // authorize via this namespace's full multi-lane `via`\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n},\n```\n\n`/broadcast/v1/ws-ticket` now runs the **same first-match-wins gate** the\nnamespace uses, and issues the ticket for whichever lane matched:\n\n| Caller matched via | Ticket role |\n|---|---|\n| `attendeeOf` (relationship lane) | `attendee` |\n| `organizerOf` | `organizer` |\n| `contractorOf` | `contractor` |\n| `{ roles: [\"admin\",\"owner\"] }` (bulk lane) | the caller's **org/membership roles** — no scope role |\n\nThis closes the gap where the single-`role` form denied (`403`) an org admin who\ncould legitimately reach the room through the bulk lane but isn't a confirmed\nattendee — their realtime socket now opens.\n\n`wsTicket.namespace` may also name a namespace declared by a\n[feature area](/compiler/definitions/feature-areas) (`_area.ts`). This is the one\ndeliberate exception to the rule that root config never references area-declared\nnames: namespace-identity wiring attaches the area's **complete** gate (its full\nlane set) and constructs no new grant, so it cannot widen what the area declared.\nSuch consumers are listed in `quickback/authz-manifest.json` under the owning area.\n\n## When auto-broadcast fires (and when you call it manually)\n\nQuickback emits auto-broadcasts in **only one place**: the generated CRUD route handlers (`POST /` create, `PATCH /:id` update, `DELETE /:id` delete) for resources that **explicitly declare** a `realtime.enabled` block. The project-level `dbConfig.realtime` switch wires the *transport* (Broadcaster DO + ws-ticket route) but does **not** auto-enable broadcasting on any resource — broadcasting is opt-in per resource, like CRUD. Those handlers wrap each successful write with a `realtime.insert / update / delete` call before responding.\n\nAuto-broadcasts carry the table's declared gates: the `realtime.access.roles`\naudience (or the deprecated `requiredRoles` alias) becomes the broadcast's\n`targetRoles` (with role-hierarchy `+` expanded and UPPERCASE pseudo-roles like\n`PUBLIC`/`USER` evaluated at fanout exactly as REST evaluates them), and the\ntable's effective masking config —\ndeclared plus auto-detected sensitive columns — is applied per subscriber\nrole at fanout, matching what the HTTP routes mask. A `type: 'custom'` mask\nfunction can't be replicated by the Broadcaster, so those columns broadcast\nas `[REDACTED]` (fail closed). Tables that declare neither broadcast openly,\nas before.\n\nEverywhere else — action handlers, queue consumers, scheduled jobs, custom Hono routes — you broadcast manually **unless the table opts in to action emission** (see below). In action handlers on realtime-enabled projects, Quickback injects a typed `realtime` helper directly into `execute(...)`; outside actions you still call `createRealtime(env)` yourself.\n\n| Mutation site | Auto-broadcast? | Why |\n|---|---|---|\n| Generated CRUD route (`POST /`, `PATCH /:id`, `DELETE /:id`) | Yes | The compiler emits the call after the write returns. |\n| Generated batch route (`/batch/...`) | Yes | Same pattern, emitted per record. |\n| `db.insert/update/delete` inside a record-bound action, table declares `realtime.emitFromActions: true` | Yes — after commit | The scoped db records each write into a per-request capture collector (recording only — it never calls the transport itself); the route emits identical auto-CRUD frames after `execute` succeeds, via the after-commit effects machinery. |\n| `db.insert/update/delete` inside an action handler (no `emitFromActions`) | No — manual | Scoped-db stays a query-shape wrapper (firewall + soft-delete WHERE injection) with no broadcast side-effects. |\n| `unsafeDb` writes in actions (or any custom route) | No — manual | `unsafeDb` is the un-wrapped escape hatch — invisible to capture too. |\n| Queue consumers, cron jobs, webhook handlers | No — manual | These run outside the CRUD path entirely. |\n\nThe rule of thumb: opt the table into `realtime: { emitFromActions: true }` (or give the action an `emit:` block for the pre-bound `emitCrud(row, oldRow?)` helper) and the frames take care of themselves; otherwise, if your code calls `db.insert(...)` directly, you also call `realtime.insert(...)` directly on the next line.\n\nTwo capture caveats: inserts that skip `.returning()` emit the values as written (DB-default columns absent), and updates/deletes cost one extra pre-select on the same WHERE — it replaces the hand-written read every manual emit needed anyway. Capture covers the feature's own table on record-bound and bulk routes; standalone actions and cross-feature writes use `emit:`/`emitCrud` or the raw `realtime.*` API.\n\n## Generated Helper\n\nAction handlers on realtime-enabled projects receive a typed `realtime` param. The underlying `createRealtime()` factory still powers it and remains the API to use from queues, cron jobs, and other non-action code:\n\n```typescript\nexport const execute: ActionExecutor = async ({ db, ctx, input, realtime }) => {\n // After creating a record\n await realtime.insert('applications', newApplication, ctx.activeOrgId!);\n\n // After updating a record\n await realtime.update('applications', newApplication, oldApplication, ctx.activeOrgId!);\n\n // After deleting a record\n await realtime.delete('applications', { id: applicationId }, ctx.activeOrgId!);\n\n return { success: true };\n};\n```\n\n`env` is also typed in action handlers, so custom bindings like R2, D1, Queues, Durable Objects, and auth env vars no longer need `(env as any)` casts.\n\nFor explicit targeting, pass an object instead of the historical org string:\n\n```typescript\nawait realtime.broadcast(\"event-page-updated\", payload, {\n scopeKey: `events:${input.eventId}`,\n});\n\nawait realtime.broadcast(\"dm\", payload, {\n userId: recipientId,\n});\n```\n\n## Event Format\n\nQuickback broadcasts events in a structured JSON format for easy client-side handling.\n\n### Insert Event\n\n```typescript\nawait realtime.insert('applications', {\n id: 'app_123',\n candidateId: 'cnd_456',\n stage: 'applied'\n}, ctx.activeOrgId!);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"INSERT\",\n \"schema\": \"public\",\n \"new\": {\n \"id\": \"app_123\",\n \"candidateId\": \"cnd_456\",\n \"stage\": \"applied\"\n },\n \"old\": null\n}\n```\n\n### Update Event\n\n```typescript\nawait realtime.update('applications',\n { id: 'app_123', stage: 'interview' }, // new\n { id: 'app_123', stage: 'screening' }, // old\n ctx.activeOrgId!\n);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"UPDATE\",\n \"schema\": \"public\",\n \"new\": { \"id\": \"app_123\", \"stage\": \"interview\" },\n \"old\": { \"id\": \"app_123\", \"stage\": \"screening\" }\n}\n```\n\n### Delete Event\n\n```typescript\nawait realtime.delete('applications',\n { id: 'app_123' },\n ctx.activeOrgId!\n);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"DELETE\",\n \"schema\": \"public\",\n \"new\": null,\n \"old\": { \"id\": \"app_123\" }\n}\n```\n\n## Custom Broadcasts\n\nFor arbitrary events that don't map to CRUD operations:\n\n```typescript\nawait realtime.broadcast('screening-complete', {\n applicationId: 'app_123',\n candidateId: 'cnd_456',\n stage: 'interview'\n}, ctx.activeOrgId!, {\n targetRoles: ['AUTHENTICATED'],\n});\n```\n\n**Every send needs an audience.** Delivery is fail-closed: a broadcast whose\n`targetRoles` is omitted or empty reaches **nobody**. \"Everyone in the room\" is\nspelled explicitly — `targetRoles: ['AUTHENTICATED']` (any authenticated\nsubscriber) or `['PUBLIC']`.\n\nBroadcasts:\n```json\n{\n \"type\": \"broadcast\",\n \"event\": \"screening-complete\",\n \"payload\": {\n \"applicationId\": \"app_123\",\n \"candidateId\": \"cnd_456\",\n \"stage\": \"interview\"\n }\n}\n```\n\n## User-Specific Broadcasts\n\nTarget a specific user instead of the entire organization:\n\n```typescript\n// Only this user receives the notification\nawait realtime.insert('notifications', newNotification, ctx.activeOrgId!, {\n userId: ctx.userId,\n targetRoles: ['AUTHENTICATED'],\n});\n\n// Notify a hiring manager of a new application\nawait realtime.broadcast('application-received', {\n applicationId: 'app_123',\n jobId: 'job_789'\n}, ctx.activeOrgId!, {\n userId: hiringManagerId,\n targetRoles: ['AUTHENTICATED'],\n});\n```\n\n`userId` targeting matches the **socket identity** — the Better Auth user id, or\nthe synthetic `scope:<subjectId>` principal for sessionless scope connections. If\nthe same person can connect through either door, prefer\n[identity-tag targeting](#identity-tag-targeting) — one send reaches both.\n\n## Role-Based Filtering\n\nLimit which roles receive a broadcast using `targetRoles`:\n\n```typescript\n// Only hiring managers and recruiters receive this broadcast\nawait realtime.insert('applications', application, ctx.activeOrgId!, {\n targetRoles: ['hiring-manager', 'recruiter']\n});\n\n// Interviewers only see applications assigned to them\nawait realtime.update('applications', newRecord, oldRecord, ctx.activeOrgId!, {\n targetRoles: ['hiring-manager']\n});\n```\n\n**Fail-closed (v0.48+):** an omitted or empty `targetRoles` delivers to\n**nobody** — there is no implicit \"everyone\" fallback. To reach every\nauthenticated subscriber in the scope, say so explicitly with\n`targetRoles: ['AUTHENTICATED']`. UPPERCASE pseudo-roles (`PUBLIC`,\n`AUTHENTICATED`, `USER`, `SYSADMIN`) are evaluated exactly as the REST access\nevaluator does.\n\n> **Migrating from pre-0.48:** custom `realtime.broadcast(...)` /\n> `realtime.insert(...)` calls that omitted `targetRoles` used to fan out to\n> everyone; they now silently deliver to nobody. Audit every manual send and add\n> an explicit audience.\n\n## Identity-Tag Targeting\n\nEvery connection carries **identity tags**, proven at ticket mint and signed\ninto the ticket (never client-supplied):\n\n- `user:<userId>` — every Better Auth caller\n- `scope:<kind>:<subjectId>` — when a scope subject is proven, on **either**\n door: a sessionless scope principal's verified claim, or a Better Auth caller\n whose matched relationship lane maps to a scope kind with\n `subject: 'supplied' | 'both'`. Both doors stamp the **identical** tag (the\n subject row's id), which is the point.\n\nTarget them with `targetTags`:\n\n```typescript\n// ONE send reaches this guest whether they're connected via their Better Auth\n// session or a sessionless scope link — no per-identity double-send.\nawait realtime.broadcast('chat.frame', payload, { scopeKey }, {\n targetTags: [`scope:guest:${guestId}`],\n targetRoles: ['AUTHENTICATED'],\n});\n\n// Reach a person under either identity explicitly (deduped per socket):\nawait realtime.broadcast('rsvp.updated', payload, { scopeKey }, {\n targetTags: [`scope:guest:${guestId}`, `user:${linkedUserId}`],\n targetRoles: ['AUTHENTICATED'],\n});\n```\n\nSemantics:\n\n- Delivery is the **deduplicated union** of the runtime's indexed tag lookup\n (`getWebSockets(tag)`) — no attachment scan, and a dual-identity socket\n matches once.\n- `targetTags` **replaces the `userId` identity arm** when present; the\n scope/org bind and the `targetRoles` audience still apply on top.\n- **Fail-closed:** `targetTags: []` delivers to nobody.\n- Tags are **immutable** for a socket's lifetime (a Workers hibernation-tag\n constraint) — an identity change requires a reconnect.\n- Limits: at most 10 tags per connection, 256 characters per tag. The mint\n rejects violations; it never truncates.\n\n## Authorization Lease\n\nThe 60-second ws-ticket is verified once, at upgrade — but Durable Object\nhibernation keeps sockets alive indefinitely. Without a lease, a ban, member\nremoval, or subject revocation (say, an organizer cancelling a guest) would\nnever affect an already-connected socket. The lease closes that gap:\n\n- At upgrade, the connection stores `authExpiresAt = ticket.iat + lease`\n (default **15 minutes**).\n- The fan-out **skips expired connections** — they receive nothing — and closes\n them with code **4401** so the client knows to re-ticket rather than blindly\n reconnect. Inbound messages (even pings) are enforced the same way.\n- Renewal happens at mint: `POST /broadcast/v1/ws-ticket` re-runs the full\n authorization gate (session validity, revocation checks, relationship /\n scope-claim probes), so a revoked principal simply can't obtain a renewal\n ticket. Revocation propagates within one lease period with no polling.\n\nConfigure it on the realtime transport:\n\n```typescript\nproviders: {\n database: {\n config: {\n realtime: {\n enabled: true,\n lease: '15m', // default; also '900s', '1h', or a number of seconds\n // lease: false // disable (discouraged — reopens the revocation gap)\n },\n },\n },\n}\n```\n\nThe lease must be at least 60 seconds (the handshake-ticket TTL).\n\n### In-place renewal (`reauth`)\n\nInstead of reconnecting every lease period, a client can renew in place: mint a\nfresh ticket and send it over the open socket.\n\n```typescript\n// On a timer comfortably inside the lease (e.g. every 10 min for a 15m lease):\nconst { wsTicket } = await mintTicket(); // POST /broadcast/v1/ws-ticket\nws.send(JSON.stringify({ type: 'reauth', ticket: wsTicket }));\n\nws.onmessage = (event) => {\n const msg = JSON.parse(event.data);\n if (msg.type === 'reauth_ok') {\n scheduleNextRenewal(msg.authExpiresAt); // lease extended, roles refreshed\n }\n if (msg.type === 'error' && msg.code === 'REAUTH_FAILED') {\n // Ticket invalid/expired — mint a fresh one and retry before the lease lapses.\n }\n};\n\nws.onclose = (event) => {\n if (event.code === 4401) {\n // Lease expired or identity drift: mint a fresh ticket and reconnect.\n reconnectWithFreshTicket();\n }\n};\n```\n\nRenewal is **strict**: the fresh ticket must carry the same `userId`,\n`scopeKey`/`organizationId`, and the **exact same tag set** as the live socket\n(tags are immutable). A renewal that matches extends the lease and refreshes\n`role`/`roles` in place — live permission changes without socket churn. One\nthat doesn't closes the socket with 4401: reconnect fresh.\n\nClients that never send `reauth` still work — their socket is closed with 4401\nonce per lease and normal reconnect logic (with a fresh ticket) re-runs the\nfull gate. The lease is the server-side invariant either way.\n\n## Per-Role Field Masking\n\nApply different field masking based on the subscriber's role using `maskingConfig`:\n\n```typescript\nawait realtime.insert('candidates', newCandidate, ctx.activeOrgId!, {\n maskingConfig: {\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n email: { type: 'email', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n resumeUrl: { type: 'redact', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n },\n});\n```\n\n**How masking works:**\n- Each subscriber receives a payload masked according to their role\n- Roles in the `show.roles` array see unmasked values\n- All other roles see the masked version\n- Masking is pre-computed per-role (O(roles) not O(subscribers))\n\n**Available mask types:**\n| Type | Example Output |\n|------|----------------|\n| `email` | `j***@y*********.com` |\n| `phone` | `******4567` |\n| `ssn` | `*****6789` |\n| `creditCard` | `**** **** **** 1111` |\n| `name` | `J***` |\n| `redact` | `[REDACTED]` |\n\n### Owner-Based Masking\n\nShow unmasked data to the record owner:\n\n```typescript\nmaskingConfig: {\n phone: {\n type: 'phone',\n show: { roles: ['hiring-manager'], or: 'owner' } // Hiring manager OR owner sees unmasked\n },\n}\n```\n\n## Client-Side Subscription\n\n### WebSocket Authentication\n\nQuickback uses **ticket-based authentication** for WebSocket connections. The client first obtains a short-lived ticket from the main API, then connects with it as a URL parameter. The Broadcaster verifies the ticket cryptographically at upgrade time — no HTTP round-trip needed.\n\n```typescript\n// 1. Get a ws-ticket from your API (requires session auth)\nconst response = await fetch('/broadcast/v1/ws-ticket', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${sessionToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ eventId: 'evt_123' }),\n});\nconst { wsTicket } = await response.json();\n\n// 2. Connect with ticket as URL param\nconst ws = new WebSocket(\n `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}`\n);\n\nws.onopen = () => {\n console.log('Connected and authenticated!');\n // No auth message needed — pre-authenticated at upgrade\n};\n```\n\nTickets expire after 60 seconds, so fetch a fresh one before each connection or reconnection.\n\n### Handling Messages\n\n```typescript\nws.onmessage = (event) => {\n const msg = JSON.parse(event.data);\n\n // Handle CRUD events\n if (msg.type === 'postgres_changes') {\n const { table, eventType, new: newRecord, old: oldRecord } = msg;\n\n if (eventType === 'INSERT') {\n addRecord(table, newRecord);\n } else if (eventType === 'UPDATE') {\n updateRecord(table, newRecord);\n } else if (eventType === 'DELETE') {\n removeRecord(table, oldRecord.id);\n }\n }\n\n // Handle custom broadcasts\n if (msg.type === 'broadcast') {\n const { event, payload } = msg;\n\n if (event === 'screening-complete') {\n refreshApplication(payload.applicationId);\n } else if (event === 'interview-scheduled') {\n showInterviewNotification(payload.applicationId);\n }\n }\n};\n```\n\n## Environment\n\nNo additional environment variables are needed for realtime. The Broadcaster DO runs inline in your main worker and uses `BETTER_AUTH_SECRET` (already required for auth) to sign and verify WebSocket tickets.\n\n| Variable | Description |\n|----------|-------------|\n| `BETTER_AUTH_SECRET` | Signs/verifies WebSocket tickets (already set for auth) |\n\nThe `BROADCASTER` binding is a `DurableObjectNamespace` — the compiler generates this in your `wrangler.toml` automatically:\n\n```toml\n[[durable_objects.bindings]]\nname = \"BROADCASTER\"\nclass_name = \"Broadcaster\"\n\n[[migrations]]\ntag = \"v1\"\nnew_classes = [\"Broadcaster\"]\n```\n\n## Architecture\n\n```\n 1. POST /ws-ticket\n┌───────────────────────────────────────────────┐ ┌─────────────────┐\n│ Quickback Worker │ ◄──│ Browser Client │\n│ │ ──►│ │\n│ ┌──────────┐ DO binding ┌────────────────┐ │ └───────┬─────────┘\n│ │ Hono API │ ───────────► │ Broadcaster DO │ │ │\n│ └──────────┘ (in-process)└───────┬────────┘ │ 2. WS ?ws_ticket=...\n│ │ │ │\n└────────────────────────────────────┼──────────┘ │\n │◄──────────────────────┘\n WebSocket (verified at upgrade)\n```\n\n1. **Client gets a ticket** — `POST /broadcast/v1/ws-ticket` on the main API (session-authenticated). Returns a 60-second HMAC-signed ticket.\n2. **Client connects** — Opens WebSocket with `?ws_ticket=<ticket>`. The Durable Object verifies the ticket cryptographically at upgrade and attaches the socket to the ticket's `scopeKey`, `organizationId`, or `userId`.\n3. **API broadcasts** — After CRUD ops, or from custom handlers, the API calls the Broadcaster DO directly via its binding (in-process, no network hop) using the same target model.\n\n## Best Practices\n\n### Broadcast After Commit\n\nAlways broadcast after the database operation succeeds:\n\n```typescript\n// Good - broadcast after successful insert\nconst [newApp] = await db.insert(applications).values(data).returning();\nawait realtime.insert('applications', newApp, ctx.activeOrgId!);\n\n// Bad - don't broadcast before confirming success\nawait realtime.insert('applications', data, ctx.activeOrgId!);\nawait db.insert(applications).values(data); // Could fail!\n```\n\n### Minimal Payloads\n\nOnly include necessary data in broadcasts:\n\n```typescript\n// Good - minimal payload\nawait realtime.update('applications',\n { id: record.id, stage: 'interview' },\n { id: record.id, stage: 'screening' },\n ctx.activeOrgId!\n);\n\n// Avoid - sending entire record with large content\nawait realtime.update('applications', fullRecord, oldRecord, ctx.activeOrgId!);\n```\n\n### Use Broadcasts for Complex Events\n\nFor events that don't map cleanly to CRUD:\n\n```typescript\n// Hiring pipeline stage completed\nawait realtime.broadcast('pipeline-stage-complete', {\n applicationId: application.id,\n stages: ['applied', 'screening', 'interview'],\n currentStage: 'offer',\n candidateId: application.candidateId\n}, ctx.activeOrgId!);\n```\n\n## Custom Event Namespaces\n\nFor complex applications with many custom events, you can define typed event namespaces using `defineRealtime`. This generates strongly-typed helper methods for your custom events.\n\n### Defining Event Namespaces\n\nCreate a file in `services/realtime/`:\n\n```typescript\n// services/realtime/screening.ts\n\nexport default defineRealtime({\n name: 'screening',\n events: ['started', 'progress', 'completed', 'failed'],\n description: 'Candidate screening pipeline events',\n});\n```\n\n### Generated Helper Methods\n\nAfter compilation, the `createRealtime()` helper includes your custom namespace:\n\n```typescript\n\nexport const execute: ActionExecutor = async ({ ctx, input }) => {\n const realtime = createRealtime(ctx.env);\n\n // Type-safe custom event methods\n await realtime.screening.started({\n applicationId: input.applicationId,\n }, ctx.activeOrgId!);\n\n // Progress updates\n await realtime.screening.progress({\n applicationId: input.applicationId,\n percent: 50,\n step: 'background-check',\n }, ctx.activeOrgId!);\n\n // Completion\n await realtime.screening.completed({\n applicationId: input.applicationId,\n result: 'passed',\n duration: 1234,\n }, ctx.activeOrgId!);\n\n return { success: true };\n};\n```\n\n### Event Format\n\nCustom namespace events use the `broadcast` type with namespaced event names:\n\n```json\n{\n \"type\": \"broadcast\",\n \"event\": \"screening:started\",\n \"payload\": {\n \"applicationId\": \"app_123\"\n }\n}\n```\n\n### Multiple Namespaces\n\nDefine multiple namespaces for different parts of your application:\n\n```typescript\n// services/realtime/notifications.ts\nexport default defineRealtime({\n name: 'notifications',\n events: ['interview-reminder', 'offer-update', 'application-received'],\n description: 'Recruitment notification events',\n});\n\n// services/realtime/presence.ts\nexport default defineRealtime({\n name: 'presence',\n events: ['joined', 'left', 'reviewing', 'idle'],\n description: 'Who is reviewing which candidate',\n});\n```\n\nUsage:\n```typescript\nconst realtime = createRealtime(ctx.env);\n\n// Notification events\nawait realtime.notifications['interview-reminder']({ ... }, ctx.activeOrgId!);\n\n// Presence events — who's reviewing which candidate\nawait realtime.presence.reviewing({ userId: ctx.userId, candidateId: 'cnd_456' }, ctx.activeOrgId!);\n```\n\n### Namespace vs Generic Broadcast\n\n| Use Case | Approach |\n|----------|----------|\n| One-off custom event | `realtime.broadcast('event-name', payload, orgId)` |\n| Repeated event patterns | `defineRealtime` namespace |\n| Type-safe events | `defineRealtime` namespace |\n| Event discovery | `defineRealtime` (appears in generated types) |"
451
463
  },
452
464
  "stack/realtime": {
453
465
  "title": "Realtime",
454
- "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`. The `/broadcast/v1` version segment tracks `contract.version` — contract-v2 projects mount the same surface at `/broadcast/v2` (no hidden v1 alias). Documented on this page. For **typed, targeted \"this changed — refresh\" signals** fired from an action after commit (with optional per-recipient narrowing), see [Named invalidations](/stack/realtime/named-invalidations).\n- **`/realtime/<binding>/<room-id>` — bidirectional rooms.** One DO instance per room (per document, per interview, per game). Client↔client messages, presence, and CRDT-friendly state. Use these for collaborative editing. See [PartyServer rooms](/stack/realtime/partyserver-rooms).\n\nBoth share the same auth model and ride on the same compiled worker; they solve different problems.\n\n## Architecture\n\n```\n┌──────────────────────────────────────────┐\n│ Quickback Worker │\n│ │\n│ ┌──────────┐ DO binding ┌────────────────────┐\n│ │ Hono API │ ──────────────► │ Broadcaster (DO) │\n│ │ │ │ WebSocket manager │\n│ └──────────┘ └─────────┬──────────┘\n│ │\n└─────────────────────────────────────────┼┘\n │ WebSocket\n │\n ┌────────▼─────────┐\n │ Browser Clients │\n │ (CMS, Account, │\n │ Admin, Custom) │\n └──────────────────┘\n```\n\nThe Broadcaster Durable Object runs **inline** in your main Quickback worker — no separate worker deployment needed. The API calls the DO directly via its binding (in-process, no network hop).\n\n1. **Quickback Worker** — Your compiled API with the Broadcaster DO class exported from the same worker.\n2. **Broadcaster (Durable Object)** — Manages WebSocket connections per subscription scope. One instance per `scopeKey`, organization, or user lane.\n3. **Browser Clients** — CMS, Account, Admin, and custom frontends connect via WebSocket on the same origin.\n\n## Key Features\n\n| Feature | Description |\n|---------|-------------|\n| Scope-aware fan-out | Routes by `scopeKey`, `organizationId`, or `userId` |\n| Role-based filtering | Only send events to users with matching roles |\n| Per-role masking | Different users see different field values based on their role |\n| User-specific targeting | Send events to a specific user within an org |\n| Resource-scoped tickets | Mint scope-bound ws tickets gated by org-membership roles, authz relationship roles, or FGA relations |\n| Custom broadcasts | Arbitrary events beyond CRUD |\n| Custom namespaces | `defineRealtime()` for type-safe event helpers |\n| Ticket-based auth | HMAC-signed tickets verified at WebSocket upgrade — no HTTP round-trip |\n\n## Enabling Realtime\n\nBroadcasting is **opt-in per resource**, exactly like CRUD — a table broadcasts\nonly if it declares its own `realtime` block. Add `realtime` to individual table\ndefinitions:\n\n```typescript\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n realtime: {\n enabled: true,\n onInsert: true,\n onUpdate: true,\n onDelete: true,\n // Audience — WHO may receive these live rows. Same { roles } shape as\n // read.access / crud.*.access. MANDATORY and fail-closed: a broadcast\n // reaches every subscriber in the room, so the audience is not optional.\n // Omit it (or leave it empty) and compilation fails. Roles may be concrete\n // membership/scope roles or UPPERCASE pseudo-roles.\n access: { roles: [\"recruiter\", \"hiring-manager\"] },\n fields: [\"id\", \"candidateId\", \"stage\"],\n },\n});\n```\n\nAnd enable the realtime **transport** in your database config. This is a\nproject-level switch that stands up the Broadcaster Durable Object + the\nconnection route; it does **not** by itself make any resource broadcast\n(that's the per-resource `realtime` block above). The compiler generates the\nDurable Object class, helper functions, and wrangler bindings — all within\nyour main worker.\n\nFor most apps — including org-scoped apps like chat, feeds, and dashboards —\nthe boolean form is all you need. Session-authenticated members subscribe\ndirectly; audiences come from each resource's `realtime.access.roles`:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: true,\n }),\n}\n```\n\nThe object form is the **advanced** variant, only needed when you mint\nresource-scoped tickets (e.g. an external attendee who may join one event's\nchannel, or an org member who may join one project's room). The mint gate is\ndeclared with `wsTicket.access`, a discriminated union — the arm names the\nauthorization vocabulary, so a bare name can never silently mean two things:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: {\n wsTicket: {\n // Pick EXACTLY ONE arm:\n access: { roles: [\"member+\"] }, // org-membership roles (hierarchy expands)\n // access: { authzRole: \"attendee\" }, // authz relationship role\n // access: { fga: { relation: \"viewer\", object: \"event:{id}\" } }, // FGA relation on the scope row\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n },\n }),\n}\n```\n\n- **`{ roles }` — org-membership roles.** `\"member+\"` expands via\n `auth.roleHierarchy` (compile error without it). Firewall-consistent: the\n route verifies the caller's org role **and** that the requested `scopeTable`\n row belongs to the caller's *active* organization — an org-A member cannot\n mint a ticket to org B's room. The scope table must therefore carry an\n organization column (compile error otherwise). UPPERCASE pseudo-roles are\n rejected here: a `PUBLIC`/`AUTHENTICATED` ticket factory would hand signed\n room credentials to callers with no org standing.\n- **`{ authzRole }` — a declared `authz.roles` relationship role** (`{ via }`).\n The route probes the relationship table against `body.eventId`; the ticket\n carries the relationship role (e.g. `attendee`). The legacy\n `role: \"attendee\"` string is the back-compat shorthand for this arm and\n compiles identically. Org-membership names (`member`/`admin`/`owner`) are\n still rejected in this arm — spell those `access: { roles: [...] }`.\n- **`{ fga }` — an FGA relation.** The route loads the `scopeTable` row through\n its own firewall (tenant bind), derives the object from the template\n (`\"event:{id}\"` — `{field}` tokens read from the row, the same template\n language as the read path's `access: { fga }`), and requires the caller to\n hold `relation` on it via the same org-scoped check evaluator the read path\n uses. Requires `authz.fga`; the object type and relation are validated\n against the model at compile time.\n\nWhichever arm you pick, `/broadcast/v1/ws-ticket` authenticates the caller,\nruns that gate against `body.eventId`, and mints a short-lived ticket scoped to\nthe resolved `events:<id>` channel. Everything fails closed at compile time:\na bare name that exists in more than one vocabulary is an ambiguity error\ndemanding the explicit arm, and a missing hierarchy, missing FGA model, or\nmissing organization column fails the build with an actionable message.\n\n## Pages\n\n- **[Durable Objects Setup](/stack/realtime/durable-objects)** — Broadcaster configuration, wrangler bindings, event formats, masking, and custom namespaces\n- **[Using Realtime](/stack/realtime/using-realtime)** — Subscribing to `/broadcast/v1/*`: WebSocket connection, ticket auth, client-side handling\n- **[Named Invalidations](/stack/realtime/named-invalidations)** — Typed, targeted \"this changed — refresh\" signals fired from actions after commit, with optional per-recipient narrowing\n- **[Live Views](/stack/realtime/live-views)** — Keep an open view's full join-surface (root + related children) live with hybrid-delta updates and resync-on-reconnect\n- **[PartyServer Rooms](/stack/realtime/partyserver-rooms)** — Per-room collab via `/realtime/<binding>/<room-id>`: presence, live notes, room IDs"
466
+ "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`. The `/broadcast/v1` version segment tracks `contract.version` — contract-v2 projects mount the same surface at `/broadcast/v2` (no hidden v1 alias). Documented on this page. For **typed, targeted \"this changed — refresh\" signals** fired from an action after commit (with optional per-recipient narrowing), see [Named invalidations](/stack/realtime/named-invalidations).\n- **`/realtime/<binding>/<room-id>` — bidirectional rooms.** One DO instance per room (per document, per interview, per game). Client↔client messages, presence, and CRDT-friendly state. Use these for collaborative editing. See [PartyServer rooms](/stack/realtime/partyserver-rooms).\n\nBoth share the same auth model and ride on the same compiled worker; they solve different problems.\n\n## Architecture\n\n```\n┌──────────────────────────────────────────┐\n│ Quickback Worker │\n│ │\n│ ┌──────────┐ DO binding ┌────────────────────┐\n│ │ Hono API │ ──────────────► │ Broadcaster (DO) │\n│ │ │ │ WebSocket manager │\n│ └──────────┘ └─────────┬──────────┘\n│ │\n└─────────────────────────────────────────┼┘\n │ WebSocket\n │\n ┌────────▼─────────┐\n │ Browser Clients │\n │ (CMS, Account, │\n │ Admin, Custom) │\n └──────────────────┘\n```\n\nThe Broadcaster Durable Object runs **inline** in your main Quickback worker — no separate worker deployment needed. The API calls the DO directly via its binding (in-process, no network hop).\n\n1. **Quickback Worker** — Your compiled API with the Broadcaster DO class exported from the same worker.\n2. **Broadcaster (Durable Object)** — Manages WebSocket connections per subscription scope. One instance per `scopeKey`, organization, or user lane.\n3. **Browser Clients** — CMS, Account, Admin, and custom frontends connect via WebSocket on the same origin.\n\n## Key Features\n\n| Feature | Description |\n|---------|-------------|\n| Scope-aware fan-out | Routes by `scopeKey`, `organizationId`, or `userId` |\n| Role-based filtering | Only send events to users with matching roles |\n| Per-role masking | Different users see different field values based on their role |\n| User-specific targeting | Send events to a specific user within an org |\n| Resource-scoped tickets | Mint scope-bound ws tickets gated by org-membership roles, authz relationship roles, or FGA relations |\n| Custom broadcasts | Arbitrary events beyond CRUD |\n| Custom namespaces | `defineRealtime()` for type-safe event helpers |\n| Ticket-based auth | HMAC-signed tickets verified at WebSocket upgrade — no HTTP round-trip |\n\n## Enabling Realtime\n\nBroadcasting is **opt-in per resource**, exactly like CRUD — a table broadcasts\nonly if it declares its own `realtime` block. Add `realtime` to individual table\ndefinitions:\n\n```typescript\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n realtime: {\n enabled: true,\n onInsert: true,\n onUpdate: true,\n onDelete: true,\n // Audience — WHO may receive these live rows. Same { roles } shape as\n // read.access / crud.*.access. MANDATORY and fail-closed: a broadcast\n // reaches every subscriber in the room, so the audience is not optional.\n // Omit it (or leave it empty) and compilation fails. Roles may be concrete\n // membership/scope roles or UPPERCASE pseudo-roles.\n access: { roles: [\"recruiter\", \"hiring-manager\"] },\n fields: [\"id\", \"candidateId\", \"stage\"],\n },\n});\n```\n\nAnd enable the realtime **transport** in your database config. This is a\nproject-level switch that stands up the Broadcaster Durable Object + the\nconnection route; it does **not** by itself make any resource broadcast\n(that's the per-resource `realtime` block above). The compiler generates the\nDurable Object class, helper functions, and wrangler bindings — all within\nyour main worker.\n\nFor most apps — including org-scoped apps like chat, feeds, and dashboards —\nthe boolean form is all you need. Session-authenticated members subscribe\ndirectly; audiences come from each resource's `realtime.access.roles`:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: true,\n }),\n}\n```\n\nThe object form is the **advanced** variant, only needed when you mint\nresource-scoped tickets (e.g. an external attendee who may join one event's\nchannel, or an org member who may join one project's room). The mint gate is\ndeclared with `wsTicket.access`, a discriminated union — the arm names the\nauthorization vocabulary, so a bare name can never silently mean two things:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: {\n wsTicket: {\n // Pick EXACTLY ONE arm:\n access: { roles: [\"member+\"] }, // org-membership roles (hierarchy expands)\n // access: { authzRole: \"attendee\" }, // authz relationship role\n // access: { fga: { relation: \"viewer\", object: \"event:{id}\" } }, // FGA relation on the scope row\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n },\n }),\n}\n```\n\n- **`{ roles }` — org-membership roles.** `\"member+\"` expands via\n `auth.roleHierarchy` (compile error without it). Firewall-consistent: the\n route verifies the caller's org role **and** that the requested `scopeTable`\n row belongs to the caller's *active* organization — an org-A member cannot\n mint a ticket to org B's room. The scope table must therefore carry an\n organization column (compile error otherwise). UPPERCASE pseudo-roles are\n rejected here: a `PUBLIC`/`AUTHENTICATED` ticket factory would hand signed\n room credentials to callers with no org standing.\n- **`{ authzRole }` — a declared `authz.roles` relationship role** (`{ via }`).\n The route probes the relationship table against `body.eventId`; the ticket\n carries the relationship role (e.g. `attendee`). The legacy\n `role: \"attendee\"` string is the back-compat shorthand for this arm and\n compiles identically. Org-membership names (`member`/`admin`/`owner`) are\n still rejected in this arm — spell those `access: { roles: [...] }`.\n- **`{ fga }` — an FGA relation.** The route loads the `scopeTable` row through\n its own firewall (tenant bind), derives the object from the template\n (`\"event:{id}\"` — `{field}` tokens read from the row, the same template\n language as the read path's `access: { fga }`), and requires the caller to\n hold `relation` on it via the same org-scoped check evaluator the read path\n uses. Requires `authz.fga`; the object type and relation are validated\n against the model at compile time.\n\nWhichever arm you pick, `/broadcast/v1/ws-ticket` authenticates the caller,\nruns that gate against `body.eventId`, and mints a short-lived ticket scoped to\nthe resolved `events:<id>` channel. Everything fails closed at compile time:\na bare name that exists in more than one vocabulary is an ambiguity error\ndemanding the explicit arm, and a missing hierarchy, missing FGA model, or\nmissing organization column fails the build with an actionable message.\n\n## Pages\n\n- **[Durable Objects Setup](/stack/realtime/durable-objects)** — Broadcaster configuration, wrangler bindings, event formats, masking, and custom namespaces\n- **[Using Realtime](/stack/realtime/using-realtime)** — Subscribing to `/broadcast/v1/*`: WebSocket connection, ticket auth, client-side handling\n- **[Named Invalidations](/stack/realtime/named-invalidations)** — Typed, targeted \"this changed — refresh\" signals fired from actions after commit, with optional per-recipient narrowing\n- **[Live Views](/stack/realtime/live-views)** — Keep an open view's full join-surface (root + related children) live with hybrid-delta updates and resync-on-reconnect\n- **[PartyServer Rooms](/stack/realtime/partyserver-rooms)** — Per-room collab via `/realtime/<binding>/<room-id>`: presence, live notes, room IDs\n\nThere are **three declarative emission surfaces** — pick by what did the write:\n\n| The write is… | Emit with | Where |\n|---|---|---|\n| A CRUD row change | the table's **`realtime`** block (postgres_changes frames) | this page |\n| A custom action | **`invalidates:`** on the action | [Named invalidations](/stack/realtime/named-invalidations) |\n| An [aggregate changeset](/compiler/definitions/changesets) (`owns`) | **`afterCommit`** on the aggregate root — one CloudEvent after commit | [changesets → afterCommit](/compiler/definitions/changesets#aftercommit--emit-a-realtime-signal-after-the-changeset-commits) |\n\n## CloudEvents (contract v2) + AsyncAPI (any contract)\n\nOn the v2 contract, realtime data frames are delivered as CloudEvents 1.0\nenvelopes on `/broadcast/v2` (control frames stay raw). See\n[Using Realtime](/stack/realtime/using-realtime#cloudevents-envelopes-contract-v2)\nfor the frame mapping.\n\nThe project's event surface — realtime channels, named-invalidation events,\nand outbound webhook messages — is published as an AsyncAPI 3.0 document at\n`GET /asyncapi.json` (same auth gating as `/openapi.json`). The document is\n**contract-version-independent**: it is emitted for any project with realtime\nor webhooks (v1 included); only the message payload *schemas* are shaped by\nthe pinned contract — raw frames on v1, CloudEvents envelopes on v2."
455
467
  },
456
468
  "stack/realtime/live-views": {
457
469
  "title": "Live Views",
458
- "content": "A **live view** is a named *surface*: a root row plus the related data a screen\nshows around it — forward foreign-key display values and reverse-FK child\ncollections. When a client subscribes to a live view, the open surface stays\nwhole in realtime: any write to the root row **or** a related row that shares a\nforeign key is pushed as a `view_changes` delta the client splices in place.\n\nThis is the difference from table-level [`postgres_changes`](/stack/realtime/using-realtime)\nbroadcasts, which are single-row, single-table. A person-detail screen that\nshows a `people` row plus rows from a normalized `phone_numbers` table would\notherwise have to stitch together separate per-table events and figure out that\na `phone_numbers` insert with `personId = X` belongs to the person it has open.\nLive views do that mapping for you.\n\n> Live views ride the realtime Broadcaster. You must have realtime enabled\n> (`providers.database.config.realtime: true`). Declaring a view without\n> realtime is a compile-time error.\n\n## Defining a view\n\nViews live in `services/views/<name>.ts`:\n\n```typescript\n// services/views/person-detail.ts\n\nexport default defineView({\n name: 'person-detail',\n root: 'people',\n include: [\n { relation: 'companyId' }, // forward FK → company display value\n { relation: 'phone_numbers' }, // reverse FK → phoneNumbers[] collection\n ],\n});\n```\n\n- **`root`** — the table the surface is keyed by. Must be a `defineTable`\n resource (its firewall + read access gate the surface).\n- **`include[].relation`** — a forward-FK column on the root (`companyId`), or\n the name of a child table that references the root (`phone_numbers`). The\n compiler auto-detects the direction from the foreign-key graph; pass\n `kind: 'forward' | 'reverse'` to disambiguate.\n- **`as`** — the response key the related data is spliced under. Defaults to a\n derived name: forward strips a trailing `Id` (`companyId` → `company`),\n reverse uses the child table name (`phone_numbers` → `phoneNumbers`).\n- **`fields`** — optional column projection on the included table.\n\nThe materialized surface looks like:\n\n```jsonc\n{\n \"id\": \"person_123\",\n \"name\": \"Ada Lovelace\",\n \"email\": \"ad***@example.com\", // masked per the people table's masking config\n \"company\": \"Analytical Engines\", // forward display value\n \"phoneNumbers\": [ // reverse-FK child collection\n { \"id\": \"ph_1\", \"number\": \"+1...\" }\n ]\n}\n```\n\nEvery included table is read through **its own** `firewall` and `masking` — a\nsubscriber only ever sees related rows they're already allowed to read, masked\nexactly as they would be on a normal read.\n\n## Reading a surface\n\nThe compiler generates a read endpoint per view:\n\n```http\nGET /api/v1/views/person-detail/person_123\n→ { \"data\": { ...surface }, \"seq\": 7 }\n```\n\n`seq` is the surface's current monotonic sequence — the client uses it to detect\ndropped deltas. A `404` is returned when the caller can't read the root row\n(indistinguishable from \"doesn't exist\", closing the id-probe channel).\n\n## Subscribing (client)\n\nThe built-in CMS and Account SPAs ship a `useView` hook:\n\n```tsx\n\nfunction PersonDetail({ personId }: { personId: string }) {\n const { data, connected, loading } = useView('person-detail', personId);\n // `data` stays live: editing the person merges into the root; adding a phone\n // appends to data.phoneNumbers; deleting one removes it — no refetch.\n}\n```\n\nUnder the hood `useView` uses a **subscribe-then-snapshot** flow so no change\nslips through the gap between reading the surface and the socket going live:\n\n1. Requests a **view-scoped ws-ticket** (`POST /broadcast/v1/ws-ticket` — `/broadcast/v2/ws-ticket` on contract-v2 projects — with\n `{ view, rootId }`) — gated by the same root firewall as the read endpoint —\n and opens a WebSocket scoped to `view:<view>:<rootId>`.\n2. Once the socket is open, fetches the full surface via\n `GET /api/v1/views/<view>/:rootId`. Deltas arriving during that fetch are\n **buffered**, then replayed after the snapshot applies (the route reads the\n `seq` baseline *before* materializing, so the snapshot is at least as fresh\n as `seq`, and replay is idempotent — collections key by row `id`).\n3. Applies `view_changes` deltas in place (the **hybrid-delta** model):\n - `target: 'root'` + `UPDATE` → shallow-merge into the surface root\n - `target: 'root'` + `DELETE` → surface cleared\n - `target: 'collection'` → append / replace-by-key / remove-by-key on `data[as]`\n - `delta.resync` → refetch the surface (the stricter-child path above)\n4. Tracks `seq`. A gap (`seq !== last + 1`) or a WebSocket reconnect triggers a\n full **resync** — the safety net that heals any dropped delta (Cloudflare D1\n has no transactions, so emit is best-effort by design). If the server can't\n read the baseline it returns `seq: null`; the client then adopts the first\n delta's `seq` instead of treating it as `0`, so a transient read error never\n spirals into a resync loop. Overlapping resyncs are token-guarded so a slow\n earlier fetch can't clobber a newer surface.\n\nTo subscribe from a custom client, request a ticket with `{ view, rootId }` and\nconnect to `…/broadcast/v1/websocket?ws_ticket=<ticket>`. Messages are:\n\n```jsonc\n{\n \"type\": \"view_changes\",\n \"view\": \"person-detail\",\n \"rootId\": \"person_123\",\n \"seq\": 8,\n \"delta\": { \"target\": \"collection\", \"op\": \"INSERT\", \"as\": \"phoneNumbers\",\n \"key\": \"ph_2\", \"row\": { \"id\": \"ph_2\", \"number\": \"+1...\" } }\n}\n```\n\n## How changes are captured\n\nDeltas are emitted from the **write chokepoint** — the same wrapper that injects\naudit fields wraps every `db.insert/update/delete`. Because CRUD routes *and*\naction handlers write through that db, both emit deltas; there's no separate\nhook to wire. A write taps its result and, when it used `.returning()`, fans a\ndelta to each affected surface. Soft deletes (an `UPDATE` that sets `deletedAt`)\nare emitted as `DELETE` so the row leaves the surface.\n\n## Security\n\n- The **subscribe gate** reuses the view materializer: a ticket is only minted\n when the caller can read the root row.\n- Each included table's `firewall` + `masking` apply on both the initial\n materialize and the live deltas (masking is applied per subscriber role at\n fanout), so the two are consistent.\n- A table-level `realtime.access.roles` audience is honored on view deltas\n too: `view_changes` for that table fan out only to subscribers within the\n declared audience (evaluated with the same pseudo-role semantics as REST),\n exactly like its row-stream broadcasts. Tables that don't declare a\n broadcasting `realtime` block don't emit row-stream broadcasts, but their\n rows can still surface through a live view they participate in.\n- **Stricter-child guard.** When a reverse-FK child's firewall is *stricter*\n than the root's (e.g. an owner-scoped note under an org-scoped person), the\n raw child row is **never broadcast**. Instead the server emits a *resync\n signal* and the client refetches the surface through the materializer, which\n applies the child's own firewall per subscriber. Row-bearing deltas are sent\n only when the child is no stricter than the root.\n- **Masking fails closed.** A mask type the Broadcaster can't replicate —\n notably `type: 'custom'`, whose function is stripped during codegen — is\n fully redacted (`[REDACTED]`) in deltas rather than passed through.\n- **Projection parity.** An include's `fields` projection is applied to deltas\n too, so a delta never carries a column the surface deliberately omits.\n\n## v1 limitations\n\n- **Depth-1 includes only.** Nested includes are a compile-time error — flatten\n the surface or split into multiple views.\n- **Forward includes** (e.g. a company name on a person) are materialized into\n the surface and refreshed on resync, but a change to the *referenced parent*\n does not push a live delta — it surfaces on the next resync/reconnect.\n- **Writes without `.returning()`** (and raw action writes that don't return\n rows) don't push a live delta; resync-on-reconnect heals the surface."
470
+ "content": "A **live view** is a named *surface*: a root row plus the related data a screen\nshows around it — forward foreign-key display values and reverse-FK child\ncollections. When a client subscribes to a live view, the open surface stays\nwhole in realtime: any write to the root row **or** a related row that shares a\nforeign key is pushed as a `view_changes` delta the client splices in place.\n\nThis is the difference from table-level [`postgres_changes`](/stack/realtime/using-realtime)\nbroadcasts, which are single-row, single-table. A person-detail screen that\nshows a `people` row plus rows from a normalized `phone_numbers` table would\notherwise have to stitch together separate per-table events and figure out that\na `phone_numbers` insert with `personId = X` belongs to the person it has open.\nLive views do that mapping for you.\n\n> Live views ride the realtime Broadcaster. You must have realtime enabled\n> (`providers.database.config.realtime: true`). Declaring a view without\n> realtime is a compile-time error.\n\n## Defining a view\n\nViews live in `services/views/<name>.ts`:\n\n```typescript\n// services/views/person-detail.ts\n\nexport default defineView({\n name: 'person-detail',\n root: 'people',\n include: [\n { relation: 'companyId' }, // forward FK → company display value\n { relation: 'phone_numbers' }, // reverse FK → phoneNumbers[] collection\n ],\n});\n```\n\n- **`root`** — the table the surface is keyed by. Must be a `defineTable`\n resource (its firewall + read access gate the surface).\n- **`include[].relation`** — a forward-FK column on the root (`companyId`), or\n the name of a child table that references the root (`phone_numbers`). The\n compiler auto-detects the direction from the foreign-key graph; pass\n `kind: 'forward' | 'reverse'` to disambiguate.\n- **`as`** — the response key the related data is spliced under. Defaults to a\n derived name: forward strips a trailing `Id` (`companyId` → `company`),\n reverse uses the child table name (`phone_numbers` → `phoneNumbers`).\n- **`fields`** — optional column projection on the included table.\n\nThe materialized surface looks like:\n\n```jsonc\n{\n \"id\": \"person_123\",\n \"name\": \"Ada Lovelace\",\n \"email\": \"ad***@example.com\", // masked per the people table's masking config\n \"company\": \"Analytical Engines\", // forward display value\n \"phoneNumbers\": [ // reverse-FK child collection\n { \"id\": \"ph_1\", \"number\": \"+1...\" }\n ]\n}\n```\n\nEvery included table is read through **its own** `firewall` and `masking` — a\nsubscriber only ever sees related rows they're already allowed to read, masked\nexactly as they would be on a normal read.\n\n## Auth-DB includes (`source: 'auth'`)\n\nA view may join **read-only** display data from the Better Auth tables\n(`user`, `member`, `invitation`, `organization`) — the \"staff picker\" pattern:\n\n```typescript\nexport default defineView({\n name: 'staff-board',\n root: 'sessions',\n include: [\n // dereference the creating user's display fields\n { source: 'auth', table: 'user', on: { local: 'createdBy', auth: 'id' },\n fields: ['name', 'email'], as: 'creator' },\n // the creator's role in the caller's org — tenant-anchored\n { source: 'auth', table: 'member', on: { local: 'createdBy', auth: 'userId' },\n tenant: { auth: 'organizationId', equals: 'ctx.activeOrgId' },\n fields: ['role'], as: 'creatorMembership' },\n ],\n});\n```\n\nAuth tables carry no firewall/masking to inherit, so the include **is** the\nsecurity boundary — every rule is fail-closed at compile time:\n\n- **`fields` is a mandatory allowlist** of compiler-known display columns\n (deny-by-default; secret/auth-internal tables and columns are never\n exposable).\n- **`tenant` is mandatory for `member` / `invitation`** — those tables hold\n per-organization rows keyed by columns that recur across orgs; an\n un-anchored single-row join would return an arbitrary org's row.\n- An **un-tenanted** join's `on.local` must be a non-writable, auto-stamped\n column (`createdBy` / `modifiedBy`, or the root's declared scope columns) —\n a caller-writable join key would let a caller dereference arbitrary\n identities.\n\nWith a declared [`authz.tenants` anchor](/compiler/definitions/firewall#named-tenant-anchors-tenant),\nthe tenant can be referenced **by name** — same resolved include, same gates:\n\n```typescript\n// quickback.config.ts\nauthz: { tenants: { org: { column: 'organizationId', equals: 'ctx.activeOrgId' } } }\n\n// the include\n{ source: 'auth', table: 'member', on: { local: 'createdBy', auth: 'userId' },\n tenant: 'org', fields: ['role'], as: 'creatorMembership' }\n```\n\nThe referenced anchor must bind a **single-segment session claim** (`ctx.<claim>`, e.g. `ctx.activeOrgId`) — the same grammar the inline object form enforces. An anchor bound to a scope-principal claim (`ctx.scope.*`) is valid in firewall lanes but is a compile error when referenced from an auth-view include.\n\n## Reading a surface\n\nThe compiler generates a read endpoint per view:\n\n```http\nGET /api/v1/views/person-detail/person_123\n→ { \"data\": { ...surface }, \"seq\": 7 }\n```\n\n`seq` is the surface's current monotonic sequence — the client uses it to detect\ndropped deltas. A `404` is returned when the caller can't read the root row\n(indistinguishable from \"doesn't exist\", closing the id-probe channel).\n\n## Subscribing (client)\n\nThe built-in CMS and Account SPAs ship a `useView` hook:\n\n```tsx\n\nfunction PersonDetail({ personId }: { personId: string }) {\n const { data, connected, loading } = useView('person-detail', personId);\n // `data` stays live: editing the person merges into the root; adding a phone\n // appends to data.phoneNumbers; deleting one removes it — no refetch.\n}\n```\n\nUnder the hood `useView` uses a **subscribe-then-snapshot** flow so no change\nslips through the gap between reading the surface and the socket going live:\n\n1. Requests a **view-scoped ws-ticket** (`POST /broadcast/v1/ws-ticket` — `/broadcast/v2/ws-ticket` on contract-v2 projects — with\n `{ view, rootId }`) — gated by the same root firewall as the read endpoint —\n and opens a WebSocket scoped to `view:<view>:<rootId>`.\n2. Once the socket is open, fetches the full surface via\n `GET /api/v1/views/<view>/:rootId`. Deltas arriving during that fetch are\n **buffered**, then replayed after the snapshot applies (the route reads the\n `seq` baseline *before* materializing, so the snapshot is at least as fresh\n as `seq`, and replay is idempotent — collections key by row `id`).\n3. Applies `view_changes` deltas in place (the **hybrid-delta** model):\n - `target: 'root'` + `UPDATE` → shallow-merge into the surface root\n - `target: 'root'` + `DELETE` → surface cleared\n - `target: 'collection'` → append / replace-by-key / remove-by-key on `data[as]`\n - `delta.resync` → refetch the surface (the stricter-child path above)\n4. Tracks `seq`. A gap (`seq !== last + 1`) or a WebSocket reconnect triggers a\n full **resync** — the safety net that heals any dropped delta (Cloudflare D1\n has no transactions, so emit is best-effort by design). If the server can't\n read the baseline it returns `seq: null`; the client then adopts the first\n delta's `seq` instead of treating it as `0`, so a transient read error never\n spirals into a resync loop. Overlapping resyncs are token-guarded so a slow\n earlier fetch can't clobber a newer surface.\n\nTo subscribe from a custom client, request a ticket with `{ view, rootId }` and\nconnect to `…/broadcast/v1/websocket?ws_ticket=<ticket>`. Messages are:\n\n```jsonc\n{\n \"type\": \"view_changes\",\n \"view\": \"person-detail\",\n \"rootId\": \"person_123\",\n \"seq\": 8,\n \"delta\": { \"target\": \"collection\", \"op\": \"INSERT\", \"as\": \"phoneNumbers\",\n \"key\": \"ph_2\", \"row\": { \"id\": \"ph_2\", \"number\": \"+1...\" } }\n}\n```\n\n## How changes are captured\n\nDeltas are emitted from the **write chokepoint** — the same wrapper that injects\naudit fields wraps every `db.insert/update/delete`. Because CRUD routes *and*\naction handlers write through that db, both emit deltas; there's no separate\nhook to wire. A write taps its result and, when it used `.returning()`, fans a\ndelta to each affected surface. Soft deletes (an `UPDATE` that sets `deletedAt`)\nare emitted as `DELETE` so the row leaves the surface.\n\n**Changeset writes** ([aggregate `owns`](/compiler/definitions/changesets)) do not\nflow through the per-row delta chokepoint — they emit one aggregate-level signal\nvia [`afterCommit`](/compiler/definitions/changesets#aftercommit--emit-a-realtime-signal-after-the-changeset-commits)\non the root. Declare `afterCommit` on the aggregate root so live views observe\nchangeset writes; without it the compiler warns that changeset writes to a\n`realtime` table go unobserved.\n\n## Security\n\n- The **subscribe gate** reuses the view materializer: a ticket is only minted\n when the caller can read the root row.\n- Each included table's `firewall` + `masking` apply on both the initial\n materialize and the live deltas (masking is applied per subscriber role at\n fanout), so the two are consistent.\n- A table-level `realtime.access.roles` audience is honored on view deltas\n too: `view_changes` for that table fan out only to subscribers within the\n declared audience (evaluated with the same pseudo-role semantics as REST),\n exactly like its row-stream broadcasts. Tables that don't declare a\n broadcasting `realtime` block don't emit row-stream broadcasts, but their\n rows can still surface through a live view they participate in.\n- **Stricter-child guard.** When a reverse-FK child's firewall is *stricter*\n than the root's (e.g. an owner-scoped note under an org-scoped person), the\n raw child row is **never broadcast**. Instead the server emits a *resync\n signal* and the client refetches the surface through the materializer, which\n applies the child's own firewall per subscriber. Row-bearing deltas are sent\n only when the child is no stricter than the root.\n- **Masking fails closed.** A mask type the Broadcaster can't replicate —\n notably `type: 'custom'`, whose function is stripped during codegen — is\n fully redacted (`[REDACTED]`) in deltas rather than passed through.\n- **Projection parity.** An include's `fields` projection is applied to deltas\n too, so a delta never carries a column the surface deliberately omits.\n\n## v1 limitations\n\n- **Depth-1 includes only.** Nested includes are a compile-time error — flatten\n the surface or split into multiple views.\n- **Forward includes** (e.g. a company name on a person) are materialized into\n the surface and refreshed on resync, but a change to the *referenced parent*\n does not push a live delta — it surfaces on the next resync/reconnect.\n- **Writes without `.returning()`** (and raw action writes that don't return\n rows) don't push a live delta; resync-on-reconnect heals the surface."
459
471
  },
460
472
  "stack/realtime/named-invalidations": {
461
473
  "title": "Named Invalidations",
@@ -467,7 +479,7 @@ export const DOCS = {
467
479
  },
468
480
  "stack/realtime/using-realtime": {
469
481
  "title": "Using Realtime",
470
- "content": "This page covers connecting to the Quickback realtime system from client applications — authentication, subscribing to events, and handling messages.\n\n## Connecting\n\nOpen a WebSocket connection to the realtime worker:\n\n```typescript\nconst ws = new WebSocket(\"wss://api.yourdomain.com/broadcast/v1/websocket\");\n// Note: /broadcast/v1 tracks contract.version — use /broadcast/v2 on contract-v2 projects.\n```\n\n## Authentication\n\nQuickback uses **ticket-based authentication** for WebSocket connections. This is a two-step process:\n\n1. **Get a ticket** — Call the ws-ticket endpoint with your session auth\n2. **Connect with ticket** — Pass the ticket as a URL parameter when opening the WebSocket\n\nThis approach is faster and more secure than in-band auth messages — the connection is authenticated at upgrade time with no HTTP round-trip from the Durable Object.\n\n### Step 1: Get a WebSocket Ticket\n\n```typescript\nconst response = await fetch(\"/broadcast/v1/ws-ticket\", {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${sessionToken}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ eventId: \"evt_123\" }), // optional; used by resource-scoped wsTicket config\n});\nconst { wsTicket, expiresIn } = await response.json();\n// expiresIn = 60 (seconds)\n```\n\nThe ticket is a short-lived (60-second) HMAC-signed token containing your userId, roles, and the resolved subscription scope.\n\n### Step 2: Connect with Ticket\n\n```typescript\nconst ws = new WebSocket(\n `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}`\n);\n\nws.onopen = () => {\n console.log(\"Connected and authenticated!\");\n // No auth message needed — connection is pre-authenticated\n};\n```\n\nIf the ticket is invalid or expired, the WebSocket upgrade is rejected with a 401 status.\n\n## Handling Messages\n\n### CRUD Events\n\nCRUD events use the `postgres_changes` type:\n\n```typescript\nws.onmessage = (event) => {\n const msg = JSON.parse(event.data);\n\n if (msg.type === \"postgres_changes\") {\n const { table, eventType, new: newRecord, old: oldRecord } = msg;\n\n switch (eventType) {\n case \"INSERT\":\n addRecord(table, newRecord);\n break;\n case \"UPDATE\":\n updateRecord(table, newRecord);\n break;\n case \"DELETE\":\n removeRecord(table, oldRecord.id);\n break;\n }\n }\n};\n```\n\n**Event payload:**\n\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"schema\": \"public\",\n \"eventType\": \"INSERT\",\n \"new\": { \"id\": \"app_123\", \"candidateId\": \"cnd_456\", \"stage\": \"interview\" },\n \"old\": null\n}\n```\n\nFor UPDATE events, both `new` and `old` are populated. For DELETE events, only `old` is populated.\n\n### Custom Broadcasts\n\nCustom events use the `broadcast` type:\n\n```typescript\nif (msg.type === \"broadcast\") {\n const { event, payload } = msg;\n\n if (event === \"screening-complete\") {\n refreshApplication(payload.applicationId);\n } else if (event === \"screening:progress\") {\n updateProgressBar(payload.percent);\n }\n}\n```\n\n**Event payload:**\n\n```json\n{\n \"type\": \"broadcast\",\n \"event\": \"screening-complete\",\n \"payload\": {\n \"applicationId\": \"app_123\",\n \"candidateId\": \"cnd_456\",\n \"stage\": \"interview\"\n }\n}\n```\n\nCustom namespaces (from `defineRealtime()`) use the format `namespace:event` — e.g., `screening:started`, `screening:progress`.\n\n## Security\n\n### Role-Based Filtering\n\nEvents are only delivered to subscribers who fall within the broadcast's audience. A broadcasting table's realtime config **must** declare `access: { roles: [...] }` — e.g. `access: { roles: [\"hiring-manager\", \"recruiter\"] }` delivers only to those roles. The audience is evaluated at fanout with the same uppercase pseudo-role semantics as REST (`PUBLIC` = everyone in the room, `AUTHENTICATED`, `USER`, `SYSADMIN`), plus concrete membership/scope roles. This is **fail-closed**: an empty or omitted audience delivers to no one (and is a compile error for a broadcasting resource). Applies to generated CRUD broadcasts and to [live view](/stack/realtime/live-views) `view_changes` deltas alike.\n\n### Per-Role Masking\n\nField values are masked according to the subscriber's role. For example, with this masking config:\n\n```typescript\nmasking: {\n ssn: { type: \"ssn\", show: { roles: [\"owner\"] } },\n}\n```\n\n- **Owner sees:** `{ ssn: \"123-45-6789\" }`\n- **Recruiter sees:** `{ ssn: \"*****6789\" }`\n\nMasking is pre-computed per-role (O(roles), not O(subscribers)) for efficiency. A `type: 'custom'` mask function can't run inside the Broadcaster — those columns broadcast as `[REDACTED]` (fail closed).\n\n### User-Specific Events\n\nEvents can target a specific user lane. Only that user receives the broadcast — all other connections on the same scope are skipped.\n\n### Scope Isolation\n\nEach WebSocket connection is attached to exactly one resolved scope: `scopeKey`, `organizationId`, or `userId`. Users can only subscribe to the scope stamped into their ws ticket, enforced during authentication and ticket minting.\n\n## Reconnection\n\nWebSocket connections can drop due to network issues. Implement reconnection logic in your client — note that you need to fetch a fresh ticket on each reconnect since tickets expire after 60 seconds:\n\n```typescript\nasync function connect() {\n // Get a fresh ticket each time\n const res = await fetch(\"/broadcast/v1/ws-ticket\", {\n method: \"POST\",\n headers: { Authorization: `Bearer ${sessionToken}` },\n body: JSON.stringify({ eventId: \"evt_123\" }),\n });\n const { wsTicket } = await res.json();\n\n const ws = new WebSocket(\n `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}`\n );\n\n ws.onclose = () => {\n // Reconnect after delay\n setTimeout(connect, 2000);\n };\n\n ws.onmessage = (event) => {\n const msg = JSON.parse(event.data);\n handleMessage(msg);\n };\n\n return ws;\n}\n```\n\n## Environment\n\nNo additional environment variables are needed for realtime. The Broadcaster Durable Object runs inline in your main worker and reuses `BETTER_AUTH_SECRET` for WebSocket ticket signing.\n\nThe compiler generates the required `wrangler.toml` bindings automatically:\n\n```toml\n[[durable_objects.bindings]]\nname = \"BROADCASTER\"\nclass_name = \"Broadcaster\"\n\n[[migrations]]\ntag = \"v1\"\nnew_classes = [\"Broadcaster\"]\n```\n\n## Cloudflare Only\n\nRealtime requires Cloudflare Durable Objects and is only available with the Cloudflare runtime.\n\n## See Also\n\n- [Durable Objects Setup](/stack/realtime/durable-objects) — Configuration, event formats, masking, and custom namespaces\n- [Masking](/compiler/definitions/masking) — Field masking configuration"
482
+ "content": "This page covers connecting to the Quickback realtime system from client applications — authentication, subscribing to events, and handling messages.\n\n## Connecting\n\nOpen a WebSocket connection to the realtime worker:\n\n```typescript\nconst ws = new WebSocket(\"wss://api.yourdomain.com/broadcast/v1/websocket\");\n// Note: /broadcast/v1 tracks contract.version — use /broadcast/v2 on contract-v2 projects.\n```\n\n## Authentication\n\nQuickback uses **ticket-based authentication** for WebSocket connections. This is a two-step process:\n\n1. **Get a ticket** — Call the ws-ticket endpoint with your session auth\n2. **Connect with ticket** — Pass the ticket as a URL parameter when opening the WebSocket\n\nThis approach is faster and more secure than in-band auth messages — the connection is authenticated at upgrade time with no HTTP round-trip from the Durable Object.\n\n### Step 1: Get a WebSocket Ticket\n\n```typescript\nconst response = await fetch(\"/broadcast/v1/ws-ticket\", {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${sessionToken}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ eventId: \"evt_123\" }), // optional; used by resource-scoped wsTicket config\n});\nconst { wsTicket, expiresIn } = await response.json();\n// expiresIn = 60 (seconds)\n```\n\nThe ticket is a short-lived (60-second) HMAC-signed token containing your userId, roles, and the resolved subscription scope.\n\n### Step 2: Connect with Ticket\n\n```typescript\nconst ws = new WebSocket(\n `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}`\n);\n\nws.onopen = () => {\n console.log(\"Connected and authenticated!\");\n // No auth message needed — connection is pre-authenticated\n};\n```\n\nIf the ticket is invalid or expired, the WebSocket upgrade is rejected with a 401 status.\n\n## Handling Messages\n\n### CRUD Events\n\nCRUD events use the `postgres_changes` type:\n\n```typescript\nws.onmessage = (event) => {\n const msg = JSON.parse(event.data);\n\n if (msg.type === \"postgres_changes\") {\n const { table, eventType, new: newRecord, old: oldRecord } = msg;\n\n switch (eventType) {\n case \"INSERT\":\n addRecord(table, newRecord);\n break;\n case \"UPDATE\":\n updateRecord(table, newRecord);\n break;\n case \"DELETE\":\n removeRecord(table, oldRecord.id);\n break;\n }\n }\n};\n```\n\n**Event payload:**\n\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"schema\": \"public\",\n \"eventType\": \"INSERT\",\n \"new\": { \"id\": \"app_123\", \"candidateId\": \"cnd_456\", \"stage\": \"interview\" },\n \"old\": null\n}\n```\n\nFor UPDATE events, both `new` and `old` are populated. For DELETE events, only `old` is populated.\n\n### Custom Broadcasts\n\nCustom events use the `broadcast` type:\n\n```typescript\nif (msg.type === \"broadcast\") {\n const { event, payload } = msg;\n\n if (event === \"screening-complete\") {\n refreshApplication(payload.applicationId);\n } else if (event === \"screening:progress\") {\n updateProgressBar(payload.percent);\n }\n}\n```\n\n**Event payload:**\n\n```json\n{\n \"type\": \"broadcast\",\n \"event\": \"screening-complete\",\n \"payload\": {\n \"applicationId\": \"app_123\",\n \"candidateId\": \"cnd_456\",\n \"stage\": \"interview\"\n }\n}\n```\n\nCustom namespaces (from `defineRealtime()`) use the format `namespace:event` — e.g., `screening:started`, `screening:progress`.\n\n## Security\n\n### Role-Based Filtering\n\nEvents are only delivered to subscribers who fall within the broadcast's audience. A broadcasting table's realtime config **must** declare `access: { roles: [...] }` — e.g. `access: { roles: [\"hiring-manager\", \"recruiter\"] }` delivers only to those roles. The audience is evaluated at fanout with the same uppercase pseudo-role semantics as REST (`PUBLIC` = everyone in the room, `AUTHENTICATED`, `USER`, `SYSADMIN`), plus concrete membership/scope roles. This is **fail-closed**: an empty or omitted audience delivers to no one (and is a compile error for a broadcasting resource). Applies to generated CRUD broadcasts and to [live view](/stack/realtime/live-views) `view_changes` deltas alike.\n\n### Named rules and gates in `requiredRoles`\n\nDeclared [`authz.roles`](/compiler/definitions/access#centrally-defined-access-rules) and [`authz.rules` gates](/compiler/definitions/access#named-gates-authzrules) can appear in `realtime.requiredRoles`. The compiler lowers them to flat static role names at build time, because the WebSocket ticket handshake has no DB in hand:\n\n- A named role lowers to its composing static roles; relationship (`via:`) arms contribute nothing at the handshake (the row-stream firewall enforces that dimension later) and emit a warning.\n- A **who-only gate** lowers as its `who`. A gate carrying `record:` or `firewall` arms is undecidable at the handshake — it contributes nothing, with a warning.\n- **Fail-closed rule:** a declared non-empty `requiredRoles` that lowers to an **empty** set is a **compile error**, never a silently-assigned `[]`. The error names which entries lowered to nothing and why. Fix it by referencing a who-only rule, adding a static BA/pseudo-role fallback arm, or dropping the undecidable entries and relying on the row-stream firewall.\n\n### Per-Role Masking\n\nField values are masked according to the subscriber's role. For example, with this masking config:\n\n```typescript\nmasking: {\n ssn: { type: \"ssn\", show: { roles: [\"owner\"] } },\n}\n```\n\n- **Owner sees:** `{ ssn: \"123-45-6789\" }`\n- **Recruiter sees:** `{ ssn: \"*****6789\" }`\n\nMasking is pre-computed per-role (O(roles), not O(subscribers)) for efficiency. A `type: 'custom'` mask function can't run inside the Broadcaster — those columns broadcast as `[REDACTED]` (fail closed).\n\n### User-Specific Events\n\nEvents can target a specific user lane. Only that user receives the broadcast — all other connections on the same scope are skipped.\n\n### Scope Isolation\n\nEach WebSocket connection is attached to exactly one resolved scope: `scopeKey`, `organizationId`, or `userId`. Users can only subscribe to the scope stamped into their ws ticket, enforced during authentication and ticket minting.\n\n## Reconnection\n\nWebSocket connections can drop due to network issues. Implement reconnection logic in your client — note that you need to fetch a fresh ticket on each reconnect since tickets expire after 60 seconds:\n\n```typescript\nasync function connect() {\n // Get a fresh ticket each time\n const res = await fetch(\"/broadcast/v1/ws-ticket\", {\n method: \"POST\",\n headers: { Authorization: `Bearer ${sessionToken}` },\n body: JSON.stringify({ eventId: \"evt_123\" }),\n });\n const { wsTicket } = await res.json();\n\n const ws = new WebSocket(\n `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}`\n );\n\n ws.onclose = () => {\n // Reconnect after delay\n setTimeout(connect, 2000);\n };\n\n ws.onmessage = (event) => {\n const msg = JSON.parse(event.data);\n handleMessage(msg);\n };\n\n return ws;\n}\n```\n\n## Environment\n\nNo additional environment variables are needed for realtime. The Broadcaster Durable Object runs inline in your main worker and reuses `BETTER_AUTH_SECRET` for WebSocket ticket signing.\n\nThe compiler generates the required `wrangler.toml` bindings automatically:\n\n```toml\n[[durable_objects.bindings]]\nname = \"BROADCASTER\"\nclass_name = \"Broadcaster\"\n\n[[migrations]]\ntag = \"v1\"\nnew_classes = [\"Broadcaster\"]\n```\n\n## CloudEvents envelopes (contract v2)\n\nOn `contract: { version: \"v2\" }` the WebSocket endpoint moves to\n`/broadcast/v2` and every **data frame** is wrapped in a\n[CloudEvents 1.0](https://cloudevents.io) envelope at the Durable Object's\nsend boundary. Control frames (`pong`, `error`, `reauth_ok`) stay raw on both\nversions, and pinned-v1 projects keep the raw frames byte-identically.\n\n| v1 frame | CloudEvents `type` | `data` | extensions |\n|---|---|---|---|\n| `broadcast` (named invalidation) | the wire name verbatim | payload minus `version`/`reason` | `qbframe: \"broadcast\"`, `qbversion`, `qbreason` |\n| `postgres_changes` | `<project>.<table>.<insert\\|update\\|delete>` | `{ table, schema, eventType, new, old }` | `qbframe: \"postgres_changes\"` |\n| `view_changes` | `<project>.view.<viewName>.changed` | `{ view, rootId, delta }` | `qbframe: \"view_changes\"`, `qbseq` (the per-surface monotonic seq — your reconnect/gap-detection contract) |\n\nDiscriminate frames on the `qbframe` extension, **never** on payload keys —\nnamed-invalidation payloads are author-supplied maps, so a broadcast whose\npayload happens to carry `view`/`delta` or `table`/`eventType` keys must not\nbe mistaken for a system frame.\n\nA changeset's [`afterCommit`](/compiler/definitions/changesets#aftercommit--emit-a-realtime-signal-after-the-changeset-commits)\nbroadcast rides the **same `broadcast` frame** (the referenced typed event's\n`wireName` verbatim), so clients handle it exactly like any named invalidation —\none CloudEvent per aggregate write, carrying the mapped payload (e.g.\n`{ eventId, reservationId, occupantIds }`). Its optional root-row frame arrives\nas a normal `postgres_changes` frame on the table's room.\n\n```json\n{ \"specversion\": \"1.0\",\n \"id\": \"evt_9f2…\",\n \"source\": \"/broadcast/v2/websocket\",\n \"type\": \"event.mobile-bundle.changed\",\n \"time\": \"2026-07-20T12:00:00Z\",\n \"datacontenttype\": \"application/json\",\n \"qbframe\": \"broadcast\",\n \"qbversion\": 1, \"qbreason\": \"document.created\",\n \"data\": { \"eventId\": \"…\", \"documentId\": \"…\" } }\n```\n\nThe bundled CMS unwraps envelopes automatically. The full channel/message\ncatalog ships as `GET /asyncapi.json` (AsyncAPI 3.0), served under the same\nauth gating as `/openapi.json`. The catalog itself is not v2-only — any\nproject with realtime or webhooks serves it, on either contract version;\nwhat the pinned contract shapes is the message payload schemas it documents\n(raw frames on v1, the CloudEvents envelopes above on v2).\n\n## Cloudflare Only\n\nRealtime requires Cloudflare Durable Objects and is only available with the Cloudflare runtime.\n\n## See Also\n\n- [Durable Objects Setup](/stack/realtime/durable-objects) — Configuration, event formats, masking, and custom namespaces\n- [Masking](/compiler/definitions/masking) — Field masking configuration"
471
483
  },
472
484
  "stack/schedules": {
473
485
  "title": "Schedules (Cron)",
@@ -507,7 +519,7 @@ export const DOCS = {
507
519
  },
508
520
  "stack/webhooks/inbound": {
509
521
  "title": "Inbound Webhooks",
510
- "content": "Inbound webhooks allow external services (Stripe, Paddle, GitHub, etc.) to notify your API of events. Quickback generates endpoints that verify signatures, deduplicate events, and dispatch to your handler functions via a Cloudflare Queue.\n\n## Endpoint\n\n```\nPOST /webhooks/v1/inbound/:provider\n```\n\nThe `:provider` parameter identifies which service sent the webhook (e.g., `stripe`, `paddle`, `github`). Each provider has its own signature verification logic.\n\n## How It Works\n\n```\nExternal Service → POST /webhooks/v1/inbound/stripe\n │\n ├─ 1. Verify signature (HMAC-SHA256)\n ├─ 2. Parse event (provider-specific)\n ├─ 3. Deduplicate via externalId\n ├─ 4. Store in webhook_events table\n ├─ 5. Enqueue for async processing\n └─ 6. Return 200 OK immediately\n\n Queue Consumer\n │\n ├─ 1. Update status → 'processing'\n ├─ 2. Call registered handlers\n └─ 3. Update status → 'processed' or 'failed'\n```\n\nThe API returns `200 OK` immediately after enqueuing. Your handler logic runs asynchronously via the queue consumer, so external services don't time out waiting for your processing to complete.\n\n## Registering Handlers\n\nUse `onWebhookEvent()` in your action code to register handlers for specific events:\n\n```typescript\nonWebhookEvent(\"stripe:checkout.session.completed\", async (ctx) => {\n const { type, data, event, provider, env } = ctx;\n // ctx.event is the full Stripe envelope; ctx.data is event.data.object\n await createSubscription(data, env);\n});\n\n// Wildcard — handle all events from a provider\nonWebhookEvent(\"stripe:*\", async (ctx) => {\n console.log(`Received ${ctx.type} from ${ctx.provider}`);\n});\n```\n\n**Handler context:**\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `type` | `string` | Event type (e.g., `checkout.session.completed`) |\n| `data` | `unknown` | The convenience slice of the payload. For Stripe this is `event.data.object`. |\n| `event` | `unknown` | The **full event envelope**, exactly as the provider sent it — nothing dropped. For Stripe this carries `account` (Connect connected-account id), `id`, `livemode`, `api_version`, `request`, etc. |\n| `provider` | `string` | Provider name (e.g., `stripe`) |\n| `env` | `CloudflareBindings` | Cloudflare environment bindings |\n\nFor `stripe:` patterns the context is typed automatically: `ctx.event` is a\n`StripeWebhookEvent` and `ctx.data` is its `data.object`, so `ctx.event.account`,\n`ctx.event.id`, and `ctx.event.livemode` are all typed with no cast.\n\n```typescript\nonWebhookEvent(\"stripe:invoice.paid\", async (ctx) => {\n ctx.event.account; // string | undefined — the acct_… (Connect)\n ctx.event.id; // string — evt_…\n ctx.event.livemode; // boolean\n ctx.data; // event.data.object (Record<string, unknown>)\n});\n```\n\n`data.object` is an open record. Cast it when you need inner-field typing:\n\n```typescript\nconst session = ctx.data as import(\"stripe\").Stripe.Checkout.Session;\n```\n\n**Execution order:**\n1. Specific handlers run first (exact match on event type)\n2. Wildcard handlers run after\n3. All matching handlers run in parallel\n4. If any handler throws, the message is retried\n\n## Signature Verification\n\nEach provider verifies signatures differently. The secret is read from an environment variable.\n\n### Stripe\n\n**Environment variable:** `STRIPE_WEBHOOK_SECRET`\n\nStripe uses HMAC-SHA256 with a timestamp-based signature:\n\n```\nStripe-Signature: t=1614556800,v1=abc123...\n```\n\nThe signed payload is `<timestamp>.<raw_body>`. Verification checks:\n- HMAC matches\n- Timestamp is within 5 minutes (prevents replay attacks)\n\n#### Stripe Connect\n\nThe single-secret model is exactly what a Connect platform needs. With Standard\nconnected accounts and direct charges, each of your customers connects their own\nStripe account, and **one** webhook endpoint on your platform receives events\nfrom **all** connected accounts — every delivery signed with your **one**\nplatform signing secret.\n\n1. In the Stripe Dashboard, add a webhook endpoint pointing at\n `https://<your-api>/webhooks/v1/inbound/stripe` and enable **\"Listen to\n events on Connected accounts.\"**\n2. Set that endpoint's signing secret as `STRIPE_WEBHOOK_SECRET` (one secret\n covers every connected account — no per-account configuration).\n\nTo know **which connected account** an event belongs to, read the top-level\n`event.account` (an `acct_…` id) off the envelope via `ctx.event.account`. It is\n**not** inside `event.data.object`.\n\n```typescript\nonWebhookEvent(\"stripe:checkout.session.completed\", async (ctx) => {\n const connectedAccount = ctx.event.account; // acct_… — which organizer\n if (!connectedAccount) return; // platform-account event, ignore\n\n // Route to the org that owns this connected account, and validate the match.\n const org = await findOrgByStripeAccount(connectedAccount, ctx.env);\n if (!org) throw new Error(`Unknown connected account ${connectedAccount}`);\n\n await fulfillOrder(ctx.data, org, ctx.env);\n});\n```\n\n`ctx.data` remains `event.data.object` (the Checkout Session) for convenience;\n`ctx.event` gives you the rest of the envelope — `account`, `id`, `livemode`,\n`api_version`, `request` — so nothing about the delivery is lost.\n\n### Custom Providers\n\nProviders implement this interface:\n\n```typescript\ninterface InboundProvider {\n name: string;\n verifySignature(payload: string, signature: string, secret: string): Promise<boolean>;\n parseEvent(payload: string): {\n type: string;\n data: unknown; // convenience slice (e.g. Stripe's data.object)\n externalId?: string; // provider event id, for idempotency\n envelope?: unknown; // full event envelope, when available\n };\n}\n```\n\n## Idempotency\n\nEvents are deduplicated on the tuple `(provider, externalId)` (e.g., Stripe's `event.id`). The `webhook_events` table carries a **unique index** on this pair, and inbound delivery uses `INSERT … ON CONFLICT DO NOTHING` so concurrent deliveries collapse deterministically:\n\n- The first delivery to win the race inserts the row, enqueues processing, and returns `{ received: true, eventId }`.\n- Any concurrent delivery with the same `(provider, externalId)` short-circuits and returns `{ received: true, duplicate: true }` — the queue is **never** sent the duplicate, so handlers run exactly once.\n\nEvents without an `externalId` (NULL) are not deduplicated. SQLite treats NULLs as distinct in unique indexes, so providers that don't supply a stable event ID continue to insert one row per delivery.\n\n### Migrating an existing deployment\n\nThe unique index was added in v0.10.x. Existing deployments may have duplicate rows from before the constraint existed; drizzle-kit's migration will fail until they are cleaned up. Run this once before applying the migration:\n\n```sql\nDELETE FROM webhook_events\nWHERE rowid NOT IN (\n SELECT MIN(rowid) FROM webhook_events\n WHERE external_id IS NOT NULL\n GROUP BY provider, external_id\n);\n```\n\nThis keeps the earliest row for each `(provider, external_id)` pair and discards the duplicates.\n\n## Database Schema\n\nInbound events are stored in the `webhook_events` table:\n\n| Column | Type | Description |\n|--------|------|-------------|\n| `id` | text | Primary key (`whe_<uuid>`) |\n| `provider` | text | Provider name |\n| `eventType` | text | Event type from provider |\n| `externalId` | text | Provider's event ID (for deduplication) |\n| `payload` | text | Raw JSON payload |\n| `status` | text | `received`, `processing`, `processed`, `failed` |\n| `attempts` | integer | Processing attempt count |\n| `processedAt` | timestamp | When successfully processed |\n| `error` | text | Error message if failed |\n| `createdAt` | timestamp | When received |\n\n## Admin Routes\n\nTwo admin-only routes are generated for monitoring inbound webhooks:\n\n### List Events\n\n```\nGET /webhooks/v1/inbound/events\n```\n\nReturns recent inbound events with their status. Requires admin role.\n\n### Retry Failed Event\n\n```\nPOST /webhooks/v1/inbound/events/:id/retry\n```\n\nRe-queues a failed event for processing. Requires admin role.\n\n## Error Handling\n\n- **Invalid signature** — Returns `401 Unauthorized`, event not stored\n- **Handler failure** — Event marked as `failed`, message retried (up to 3 times via queue)\n- **All retries exhausted** — Event remains in `failed` status; use the admin retry endpoint to re-process manually\n\n## Configuration\n\nWebhooks are enabled by setting `webhooksBinding` in your database config:\n\n```typescript\ndatabase: defineDatabase(\"cloudflare-d1\", {\n binding: \"DB\",\n webhooksBinding: \"WEBHOOKS_DB\",\n})\n```\n\nSet the provider secret as a Wrangler secret:\n\n```bash\nwrangler secret put STRIPE_WEBHOOK_SECRET\n```\n\n## See Also\n\n- [Outbound Webhooks](/stack/webhooks/outbound) — Send webhooks when data changes\n- [Queues](/stack/queues) — Background processing infrastructure"
522
+ "content": "Inbound webhooks allow external services (Stripe, Paddle, GitHub, etc.) to notify your API of events. Quickback generates endpoints that verify signatures, deduplicate events, and dispatch to your handler functions via a Cloudflare Queue.\n\n## Endpoint\n\n```\nPOST /webhooks/v1/inbound/:provider\n```\n\nThe `:provider` parameter identifies which service sent the webhook (e.g., `stripe`, `paddle`, `github`). Each provider has its own signature verification logic.\n\n## How It Works\n\n```\nExternal Service → POST /webhooks/v1/inbound/stripe\n │\n ├─ 1. Verify signature (HMAC-SHA256)\n ├─ 2. Parse event (provider-specific)\n ├─ 3. Deduplicate via externalId\n ├─ 4. Store in webhook_events table\n ├─ 5. Enqueue for async processing\n └─ 6. Return 200 OK immediately\n\n Queue Consumer\n │\n ├─ 1. Update status → 'processing'\n ├─ 2. Call registered handlers\n └─ 3. Update status → 'processed' or 'failed'\n```\n\nThe API returns `200 OK` immediately after enqueuing. Your handler logic runs asynchronously via the queue consumer, so external services don't time out waiting for your processing to complete.\n\n## Registering Handlers\n\nUse `onWebhookEvent()` in your action code to register handlers for specific events:\n\n```typescript\nonWebhookEvent(\"stripe:checkout.session.completed\", async (ctx) => {\n const { type, data, event, provider, env } = ctx;\n // ctx.event is the full Stripe envelope; ctx.data is event.data.object\n await createSubscription(data, env);\n});\n\n// Wildcard — handle all events from a provider\nonWebhookEvent(\"stripe:*\", async (ctx) => {\n console.log(`Received ${ctx.type} from ${ctx.provider}`);\n});\n```\n\n**Handler context:**\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `type` | `string` | Event type (e.g., `checkout.session.completed`) |\n| `data` | `unknown` | The convenience slice of the payload. For Stripe this is `event.data.object`. |\n| `event` | `unknown` | The **full event envelope**, exactly as the provider sent it — nothing dropped. For Stripe this carries `account` (Connect connected-account id), `id`, `livemode`, `api_version`, `request`, etc. |\n| `provider` | `string` | Provider name (e.g., `stripe`) |\n| `env` | `CloudflareBindings` | Cloudflare environment bindings |\n\nFor `stripe:` patterns the context is typed automatically: `ctx.event` is a\n`StripeWebhookEvent` and `ctx.data` is its `data.object`, so `ctx.event.account`,\n`ctx.event.id`, and `ctx.event.livemode` are all typed with no cast.\n\n```typescript\nonWebhookEvent(\"stripe:invoice.paid\", async (ctx) => {\n ctx.event.account; // string | undefined — the acct_… (Connect)\n ctx.event.id; // string — evt_…\n ctx.event.livemode; // boolean\n ctx.data; // event.data.object (Record<string, unknown>)\n});\n```\n\n`data.object` is an open record. Cast it when you need inner-field typing:\n\n```typescript\nconst session = ctx.data as import(\"stripe\").Stripe.Checkout.Session;\n```\n\n**Execution order:**\n1. Specific handlers run first (exact match on event type)\n2. Wildcard handlers run after\n3. All matching handlers run in parallel\n4. If any handler throws, the message is retried\n\n## Signature Verification\n\nEach provider verifies signatures differently. The secret is read from an environment variable.\n\n### Stripe\n\n**Environment variable:** `STRIPE_WEBHOOK_SECRET`\n\nStripe uses HMAC-SHA256 with a timestamp-based signature:\n\n```\nStripe-Signature: t=1614556800,v1=abc123...\n```\n\nThe signed payload is `<timestamp>.<raw_body>`. Verification checks:\n- HMAC matches\n- Timestamp is within 5 minutes (prevents replay attacks)\n\n#### Stripe Connect\n\nThe single-secret model is exactly what a Connect platform needs. With Standard\nconnected accounts and direct charges, each of your customers connects their own\nStripe account, and **one** webhook endpoint on your platform receives events\nfrom **all** connected accounts — every delivery signed with your **one**\nplatform signing secret.\n\n1. In the Stripe Dashboard, add a webhook endpoint pointing at\n `https://<your-api>/webhooks/v1/inbound/stripe` and enable **\"Listen to\n events on Connected accounts.\"**\n2. Set that endpoint's signing secret as `STRIPE_WEBHOOK_SECRET` (one secret\n covers every connected account — no per-account configuration).\n\nTo know **which connected account** an event belongs to, read the top-level\n`event.account` (an `acct_…` id) off the envelope via `ctx.event.account`. It is\n**not** inside `event.data.object`.\n\n```typescript\nonWebhookEvent(\"stripe:checkout.session.completed\", async (ctx) => {\n const connectedAccount = ctx.event.account; // acct_… — which organizer\n if (!connectedAccount) return; // platform-account event, ignore\n\n // Route to the org that owns this connected account, and validate the match.\n const org = await findOrgByStripeAccount(connectedAccount, ctx.env);\n if (!org) throw new Error(`Unknown connected account ${connectedAccount}`);\n\n await fulfillOrder(ctx.data, org, ctx.env);\n});\n```\n\n`ctx.data` remains `event.data.object` (the Checkout Session) for convenience;\n`ctx.event` gives you the rest of the envelope — `account`, `id`, `livemode`,\n`api_version`, `request` — so nothing about the delivery is lost.\n\n### Custom Providers\n\nProviders implement this interface:\n\n```typescript\ninterface InboundProvider {\n name: string;\n verifySignature(payload: string, signature: string, secret: string): Promise<boolean>;\n parseEvent(payload: string): {\n type: string;\n data: unknown; // convenience slice (e.g. Stripe's data.object)\n externalId?: string; // provider event id, for idempotency\n envelope?: unknown; // full event envelope, when available\n };\n}\n```\n\n## Idempotency\n\nEvents are deduplicated on the tuple `(provider, externalId)` (e.g., Stripe's `event.id`). The `webhook_events` table carries a **unique index** on this pair, and inbound delivery uses `INSERT … ON CONFLICT DO NOTHING` so concurrent deliveries collapse deterministically:\n\n- The first delivery to win the race inserts the row, enqueues processing, and returns `{ received: true, eventId }`.\n- Any concurrent delivery with the same `(provider, externalId)` short-circuits and returns `{ received: true, duplicate: true }` — the queue is **never** sent the duplicate, so handlers run exactly once.\n\nEvents without an `externalId` (NULL) are not deduplicated. SQLite treats NULLs as distinct in unique indexes, so providers that don't supply a stable event ID continue to insert one row per delivery.\n\n### Migrating an existing deployment\n\nThe unique index was added in v0.10.x. Existing deployments may have duplicate rows from before the constraint existed; drizzle-kit's migration will fail until they are cleaned up. Run this once before applying the migration:\n\n```sql\nDELETE FROM webhook_events\nWHERE rowid NOT IN (\n SELECT MIN(rowid) FROM webhook_events\n WHERE external_id IS NOT NULL\n GROUP BY provider, external_id\n);\n```\n\nThis keeps the earliest row for each `(provider, external_id)` pair and discards the duplicates.\n\n## Database Schema\n\nInbound events are stored in the `webhook_events` table:\n\n| Column | Type | Description |\n|--------|------|-------------|\n| `id` | text | Primary key (`whe_<uuid>`) |\n| `provider` | text | Provider name |\n| `eventType` | text | Event type from provider |\n| `externalId` | text | Provider's event ID (for deduplication) |\n| `payload` | text | Raw JSON payload |\n| `status` | text | `received`, `processing`, `processed`, `failed` |\n| `attempts` | integer | Processing attempt count |\n| `processedAt` | timestamp | When successfully processed |\n| `error` | text | Error message if failed |\n| `createdAt` | timestamp | When received |\n\n## Admin Routes\n\nTwo admin-only routes are generated for monitoring inbound webhooks:\n\n### List Events\n\n```\nGET /webhooks/v1/inbound/events\n```\n\nReturns recent inbound events with their status. Requires admin role.\n\n### Retry Failed Event\n\n```\nPOST /webhooks/v1/inbound/events/:id/retry\n```\n\nRe-queues a failed event for processing. Requires admin role.\n\n## Error Handling\n\n- **Invalid signature** — Returns `401 Unauthorized`, event not stored\n- **Handler failure** — Event marked as `failed`, message retried (up to 3 times via queue)\n- **All retries exhausted** — Event remains in `failed` status; use the admin retry endpoint to re-process manually\n\n## Configuration\n\nWebhooks are enabled by setting `webhooksBinding` in your database config:\n\n```typescript\ndatabase: defineDatabase(\"cloudflare-d1\", {\n binding: \"DB\",\n webhooksBinding: \"WEBHOOKS_DB\",\n})\n```\n\nSet the provider secret as a Wrangler secret:\n\n```bash\nwrangler secret put STRIPE_WEBHOOK_SECRET\n```\n\n## See Also\n\n- [Outbound Webhooks](/stack/webhooks/outbound) — Send webhooks when data changes\n- [Queues](/stack/queues) — Background processing infrastructure\n\n## Verified webhook actions (`webhook:` on defineAction)\n\nFor gateways that should hit a **custom action** rather than the queued\n`/webhooks/v1/inbound/:provider` pipeline, declare verification on the action\nitself. Verification runs **before** JSON parse, input validation, and access\nevaluation, over the raw request bytes — and it is additive to the access\ngate (a PUBLIC webhook action keeps its public-audit block).\n\n```ts title=\"quickback/features/comms/actions/sesDeliveryWebhook.ts\"\nexport default defineAction({\n path: \"/comms/hooks/delivery\",\n method: \"POST\",\n access: { roles: [\"PUBLIC\"] },\n webhook: {\n verify: \"standard-webhooks\", // webhook-id / webhook-timestamp / webhook-signature\n secretEnv: \"SES_WEBHOOK_SECRET\", // env binding, validated at compile time\n tolerance: 300, // seconds (default 300)\n },\n input: z.object({ messageId: z.string(), event: z.string() }),\n execute: async ({ input }) => { /* ... */ },\n});\n```\n\nFor gateways speaking `sha256=`-hex HMAC instead of Standard Webhooks:\n\n```ts\nwebhook: {\n verify: {\n scheme: \"hmac-sha256\",\n header: \"X-Signature\",\n prefix: \"sha256=\",\n timestampHeader: \"X-Webhook-Timestamp\",\n signedContent: \"timestamp.body\", // MAC covers `${timestamp}.${rawBody}`\n tolerance: 300,\n },\n secretEnv: \"WEBHOOK_SIGNING_SECRET\",\n}\n```\n\n**Replay semantics — read this before choosing `signedContent`:** a tolerance\nwindow only closes replay when the timestamp is *inside* the signed content.\nWith `signedContent: \"body\"` the MAC covers raw bytes only, so a captured\nrequest can be replayed forever with a fresh timestamp header — which is why\nthe compiler **rejects** `tolerance`/`timestampHeader` on body-only schemes\ninstead of pretending they help. Pair body-only receivers with\n[`Idempotency-Key`](/stack/api-contract) or gateway-event-id dedupe.\n\nFor AWS SNS (SES/SMS event topics) — asymmetric X.509 verification, no shared\nsecret:\n\n```ts\nwebhook: {\n verify: {\n scheme: \"aws-sns\",\n topicArnsEnv: \"AWS_SES_SNS_TOPIC_ARNS\", // comma-separated allowlist (REQUIRED)\n // autoConfirmSubscription: true (default) — verified SubscriptionConfirmation\n // handshakes are completed and short-circuited; your action never runs for them.\n },\n}\n```\n\n`topicArnsEnv` is **compile-required**: without a TopicArn allowlist the\nsignature check proves only \"AWS signed it\" — any AWS account could create\nits own topic, subscribe your endpoint (auto-confirmed by the handshake),\nand deliver arbitrary messages that pass verification. The compiler refuses\nthe declaration rather than defaulting to accept-any-topic.\n\nThe signing certificate URL and SubscribeURL are validated against the\n`sns.<region>.amazonaws.com` allowlist before any fetch; a topic allowlist\nthat resolves empty at runtime fails closed (500). The signed `Timestamp`\nis bounded to a 1-hour tolerance window — it sits *inside* the signed\ncanonical string, so this is a real replay bound (a captured envelope stops\nreplaying), while staying generous enough for SNS's own delivery retries,\nwhich re-send the original signed envelope.\n\n**Fail-closed runtime posture for every scheme:** an unset secret env is a\n500 rejection — never a verify-skip; any signature failure is a 401 Problem\nbefore the body is ever parsed."
511
523
  },
512
524
  "stack/webhooks": {
513
525
  "title": "Webhooks",
@@ -515,7 +527,7 @@ export const DOCS = {
515
527
  },
516
528
  "stack/webhooks/outbound": {
517
529
  "title": "Outbound Webhooks",
518
- "content": "Outbound webhooks notify external services when events happen in your API. Users register webhook endpoints, subscribe to event types, and receive signed HTTP POST requests when events are emitted.\n\n## Overview\n\nOutbound webhooks are a multi-step system:\n\n1. **Users register endpoints** via the REST API\n2. **Your code emits events** using `emitWebhookEvent()`\n3. **Quickback queues deliveries** for each matching endpoint\n4. **The queue consumer delivers** with retry and exponential backoff\n5. **Payloads are signed** with HMAC-SHA256 (Stripe-compatible format)\n\n## Emitting Events\n\nCall `emitWebhookEvent()` in your actions or custom routes:\n\n```typescript\n\n// After creating a user\nconst newUser = await db.insert(users).values(data).returning();\n\nawait emitWebhookEvent(\n \"user.created\",\n newUser[0],\n { organizationId: ctx.activeOrgId },\n env\n);\n```\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `eventType` | `string` | Event name (e.g., `user.created`) |\n| `payload` | `unknown` | Event data (auto-wrapped with metadata) |\n| `options` | `object` | `{ organizationId?, userId? }` — scope for endpoint matching |\n| `env` | `CloudflareBindings` | Cloudflare environment bindings |\n\n**Note:** The compiler does NOT auto-emit events after CRUD operations. You must call `emitWebhookEvent()` explicitly where you want webhooks triggered.\n\n## Event Types\n\nQuickback provides recommended event naming conventions:\n\n| Category | Events |\n|----------|--------|\n| User | `user.created`, `user.updated`, `user.deleted` |\n| Subscription | `subscription.created`, `subscription.updated`, `subscription.cancelled`, `subscription.renewed` |\n| Organization | `organization.created`, `organization.updated`, `organization.deleted`, `organization.member_added`, `organization.member_removed` |\n| File | `file.uploaded`, `file.deleted` |\n\nYou can emit any custom event type — these are conventions, not restrictions.\n\n## Payload Format\n\nThe emitted payload is wrapped automatically:\n\n```json\n{\n \"type\": \"user.created\",\n \"data\": {\n \"id\": \"usr_abc123\",\n \"name\": \"Jane Doe\",\n \"email\": \"jane@example.com\"\n },\n \"createdAt\": \"2025-01-15T10:00:00.000Z\"\n}\n```\n\n## Payload Signing\n\nEvery delivery is signed with HMAC-SHA256 using the endpoint's secret. The signature format is Stripe-compatible:\n\n```\nX-Webhook-Signature: t=1705312800,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd\n```\n\n**Signed payload:** `<timestamp>.<json_body>`\n\n**Additional headers:**\n\n| Header | Description |\n|--------|-------------|\n| `X-Webhook-Signature` | `t=<timestamp>,v1=<hmac>` |\n| `X-Webhook-Event` | Event type (e.g., `user.created`) |\n| `X-Webhook-Delivery` | Delivery ID for tracking |\n| `Content-Type` | `application/json` |\n\n### Verifying Signatures (Consumer Side)\n\n```typescript\n\nfunction verifyWebhook(payload: string, signature: string, secret: string): boolean {\n const [tPart, v1Part] = signature.split(',');\n const timestamp = tPart.replace('t=', '');\n const expectedSig = v1Part.replace('v1=', '');\n\n // Check timestamp (5 minute tolerance)\n const age = Date.now() / 1000 - parseInt(timestamp);\n if (age > 300) return false;\n\n const signed = `${timestamp}.${payload}`;\n const computed = createHmac('sha256', secret).update(signed).digest('hex');\n return timingSafeEqual(Buffer.from(computed), Buffer.from(expectedSig));\n}\n```\n\n## Endpoint Management API\n\n### Register an Endpoint\n\n```\nPOST /webhooks/v1/endpoints\n```\n\n```json\n{\n \"name\": \"My Integration\",\n \"url\": \"https://example.com/webhook\",\n \"events\": [\"user.created\", \"subscription.*\"]\n}\n```\n\n**Response (201):**\n\n```json\n{\n \"id\": \"wep_abc123\",\n \"name\": \"My Integration\",\n \"url\": \"https://example.com/webhook\",\n \"secret\": \"whsec_a1b2c3d4...\",\n \"events\": [\"user.created\", \"subscription.*\"],\n \"enabled\": true,\n \"createdAt\": \"2025-01-15T10:00:00.000Z\"\n}\n```\n\nThe `secret` is only returned on creation. Store it securely.\n\n### Event Pattern Matching\n\nEndpoints subscribe to events using patterns:\n\n| Pattern | Matches |\n|---------|---------|\n| `user.created` | Exact match only |\n| `user.*` | All user events |\n| `*` | All events |\n\n### Other Endpoints\n\n| Method | Path | Description |\n|--------|------|-------------|\n| `GET` | `/webhooks/v1/endpoints` | List your endpoints |\n| `GET` | `/webhooks/v1/endpoints/:id` | Get endpoint details (secret masked) |\n| `PATCH` | `/webhooks/v1/endpoints/:id` | Update endpoint (name, url, events, enabled) |\n| `DELETE` | `/webhooks/v1/endpoints/:id` | Delete endpoint |\n| `GET` | `/webhooks/v1/endpoints/:id/deliveries` | List delivery attempts |\n| `POST` | `/webhooks/v1/endpoints/:id/test` | Send a test event |\n| `POST` | `/webhooks/v1/endpoints/:id/rotate-secret` | Generate a new signing secret |\n| `GET` | `/webhooks/v1/events` | List available event types |\n\n### Access Control\n\nEndpoints are scoped by `userId` or `organizationId`. Users can only manage their own endpoints. When emitting events, only endpoints matching the event's scope receive deliveries.\n\n### URL Validation (anti-SSRF)\n\nRegistered URLs are validated at registration and again before each delivery attempt. The default policy rejects:\n\n- Any scheme other than `https:` (matches Stripe, GitHub, and Slack webhook conventions)\n- Loopback hosts (`localhost`, `127.0.0.1`, `::1`)\n- Cloud metadata endpoints (`169.254.169.254`, `metadata.google.internal`)\n- RFC 1918 private ranges (`10/8`, `172.16/12`, `192.168/16`), `169.254/16`, and `0.0.0.0/8`\n- Hosts ending in `.internal` or `.local`\n\nPlaintext `http:` is rejected by default. To allow `http:` (e.g. for a self-hosted dev environment without TLS), set `webhookAllowInsecure: true` on the database provider config:\n\n```ts\n// quickback.config.ts\nproviders: {\n database: {\n name: 'cloudflare-d1',\n config: {\n webhooksBinding: 'WEBHOOKS_DB',\n webhookAllowInsecure: true, // dev/self-host only\n },\n },\n}\n```\n\nThe other validation rules (private/loopback/metadata blocking) still apply when this flag is on.\n\n### Redirect Handling\n\nOutbound delivery uses `redirect: \"manual\"` — the runtime refuses to follow 3xx responses. A redirect is treated as a **terminal** delivery failure (no retry), and the redirect target is recorded in the `responseBody`. This protects signed payloads from being bounced to a different host than the one the user registered.\n\nIf your endpoint legitimately needs to relocate, update the `url` on the endpoint record instead of relying on a 301/302.\n\n## Delivery and Retry\n\nDeliveries are processed asynchronously via a Cloudflare Queue.\n\n**Success:** HTTP 2xx response marks the delivery as `delivered`.\n\n**Failure:** HTTP 4xx/5xx or network errors trigger retries with exponential backoff:\n\n| Attempt | Delay |\n|---------|-------|\n| 1st retry | ~2 seconds |\n| 2nd retry | ~4 seconds |\n| 3rd retry (final) | ~8 seconds |\n\nMaximum backoff is capped at 1 hour. After 3 failed attempts, the delivery is marked as `failed`.\n\n**Disabled endpoints:** If an endpoint is disabled or deleted between emission and delivery, the delivery is marked as failed immediately.\n\n### Delivery Record\n\nEach delivery attempt is tracked in the `webhook_deliveries` table:\n\n| Field | Description |\n|-------|-------------|\n| `status` | `pending`, `delivered`, or `failed` |\n| `attempts` | Number of delivery attempts |\n| `responseStatus` | HTTP status from last attempt |\n| `responseBody` | Response body (truncated to 1000 chars) |\n| `lastAttemptAt` | Timestamp of last attempt |\n| `nextRetryAt` | When the next retry will occur |\n\n## Infrastructure\n\n### Queue Configuration\n\nOutbound webhooks use a dedicated Cloudflare Queue:\n\n```toml\n# Auto-generated in wrangler.toml\n[[queues.producers]]\nqueue = \"my-app-webhooks-queue\"\nbinding = \"WEBHOOKS_QUEUE\"\n\n[[queues.consumers]]\nqueue = \"my-app-webhooks-queue\"\nmax_batch_size = 10\nmax_batch_timeout = 30\nmax_retries = 3\ndead_letter_queue = \"my-app-webhooks-dlq\"\n```\n\n### Dead Letter Queue\n\nFailed webhook deliveries (after all retries) are sent to a dead letter queue for investigation:\n\n```toml\n[[queues.consumers]]\nqueue = \"my-app-webhooks-dlq\"\nmax_batch_size = 1\n```\n\n## Enabling Webhooks\n\nSet `webhooksBinding` in your database provider config:\n\n```typescript\ndatabase: defineDatabase(\"cloudflare-d1\", {\n binding: \"DB\",\n webhooksBinding: \"WEBHOOKS_DB\",\n})\n```\n\nThis generates the webhook database schema, routes, queue consumer, and all supporting code.\n\n### On Neon (Postgres)\n\nWebhooks are supported on the `neon` provider too. `webhooksBinding` acts as a\npure enable flag — there is no separate webhooks database. The webhook tables\nlive in a dedicated `webhooks` Postgres schema of your single Neon database,\ncreated by the standard drizzle migration set, and are locked down by an RLS\npolicy so only the Worker's internal service-role handle can touch them:\n\n```typescript\ndatabase: defineDatabase(\"neon\", {\n connectionMode: \"http\", // required for webhooks\n webhooksBinding: \"WEBHOOKS_DB\", // enable flag; no D1 binding is emitted\n // queue names stay configurable on any provider:\n webhooksQueueName: \"my-app-webhooks-queue\",\n webhooksDlqName: \"my-app-webhooks-dlq\",\n})\n```\n\nThe D1-only keys `webhooksDatabaseId` / `webhooksDatabaseName` are rejected at\ncompile time on Neon, and webhooks require `connectionMode: 'http'` (the\nCloudflare default). Queue wiring (`WEBHOOKS_QUEUE`, the consumer, and the\ndead letter queue) is identical across providers.\n\n## See Also\n\n- [Inbound Webhooks](/stack/webhooks/inbound) — Receive webhooks from external services\n- [Queues](/stack/queues) — Background processing infrastructure"
530
+ "content": "Outbound webhooks notify external services when events happen in your API. Users register webhook endpoints, subscribe to event types, and receive signed HTTP POST requests when events are emitted.\n\n## Overview\n\nOutbound webhooks are a multi-step system:\n\n1. **Users register endpoints** via the REST API\n2. **Your code emits events** using `emitWebhookEvent()`\n3. **Quickback queues deliveries** for each matching endpoint\n4. **The queue consumer delivers** with retry and exponential backoff\n5. **Payloads are signed** with HMAC-SHA256 (Stripe-compatible format)\n\n## Emitting Events\n\nCall `emitWebhookEvent()` in your actions or custom routes:\n\n```typescript\n\n// After creating a user\nconst newUser = await db.insert(users).values(data).returning();\n\nawait emitWebhookEvent(\n \"user.created\",\n newUser[0],\n { organizationId: ctx.activeOrgId },\n env\n);\n```\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `eventType` | `string` | Event name (e.g., `user.created`) |\n| `payload` | `unknown` | Event data (auto-wrapped with metadata) |\n| `options` | `object` | `{ organizationId?, userId? }` — scope for endpoint matching |\n| `env` | `CloudflareBindings` | Cloudflare environment bindings |\n\n**Note:** The compiler does NOT auto-emit events after CRUD operations. You must call `emitWebhookEvent()` explicitly where you want webhooks triggered.\n\n## Event Types\n\nQuickback provides recommended event naming conventions:\n\n| Category | Events |\n|----------|--------|\n| User | `user.created`, `user.updated`, `user.deleted` |\n| Subscription | `subscription.created`, `subscription.updated`, `subscription.cancelled`, `subscription.renewed` |\n| Organization | `organization.created`, `organization.updated`, `organization.deleted`, `organization.member_added`, `organization.member_removed` |\n| File | `file.uploaded`, `file.deleted` |\n\nYou can emit any custom event type — these are conventions, not restrictions.\n\n## Payload Format\n\nThe emitted payload is wrapped automatically:\n\n```json\n{\n \"type\": \"user.created\",\n \"data\": {\n \"id\": \"usr_abc123\",\n \"name\": \"Jane Doe\",\n \"email\": \"jane@example.com\"\n },\n \"createdAt\": \"2025-01-15T10:00:00.000Z\"\n}\n```\n\n## Payload Signing\n\nEvery delivery is signed with HMAC-SHA256 using the endpoint's secret. The signature format is Stripe-compatible:\n\n```\nX-Webhook-Signature: t=1705312800,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd\n```\n\n**Signed payload:** `<timestamp>.<json_body>`\n\n**Additional headers:**\n\n| Header | Description |\n|--------|-------------|\n| `X-Webhook-Signature` | `t=<timestamp>,v1=<hmac>` |\n| `X-Webhook-Event` | Event type (e.g., `user.created`) |\n| `X-Webhook-Delivery` | Delivery ID for tracking |\n| `Content-Type` | `application/json` |\n\n### Verifying Signatures (Consumer Side)\n\n```typescript\n\nfunction verifyWebhook(payload: string, signature: string, secret: string): boolean {\n const [tPart, v1Part] = signature.split(',');\n const timestamp = tPart.replace('t=', '');\n const expectedSig = v1Part.replace('v1=', '');\n\n // Check timestamp (5 minute tolerance)\n const age = Date.now() / 1000 - parseInt(timestamp);\n if (age > 300) return false;\n\n const signed = `${timestamp}.${payload}`;\n const computed = createHmac('sha256', secret).update(signed).digest('hex');\n return timingSafeEqual(Buffer.from(computed), Buffer.from(expectedSig));\n}\n```\n\n## Endpoint Management API\n\n### Register an Endpoint\n\n```\nPOST /webhooks/v1/endpoints\n```\n\n```json\n{\n \"name\": \"My Integration\",\n \"url\": \"https://example.com/webhook\",\n \"events\": [\"user.created\", \"subscription.*\"]\n}\n```\n\n**Response (201):**\n\n```json\n{\n \"id\": \"wep_abc123\",\n \"name\": \"My Integration\",\n \"url\": \"https://example.com/webhook\",\n \"secret\": \"whsec_a1b2c3d4...\",\n \"events\": [\"user.created\", \"subscription.*\"],\n \"enabled\": true,\n \"createdAt\": \"2025-01-15T10:00:00.000Z\"\n}\n```\n\nThe `secret` is only returned on creation. Store it securely.\n\n### Event Pattern Matching\n\nEndpoints subscribe to events using patterns:\n\n| Pattern | Matches |\n|---------|---------|\n| `user.created` | Exact match only |\n| `user.*` | All user events |\n| `*` | All events |\n\n### Other Endpoints\n\n| Method | Path | Description |\n|--------|------|-------------|\n| `GET` | `/webhooks/v1/endpoints` | List your endpoints |\n| `GET` | `/webhooks/v1/endpoints/:id` | Get endpoint details (secret masked) |\n| `PATCH` | `/webhooks/v1/endpoints/:id` | Update endpoint (name, url, events, enabled) |\n| `DELETE` | `/webhooks/v1/endpoints/:id` | Delete endpoint |\n| `GET` | `/webhooks/v1/endpoints/:id/deliveries` | List delivery attempts |\n| `POST` | `/webhooks/v1/endpoints/:id/test` | Send a test event |\n| `POST` | `/webhooks/v1/endpoints/:id/rotate-secret` | Generate a new signing secret |\n| `GET` | `/webhooks/v1/events` | List available event types |\n\n### Access Control\n\nEndpoints are scoped by `userId` or `organizationId`. Users can only manage their own endpoints. When emitting events, only endpoints matching the event's scope receive deliveries.\n\n### URL Validation (anti-SSRF)\n\nRegistered URLs are validated at registration and again before each delivery attempt. The default policy rejects:\n\n- Any scheme other than `https:` (matches Stripe, GitHub, and Slack webhook conventions)\n- Loopback hosts (`localhost`, `127.0.0.1`, `::1`)\n- Cloud metadata endpoints (`169.254.169.254`, `metadata.google.internal`)\n- RFC 1918 private ranges (`10/8`, `172.16/12`, `192.168/16`), `169.254/16`, and `0.0.0.0/8`\n- Hosts ending in `.internal` or `.local`\n\nPlaintext `http:` is rejected by default. To allow `http:` (e.g. for a self-hosted dev environment without TLS), set `webhookAllowInsecure: true` on the database provider config:\n\n```ts\n// quickback.config.ts\nproviders: {\n database: {\n name: 'cloudflare-d1',\n config: {\n webhooksBinding: 'WEBHOOKS_DB',\n webhookAllowInsecure: true, // dev/self-host only\n },\n },\n}\n```\n\nThe other validation rules (private/loopback/metadata blocking) still apply when this flag is on.\n\n### Redirect Handling\n\nOutbound delivery uses `redirect: \"manual\"` — the runtime refuses to follow 3xx responses. A redirect is treated as a **terminal** delivery failure (no retry), and the redirect target is recorded in the `responseBody`. This protects signed payloads from being bounced to a different host than the one the user registered.\n\nIf your endpoint legitimately needs to relocate, update the `url` on the endpoint record instead of relying on a 301/302.\n\n## Delivery and Retry\n\nDeliveries are processed asynchronously via a Cloudflare Queue.\n\n**Success:** HTTP 2xx response marks the delivery as `delivered`.\n\n**Failure:** HTTP 4xx/5xx or network errors trigger retries with exponential backoff:\n\n| Attempt | Delay |\n|---------|-------|\n| 1st retry | ~2 seconds |\n| 2nd retry | ~4 seconds |\n| 3rd retry (final) | ~8 seconds |\n\nMaximum backoff is capped at 1 hour. After 3 failed attempts, the delivery is marked as `failed`.\n\n**Disabled endpoints:** If an endpoint is disabled or deleted between emission and delivery, the delivery is marked as failed immediately.\n\n### Delivery Record\n\nEach delivery attempt is tracked in the `webhook_deliveries` table:\n\n| Field | Description |\n|-------|-------------|\n| `status` | `pending`, `delivered`, or `failed` |\n| `attempts` | Number of delivery attempts |\n| `responseStatus` | HTTP status from last attempt |\n| `responseBody` | Response body (truncated to 1000 chars) |\n| `lastAttemptAt` | Timestamp of last attempt |\n| `nextRetryAt` | When the next retry will occur |\n\n## Infrastructure\n\n### Queue Configuration\n\nOutbound webhooks use a dedicated Cloudflare Queue:\n\n```toml\n# Auto-generated in wrangler.toml\n[[queues.producers]]\nqueue = \"my-app-webhooks-queue\"\nbinding = \"WEBHOOKS_QUEUE\"\n\n[[queues.consumers]]\nqueue = \"my-app-webhooks-queue\"\nmax_batch_size = 10\nmax_batch_timeout = 30\nmax_retries = 3\ndead_letter_queue = \"my-app-webhooks-dlq\"\n```\n\n### Dead Letter Queue\n\nFailed webhook deliveries (after all retries) are sent to a dead letter queue for investigation:\n\n```toml\n[[queues.consumers]]\nqueue = \"my-app-webhooks-dlq\"\nmax_batch_size = 1\n```\n\n## Enabling Webhooks\n\nSet `webhooksBinding` in your database provider config:\n\n```typescript\ndatabase: defineDatabase(\"cloudflare-d1\", {\n binding: \"DB\",\n webhooksBinding: \"WEBHOOKS_DB\",\n})\n```\n\nThis generates the webhook database schema, routes, queue consumer, and all supporting code.\n\n### On Neon (Postgres)\n\nWebhooks are supported on the `neon` provider too. `webhooksBinding` acts as a\npure enable flag — there is no separate webhooks database. The webhook tables\nlive in a dedicated `webhooks` Postgres schema of your single Neon database,\ncreated by the standard drizzle migration set, and are locked down by an RLS\npolicy so only the Worker's internal service-role handle can touch them:\n\n```typescript\ndatabase: defineDatabase(\"neon\", {\n connectionMode: \"http\", // required for webhooks\n webhooksBinding: \"WEBHOOKS_DB\", // enable flag; no D1 binding is emitted\n // queue names stay configurable on any provider:\n webhooksQueueName: \"my-app-webhooks-queue\",\n webhooksDlqName: \"my-app-webhooks-dlq\",\n})\n```\n\nThe D1-only keys `webhooksDatabaseId` / `webhooksDatabaseName` are rejected at\ncompile time on Neon, and webhooks require `connectionMode: 'http'` (the\nCloudflare default). Queue wiring (`WEBHOOKS_QUEUE`, the consumer, and the\ndead letter queue) is identical across providers.\n\n## See Also\n\n- [Inbound Webhooks](/stack/webhooks/inbound) — Receive webhooks from external services\n- [Queues](/stack/queues) — Background processing infrastructure\n\n## Standard Webhooks signing\n\nOutbound deliveries are signed in the [Standard Webhooks](https://www.standardwebhooks.com)\nformat:\n\n| Header | Value |\n|---|---|\n| `webhook-id` | the delivery id (unique per delivery) |\n| `webhook-timestamp` | unix seconds |\n| `webhook-signature` | `v1,<base64 HMAC-SHA256 over id.timestamp.body>` |\n\nOn **contract v1** these are sent **in addition to** the legacy\n`X-Webhook-Signature` / `X-Webhook-Event` / `X-Webhook-Delivery` set, so\nexisting receivers keep working during the migration window. On\n**contract v2** only the Standard Webhooks headers are sent — the legacy set\n(and its Stripe-format signature) is dropped.\n\nReceiver verification (any Standard Webhooks library works):\n\n```ts\n\nconst wh = new Webhook(endpointSecret); // whsec_…\nconst payload = wh.verify(rawBody, {\n \"webhook-id\": req.headers[\"webhook-id\"],\n \"webhook-timestamp\": req.headers[\"webhook-timestamp\"],\n \"webhook-signature\": req.headers[\"webhook-signature\"],\n});\n```\n\nThe timestamp is inside the MAC, so the library's tolerance window is a real\nreplay bound."
519
531
  }
520
532
  };
521
533
  export const TOPIC_LIST = [
@@ -542,9 +554,11 @@ export const TOPIC_LIST = [
542
554
  "compiler/definitions/actions",
543
555
  "compiler/definitions/arrows",
544
556
  "compiler/definitions/bundles",
557
+ "compiler/definitions/changesets",
545
558
  "compiler/definitions/concepts",
546
559
  "compiler/definitions/diagnostics",
547
560
  "compiler/definitions/encryption",
561
+ "compiler/definitions/feature-areas",
548
562
  "compiler/definitions/feature",
549
563
  "compiler/definitions/fga",
550
564
  "compiler/definitions/firewall",
@@ -603,6 +617,7 @@ export const TOPIC_LIST = [
603
617
  "stack/account-ui/hooks",
604
618
  "stack/account-ui",
605
619
  "stack/account-ui/with-quickback",
620
+ "stack/api-contract",
606
621
  "stack/auth/api-keys",
607
622
  "stack/auth/device-auth",
608
623
  "stack/auth",