@quickback-dev/cli 0.52.0 → 0.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/commands/push.d.ts +20 -0
  2. package/dist/commands/push.d.ts.map +1 -0
  3. package/dist/commands/push.js +144 -0
  4. package/dist/commands/push.js.map +1 -0
  5. package/dist/commands/push.test.d.ts +2 -0
  6. package/dist/commands/push.test.d.ts.map +1 -0
  7. package/dist/commands/push.test.js +76 -0
  8. package/dist/commands/push.test.js.map +1 -0
  9. package/dist/docs/content.d.ts.map +1 -1
  10. package/dist/docs/content.js +12 -7
  11. package/dist/docs/content.js.map +1 -1
  12. package/dist/index.js +7 -1
  13. package/dist/index.js.map +1 -1
  14. package/dist/lib/api-client.d.ts +6 -2
  15. package/dist/lib/api-client.d.ts.map +1 -1
  16. package/dist/lib/api-client.js +12 -5
  17. package/dist/lib/api-client.js.map +1 -1
  18. package/dist/skill/SKILL.md +1 -0
  19. package/dist/skill/docs/changelog.md +65 -0
  20. package/dist/skill/docs/compiler/config/index.md +1 -1
  21. package/dist/skill/docs/compiler/config/providers.md +2 -0
  22. package/dist/skill/docs/stack/push/index.md +290 -0
  23. package/dist/skill/docs/stack/realtime/durable-objects.md +1 -1
  24. package/dist/skill/docs/stack/realtime/index.md +1 -1
  25. package/dist/skill/docs/stack/realtime/live-views.md +1 -1
  26. package/dist/skill/docs/stack/realtime/using-realtime.md +1 -0
  27. package/package.json +1 -1
  28. package/src/skill/SKILL.md +1 -0
  29. package/src/skill/docs/changelog.md +65 -0
  30. package/src/skill/docs/compiler/config/index.md +1 -1
  31. package/src/skill/docs/compiler/config/providers.md +2 -0
  32. package/src/skill/docs/stack/push/index.md +290 -0
  33. package/src/skill/docs/stack/realtime/durable-objects.md +1 -1
  34. package/src/skill/docs/stack/realtime/index.md +1 -1
  35. package/src/skill/docs/stack/realtime/live-views.md +1 -1
  36. package/src/skill/docs/stack/realtime/using-realtime.md +1 -0
@@ -3,7 +3,7 @@
3
3
  export const DOCS = {
4
4
  "changelog": {
5
5
  "title": "Changelog",
6
- "content": "## 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": "## 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), `/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`, `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"
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`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\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",
@@ -429,6 +429,10 @@ export const DOCS = {
429
429
  "title": "Quickback Stack",
430
430
  "content": "**Quickback Stack** is the runtime services that surround your compiled API. While the [Quickback Compiler](/compiler) generates your routes and security policies, the Stack is everything else you need to ship a real application — auth, storage, realtime, queues, an admin UI, an account UI — all on your own Cloudflare account.\n\n## What you get\n\n| Component | Service | Purpose |\n|-----------|---------|---------|\n| [Auth](/stack/auth) | Better Auth | Email/OTP, passkeys, organizations, admin |\n| [Storage](/stack/storage) | KV, R2 | Sessions, cache, files |\n| [Realtime](/stack/realtime) | Durable Objects | WebSocket for live updates |\n| [Queues](/stack/queues) | Cloudflare Queues | Background jobs, webhook delivery |\n| [Schedules](/stack/schedules) | Cron Triggers | `defineSchedule` cron jobs, server-internal |\n| [Vector & AI](/stack/vector) | Workers AI | Embeddings, semantic search |\n| [Webhooks](/stack/webhooks) | Hono + Queues | Signed inbound, retried outbound |\n| [Quickback CMS](/stack/cms) | Embedded SPA | Schema-driven admin UI |\n| [Account UI](/stack/account-ui) | Embedded SPA | Login, profile, orgs, admin |\n\n## Architecture\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│ Cloudflare Edge │\n├─────────────────────────────────────────────────────────────┤\n│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │\n│ │ Workers │ │ Durable │ │ KV │ │\n│ │ (API/CMS) │ │ Objects │ │ (Cache) │ │\n│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │\n│ │ │ │ │\n│ ┌──────┴──────┐ ┌──────┴──────┐ ┌──────┴──────┐ │\n│ │ D1 │ │ Realtime │ │ R2 │ │\n│ │ (or Neon) │ │ (WebSocket)│ │ (Storage) │ │\n│ └─────────────┘ └─────────────┘ └─────────────┘ │\n│ │\n│ ┌─────────────┐ ┌─────────────────────────────────┐ │\n│ │ Queues │ │ Better Auth │ │\n│ │ (Background)│ │ (Email OTP, Passkeys, etc.) │ │\n│ └─────────────┘ └─────────────────────────────────┘ │\n│ │\n│ ┌─────────────┐ │\n│ │ Schedules │ │\n│ │ (Cron) │ │\n│ └─────────────┘ │\n└─────────────────────────────────────────────────────────────┘\n```\n\n## Your account, your data\n\nEverything in Quickback Stack runs on your own Cloudflare account:\n\n- **Workers** — your deployments, your logs\n- **Storage** — your KV namespaces, your R2 buckets\n- **Secrets** — your API keys, in your Wrangler secrets\n\nQuickback provides the architecture and the code generation. You own the infrastructure.\n\n## Quick start\n\n```bash\n# Scaffold + compile interactively\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n\n# Deploy to your Cloudflare account\nnpm i -g wrangler\nwrangler deploy\n```\n\n`start` handles scaffold, login (only when needed), and the first compile in one shot. The deploy step uses your own wrangler auth and ships everything to your Cloudflare account.\n\n## See also\n\n- [Quickback Compiler](/compiler) — the build tool that generates your API\n- [Quickback for Hono API](/compiler/targets/hono-api) — what the compiler outputs\n- [Definitions](/compiler/definitions) — the security model the Stack runs"
431
431
  },
432
+ "stack/push": {
433
+ "title": "Web Push",
434
+ "content": "Quickback's push pillar emits a self-contained Web Push delivery module into your project when you set `push.provider: 'web-push'`. The helper handles VAPID JWT signing (RFC 8292), aes128gcm payload encryption (RFC 8291), HTTP delivery to the push service, and 404/410 cleanup — using only `crypto.subtle` and `fetch`. No `web-push` npm package, no Node polyfills, runs unchanged in Cloudflare Workers, Bun, and Deno.\n\nAPNs is planned as a second provider. The helper signature is shared, so most code that calls `sendPush` today will keep working.\n\n## What you get\n\n- **`enqueuePushFanout(queue, target, payload, opts?)`** — the primary send surface. Takes a declarative audience (`{ userIds }`, `{ targetTags }`, `{ targetRoles }`, `{ all: true }`) or an explicit subscription list, and routes between inline delivery and queue fan-out.\n- **`sendPush(subscription, payload, vapid)`** — single-recipient delivery. Returns `{ status: 'sent' | 'gone' | 'failed', statusCode, ... }`.\n- **`sendPushBulk(subscriptions, payload, vapid, opts?)`** — in-request fan-out with a default concurrency cap of 8 (Workers subrequest-budget friendly).\n- **`vapidFromEnv(env)`** — assembles the `VapidConfig` from `VAPID_PUBLIC_KEY` / `VAPID_PRIVATE_KEY` / `VAPID_SUBJECT`.\n- **A generated queue consumer** — resolves declarative targets against `push_subscriptions` server-side and delivers chunks of up to 250 recipients per invocation, with automatic 404/410 cleanup.\n- **`quickback push generate-keys [--out <file>]`** — mints a VAPID keypair in the right format. With `--out`, the private key is written to a `0600` file and never printed.\n- **CMS + Account SPA bundles** automatically carry `VITE_QUICKBACK_VAPID_PUBLIC_KEY` (and `vapidPublicKey` on `window.__QUICKBACK_RUNTIME`) so `pushManager.subscribe({ applicationServerKey })` works without extra plumbing.\n\n## Quickstart\n\n### 1. Mint a VAPID keypair\n\n```bash\nquickback push generate-keys --out .vapid-private-key\n```\n\nThe public key prints to the terminal; the private key goes only into the file (mode `0600`). Load it into a Wrangler secret and delete the file:\n\n```bash\nnpx wrangler secret put VAPID_PRIVATE_KEY < .vapid-private-key\nrm .vapid-private-key\n```\n\nAvoid `echo \"<key>\" | wrangler secret put …` — that writes the private key into your shell history. Without `--out`, the key prints once to the terminal and `wrangler secret put` prompts for an interactive paste.\n\nThe private key is minted **only once**. Losing it means re-subscribing every user.\n\n### 2. Configure `quickback.config.ts`\n\n```typescript\npush: {\n provider: 'web-push',\n vapidPublicKey: 'BEl62iUYgUivxIkv69yViEuiBIa-Ib9-SkvMeAtA3LFgDzkrxZJjSgSnfckjBJuBkr3qBUYIHBQFLXYp5Nksh8U',\n vapidPrivateKey: 'env:VAPID_PRIVATE_KEY',\n vapidSubject: 'mailto:notifications@example.com',\n defaultSchema: true,\n}\n```\n\n`env:VAPID_PRIVATE_KEY` is the convention for \"resolve from `wrangler secret put` at runtime\" — a **literal private key in config is a compile error**, and the scalar is never written into `wrangler.toml` or any committed file. The worker refuses to boot (503 with an explicit missing-var list) until all three VAPID vars are present.\n\nThe public key is not a secret. Keep it literal in config so it can be baked into the CMS/Account SPA bundles — an `env:`-referenced public key can't be resolved at compile time, so nothing is baked and your subscribe UI has to source it some other way.\n\n### 3. The `push_subscriptions` table\n\nWith `push.defaultSchema: true`, the compiler injects a hardened, owner-scoped `push_subscriptions` resource:\n\n- **INTERNAL-only reads** — the crypto fields (`endpoint`, `p256dh`, `auth`) never leave the worker via any HTTP path. A `views.mine` projection exposes only `id`, `userAgent`, `lastSeenAt`, `createdAt` for \"Your devices\" UIs.\n- **Owner firewall** — `owner_id` is auto-stamped on create; user A can never read or delete user B's subscription.\n- **Create-time validation** — the endpoint must be `https:` (the worker POSTs VAPID-signed requests at that URL, so an arbitrary endpoint is an SSRF primitive), `p256dh` must decode to a 65-byte uncompressed P-256 point, and `auth` to a 16-byte secret. The `https:` check is not the whole SSRF story: at send time the push sender additionally rejects any endpoint whose host resolves to a private, link-local, loopback, `localhost`, or `.internal` address. Together — **https + a non-public-host block** — this narrows the SSRF surface; treat it as defense-in-depth, not a guarantee that SSRF is impossible.\n- **Proven identity tags** — a `tags` column is stamped **server-side** from `ctx` (`user:<id>`, `role:<name>`, and — only when the request carries a scoped token — `scope:<kind>:<subject>`, the same dialect realtime tickets use). Client-supplied tags are ignored: they drive fan-out targeting. A normal session-cookie subscribe therefore stamps `user:` and `role:` but no `scope:` tag; see [Targeting](#targeting).\n- **Rate limit + cap** — creates are limited to 10/minute per caller, and only the newest 10 live subscriptions per user are kept (older rows are soft-deleted, so a user's new device always works).\n\nThis create-time hardening (endpoint/key validation, server-side tag stamping, the per-user cap) runs in JS before/after-insert hooks that fire **only on audit-wrapped writes** — the REST create path and actions. The normal browser subscribe is REST, so it's fully covered; but raw-SQL writes, queue/cron inserts, or direct INTERNAL-context inserts into `push_subscriptions` bypass all of it. Don't hand-insert subscription rows expecting the guards to apply.\n\nDeclaring your own `push_subscriptions` table while `defaultSchema: true` is set is a compile error — pick one owner for the schema.\n\nIf you roll your own (write it in canonical `pgTable` form; the compiler transforms per target dialect), keep the same security stance and column names — the generated fan-out consumer resolves targets against `endpoint` / `p256dh` / `auth` / `ownerId` / `tags` / `deletedAt`:\n\n```typescript\n\nexport const pushSubscriptions = pgTable(\"push_subscriptions\", {\n id: text(\"id\").primaryKey(),\n endpoint: text(\"endpoint\").notNull().unique(),\n p256dh: text(\"p256dh\").notNull(),\n auth: text(\"auth\").notNull(),\n ownerId: text(\"owner_id\").notNull(), // user-scoped firewall auto-detected\n tags: text(\"tags\"), // JSON array of proven identity tags\n userAgent: text(\"user_agent\"),\n lastSeenAt: timestamp(\"last_seen_at\", { withTimezone: true }),\n createdAt: timestamp(\"created_at\", { withTimezone: true }).notNull().defaultNow(),\n deletedAt: timestamp(\"deleted_at\", { withTimezone: true }),\n});\n\nexport default defineTable(pushSubscriptions, {\n read: {\n // Crypto fields never leave the worker — even the owning user can't\n // enumerate their own subscriptions via the API. A compromised session\n // must not be able to leak the user's other devices.\n access: { roles: ['INTERNAL'] },\n views: {\n mine: {\n fields: ['id', 'userAgent', 'lastSeenAt', 'createdAt'],\n access: { roles: ['USER'] },\n },\n },\n },\n crud: {\n create: { access: { roles: ['USER'] } },\n delete: { access: { roles: ['USER'] }, mode: 'soft' },\n },\n});\n```\n\nSee [Access — INTERNAL pseudo-role](/compiler/definitions/access) for the full security stance.\n\n### 4. Subscribe from the browser (DIY for now)\n\nQuickback does not yet generate a service worker or subscribe UI — this half is yours. Two pieces:\n\n**A minimal `sw.js`** (serve it from your app's origin root):\n\n```javascript\nself.addEventListener('push', (event) => {\n const data = event.data?.json() ?? {};\n event.waitUntil(\n self.registration.showNotification(data.title ?? 'Notification', {\n body: data.body,\n icon: data.icon,\n tag: data.tag,\n data, // url + your structured data, read back in notificationclick\n }),\n );\n});\n\nself.addEventListener('notificationclick', (event) => {\n event.notification.close();\n const url = event.notification.data?.url;\n if (url) event.waitUntil(clients.openWindow(url));\n});\n```\n\n**Subscribe + register with the API:**\n\n```typescript\n\nasync function subscribeToPush() {\n await navigator.serviceWorker.register('/sw.js');\n const reg = await navigator.serviceWorker.ready;\n const sub = await reg.pushManager.subscribe({\n userVisibleOnly: true,\n // Baked at compile time; also available as\n // window.__QUICKBACK_RUNTIME.vapidPublicKey on served SPA shells.\n applicationServerKey: import.meta.env.VITE_QUICKBACK_VAPID_PUBLIC_KEY,\n });\n\n // The subscription object exposes endpoint + base64url-encoded keys.\n const json = sub.toJSON() as { endpoint: string; keys: { p256dh: string; auth: string } };\n\n await api.post('/push_subscriptions', {\n endpoint: json.endpoint,\n p256dh: json.keys.p256dh,\n auth: json.keys.auth,\n userAgent: navigator.userAgent,\n });\n}\n```\n\nDon't send a `tags` field — the server stamps it from the session and ignores anything the client supplies.\n\n### 5. Send from an action\n\nSends ride the **after-commit effects phase**, so a rolled-back write never notifies anyone and `dryRun` sends nothing. Enqueue the fan-out from inside `execute`:\n\n```typescript\n// features/events/actions/publish.ts\n\nexport default defineAction({\n description: \"Publish an event and notify admins.\",\n input: z.object({}),\n access: { roles: [\"owner\", \"admin\"] },\n async execute({ record, env, effects }) {\n // ...your committed write happens here...\n\n // After-commit: notify every subscribed admin.\n effects.enqueue(\"push:eventPublished\", () =>\n enqueuePushFanout(\n env.PUSH_FANOUT_QUEUE!,\n { targetRoles: [\"admin\"] },\n {\n title: record.name,\n body: \"Event published — tap to review\",\n url: `https://app.example.com/events/${record.id}`,\n tag: `event-${record.id}`,\n },\n ),\n );\n\n return { published: true };\n },\n});\n```\n\nThe declarative form enqueues **one small message**; the generated queue consumer resolves the audience against `push_subscriptions` inside the server-internal trust zone and fans out delivery chunks. Subscription crypto never enters your action code.\n\nTarget by `{ targetRoles }` or `{ userIds }` — these match the `role:<name>` and `user:<id>` tags that **every** subscription carries, because they're stamped from `ctx` on a normal session-cookie subscribe. `{ targetTags: ['scope:events:e9'] }` only matches subscriptions created inside a scoped context (see the note under [Targeting](#targeting)); against ordinary session-created rows it selects nobody.\n\n### Targeting\n\n`enqueuePushFanout` speaks the same identity-tag dialect as [realtime targeting](/stack/realtime/durable-objects). For the common browser subscribe flow, reach for `{ targetRoles }` or `{ userIds }` first — those tags are stamped on every session-created subscription:\n\n| Target | Selects |\n|---|---|\n| `{ targetRoles: ['admin'] }` | Rows whose tags include `role:admin` (any listed role) |\n| `{ userIds: ['u1', 'u2'] }` | Subscriptions owned by those users |\n| `{ all: true }` | Every live subscription — broadcast must be this explicit |\n| `{ targetTags: ['scope:events:e9'] }` | Rows whose stamped tags include ANY listed tag — **but `scope:*` tags exist only on scoped-token subscribes** (see note below); against session-created rows this selects nobody |\n| `{ targetTags: [...], targetRoles: [...] }` | Rows matching BOTH arms (AND across arms, union within) |\n| `{ subscriptions: [...] }` | An explicit list you already hold |\n\nSelection is **fail-closed**: an empty array selects *nobody* (nothing is enqueued), and a target with no arms at all throws — accidental broadcast is structurally impossible. Tags are proven at subscribe time from `ctx`; clients cannot forge their way into an audience.\n\nWith an explicit `{ subscriptions }` list, passing `opts.vapid` (via `vapidFromEnv(env)`) lets lists at or under `push.fanout.threshold` (default 500) deliver **inline** with per-recipient results; larger lists chunk onto the queue.\n\n## Notifications API payload\n\n```typescript\n{\n title: 'Your invite is ready',\n body: 'Tap to RSVP for The Summit',\n url: 'https://attend.vip/rsvp/abc123', // click destination\n icon: 'https://attend.vip/icon-192.png', // 192px PNG\n tag: 'invite-abc123', // collapse with existing notif of same tag\n data: { eventId, guestId }, // arbitrary structured data\n topic: 'invites', // push-service collapse key\n ttl: 86400, // seconds; default push.defaultTtl (86400)\n urgency: 'high', // very-low | low | normal | high; default push.defaultUrgency\n}\n```\n\nThe browser's service worker decides what to do with the data (see the `sw.js` above).\n\n### Masking does not cover push payloads\n\nPush payloads are an egress channel the [masking pillar](/compiler/definitions/masking) does **not** see. Masking applies to API reads — a payload you build in an action ships exactly what you put in it, to every device in the audience. Before putting a field in `title`/`body`/`data`, ask whether every targeted recipient is allowed to see it unmasked. Prefer notification-shaped summaries plus a `url` — let the click-through fetch the details through the API, where firewall, access, and masking all apply.\n\n## Status semantics\n\n| `result.status` | When | Action |\n|---|---|---|\n| `sent` | HTTP 200/201/202 from push service | Done. `messageId` (from `Location` header) optionally available. |\n| `gone` | HTTP 404 or 410 | Subscription is permanently dead — soft-delete it. |\n| `failed` | Other 4xx/5xx, or network error | Caller decides whether to retry. `retryAfter` populated if the service returned a `Retry-After` header. |\n\nTreat `gone` as authoritative. Once a push service returns 410, the endpoint will never work again. The generated queue consumer soft-deletes `gone` rows automatically; only inline `sendPush`/`sendPushBulk` callers need to handle it themselves.\n\n## Queue fan-out\n\nFan-out above the Workers subrequest budget runs through Cloudflare Queues. The compiler wires everything when `push.provider` is set:\n\n- **Producer** — a `[[queues.producers]]` binding (`PUSH_FANOUT_QUEUE`) that `enqueuePushFanout` writes to, in batches of ≤100.\n- **Consumer** — a `push-fanout` branch in the unified `src/queue-consumer.ts` dispatcher, with `max_batch_size: 1` so each ≤250-recipient chunk gets its own invocation. Declarative targets arrive as one `resolve` message; the consumer reads `push_subscriptions` (server-internal trust zone), applies the fail-closed tag match, and re-enqueues `send` chunks.\n- **Per-recipient handling** — one bad endpoint doesn't doom the chunk, and `gone` results are soft-deleted in the same invocation.\n- **Dead letter queue** — after 3 retries, failed chunks land on `<queue>-dlq` and are logged **by count only**: fan-out payloads carry subscription crypto and must never hit logs.\n\nTune via `push.fanout.{threshold, chunkSize, queueName, maxConcurrency}` — defaults 500 / 250 / `{name}-push-fanout` / 5. `chunkSize` is hard-capped at 250 (~25% of the subrequest budget, ~62KB message size).\n\n## Browser support\n\n- ✅ Chrome (Android, desktop) via FCM\n- ✅ Firefox (Android, desktop) via Mozilla autopush\n- ✅ Edge (desktop) via Windows Push Notification Service\n- ✅ Safari iOS 16.4+ — **only inside installed PWAs** (Add to Home Screen). Apple's push endpoints have known quirks around payload size and TTL semantics; test on real hardware.\n- ❌ Safari macOS — partial support; the helper works but iOS PWA is the supported path.\n\n## Privacy posture\n\nPush subscription rows contain endpoints that uniquely identify a user's browser instance. Quickback's defaults treat them as personal data:\n\n- **`read.access: { roles: ['INTERNAL'] }`** on the table — no public CRUD path, even for the owning user. Compromised sessions cannot enumerate the user's other devices.\n- **`views.mine`** projection exposes only `id`, `userAgent`, `lastSeenAt`, `createdAt` — never the cryptographic material — for \"Your devices\" UIs.\n- **`VAPID_PRIVATE_KEY`** is wrangler-secret-only; a literal scalar in config is a compile error.\n- **Declarative targeting** keeps subscription crypto out of action code entirely — the audience resolves inside the queue consumer.\n- **410 cleanup** is automatic in the queue consumer, so dead subscription rows don't accumulate.\n\nGDPR Article 32 maps cleanly: push endpoints are restricted to those who need them (the worker code that sends), not anyone who could read the table via the API.\n\n## References\n\n- [RFC 8030](https://datatracker.ietf.org/doc/html/rfc8030) — Generic Event Delivery Using HTTP Push\n- [RFC 8291](https://datatracker.ietf.org/doc/html/rfc8291) — Message Encryption for Web Push (aes128gcm)\n- [RFC 8292](https://datatracker.ietf.org/doc/html/rfc8292) — VAPID for Web Push\n- [Web Push Protocol — MDN](https://developer.mozilla.org/en-US/docs/Web/API/Push_API)"
435
+ },
432
436
  "stack/queues/handlers": {
433
437
  "title": "Custom Queue Handlers",
434
438
  "content": "Quickback lets you define custom queue handlers that integrate seamlessly with the generated queue consumer. This is useful for background processing like material extraction pipelines, batch jobs, and async workflows.\n\n## Overview\n\nCustom queue handlers are defined in the `services/queues/` directory using the `defineQueue` helper. The compiler extracts your handler logic and generates a unified queue consumer that dispatches messages based on their type.\n\n```\nquickback/\n├── features/ # Data layer (CRUD, actions, security)\n│ ├── materials/\n│ └── claims/\n└── services/ # Infrastructure layer\n └── queues/\n ├── ingest.ts # Material processing\n └── claim-batches.ts # Batch processing\n```\n\n## Defining a Queue Handler\n\nUse `defineQueue` to create a handler:\n\n```typescript\n// services/queues/ingest.ts\n\ninterface ProcessMaterialMessage {\n type: 'process_material';\n materialId: string;\n organizationId: string;\n}\n\nexport default defineQueue<ProcessMaterialMessage>({\n name: 'ingest',\n messageType: 'process_material',\n description: 'Process materials through extraction pipeline',\n\n execute: async ({ message, db, env, services, ack, retry }) => {\n const { materialId, organizationId } = message;\n\n // Dynamic import of schema\n const { materials } = await import('./features/materials/schema');\n\n // Get material from database\n const [material] = await db\n .select()\n .from(materials)\n .where(eq(materials.id, materialId))\n .limit(1);\n\n if (!material) {\n console.error('[IngestQueue] Material not found:', materialId);\n return { success: false, error: 'Material not found' };\n }\n\n // Process the material...\n await db\n .update(materials)\n .set({ extractionStatus: 'processing' })\n .where(eq(materials.id, materialId));\n\n // Your processing logic here\n\n return { success: true };\n },\n});\n```\n\n## Configuration Options\n\n| Option | Type | Required | Description |\n|--------|------|----------|-------------|\n| `name` | `string` | Yes | Handler identifier (used in logs) |\n| `messageType` | `string` | Yes | Message type to match (e.g., `'process_material'`) |\n| `description` | `string` | No | Human-readable description |\n| `execute` | `function` | Yes | Handler function |\n\n## Execute Function\n\nThe `execute` function receives a context object:\n\n```typescript\nexecute: async ({ message, db, env, services, ack, retry }) => {\n // message - The message payload (typed via generic)\n // db - Drizzle database instance\n // env - Cloudflare bindings (AI, queues, etc.)\n // services - Generated services (ai, etc.)\n // ack() - Acknowledge message (auto-called on success)\n // retry() - Retry message (auto-called on failure)\n\n return { success: true }; // or { success: false, error: 'reason' }\n}\n```\n\n## Constants and Imports\n\nThe compiler extracts top-level constants and imports from your handler file and includes them in the generated queue consumer:\n\n```typescript\n// services/queues/ingest.ts\n\nconst TEXT_GENERATION_MODEL = '@cf/meta/llama-3.1-8b-instruct';\n\nconst EXTRACTION_PROMPT = `You are a news analyst. Extract factual claims from this article.\n\nFor each claim, output a JSON object with:\n- content: The claim as a complete, standalone sentence\n- claimType: One of NEWS, QUOTE, OFFICIAL, ALLEGATION, STATISTIC, FINDING\n- urgency: 1-5 (5 = most urgent/breaking)\n\nOutput ONLY a JSON array of claims, no other text.`;\n\nexport default defineQueue({\n // ... handler definition\n});\n```\n\nThe compiler:\n1. Extracts all `import` statements\n2. Extracts top-level `const` declarations (including multi-line template literals)\n3. Inlines them in the generated queue consumer\n\n## Dynamic Schema Imports\n\nSince your schema files are generated by Quickback, use dynamic imports to reference them:\n\n```typescript\nexecute: async ({ message, db }) => {\n // Dynamic import - path is relative to generated src/ directory\n const { materials, claimExtractionBatches } = await import('./features/materials/schema');\n\n const [material] = await db\n .select()\n .from(materials)\n .where(eq(materials.id, message.materialId));\n\n // ...\n}\n```\n\n## Sending to Other Queues\n\nChain queue handlers by sending messages to other queues:\n\n```typescript\nexecute: async ({ message, db, env }) => {\n const { materialId } = message;\n\n // Process and create batch...\n const batchId = generateId('batch');\n\n // Send to next stage\n if (env.CLAIM_BATCHES_QUEUE) {\n await env.CLAIM_BATCHES_QUEUE.send({\n type: 'claim_batch_stage',\n batch_id: batchId,\n material_id: materialId,\n stage: 'subeditor',\n });\n }\n\n return { success: true };\n}\n```\n\n## Generated Output\n\nWhen queue handlers are defined, the compiler generates a unified `queue-consumer.ts`:\n\n```typescript\n// src/queue-consumer.ts (generated)\n\nconst TEXT_GENERATION_MODEL = '@cf/meta/llama-3.1-8b-instruct';\nconst EXTRACTION_PROMPT = `...`;\n\n// Embedding handler (if embeddings configured)\nconst embeddingQueueHandler = async (batch, env) => { ... };\n\n// Custom handler: ingest\nconst ingestQueueHandler = async (batch, env) => {\n const db = drizzle(env.DB);\n const services = createServices(env);\n\n for (const message of batch.messages) {\n try {\n const result = await executeHandler({\n message: message.body,\n env, db, services,\n ack: () => message.ack(),\n retry: () => message.retry(),\n });\n\n if (result.success) message.ack();\n else message.retry();\n } catch (error) {\n message.retry();\n }\n }\n};\n\n// Unified dispatcher\nexport const queue = async (batch, env) => {\n const messageType = batch.messages[0]?.body?.type;\n\n switch (messageType) {\n case 'embedding':\n await embeddingQueueHandler(batch, env);\n break;\n case 'process_material':\n await ingestQueueHandler(batch, env);\n break;\n default:\n console.warn('[Queue] Unknown message type:', messageType);\n for (const msg of batch.messages) msg.ack();\n }\n};\n```\n\n## wrangler.toml Configuration\n\nConfigure your queues in wrangler.toml:\n\n```toml\n# Queue producers (send to queues)\n[[queues.producers]]\nqueue = \"my-app-ingest-queue\"\nbinding = \"INGEST_QUEUE\"\n\n[[queues.producers]]\nqueue = \"my-app-claim-batches-queue\"\nbinding = \"CLAIM_BATCHES_QUEUE\"\n\n# Queue consumers (receive from queues)\n[[queues.consumers]]\nqueue = \"my-app-ingest-queue\"\nmax_batch_size = 10\nmax_batch_timeout = 30\nmax_retries = 3\n\n[[queues.consumers]]\nqueue = \"my-app-claim-batches-queue\"\nmax_batch_size = 10\nmax_batch_timeout = 30\nmax_retries = 3\n```\n\n## Deployment\n\nAfter defining queue handlers:\n\n1. **Create the queues:**\n ```bash\n wrangler queues create my-app-ingest-queue\n wrangler queues create my-app-claim-batches-queue\n ```\n\n2. **Compile:**\n ```bash\n quickback compile\n ```\n\n3. **Deploy:**\n ```bash\n wrangler deploy\n ```\n\n## Error Handling\n\nThe queue consumer handles errors automatically:\n\n- **Return `{ success: true }`** - Message is acknowledged\n- **Return `{ success: false, error: '...' }`** - Message is retried\n- **Throw an exception** - Message is retried\n\nAfter `max_retries` (default 3), failed messages are dropped or sent to a dead-letter queue if configured.\n\n```typescript\nexecute: async ({ message, db }) => {\n try {\n // Your processing logic\n return { success: true };\n } catch (error) {\n console.error('[Handler] Failed:', error);\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error'\n };\n }\n}\n```\n\n## Combining with Embeddings\n\nCustom queue handlers work alongside automatic embeddings. The compiler generates a single queue consumer that handles both:\n\n```typescript\nswitch (messageType) {\n case 'embedding':\n // Auto-generated embedding handler\n await embeddingQueueHandler(batch, env);\n break;\n case 'process_material':\n // Your custom handler\n await ingestQueueHandler(batch, env);\n break;\n}\n```\n\nSee [Automatic Embeddings](/stack/vector/embeddings) for configuring auto-embedding on CRUD operations."
@@ -443,15 +447,15 @@ export const DOCS = {
443
447
  },
444
448
  "stack/realtime/durable-objects": {
445
449
  "title": "Realtime",
446
- "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` 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) |"
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) |"
447
451
  },
448
452
  "stack/realtime": {
449
453
  "title": "Realtime",
450
- "content": "Quickback ships **two parallel realtime primitives**, both backed by Cloudflare Durable Objects:\n\n- **`/broadcast/v1/*` — server fan-out.** One DO instance per subscription scope. Postgres-changes events from CRUD routes plus custom broadcast events flow out to every subscriber, with role filtering and per-role field masking applied. Best for \"tell every client in this shared scope that something changed.\" The scope can be an organization, a specific user, or a compiler-resolved resource key like `events:evt_123`. Documented on this page.\n- **`/realtime/<binding>/<room-id>` — bidirectional rooms.** One DO instance per room (per document, per interview, per game). Client↔client messages, presence, and CRDT-friendly state. Use these for collaborative editing. See [PartyServer rooms](/stack/realtime/partyserver-rooms).\n\nBoth share the same auth model and ride on the same compiled worker; they solve different problems.\n\n## Architecture\n\n```\n┌──────────────────────────────────────────┐\n│ Quickback Worker │\n│ │\n│ ┌──────────┐ DO binding ┌────────────────────┐\n│ │ Hono API │ ──────────────► │ Broadcaster (DO) │\n│ │ │ │ WebSocket manager │\n│ └──────────┘ └─────────┬──────────┘\n│ │\n└─────────────────────────────────────────┼┘\n │ WebSocket\n │\n ┌────────▼─────────┐\n │ Browser Clients │\n │ (CMS, Account, │\n │ Admin, Custom) │\n └──────────────────┘\n```\n\nThe Broadcaster Durable Object runs **inline** in your main Quickback worker — no separate worker deployment needed. The API calls the DO directly via its binding (in-process, no network hop).\n\n1. **Quickback Worker** — Your compiled API with the Broadcaster DO class exported from the same worker.\n2. **Broadcaster (Durable Object)** — Manages WebSocket connections per subscription scope. One instance per `scopeKey`, organization, or user lane.\n3. **Browser Clients** — CMS, Account, Admin, and custom frontends connect via WebSocket on the same origin.\n\n## Key Features\n\n| Feature | Description |\n|---------|-------------|\n| Scope-aware fan-out | Routes by `scopeKey`, `organizationId`, or `userId` |\n| Role-based filtering | Only send events to users with matching roles |\n| Per-role masking | Different users see different field values based on their role |\n| User-specific targeting | Send events to a specific user within an org |\n| Resource-scoped tickets | Mint scope-bound ws tickets gated by org-membership roles, authz relationship roles, or FGA relations |\n| Custom broadcasts | Arbitrary events beyond CRUD |\n| Custom namespaces | `defineRealtime()` for type-safe event helpers |\n| Ticket-based auth | HMAC-signed tickets verified at WebSocket upgrade — no HTTP round-trip |\n\n## Enabling Realtime\n\nBroadcasting is **opt-in per resource**, exactly like CRUD — a table broadcasts\nonly if it declares its own `realtime` block. Add `realtime` to individual table\ndefinitions:\n\n```typescript\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n realtime: {\n enabled: true,\n onInsert: true,\n onUpdate: true,\n onDelete: true,\n // Audience — WHO may receive these live rows. Same { roles } shape as\n // read.access / crud.*.access. MANDATORY and fail-closed: a broadcast\n // reaches every subscriber in the room, so the audience is not optional.\n // Omit it (or leave it empty) and compilation fails. Roles may be concrete\n // membership/scope roles or UPPERCASE pseudo-roles.\n access: { roles: [\"recruiter\", \"hiring-manager\"] },\n fields: [\"id\", \"candidateId\", \"stage\"],\n },\n});\n```\n\nAnd enable the realtime **transport** in your database config. This is a\nproject-level switch that stands up the Broadcaster Durable Object + the\nconnection route; it does **not** by itself make any resource broadcast\n(that's the per-resource `realtime` block above). The compiler generates the\nDurable Object class, helper functions, and wrangler bindings — all within\nyour main worker.\n\nFor most apps — including org-scoped apps like chat, feeds, and dashboards —\nthe boolean form is all you need. Session-authenticated members subscribe\ndirectly; audiences come from each resource's `realtime.access.roles`:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: true,\n }),\n}\n```\n\nThe object form is the **advanced** variant, only needed when you mint\nresource-scoped tickets (e.g. an external attendee who may join one event's\nchannel, or an org member who may join one project's room). The mint gate is\ndeclared with `wsTicket.access`, a discriminated union — the arm names the\nauthorization vocabulary, so a bare name can never silently mean two things:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: {\n wsTicket: {\n // Pick EXACTLY ONE arm:\n access: { roles: [\"member+\"] }, // org-membership roles (hierarchy expands)\n // access: { authzRole: \"attendee\" }, // authz relationship role\n // access: { fga: { relation: \"viewer\", object: \"event:{id}\" } }, // FGA relation on the scope row\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n },\n }),\n}\n```\n\n- **`{ roles }` — org-membership roles.** `\"member+\"` expands via\n `auth.roleHierarchy` (compile error without it). Firewall-consistent: the\n route verifies the caller's org role **and** that the requested `scopeTable`\n row belongs to the caller's *active* organization — an org-A member cannot\n mint a ticket to org B's room. The scope table must therefore carry an\n organization column (compile error otherwise). UPPERCASE pseudo-roles are\n rejected here: a `PUBLIC`/`AUTHENTICATED` ticket factory would hand signed\n room credentials to callers with no org standing.\n- **`{ authzRole }` — a declared `authz.roles` relationship role** (`{ via }`).\n The route probes the relationship table against `body.eventId`; the ticket\n carries the relationship role (e.g. `attendee`). The legacy\n `role: \"attendee\"` string is the back-compat shorthand for this arm and\n compiles identically. Org-membership names (`member`/`admin`/`owner`) are\n still rejected in this arm — spell those `access: { roles: [...] }`.\n- **`{ fga }` — an FGA relation.** The route loads the `scopeTable` row through\n its own firewall (tenant bind), derives the object from the template\n (`\"event:{id}\"` — `{field}` tokens read from the row, the same template\n language as the read path's `access: { fga }`), and requires the caller to\n hold `relation` on it via the same org-scoped check evaluator the read path\n uses. Requires `authz.fga`; the object type and relation are validated\n against the model at compile time.\n\nWhichever arm you pick, `/broadcast/v1/ws-ticket` authenticates the caller,\nruns that gate against `body.eventId`, and mints a short-lived ticket scoped to\nthe resolved `events:<id>` channel. Everything fails closed at compile time:\na bare name that exists in more than one vocabulary is an ambiguity error\ndemanding the explicit arm, and a missing hierarchy, missing FGA model, or\nmissing organization column fails the build with an actionable message.\n\n## Pages\n\n- **[Durable Objects Setup](/stack/realtime/durable-objects)** — Broadcaster configuration, wrangler bindings, event formats, masking, and custom namespaces\n- **[Using Realtime](/stack/realtime/using-realtime)** — Subscribing to `/broadcast/v1/*`: WebSocket connection, ticket auth, client-side handling\n- **[PartyServer Rooms](/stack/realtime/partyserver-rooms)** — Per-room collab via `/realtime/<binding>/<room-id>`: presence, live notes, room IDs"
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.\n- **`/realtime/<binding>/<room-id>` — bidirectional rooms.** One DO instance per room (per document, per interview, per game). Client↔client messages, presence, and CRDT-friendly state. Use these for collaborative editing. See [PartyServer rooms](/stack/realtime/partyserver-rooms).\n\nBoth share the same auth model and ride on the same compiled worker; they solve different problems.\n\n## Architecture\n\n```\n┌──────────────────────────────────────────┐\n│ Quickback Worker │\n│ │\n│ ┌──────────┐ DO binding ┌────────────────────┐\n│ │ Hono API │ ──────────────► │ Broadcaster (DO) │\n│ │ │ │ WebSocket manager │\n│ └──────────┘ └─────────┬──────────┘\n│ │\n└─────────────────────────────────────────┼┘\n │ WebSocket\n │\n ┌────────▼─────────┐\n │ Browser Clients │\n │ (CMS, Account, │\n │ Admin, Custom) │\n └──────────────────┘\n```\n\nThe Broadcaster Durable Object runs **inline** in your main Quickback worker — no separate worker deployment needed. The API calls the DO directly via its binding (in-process, no network hop).\n\n1. **Quickback Worker** — Your compiled API with the Broadcaster DO class exported from the same worker.\n2. **Broadcaster (Durable Object)** — Manages WebSocket connections per subscription scope. One instance per `scopeKey`, organization, or user lane.\n3. **Browser Clients** — CMS, Account, Admin, and custom frontends connect via WebSocket on the same origin.\n\n## Key Features\n\n| Feature | Description |\n|---------|-------------|\n| Scope-aware fan-out | Routes by `scopeKey`, `organizationId`, or `userId` |\n| Role-based filtering | Only send events to users with matching roles |\n| Per-role masking | Different users see different field values based on their role |\n| User-specific targeting | Send events to a specific user within an org |\n| Resource-scoped tickets | Mint scope-bound ws tickets gated by org-membership roles, authz relationship roles, or FGA relations |\n| Custom broadcasts | Arbitrary events beyond CRUD |\n| Custom namespaces | `defineRealtime()` for type-safe event helpers |\n| Ticket-based auth | HMAC-signed tickets verified at WebSocket upgrade — no HTTP round-trip |\n\n## Enabling Realtime\n\nBroadcasting is **opt-in per resource**, exactly like CRUD — a table broadcasts\nonly if it declares its own `realtime` block. Add `realtime` to individual table\ndefinitions:\n\n```typescript\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n realtime: {\n enabled: true,\n onInsert: true,\n onUpdate: true,\n onDelete: true,\n // Audience — WHO may receive these live rows. Same { roles } shape as\n // read.access / crud.*.access. MANDATORY and fail-closed: a broadcast\n // reaches every subscriber in the room, so the audience is not optional.\n // Omit it (or leave it empty) and compilation fails. Roles may be concrete\n // membership/scope roles or UPPERCASE pseudo-roles.\n access: { roles: [\"recruiter\", \"hiring-manager\"] },\n fields: [\"id\", \"candidateId\", \"stage\"],\n },\n});\n```\n\nAnd enable the realtime **transport** in your database config. This is a\nproject-level switch that stands up the Broadcaster Durable Object + the\nconnection route; it does **not** by itself make any resource broadcast\n(that's the per-resource `realtime` block above). The compiler generates the\nDurable Object class, helper functions, and wrangler bindings — all within\nyour main worker.\n\nFor most apps — including org-scoped apps like chat, feeds, and dashboards —\nthe boolean form is all you need. Session-authenticated members subscribe\ndirectly; audiences come from each resource's `realtime.access.roles`:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: true,\n }),\n}\n```\n\nThe object form is the **advanced** variant, only needed when you mint\nresource-scoped tickets (e.g. an external attendee who may join one event's\nchannel, or an org member who may join one project's room). The mint gate is\ndeclared with `wsTicket.access`, a discriminated union — the arm names the\nauthorization vocabulary, so a bare name can never silently mean two things:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: {\n wsTicket: {\n // Pick EXACTLY ONE arm:\n access: { roles: [\"member+\"] }, // org-membership roles (hierarchy expands)\n // access: { authzRole: \"attendee\" }, // authz relationship role\n // access: { fga: { relation: \"viewer\", object: \"event:{id}\" } }, // FGA relation on the scope row\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n },\n }),\n}\n```\n\n- **`{ roles }` — org-membership roles.** `\"member+\"` expands via\n `auth.roleHierarchy` (compile error without it). Firewall-consistent: the\n route verifies the caller's org role **and** that the requested `scopeTable`\n row belongs to the caller's *active* organization — an org-A member cannot\n mint a ticket to org B's room. The scope table must therefore carry an\n organization column (compile error otherwise). UPPERCASE pseudo-roles are\n rejected here: a `PUBLIC`/`AUTHENTICATED` ticket factory would hand signed\n room credentials to callers with no org standing.\n- **`{ authzRole }` — a declared `authz.roles` relationship role** (`{ via }`).\n The route probes the relationship table against `body.eventId`; the ticket\n carries the relationship role (e.g. `attendee`). The legacy\n `role: \"attendee\"` string is the back-compat shorthand for this arm and\n compiles identically. Org-membership names (`member`/`admin`/`owner`) are\n still rejected in this arm — spell those `access: { roles: [...] }`.\n- **`{ fga }` — an FGA relation.** The route loads the `scopeTable` row through\n its own firewall (tenant bind), derives the object from the template\n (`\"event:{id}\"` — `{field}` tokens read from the row, the same template\n language as the read path's `access: { fga }`), and requires the caller to\n hold `relation` on it via the same org-scoped check evaluator the read path\n uses. Requires `authz.fga`; the object type and relation are validated\n against the model at compile time.\n\nWhichever arm you pick, `/broadcast/v1/ws-ticket` authenticates the caller,\nruns that gate against `body.eventId`, and mints a short-lived ticket scoped to\nthe resolved `events:<id>` channel. Everything fails closed at compile time:\na bare name that exists in more than one vocabulary is an ambiguity error\ndemanding the explicit arm, and a missing hierarchy, missing FGA model, or\nmissing organization column fails the build with an actionable message.\n\n## Pages\n\n- **[Durable Objects Setup](/stack/realtime/durable-objects)** — Broadcaster configuration, wrangler bindings, event formats, masking, and custom namespaces\n- **[Using Realtime](/stack/realtime/using-realtime)** — Subscribing to `/broadcast/v1/*`: WebSocket connection, ticket auth, client-side handling\n- **[PartyServer Rooms](/stack/realtime/partyserver-rooms)** — Per-room collab via `/realtime/<binding>/<room-id>`: presence, live notes, room IDs"
451
455
  },
452
456
  "stack/realtime/live-views": {
453
457
  "title": "Live Views",
454
- "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` 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."
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."
455
459
  },
456
460
  "stack/realtime/partyserver-rooms": {
457
461
  "title": "PartyServer Rooms",
@@ -459,7 +463,7 @@ export const DOCS = {
459
463
  },
460
464
  "stack/realtime/using-realtime": {
461
465
  "title": "Using Realtime",
462
- "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```\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"
466
+ "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"
463
467
  },
464
468
  "stack/schedules": {
465
469
  "title": "Schedules (Cron)",
@@ -618,6 +622,7 @@ export const TOPIC_LIST = [
618
622
  "stack/cms/security",
619
623
  "stack/cms/table-views",
620
624
  "stack",
625
+ "stack/push",
621
626
  "stack/queues/handlers",
622
627
  "stack/queues",
623
628
  "stack/queues/using-queues",