@quickback-dev/cli 0.47.9 → 0.47.10
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.
- package/dist/commands/compile.js +2 -2
- package/dist/commands/compile.js.map +1 -1
- package/dist/docs/content.d.ts.map +1 -1
- package/dist/docs/content.js +11 -6
- package/dist/docs/content.js.map +1 -1
- package/dist/index.js +7 -1
- package/dist/index.js.map +1 -1
- package/dist/lib/file-loader.d.ts +2 -2
- package/dist/lib/file-loader.d.ts.map +1 -1
- package/dist/lib/file-loader.js +16 -15
- package/dist/lib/file-loader.js.map +1 -1
- package/dist/skill/docs/changelog.md +52 -0
- package/dist/skill/docs/compiler/config/index.md +21 -12
- package/dist/skill/docs/compiler/definitions/index.md +39 -17
- package/dist/skill/docs/compiler/definitions/triggers.md +5 -0
- package/dist/skill/docs/stack/index.md +6 -0
- package/dist/skill/docs/stack/realtime/partyserver-rooms.md +12 -0
- package/dist/skill/docs/stack/schedules/index.md +78 -0
- package/package.json +1 -1
- package/src/skill/docs/changelog.md +28 -0
- package/src/skill/docs/compiler/config/index.md +21 -12
- package/src/skill/docs/compiler/definitions/index.md +39 -17
- package/src/skill/docs/stack/index.md +6 -0
- package/src/skill/docs/stack/realtime/partyserver-rooms.md +12 -0
- package/src/skill/docs/stack/schedules/index.md +19 -1
package/dist/docs/content.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
export const DOCS = {
|
|
4
4
|
"changelog": {
|
|
5
5
|
"title": "Changelog",
|
|
6
|
-
"content": "## Unreleased\n\n### Rate limiting — the fifth security pillar\n\nPer-operation request caps on every CRUD endpoint, backed by Cloudflare's\nnative [Rate Limiting binding](/compiler/definitions/rate-limit) — no extra\nstorage, no third-party libraries. Applied to every resource by default\n(read 1000/60s, write 200/60s), overridable per-op, per-resource, or\nproject-wide; `false` opts out at any scope.\n\n- One middleware per feature router maps method→op, keys the limit by\n `<resource>:<op>:<userId>` (falling back to the client IP for anonymous\n callers), and returns `429` + `Retry-After` when over the cap.\n- Unique `(limit, period)` tuples collapse onto shared bindings — a project\n that never declares `rateLimit` ships exactly two (`RL_1000_60`,\n `RL_200_60`), emitted as GA `[[ratelimits]]` blocks in `wrangler.toml` and\n typed `RateLimit` on `CloudflareBindings`.\n- `period` is compile-time constrained to `10` or `60` (Cloudflare binding\n limit); the check no-ops when a binding is absent, so local dev never\n hard-depends on it.\n\n### Envelope encryption — `q.text().encrypted()` (encryption pillar, Phase 1)\n\nMark a text column `.encrypted()` and it is AES-256-GCM-encrypted at rest\nunder a **per-organization key**: a database breach (backup, export, leaked\ntoken, SQL injection, insider read) yields only ciphertext for that column.\nSee [Encryption](/compiler/definitions/encryption).\n\n- Per-org DEKs live wrapped under the `ENCRYPTION_KEK` worker secret in a\n compiler-owned `org_data_keys` table (lazily created, versioned for\n rotation). Deleting an org's row **crypto-shreds** every value it wrote.\n- One write chokepoint: CRUD, batch, and action-layer `db.insert/update`\n all encrypt through the audit wrapper — audit snapshots, webhook\n payloads, and realtime deltas carry ciphertext by construction.\n- Reads decrypt behind the firewall then apply masking; encrypted columns\n are compile-time excluded from `?search`/`?filter`/`?sort`, view query\n allowlists, and embedding sources.\n- `ctx.crypto.encrypt/decrypt` for explicit server-side processing in\n actions; boot guard refuses to serve without the KEK (503 `MISSING_ENV`);\n scaffolded `.dev.vars` now includes a generated `ENCRYPTION_KEK`.\n- The sealed (E2EE) and vault tiers remain compile-gated until built —\n roadmap in `apps/compiler/research/encryption-vault-spec.md`.\n\n### Postgres-style table triggers (`defineTable` / `feature` `triggers:`)\n\nTables can now declare `before`/`after` triggers on `insert`/`update`/\n`delete`, with two lowering lanes and a per-trigger compile report. See\n[Triggers](/compiler/definitions/triggers) for the full reference.\n\n- **`sql:` entries** compile to real SQLite `CREATE TRIGGER` statements,\n shipped in the journaled features migration (content-addressed — an\n unchanged trigger set appends nothing; removing a trigger drops it on the\n next migrate). They fire for **every** write path including raw SQL, run\n atomically with the triggering statement (the only transactional option\n on D1), support `when:` guards and `RAISE(ABORT, ...)` rejection, and\n `OLD.`/`NEW.` column references are validated at compile time. The\n compiler owns the `BEGIN`/`END` frame — emitted uppercase, since\n lowercase `begin` breaks remote D1's statement splitter. On soft-delete\n tables, `*Delete` events map to the `deleted_at` transition (plus a\n hard-delete variant) and `*Update` events exclude it, so a soft delete\n fires delete triggers exactly once. D1 only.\n- **`handler:` entries** run as application hooks at the audit-wrapper\n write chokepoint (REST CRUD + actions). `before*` hooks are synchronous\n and can mutate the payload or throw to reject — the write never executes\n and the request gets `TRIGGER_REJECTED` (422); audit fields are\n re-stamped after hooks and cannot be forged. `after*` hooks run once per\n returned row and are **awaited** — a throw surfaces as\n `TRIGGER_AFTER_FAILED` (500) with `details.committed: true` since the\n write already persisted. Handlers get `{ table, op, values|row, ctx, db,\n env }`; the `db` is audit-wrapped at cascade depth + 1, so hook writes\n stamp audit fields, emit live-view deltas, and fire nested triggers,\n bounded by a depth cap of 5. Each table's drizzle object is auto-imported\n into the generated registry under its authored name, and handler imports\n are usage-filtered and hoisted.\n\nThe compile output includes a lowering/coverage report and fail-closed\nwarnings: `handler:` triggers do **not** fire for queue handlers, cron, or\nraw SQL — guards that must hold universally should use `sql:` +\n`RAISE(ABORT)`. `async: true` (queue-dispatched after-hooks) and\n`withOld: true` (previous-row access) are reserved and rejected at compile\ntime until they ship.\n\nAlso in this change:\n\n- New `trigger` error layer with `TRIGGER_REJECTED` / `TRIGGER_AFTER_FAILED`\n codes in the generated error catalog, OpenAPI spec, and SDK types.\n- Parser: function-valued properties in `defineTable`/`feature` configs now\n parse as compile-time source carriers instead of failing the whole config\n with \"no dynamic expressions\" — unblocks trigger handlers (and\n function-form `access:` / custom masks) through the CLI source path.\n- Fixed a column-injection bug where a comment merely mentioning a column\n name (e.g. `\"deleted_at\"` in a docblock) suppressed audit/soft-delete\n column injection for the table.\n- Fixed a silent no-op: a project declaring `services/queues/*.ts` handlers\n without embeddings or `additionalQueues` deployed a wired `queue` export\n with no `[[queues.consumers]]` to feed it — the handlers were dead code.\n The primary queue (and its typed env binding) is now emitted for\n handlers-only projects, with a compile notice that Cloudflare Queues\n requires the paid Workers plan. Queue emission remains strictly opt-in by\n usage: projects with no queue-backed features (embeddings, queue\n handlers, `additionalQueues`, webhooks) emit no queue configuration and\n deploy on the free plan.\n## v0.47.0 — June 11, 2026\n\n### Breaking: zero-false-positive analyzer checks are now compile errors\n\nThe authz/authn analyzer (v0.37) shipped warn-only. After a release cycle of\ndata, the checks whose every trip is a definite misconfiguration — never a\nlegitimate config — are **promoted to compile errors**. Warnings nobody is\nforced to read are documentation; the pillar guarantees are now enforced.\n\n**Breaking** — a config that previously compiled with one of these warnings\nnow fails the compile:\n\n- `AUTHZ_EMPTY_PERMISSION` — a permission that is structurally unsatisfiable\n (`allOf(a, not(a))`: a fact AND its exact negation at the same AND-level).\n- `AUTHZ_CAPABILITY_CEILING` — a resource's firewall grants a\n `scope:<kind>:<role>` role access beyond its capability profile (or the\n role has no profile at all). This is the M0.2 pillar guarantee — it was\n authored as an error all along and is now enforced.\n- `AUTHN_ROUTE_COVERAGE`, `AUTHN_SURFACE_INVARIANT`,\n `AUTHN_SECRET_CONSISTENCY`, `AUTHN_CREDENTIAL_DELIVERY`,\n `AUTHN_CLAIM_PROVENANCE` — the structural-authn set (route auth coverage,\n bearer-only `/mcp`/agent surfaces + INTERNAL unreachability, mint↔verify\n key/issuer/audience pairing, anchored credential delivery, verifier-only\n identity claims). These still run against empty route/credential metadata\n on a real compile (no-ops until the generators emit it), but the severity\n contract is locked in now — they fail the build the moment they can fire.\n\nThe heuristic/advisory checks are unchanged: `AUTHZ_SHADOWED_ARM`,\n`AUTHZ_UNREACHABLE_ROLE`, `AUTHZ_UNREACHABLE_VIEW`, and\n`AUTHZ_NOT_OVER_RESOURCE` stay warnings; `AUTHZ_PUSHDOWN_COST` stays an info\nreport. `QUICKBACK_AUTHZ_STRICT=true` still promotes those warnings too.\n\n**The override escape hatch** — every promoted finding can be explicitly\naccepted, per finding, with a required reason:\n\n```ts\nauthz: {\n analyzer: {\n allow: [\n {\n check: 'AUTHZ_CAPABILITY_CEILING',\n target: 'sessions/scope:event:organizer', // from the rendered finding\n reason: 'organizer grant profile lands with the v2 rollout (TICKET-123)',\n },\n ],\n },\n}\n```\n\nAn override downgrades that exact `(check, target)` finding back to a warning\nthat cites the reason — even under strict mode (it's an explicit, reasoned\nacceptance). Every rendered error prints its exact override recipe. Guard\nrails: `check` must be one of the promoted ids (unknown or keep-warn ids are\nrejected at config validation), `reason` is required, and an `allow` entry\nthat matches no current finding is itself a compile error — no dead\noverrides accumulating after the underlying issue is fixed.\n\nAnalyzer-internal defects are still fail-open: a bug in the analyzer itself\ndowngrades to a single warning and the compile continues. Only real findings\nfail builds.\n\n### CLI: live views now compile through the CLI\n\n`defineView` files under `quickback/services/views/` were never loaded by\nthe CLI — the compile payload simply omitted them, so\n[live views](/stack/realtime/live-views) (v0.35) only worked when driving\nthe compiler API directly. The CLI now discovers and ships them like every\nother service definition, and the compile summary counts them\n(`Loaded services: … 1 live view(s)`). If you declared views and wondered\nwhy no surface ever went live: upgrade the CLI and recompile.\n\n### CLI: deterministic compile output across machines\n\nFeature and service discovery used raw `readdir` order, which differs\nbetween macOS and Linux — route registration order, schema re-exports,\nOpenAPI paths, and the Neon RLS document's content hash could all churn when\nthe same project was recompiled on a different machine. All discovery sites\nnow sort by codepoint, so the same input compiles to the same bytes\neverywhere. Expect a one-time diff on the first recompile if your previous\noutput was generated in a different filesystem order.\n\n### Fixes\n\n- Read-only resources (no `crud` block) generated routes importing a\n `CRUD_ACCESS` symbol their resource file never exported — a tsc/bundle\n break. The export is now unconditional.\n- The `blog` starter template gated writes on the removed `ADMIN`\n pseudo-role, which hard-fails current compiles; it now uses the\n org-membership `admin` role.\n- `reports/operations.manifest.json` and `reports/conformance.manifest.json`\n now also cover the realtime (`/broadcast/v1`), storage (`/storage/v1`),\n and FGA (`/fga/v1`) surfaces.\n- The dead free/pro tier plumbing is gone: no Tier row in\n `quickback whoami`, no upsell copy at login. Compiling complete projects\n requires login, exactly as before — there was never a paid gate behind it.\n- The CLI is published to npm via trusted publishing (GitHub OIDC) — signed\n provenance, no long-lived npm token in the pipeline.\n\n## v0.46.0 — June 11, 2026\n\n### Breaking: \"no organization context\" responses unified on HTTP 403\n\nGenerated APIs used to answer the same semantic condition — *the caller has no\nactive organization context* — with two different statuses: `400 ORG_REQUIRED`\nfrom the collection list guard and the create/PUT/batch org validation, but\n`403 ACCESS_NO_ORG` from standalone actions and `403\nACCESS_TENANT_SCOPE_REQUIRED` from unsafe org-scoped actions. Clients and SDKs\nhad to special-case the split.\n\n**Breaking** — recompile + redeploy required; every \"no org context\" denial is\nnow **403**:\n\n- `GET /api/v1/<resource>` (and views) without an active org or\n `?organizationId=` → `403 ORG_REQUIRED` (was 400).\n- `POST /`, `PUT /:id`, `POST /batch`, `PUT /batch` without an active org →\n `403 ORG_REQUIRED` (was 400).\n- Standalone actions (`403 ACCESS_NO_ORG`) and unsafe org-scoped actions\n (`403 ACCESS_TENANT_SCOPE_REQUIRED`) were already 403 and are unchanged.\n\nError **codes are unchanged** — `ORG_REQUIRED`, `ACCESS_NO_ORG`, and\n`ACCESS_TENANT_SCOPE_REQUIRED` keep their identities, so clients that\ndiscriminate on `code` need no changes. Only clients that branch on the raw\n`400` status for these responses must update to `403`.\n\n### Breaking: root-mounted actions lose their nested alias URLs\n\nA standalone action whose declared `path:` lives outside its feature prefix\n(e.g. `path: \"/reports/orders\"` in the `orders` feature) mounts at the root:\n`/api/v1/reports/orders`. That root URL is the one the OpenAPI spec, the MCP\nsurface, and the operations manifest have always advertised — but the\ngenerated per-feature routes file *also* carried an undocumented, fully-gated\ncopy at the nested `/api/v1/<feature><path>` URL (e.g.\n`/api/v1/orders/reports/orders`).\n\n**Breaking** — the nested alias is no longer emitted. One URL per operation:\na root-mounted action exists only at its advertised `/api/v1<path>` mount.\nAnything calling the unadvertised nested URL gets a 404 after recompile +\nredeploy; switch to the documented root URL. Actions declared *under* the\nfeature prefix are untouched, and a feature whose standalone actions are all\nroot-mounted no longer emits an (empty) feature actions routes file.\n\n### Behavior change: `PUBLIC` inside `or:` arms admits anonymous callers\n\n[Access](/compiler/definitions/access) has always documented `PUBLIC` as\nworking on every access node, but the emitted auth gate only honored it in a\nflat `roles: [...]` list. A tree like\n\n```ts\naccess: {\n or: [\n { roles: [\"PUBLIC\"] },\n { roles: [\"admin\"] },\n ],\n}\n```\n\nstill answered anonymous callers with `401`. The auth gate is now tree-aware\nand matches the documented semantics: a `PUBLIC` `or:` arm admits anonymous\ncallers past the authentication gate (an `and:` group admits them only when\n*every* arm does), and the access / org / firewall layers still evaluate the\nfull tree. One shared predicate now drives the emitted gates, the OpenAPI\n`security` blocks, and view routes (which gate per view on the\nview-effective access).\n\n**Worth a loud note:** if you have a nested `PUBLIC` arm that was silently\n401-ing, that endpoint becomes anonymously reachable after recompile —\nexactly what the config declares, but verify it's what you meant. `PUBLIC`\naudit logging applies to the newly-admitted routes as usual.\n\n### Realtime broadcasts now enforce `requiredRoles` and masking\n\nA table's declared realtime gates weren't being applied to the generated\nCRUD broadcasts: `realtime: { requiredRoles: [...] }` and column masking were\nhonored on the HTTP surface but not on the WebSocket fanout. The docs\npromised per-role, masked realtime delivery; the generated broadcasts now\nmatch it. **Recompile and redeploy** any project using realtime on\nrole-gated or masked tables.\n\nGenerated `realtime.insert / update / delete` calls now carry:\n\n- **`targetRoles`** — the table's `realtime.requiredRoles` (post role-\n hierarchy `+` expansion), enforced per subscriber at fanout.\n- **`maskingConfig`** — serialized from the same effective masking\n (declared + auto-detected sensitive columns) the HTTP mask functions are\n generated from. What HTTP masks is what the WebSocket wire masks.\n\nLive-view `view_changes` deltas honor the same table-level `requiredRoles`\nat fanout, so a role-gated table can't leak through a\n[live view](/stack/realtime/live-views) subscription either.\n\nNotes:\n\n- Recompile suffices — no config change needed.\n- If you worked around this with hand-written `realtime.*` calls passing\n `targetRoles` / `maskingConfig`, those workaround broadcasts can be\n removed.\n- `type: 'custom'` mask functions can't ride the wire — the Broadcaster\n fails closed and broadcasts `[REDACTED]` for those columns.\n- Tables without `requiredRoles` or masking are byte-identical: the open\n broadcast default is unchanged.\n\n### Batch operations inherit the base operation's access\n\nWhen a batch operation was declared without its own `access`, it didn't pick\nup the base operation's role requirement:\n\n```ts\ncrud: {\n update: { access: { roles: [\"admin\"] } },\n batchUpdate: { maxBatchSize: 25 }, // ← no access of its own\n}\n```\n\nA batch config declared without `access` now inherits the base operation's\naccess at compile time — fail closed, so runtime, the OpenAPI spec, and the\ngenerated code all agree. Explicit batch `access` still wins (including\nper-side on upserts); a base op without access still yields an\nauthenticated-only batch op. The flat `update: { batch: true }` shape and\nauto-promoted batch ops were never affected. **Recompile and redeploy** if\nyou use the explicit-batch shape without per-batch access.\n\n### Record actions, PUT upserts, and legacy firewall arms fail closed\n\nThree fail-closed hardening fixes, found and verified against the new\nconformance catalog (route × principal expectations derived from the\ncompiler's own IR — see the\n[conformance manifest](/compiler/targets/hono-api/using-the-api/openapi#operations-manifest)).\nAll apply on recompile + redeploy; no config change needed:\n\n- **Record actions evaluate the role gate before fetching the record**, so\n the denial response no longer varies with record state — a uniform\n `403 ACCESS_ROLE_REQUIRED`. (Bulk actions already had this order; unsafe\n actions write their audit row on the pre-record denial.)\n- **PUT upsert treats an out-of-scope id as a firewall miss** (`403` reveal /\n `404` hide, per your firewall error mode; a standard 207 miss entry on\n `PUT /batch`) instead of routing it into the create path. Genuinely new\n ids keep the create path.\n- **Legacy (array-form) firewall arms deny cleanly when a bound context\n claim is absent at runtime** (e.g. no active org), rather than surfacing a\n database error — the same deny-when-absent behavior the explicit `all:` /\n `any:` group forms already had.\n\n### Root-mounted standalone actions use the standard gate stack\n\nStandalone actions mounted outside their feature prefix\n(`path: \"/reports/orders\"`) were emitted through a separate code path that\ndid not apply the full access / audit / scoped-database treatment that\nin-feature standalone actions receive. They now render through the same\ngenerator, so the same access checks, security-audit writes, and\ntenant-scoped database wrapping apply everywhere. If you use root-mounted\nstandalone actions, recompile and redeploy. (Unifying the two code paths is\nalso what surfaced the two breaking changes above.)\n\n### Namespace routing fixes\n\n- An action whose declared `path` exactly equals its namespace prefix is now\n claimed by the namespace like any nested action (Hono's `/x/*` mount\n already matched the bare `/x`) — it's served through the namespace's gate\n instead of carrying a second inline copy of the resolver.\n- A namespace with zero claimed standalone actions (e.g. record-based-only)\n no longer mounts its middleware at all — a dead gate can no longer\n intercept requests under its prefix.\n\n### Custom org roles work with Better Auth member management\n\nCustom roles referenced in access trees (e.g. `roles: [\"support\"]`) are now\nauto-registered with the Better Auth organization plugin. They were already\nenforceable on routes but unprovisionable through Better Auth —\n`invite-member` / `update-member-role` rejected them with\n`400 ROLE_NOT_FOUND`, so there was no supported way to actually give a\nmember the role. Auto-registered roles carry member-equivalent permissions\n(this is about assignability; your access trees remain the authorization\nmodel). If you pass your own `roles` / `ac` to the organization plugin\noptions, those win and auto-registration is skipped. Built-in, pseudo, and\n`scope:` roles are excluded; projects with no custom roles emit\nbyte-identical output.\n\n### snake_case tables: dropped record actions and broken helpers fixed\n\nTwo fixes for tables declared with snake_case names (`event_notes`):\n\n- The generated `.quickback/define-action.ts` helpers imported the camelCase\n identifier while the generated alias file exports the verbatim declared\n name (`export { event_notes }`) — a TS2724 compile failure for any\n snake_case table with action files. The helpers now import the real export\n aliased to the camelCase local.\n- Record actions on a snake-declared table living in a kebab-named feature\n file (`event-notes/actions/pin.ts`) were not emitted — missing from both\n the generated routes and OpenAPI. They now emit and document consistently.\n\nIf you have snake_case tables with record actions, recompiling **adds routes\nthat previously didn't exist** — review the new surface.\n\n### First-class MCP OAuth config: `auth.oauth`\n\nThe OAuth 2.1 surface behind `agents.mcp.requireAuth` (v0.42.0) gains a\nfirst-class config block — env-resolvable issuer / login / consent URLs,\nscopes, RFC 8707 audiences, and a dynamic-client-registration toggle:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n oauth: {\n enabled: true,\n issuerUrl: { env: \"OAUTH_ISSUER_URL\", fallback: \"http://localhost:8787/auth/v1\" },\n loginPage: { env: \"OAUTH_LOGIN_URL\", fallback: \"http://localhost:8787/account/login\" },\n consentPage: { env: \"OAUTH_CONSENT_URL\", fallback: \"http://localhost:8787/account/consent\" },\n scopes: [\"openid\", \"profile\", \"email\", \"offline_access\"],\n audiences: [{ env: \"OAUTH_MCP_AUDIENCE\", fallback: \"http://localhost:8787/mcp\" }],\n allowDynamicClientRegistration: true,\n },\n}),\n```\n\nSetting it auto-enables the `oauthProvider`, `jwt`, and `bearer` plugins,\nemits the RFC 8414 / RFC 9728 discovery documents, and accepts the\nprovider's JWKS-signed access tokens in the standard auth middleware. A new\nproject hook, `quickback/hooks/resolve-oauth-context.ts`, lets you derive\ntenant fields (`activeOrgId` / `activeTeamId` / roles) from the validated\nOAuth identity. On Neon, the auth schema is now owned by the Better Auth CLI\nend to end (the compiler no longer emits its placeholder `src/auth/schema.ts`\nor `src/lib/neon.ts`). See\n[OAuth Provider (MCP-ready)](/stack/auth/plugins#oauth-provider-mcp-ready)\nand [Auth Hooks](/stack/account-ui/hooks#oauth-context-resolver).\n\n### Neon RLS covers force-enabled plugin tables\n\nOn Neon, row-level-security policies are generated for the Better Auth\ntables. The list of tables receiving policies was derived from your declared\nauth config and didn't account for plugins the compiler force-enables\nautomatically — so some auth-owned tables could be created without RLS\npolicies. The list now derives from the fully resolved plugin set, so every\ngenerated auth table receives appropriate policies (self-scoped where there\nis a clear owner, service-role-only otherwise — fail closed). The RLS\nmigration is content-addressed, so the update arrives as a new journaled\nentry on the next recompile + `db:migrate`. **Neon projects should recompile\nand run `db:migrate`.**\n\n### New compile reports: operations + conformance manifests\n\nEvery compile now writes two machine-readable reports next to\n`openapi.json`:\n\n- **`reports/operations.manifest.json`** — a stable, sorted index of every\n operation: `{ operationId, method, path, auth, feature, kind }`, covering\n the resource, action, view, auth, realtime, storage, and FGA surfaces. An\n extend-only public contract — the recommended integration point for\n scripting against the generated surface.\n- **`reports/conformance.manifest.json`** — for each route × principal\n class, the expected outcome (allow / 401 / 403 / cross-tenant miss …),\n derived from the same IR the emitters consume. This is the artifact the\n conformance fixes above were found and verified against.\n\nThe OpenAPI generator itself now reads the same IR as the route emitters, so\nthe spec follows the emitted surface by construction — including four\naccuracy fixes: `PUT /{id}` is documented only when actually enabled, the\nbatch surface documents the emitter's auto-promotion + access inheritance,\nand views document their effective (view-level, falling back to read-level)\naccess. See\n[Operations manifest](/compiler/targets/hono-api/using-the-api/openapi#operations-manifest).\n\n## v0.45.0 — June 9, 2026\n\n### `auth.jwt.revocationCheck: 'kv'` — sub-TTL JWT revocation\n\nThe JWT fast-path trusts signed claims for their full lifetime — that's what\nmakes it a fast-path. Until now the only revocation bounds were the TTL\n(plain claims) and the carry-forward cap (scope claims, v0.44.0). The\nlong-promised `'kv'` mode is now real on the **Cloudflare runtime**:\n\n```ts\nauth: { jwt: { revocationCheck: 'kv' } }\n```\n\n- **Per-principal revocation timestamps, not per-token denylists.** A\n revocation event writes \"everything for this principal minted before now is\n dead\" to the project's **existing `KV` binding** (keys prefixed `qbrev:`) —\n nothing extra to provision. Entries self-expire after the maximum token\n lifetime, so the store never accumulates.\n- **The bearer fast-path checks before trusting.** A verified token whose\n `iat` (or `sct`, for the relationship-scope claim) predates the stored\n timestamp is rejected and falls through to session auth, which re-checks\n membership and re-mints — an active legitimate session recovers\n transparently. Costs 2+ edge-cached KV reads per bearer verify; the\n explicit trade the opt-in buys.\n- **Written automatically where revocation actually happens:** org-member\n removal and role change (Better Auth `organizationHooks`), and\n UPDATE/DELETE of scope-conferring relationship rows — through the same\n audit-wrapper write chokepoint Live Views uses, plus the single DELETE\n route (which has the row in hand but no `.returning()`). Revoke-on-touch:\n a false positive just forces a cheap re-prove.\n- **User bans flip automatically.** The Better Auth admin plugin's ban lands\n as a user-row update, so a generated `databaseHooks.user.update.after` hook\n stamps the user-level revocation the moment `banned` flips — every\n outstanding JWT dies on its next use, and the cookie/session path already\n rejects banned sessions, completing the lockout. When outbound webhooks are\n configured, the same hook emits a `user.banned` event so subscribed\n endpoints are notified.\n- **App-code helpers** for everything else: `src/lib/jwt-revocation.ts`\n exports `revokeUserTokens` / `revokeMemberTokens` / `revokeScopeTokens`\n (e.g. call `revokeUserTokens` from a custom revoke-all flow).\n- **Fails open.** A KV outage degrades revocation to the TTL /\n carry-forward-cap bound — it never locks every bearer out.\n\nBun/Node + `'kv'` fails at compile time with a clear message (the store rides\nthe Cloudflare KV binding; those runtimes own immediate-revoke via the\ncookie/session path). Default remains `'none'`; without the flag the emitted\nmiddleware is byte-identical to v0.44.0.\n\n### Neon: `npm run db:migrate` now applies the RLS layer\n\nThe RLS SQL (helper functions, policies, triggers) used to be emitted as\norphaned `drizzle/migrations/0099–0102` files that no tool ever applied —\n`db:migrate` ran the schema migrations and silently skipped the security\nlayer. The RLS document now rides the journaled drizzle set in\n`quickback/drizzle/` as a content-addressed migration\n(`<idx>_quickback_rls_<hash>`), so one `npm run db:migrate` applies schema\n**and** security, in dependency order. The migration is idempotent\n(`DROP POLICY IF EXISTS` + re-create), so it converges over databases where\nthe old files were applied by hand; an unchanged security config appends\nnothing (the journal stays byte-stable across recompiles), and a changed one\nappends a new content-addressed entry — append-only, like every other\nmigration. Existing Neon projects: recompile + `db:migrate`, nothing breaks.\n\n### Neon: `user_sessions` is real, and the SQL layer speaks TEXT ids\n\n`get_active_org_id()` — the helper every org-scoped RLS policy reads — was\nquerying a `public.user_sessions` table that **no migration created**, and\nthe helper layer was typed `uuid` against Better Auth's TEXT ids\n(`org_abc123`), which would throw on first contact. Now:\n\n- `user_sessions` is compiler-owned migration state\n (`src/db/rls-support.schema.ts`), created by the normal journaled flow\n with a FK to the users table — outside `src/auth/schema.ts`, which the\n Better Auth CLI rewrites.\n- Generated Better Auth session hooks mirror the session's active\n organization (and team, in teams mode) into it on create/update.\n Switching to \"no org\" nulls it through — SQL-side access revokes, fail\n closed.\n- The RLS helper layer (`get_active_org_id`, `get_active_team_id`,\n `is_owner`, the audit helpers) is TEXT-typed to match Better Auth ids.\n- Policies for Better Auth's own tables use the plural physical names the\n BA CLI actually generates on Neon, and BA tables no longer get Quickback\n audit triggers for columns they don't have.\n\n### Hard deletes wire into the audit pipeline correctly\n\nTwo codegen bugs around `delete: { mode: 'hard' }`:\n\n- Firewall auto-detection emitted an `isNull(deletedAt)` predicate for\n tables with no soft-delete column — every read on a hard-delete table\n referenced a column that doesn't exist.\n- Hard-delete routes import the `logHardDelete` audit helper, but the helper\n file was only emitted when the project also had unsafe or `PUBLIC` actions\n — a project with hard deletes and neither failed at deploy time. Hard\n deletes are now a first-class trigger of the security-audit pipeline\n (helper file, `AUDIT_DB` binding, env types, audit migration); on D1 that\n means [`auditDatabaseId`](/compiler/config/providers) is required, and the\n compile error says so.\n\n### Generated output is now typechecked — with the first crop of fixes\n\nEvery compiler change now compiles a matrix of fixture projects and runs\n`tsc` + `wrangler deploy --dry-run` against the **generated output** — the\nclass of bug where the compiler emits syntactically valid TypeScript that\nfails downstream. The first runs caught real ones, all fixed here:\n\n- **Neon:** `src/db/org.schema.ts` re-exported tables that don't exist after\n the Better Auth CLI's plural rewrite; a missing `AuthDatabase` type\n export; transaction callbacks typed bare `(tx)` failing `noImplicitAny`;\n the auth middleware's member-table fallback hardcoded the singular name.\n- **Embeddings:** the queue consumer's `Ai.run` result and the optional\n `EMBEDDINGS_QUEUE` binding both failed strict checks — the route now\n returns a structured `503` when the producer binding is missing instead\n of crashing.\n- **snake_case relationship tables:** relationship/arrow emitters imported\n the camelCase identifier where the generated file exports the verbatim\n table name (`export { event_guests }`) — TS2724 for any snake_case\n relationship table. Imports now alias the real export\n (`event_guests as eventGuests`).\n\n## v0.44.0 — June 9, 2026\n\n### Scope carry-forward is now bounded (revocation fix)\n\nThe auth middleware's rolling refresh re-signs a verified `scope` claim on\nevery authed call without re-probing the relationship — that's what lets a\nscoped session ride past the short JWT TTL with zero per-request DB cost. But\nunbounded, it defeated the revocation model the docs promised: a removed\nguest/staff who kept polling got a fresh TTL on every request, so \"removal\ntakes effect within one TTL\" only held for *idle* clients, and the refresh\nalso bypassed the ≤180s scope-token ceiling (it re-signed with the raw\n`auth.jwt.expiresIn`).\n\nScope tokens now carry a proof timestamp (`sct`), stamped exclusively by the\nproven mint sites (`POST /scope/v1/enter` and the namespace resolver, via the\nshared mint helper). The rolling refresh:\n\n- **refuses once the claim's proof is older than the carry-forward cap\n (15 minutes)** — past it, the token expires within one TTL and the client\n re-proves via `enter` or any minting namespace route, which won't re-mint a\n revoked role. Worst-case post-revocation window for an active client:\n **cap + one TTL** from the last real proof, instead of unbounded.\n- **carries `sct` forward verbatim** — the refresh can never restart the\n window without an actual relationship probe. Claims without `sct`\n (pre-0.44 tokens) fail closed and simply stop refreshing.\n- **signs through the same ≤180s ceiling as the mint sites** — an\n `auth.jwt.expiresIn` above the ceiling no longer leaks into scope-bearing\n tokens via the refresh path.\n\nNo client changes needed: tokens renew exactly as before inside the window,\nand re-entering is the existing flow. For tables where even the capped window\nis too wide, gate with a `via` arm (live relationship subquery per request)\ninstead of a bare `ctx.scope.<kind>` arm; immediate revocation\n(`auth.jwt.revocationCheck: 'kv'`) remains on the roadmap.\n\n## v0.43.0 — June 4, 2026\n\n### Better Auth 1.6\n\nGenerated projects are now pinned to Better Auth **1.6**. The `agents.mcp.requireAuth` work in 0.42.0 surfaced a long-standing version drift: the compiler emitted `better-auth: ^1.5.0`, but `@better-auth/oauth-provider` resolves a tree that requires `@better-auth/core ^1.6.14` and imports `@better-auth/core/utils/host` + `/redirect-uri` — subpaths that only exist in 1.6.x. The result was a `wrangler deploy` that failed at bundle time with `Could not resolve …` and never uploaded.\n\nThis release aligns the **entire** Better Auth dependency set to a coherent 1.6.9 floor so npm resolves one consistent tree:\n\n- `better-auth`, `@better-auth/drizzle-adapter`, `@better-auth/api-key`, `@better-auth/passkey`, `@better-auth/oauth-provider` → `^1.6.9` (generated projects, the baked Docker deps, and the bundled CMS/Account SPAs).\n- Added an explicit `kysely ^0.28.16` pin: Better Auth 1.6's migrator imports `DEFAULT_MIGRATION_TABLE` / `DEFAULT_MIGRATION_LOCK_TABLE` from kysely but doesn't *declare* kysely, so the Worker bundle needs it pinned directly.\n\nNo code migration was required — Quickback already uses `@better-auth/oauth-provider` (not the now-deprecated OIDC Provider plugin), and emits no `freshAge`/SAML usage affected by 1.6's behavioral changes. Verified end to end: a `requireAuth` project and a normal project both `npm install` a clean 1.6.14 tree and bundle with `wrangler deploy --dry-run` with zero resolution errors.\n\n### Larger migration histories no longer hit the upload ceiling\n\nLong-lived projects accumulate one full-schema drizzle snapshot per migration, and the whole cumulative meta payload (snapshots + journals + `.sql`, across both the auth and features dirs) is re-sent on **every** compile — even a no-schema-change one. Projects with deep migration histories were hitting the compiler's `existingFiles` size limit and failing to compile, with no schema drift and nothing to fix on their end.\n\nThe server-side ceilings are raised so this is no longer the binding constraint:\n\n- `existingFiles` payload: **4 MiB → 16 MiB**\n- total request body: **8 MiB → 32 MiB** (kept above the per-category limits so it doesn't trip first)\n\nThis is enforced entirely on the compiler, so no CLI upgrade is needed — the new headroom applies as soon as `compiler.quickback.dev` is on this release.\n\n### Custom response headers (`security.headers`)\n\nThe generated Worker emitted a fixed set of security headers (CSP, HSTS,\n`X-Content-Type-Options`, …) with no supported way to add your own — teams that\nwanted, say, an `X-Server-Version` build stamp on every response had to\npost-patch the generated middleware after each compile.\n\nNew `security.headers` sets arbitrary response headers natively. Values are\nstatic strings or templates interpolating per-deploy Worker env vars via the\n`{{env.VAR_NAME}}` token:\n\n```ts\nsecurity: {\n headers: {\n // Both vars must be set, or the header is omitted entirely.\n 'X-Server-Version': '{{env.SERVER_VERSION}}+{{env.SERVER_BUILD}}',\n 'X-Powered-By': 'Quickback',\n },\n}\n```\n\n- **Omit-if-unset** — a header that references env vars is emitted only when\n *every* referenced var is set (non-empty) at runtime. A Worker that forgot to\n inject the var emits no header, never `X-Server-Version: undefined`. Static\n headers are always emitted.\n- The value is read from `c.env` per request, so it picks up whatever Worker\n var is injected at deploy time — nothing is baked at compile time.\n- **Managed headers are rejected** — names owned by a dedicated `security` field\n (CSP, HSTS, `X-Frame-Options`, `Referrer-Policy`, …) error at compile so the\n two emitters can't race. Malformed `{{env…}}` tokens error too, rather than\n leaking literal braces into the wire header.\n\nSurvives a clean `quickback compile` with no post-processing. See\n[Security Headers → Custom response headers](/compiler/config/security#custom-response-headers).\n\n## v0.42.0 — June 4, 2026\n\n### Interactive OAuth for the generated MCP server\n\nMCP connectors (Claude, Cursor, …) could only connect to a generated `/mcp`\nendpoint **anonymously** — they never launched a sign-in flow, so auth-gated\ntools stayed invisible. The OAuth machinery was already present (Better Auth's\n`oauth-provider` ships `/oauth2/authorize`, `/token`, `/register` + PKCE under\n`/auth/v1`); the compiler just never let a connector discover or trigger it.\n\nNew `agents.mcp.requireAuth` makes the MCP surface authenticated-only:\n\n```ts\nagents: { mcp: { requireAuth: true } },\n```\n\nWhen enabled, the compiler:\n\n- **Challenges unauthenticated `/mcp`** with `401` + `WWW-Authenticate: Bearer\n resource_metadata=\"…\"` ([RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) §5.1) — the signal connectors use to start OAuth.\n- **Force-enables `oauthProvider` + `bearer`**, so `/oauth2/authorize`, `/token`,\n and `/register` ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591) dynamic client registration) exist with PKCE.\n- **Delegates `/.well-known/oauth-authorization-server`** to Better Auth's real\n metadata instead of a hand-rolled stub that advertised a non-existent\n authorization endpoint.\n- Adds the `<origin>/mcp` resource to `validAudiences`\n ([RFC 8707](https://datatracker.ietf.org/doc/html/rfc8707)) so the connector's access token isn't rejected.\n\nLogin and consent are served by your Account SPA, so users authenticate with\nwhatever methods you already enabled. Default is unchanged (anonymous public\ntools); set `requireAuth: true` for servers meant for authenticated users.\n\n## v0.40.2 — June 3, 2026\n\n### Passwordless plugins can no longer bypass the signup gate\n\nBetter Auth's `emailOtp` and `magicLink` plugins auto-create an account when a\ncode/link is verified for an unknown email — and that path is independent of\n`emailAndPassword.disableSignUp`. As a result, `account.auth.signup: false`\nclosed `POST /auth/v1/sign-up/email` but left OTP / magic-link verification as an\nopen back-door for account creation.\n\nThe compiler now emits each plugin's own `disableSignUp` flag, and new\nper-plugin options expose it directly:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: {\n emailOtp: { disableSignUp: true }, // OTP sign-in only; unknown emails rejected\n magicLink: { disableSignUp: true }, // same for magic links\n },\n}),\n```\n\nBoth default to following the global gate: setting `account.auth.signup: false`\n(→ `emailAndPassword.disableSignUp: true`) now also gates the OTP and magic-link\npaths automatically. Set `{ disableSignUp: false }` on a plugin explicitly to\nkeep its sign-up open while password sign-up stays closed.\n\n## v0.40.1 — June 2, 2026\n\n- The generated `wrangler.toml` and `Env` type now emit the `ASSETS` binding\n type for projects that mount SPAs (CMS / Account), so handler code that\n references `c.env.ASSETS` typechecks.\n- Compiler Docker builds preserve their layer cache across rebuilds, cutting\n local recompile time.\n\n## v0.40.0 — June 2, 2026\n\nR2 file storage is now **presign-only by default**. Adding\n`defineFileStorage(\"cloudflare-r2\")` emits just the `ctx.storage` signer — no\nFILES_DB database, no `/storage/v1/*` endpoints, no files worker. You sign\npresigned URLs against a bucket and store references in your own table. The\nturnkey managed subsystem is still available, now behind `managed: true`.\n\nThis decouples the lightweight primitive from the heavyweight subsystem so you\ncan add uploads without standing up a metadata database you don't use.\n\n### Presign-only by default; managed is opt-in\n\n```ts\n// Presign-only (default) — ctx.storage against a bucket, nothing else\ndefineFileStorage(\"cloudflare-r2\", { bucketName: \"my-app-media\" })\n\n// Managed subsystem — FILES_DB + /storage/v1/* + files worker\ndefineFileStorage(\"cloudflare-r2\", { managed: true })\n```\n\n- New projects can omit `bucketName` — it defaults to `<project>-media`, so\n setup is one `wrangler r2 bucket create` plus the R2 API-token secrets.\n- Existing projects set `bucketName` to a bucket they already have. Presign-only\n emits **no** R2 bucket binding and **no** FILES_DB binding — nothing to\n provision, nothing to migrate.\n\n### Per-call bucket + custom secret names\n\n```ts\n// Sign against a different bucket than the configured default\nawait storage.signPutUrl(key, { bucket: \"my-app-public\", contentType });\n```\n\nIf your project already stores R2 credentials under different env-var names,\nmap them so the signer reads yours:\n\n```ts\ndefineFileStorage(\"cloudflare-r2\", {\n bucketName: \"my-app-media\",\n presign: { accountIdEnv: \"CF_ACCOUNT_ID\", accessKeyIdEnv: \"S3_KEY\", secretAccessKeyEnv: \"S3_SECRET\" },\n})\n```\n\n### Fixes\n\n- `maxFileSize` now accepts a human string (`\"100mb\"`, `\"5gb\"`) as well as a\n number of bytes — previously a string emitted invalid TypeScript.\n- Presign-only no longer emits a stray `FILES_DB` `[[d1_databases]]` block (with\n an invalid `database_id = \"local-files\"`) into `wrangler.toml`, which would\n have made `wrangler deploy` reject the worker.\n\n## v0.39.1 — June 2, 2026\n\nDeduplicate colliding OpenAPI `operationId`s. The auto-generated list id\n`list\n</Button>\n```\n\n`ResponsiveModal` survived the migration unchanged — it composes the higher-level Dialog + Drawer wrappers (preserved public API), not the underlying primitives.\n\n#### Caller-side API changes worth noting\n\nBase-ui ships some real behavioural changes the Radix variants didn't:\n\n- `<Select onValueChange>` now receives `(value: string | null, eventDetails) => void` (was `(value: string) => void`). Existing `Dispatch<SetStateAction<string>>` setters reject `null` — wrap callbacks defensively: `onValueChange={(v) => v != null && setX(v)}`.\n- `<DropdownMenuContent forceMount>` removed (base-ui has no `forceMount`). Use base-ui's `keepMounted` on the Popup/Positioner if you need to preserve unmounted state.\n- Component sub-names shifted (`Dialog.Content` → `Dialog.Popup`, `Dialog.Overlay` → `Dialog.Backdrop`). Data attributes are now `data-open` / `data-closed` (no more `data-state=\"open\"`).\n\n#### Adding a new primitive after this release\n\n```bash\ncd packages/ui\npnpm dlx shadcn@latest add <component> --overwrite --yes\n# Sweep generated `@/` imports to relative paths — the SPAs' vite-tsconfig-paths\n# plugin doesn't see packages/ui's @/* mapping at bundle time:\nsed -i.bak \\\n -e 's|\"@/lib/utils\"|\"../lib/utils\"|g' \\\n -e 's|\"@/components/|\"./|g' \\\n -e 's|\"@/hooks/|\"../hooks/|g' \\\n components/<component>.tsx && rm components/<component>.tsx.bak\n```\n\nIf the new primitive pulls in fresh deps, mirror them into `apps/compiler/deps-spa-{cms,account}-package.json` per the SPA build pipeline or Docker SPA builds will fail.\n\n---\n\n## v0.18.1 — May 18, 2026\n\n### Account SPA — teams, active-team picker, permission-aware UI\n\nThe Account SPA's organization surface is now feature-parity with Better Auth's `organization` plugin for the basic team workflow, and replaces the long-standing hardcoded `role === 'owner' || 'admin'` checks with `checkRolePermission` so projects that ship custom roles get a UI that respects them.\n\n#### Teams (opt-in)\n\nWhen the BA config enables teams — `organization({ teams: { enabled: true } })` — the compiler emits `VITE_ENABLE_ORG_TEAMS=true` and the Account SPA exposes a Teams tab on each organization:\n\n- **Teams index** (`/$slug/teams`) — splits into \"Your teams\" (from `listUserTeams`) and \"Other teams\" so non-admins land on what's relevant. Create / rename / delete from the list, gated on `team:create` / `team:update` / `team:delete`.\n- **Team detail** (`/$slug/teams/$teamId`) — member roster with add / remove, joining `listTeamMembers` against the org's full member list for display.\n- **Active-team picker** in the org header — calls `setActiveTeam` and exposes the choice via `OrganizationContext.activeTeamId` so downstream routes (and the BA `session.activeTeamId` server-side) stay in sync.\n- **Team-aware invites** — `InviteMemberDialog` shows an optional team picker when teams are on and forwards `teamId` to `inviteMember`, so accepting the invite drops the new member straight into the right team.\n\nTeams are loaded once by the `$slug` layout (`listTeams` + `listUserTeams`) and exposed via `OrganizationContext.teams` / `userTeamIds` / `refreshTeams`, so individual team routes don't re-fetch the list.\n\n#### Permission-aware UI via `checkRolePermission`\n\n`OrganizationContext.isOwnerOrAdmin` is gone. Routes now read `can(resource, action)` from context, which delegates to `authClient.organization.checkRolePermission` — synchronous, no roundtrip, and aware of any custom roles registered via the BA `ac` option. Multi-role users (BA stores multiple roles comma-separated) are handled by checking each role; the action is allowed if any role grants it.\n\nMigrated sites:\n\n- `$slug.tsx` tab gates → `can('invitation', 'create')`, `can('organization', 'update')`\n- `members.tsx` action menu → `can('member', 'update' | 'delete')`; the owner-hierarchy guard (non-owners can't touch owner-role members) is preserved as a client-side mirror of BA's server enforcement\n- `invitations.tsx` → `can('invitation', 'create' | 'cancel')` gates the Invite button, resend, and cancel separately\n- `settings.tsx` → `can('organization', 'update')` for the form, `can('organization', 'delete')` for the danger zone (was owner-only)\n- `teams.tsx` / `teams.$teamId.tsx` → `can('team', 'create' | 'update' | 'delete')`\n\nProjects on the default three-role hierarchy see no behaviour change; projects that defined `admin`/`member` overrides via BA's access-control API now get a UI that matches what the server will actually authorize.\n\n#### Editable slug + metadata on organization settings\n\nThe `$slug/settings.tsx` form now edits two more `organization.update` fields:\n\n- **URL slug** — full debounced `checkSlug` flow (mirroring the create-org form); on rename, the SPA navigates to `/${newSlug}/settings` and the layout re-fetches with the new slug.\n- **Metadata** — single `Record<string, any> | null` JSON textarea, parsed on submit with inline error messaging. Empty clears the field.\n\nSlug rename is non-breaking for the SPA itself, but every external link / bookmark that references the old slug becomes a 404 — the form warns about this before saving.\n\n#### Auth client wiring\n\nWhen `VITE_ENABLE_ORG_TEAMS=true`, the SPA's `organizationClient(...)` is instantiated with `teams: { enabled: true }` so the team APIs are typed end-to-end. When the flag is off, team methods aren't surfaced — and the Teams tab is hidden — keeping the bundle and UI honest about what the server actually supports.\n\n---\n\n## v0.18.0 — May 17, 2026\n\n### `config.apps` — mount user-authored SPAs on dedicated hostnames\n\nThe compiler now generates per-hostname Worker middleware for arbitrary user SPAs alongside the built-in CMS and Account UIs. Previously the only way to host a product app next to a Quickback API was a second Worker; `config.apps` brings the full stack — API, account, and product UI — onto one deployment with same-origin auth.\n\n```ts\napps: {\n www: {\n domain: \"www.example.com\",\n aliasDomains: [\"example.com\"], // apex serves the same SPA\n },\n}\n```\n\nEach entry binds one or more hostnames to a directory under `src/apps/<name>/` and inherits the Account-domain pass-through behavior — `/api/`, `/auth/`, `/admin/`, `/storage/`, and `/health` route to Hono so the SPA fetches its API without CORS. The compiler:\n\n- emits a `custom_domain = true` route in `wrangler.toml` for the primary hostname and every alias\n- adds each hostname to Better Auth's `TRUSTED_ORIGINS` (when `trustedOrigins` is left unset)\n- widens the CSP `connect-src` to cover the SPA-baked origins\n- folds the new hostnames into shared-parent detection for `crossSubDomainCookies`\n\nDrop the prebuilt SPA bundle at `quickback/apps/<name>/` — the existing source-apps passthrough copies it byte-for-byte into `src/apps/<name>/`. The compiler doesn't build the SPA; it only emits routing for whatever's already there. The names `cms`, `account`, and `public` are reserved; hostname collisions with `cms.domain` / `account.domain` / `account.adminDomain` or between two `apps[*]` entries fail at compile time.\n\nWhen `cms` and `account` are both configured, the multi-domain catchall now explicitly skips app hostnames — an API miss on an app host returns the standard 404 JSON via `app.notFound` instead of stray-serving a sibling SPA's HTML shell.\n\n### Cross-subdomain cookie inference handles apex aliases\n\nThe shared-parent detection that drives `advanced.crossSubDomainCookies` previously reduced any hostname by stripping the leftmost label — `'example.com'` collapsed to `'com'`, which broke equality against sibling subdomains. Apex hostnames (exactly two dot-segments) are now treated as already being the parent, so apex aliases (`example.com` listed alongside `www.example.com`) coexist cleanly with `auth.example.com` / `cms.example.com` and the compiler still emits `crossSubDomainCookies: { enabled: true, domain: '.example.com' }`.\n\n---\n\n## v0.17.2 — May 15, 2026\n\n### `customPlugins` escape hatch on `defineAuth(\"better-auth\", …)`\n\nThe Better Auth provider now accepts `customPlugins` alongside the named-plugin registry — a path to ship third-party plugins (`@better-auth-kit/audit`, …), unregistered built-ins, or one-off project-local plugins without forking the compiler.\n\nEach entry is an explicit import descriptor:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: { passkey: true, organization: true },\n customPlugins: [\n // (1) Project-local plugin file at quickback/plugins/long-session.ts\n { from: \"./plugins/long-session\", export: \"longSessionPlugin\" },\n // (2) Third-party npm package\n {\n from: \"@better-auth-kit/audit\",\n export: \"auditPlugin\",\n args: { events: [\"sign-in\"] },\n dependencies: { \"@better-auth-kit/audit\": \"^1.0.0\" },\n },\n ],\n}),\n```\n\n`from` is either a relative path under `./plugins/` (the CLI auto-uploads matching files from `quickback/plugins/`; the compiler copies them into `src/plugins/<name>.ts` and rewrites the emitted import) or a bare npm specifier (emitted verbatim; declare `dependencies` so the package lands in the generated `package.json`). Omit `args` to emit the symbol uncalled (plugin instance); provide `args` to emit a JSON-serialized factory call.\n\nThe descriptor is validated with Zod — typos in `from`/`export`, paths that escape `./plugins/`, and references to files the CLI didn't ship all fail at compile time with a targeted message.\n\n---\n\n## v0.17.1 — May 14, 2026\n\n### `quickback start` — interactive onboarding\n\n```bash\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n```\n\n`start` walks new users through template selection, scaffolds the project on disk, and only prompts for an account when it's ready to compile. Cancelling at the login prompt leaves the scaffold intact — sign in and run `quickback compile` whenever you're ready.\n\nThe same deferred-auth flow applies to `quickback create`. Scaffolding and (optional) Cloudflare D1 setup run before authentication, so you can preview the project on disk before committing to an account.\n\n### Named views on the free tier\n\nThe `todos` template now ships a `dashboard` named view, exposing a projected response at `GET /api/v1/todos/views/dashboard`. Named views support per-view access rules and per-view field selection while inheriting the table's firewall and masking — the canonical way to ship list-view payloads that are cheaper to fetch and easier to cache than a full collection read.\n\n### `quickback init` removed\n\nFolded into `start` and `create`. The legacy command name prints a deprecation notice pointing at its replacements.\n\n### Minor\n\n- `quickback whoami` reads the stored tier from your credentials.\n- Pro upsell copy in `quickback login` is shown only when the server returns an explicit free-tier subscription.\n- Bare scaffolds (`cloudflare`, `empty`) report accurately when there are no features to generate migrations for.\n\n---\n\n## v0.16.10 — May 14, 2026\n\n### D1-specific safety pass on generated migrations\n\nThe `cloudflare-d1` provider now runs a post-generation pass over every Drizzle migration directory (auth, features, webhooks, audit) before the compile finishes. Better Auth cleanup for retired managed tables is stripped from raw `DROP TABLE` statements. Drop-only cleanup migrations are reordered child-first when foreign-key dependencies require it. Every generated D1 migration directory is replayed against SQLite during compile, so a D1-breaking migration fails at compile time rather than at `wrangler d1 migrations apply`.\n\n---\n\n## v0.16.9 — May 13, 2026\n\n### Resource-scoped realtime tickets\n\n`providers.database.config.realtime` accepts an object form for projects whose WebSocket subscribers aren't org members:\n\n```ts\nrealtime: {\n wsTicket: {\n role: \"attendee\",\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n}\n```\n\nThe generated `/broadcast/v1/ws-ticket` route authenticates the caller, evaluates the declared relationship role against the request, and mints a short-lived WebSocket ticket scoped to the resolved resource. `realtime: true` continues to enable the org-scoped broadcaster.\n\n### Unified broadcast targeting\n\nThe realtime helper and Broadcaster now route by `scopeKey || organizationId || userId`. String targets remain shorthand for `organizationId`; explicit targets can scope a broadcast to a resource or a single user:\n\n```ts\nawait realtime.broadcast(\"event-page-updated\", payload, { scopeKey: \"events:evt_123\" });\nawait realtime.broadcast(\"dm\", payload, { userId: recipientId });\n```\n\nWebSocket tickets are Quickback-minted (signed with `BETTER_AUTH_SECRET`), not Better Auth tokens — Better Auth remains the front-door auth check; Quickback signs the upgrade ticket after authorization succeeds.\n\n---\n\n## v0.16.8 — May 13, 2026\n\n### One auth transport per request\n\nGenerated middleware treats `Cookie`, `Authorization: Bearer`, and `x-api-key` as distinct auth methods and rejects mixed requests with `400 AUTH_METHOD_CONFLICT`. Query-string API keys (`?api_key=` / `?key=`) are no longer accepted. Machine-to-machine auth is explicit; precedence rules between transports are gone.\n\n### Cookie-backed CSRF gate\n\nGenerated apps now block cross-site `POST` / `PUT` / `PATCH` / `DELETE` requests from cookie-relying callers. The middleware skips explicit `Authorization` clients, requires a trusted `Origin` or `Referer`, and blocks `Sec-Fetch-Site: cross-site`. This matters most for cross-subdomain session setups where `SameSite=None` is intentional.\n\n### First-class Wrangler observability\n\n`providers.runtime.config.observability` now supports nested `logs` / `traces` blocks for `headSamplingRate`, `destinations`, `persist`, and `logs.invocationLogs`, emitting matching `[observability]`, `[observability.logs]`, and `[observability.traces]` TOML.\n\n---\n\n## v0.16.7 — May 12, 2026\n\n### Bearer wins over cookie\n\nA request carrying both `Authorization` and a session `Cookie` resolves entirely from the bearer; the cookie is dropped before `getSession()` runs. All three Bearer flavors (API key, JWT, session-token) now behave consistently — no more silent cookie precedence on session-token bearers.\n\n### Bearer plugin defaults to `requireSignature: true`\n\nBetter Auth's `bearer` plugin defaults to unsigned tokens; Quickback now emits `bearer({ requireSignature: true })`. Tokens emitted in the CORS-exposed `set-auth-token` header are server-signed with `BETTER_AUTH_SECRET` and verified on every request. Projects that genuinely need unsigned bearers can override via `providers.auth.config.plugins.bearer`.\n\nSee [Authentication Security → Bearer Tokens and Cookie Precedence](/stack/auth/security#bearer-tokens-and-cookie-precedence).\n\n---\n\n## v0.16.5 — May 12, 2026\n\n### Flat write DSL\n\nResource write operations are now declared at the table level alongside `read`, replacing the nested `crud` block:\n\n```ts\ndefineTable(customers, {\n read: { ... },\n create: { access: { roles: [\"admin\"] } },\n update: { access: { roles: [\"admin\"] } },\n delete: { access: { roles: [\"admin\"] }, mode: \"soft\" },\n upsert: { access: { roles: [\"admin\"] } },\n guards: { ... },\n});\n```\n\n`crud` and top-level `put` still compile as deprecated compatibility aliases. Mixed usage on the same resource is rejected. `schema-registry.json` emits both shapes during the transition.\n\n### CMS placement for multi-table feature actions\n\nStandalone actions on multi-table features have an explicit placement model:\n\n- `cms.placement: \"feature\"` shows the action on every table toolbar in the feature\n- `cms.placement: \"tables\"` with `cms.tables` scopes it to specific tables\n- `cms.hidden: true` keeps it API-only\n\nFeature-root standalone actions are emitted under a new `featureActions` bucket in `schema-registry.json`. Ambiguous multi-table standalone actions without placement compile with a warning.\n\n### `openapi.types` accepts a string array\n\nOne compile can write the generated types file to multiple locations, keeping colocated SPA clients in sync:\n\n```ts\nopenapi: { types: ['api-types.gen.ts', 'apps/web/src/lib/api-types.gen.ts'] }\n```\n\n### Stable artifact ordering\n\nGenerated route files and `schema-registry.json` are emitted in a stable order across runs. Identical logical input produces identical artifacts.\n\n---\n\n## v0.16.4 — May 12, 2026\n\n### Drizzle snapshot integrity\n\nDrizzle metadata files (`<n>_snapshot.json`) are no longer stamped with a Quickback warning key. The warning is now journal-only. Projects whose snapshots were corrupted by an earlier release self-heal on the next compile — the stripped header is removed during staging and the rewritten snapshot is clean.\n\n### `account.auth.*` drives the server, not just the SPA\n\nThe Account UI's auth flags (`signup`, `password`, `passkey`, `emailOTP`, `emailVerification`) now configure the Better Auth server alongside the SPA bundle. A normalizer maps them into the server config:\n\n- `signup → emailAndPassword.disableSignUp` (inverted)\n- `password → emailAndPassword.enabled`\n- `emailVerification → emailAndPassword.requireEmailVerification`\n- `passkey` / `emailOTP` → plugin additions\n\nThe SPA's `VITE_ENABLE_*` flags are derived from the same canonicalized server config, so the bundle and the server cannot drift. Two new flags ride along: `VITE_ENABLE_API_KEYS` and `VITE_ENABLE_MAGIC_LINK`.\n\n**Breaking** for projects that implicitly relied on the SPA-only behaviour: `account.auth.signup: false` now actually disables `POST /auth/v1/sign-up/email` on the server. Set `providers.auth.config.emailAndPassword.disableSignUp: false` explicitly to keep server signup open while hiding the SPA screen.\n\n---\n\n## v0.16.3 — May 9, 2026\n\n### Standalone action mount order\n\nFeature-level standalone action routers now register before sibling CRUD routers when both mount at the exact same prefix. A literal path like `GET /api/v1/records/today-bundle` resolves to the standalone handler instead of falling through to `GET /:id` and treating `\"today-bundle\"` as a record ID.\n\n---\n\n## v0.16.1 — May 9, 2026\n\n### Cloudflare ASSETS canonicalization\n\nWorker SPA fallbacks now request `/<dir>/` instead of `/<dir>/index.html`. Cloudflare's static-assets binding rewrites `/index.html` requests as 307 redirects to the trailing-slash path under the default `html_handling=auto-trailing-slash`, which previously caused redirect loops in SPA fallback handlers. Affects CMS, Account, admin, and the multi-domain catchall.\n\n### `account.customLogin`\n\nSet `account: { customLogin: true }` to drop a project-branded sign-in page in front of the bundled SPA. Place the page at `quickback/public/account/login/index.html` (as a directory) and the existing public passthrough serves it. The route registers before the `/account/*` SPA catch-all so the static handler wins; everything else under `/account/` continues to route through the bundled SPA.\n\n### Project-level realtime defaults\n\n`providers.database.config.realtime: true` now treats every resource as realtime-enabled by default. Per-resource `realtime: { enabled: false }` still wins.\n\n### Compile-time validators\n\nTwo new compile-time errors over silent runtime failures:\n\n- `AUTHENTICATED` + org-scoped firewall is rejected. The combination silently returned empty lists to sign-in-only callers who lacked an active org; the validator names three valid resolutions (drop the org scope, use `USER`, or split the route).\n- `createRealtime` imports without `realtime: true` enabled in the config are rejected at compile.\n\n### Drizzle metadata hardening\n\nDrizzle journal files carry a \"do not edit\" header. The compiler warns when the journal entry count exceeds the snapshot file count (typically the trace of a hand-deleted snapshot).\n\n### Minor\n\n- `SYSADMIN` is now recognised by the standalone-action org gate's pseudo-role matcher.\n- Apex `/` and `/account/login` get fallback redirects to `auth.loginUrl` when neither bundled SPA is enabled.\n- Record-based action URLs are kebab-case to match the OpenAPI spec (e.g. `/api/v1/widgets/:id/send-invite`).\n\n---\n\n## v0.16.0 — May 9, 2026\n\n### Agent Auth Protocol\n\nQuickback ships a server implementation of the [Agent Auth Protocol](https://agentauthprotocol.com) via `@better-auth/agent-auth`. Enable with `auth.plugins.agentAuth: true` and the compiler emits the full agent-auth surface: discovery at `/.well-known/agent-configuration`, capability projection from the project's OpenAPI spec, a device-authorization approval page in the Account SPA at `/agents/approve`, and the four agent-auth tables added to the auth schema automatically.\n\n**OpenAPI capability projection runs by default.** Every operation with an `operationId` becomes an agent capability. Default `approvalStrength` map: `GET → \"session\"`, `POST/PUT/PATCH/DELETE → \"webauthn\"`. The proxy `onExecute` makes a self-fetch with a Better Auth JWT minted for the agent session, so the inner request hits the existing JWT fast-path and runs the full firewall + access + masking pipeline. Opt out of OpenAPI projection with `agentAuth: { fromOpenAPI: false }` and wire `capabilities` + `onExecute` by hand.\n\n### Bearer-only on `/mcp` and the agent-auth surface\n\n`/mcp` forwards only `Authorization: Bearer …` into the inner request. Cookie and `x-api-key` forwarding are removed. Three Bearer flavors land on the same header — Better Auth session token (via the `bearer` plugin), OAuth access token (via OAuth Provider), and agent JWT (via `@better-auth/agent-auth`).\n\n### Auth DSL gains first-class plugin entries\n\n`bearer`, `oauthProvider`, and `agentAuth` are now typed entries in both the array-form union and the `BetterAuthPlugins` interface, with their own options shapes (`OAuthProviderOptions`, `AgentAuthOptions`). Existing `as any` casts can come out.\n\nAuto-enable rule: turning on `agentAuth` force-adds `bearer` + `oauthProvider`. No useful agent-auth deployment ships without those two.\n\n### `queue-consumer.ts` gating\n\nThe queue consumer is emitted when any of the following are true: embeddings are configured, queue handlers exist under `services/queues/*`, or `additionalQueues` is declared. Previously the third case left projects with a wrangler binding pointing at a missing handler.\n\n---\n\n## v0.15.0 — May 7, 2026\n\n### Sysadmin tier for the CMS\n\nA new opt-in `cms: { sysadmin: true }` flag turns the CMS into a cross-tenant DB-admin tool gated by `user.role === 'sysadmin'`. Distinct from the Better Auth `'admin'` plugin role, so user-management powers and DB-admin powers stay decoupled. Off by default.\n\nWhen enabled, the compiler emits a `SYSADMIN` pseudo-role (a fifth marker alongside `PUBLIC` / `AUTHENTICATED` / `USER` / `ADMIN`), a firewall escape hatch that drops tenant scopes for sysadmins while preserving soft-delete, a true cross-tenant `/admin/v1/sysadmin/organizations` endpoint, and a relaxed cross-tenant guard for list routes.\n\nThe CMS SPA gains a two-mode design: org admins keep the existing membership-based switcher, sysadmins get an \"All organizations\" selector that pins tenants via `?organizationId=` on every API call.\n\n### Durable Object `[[migrations]]` order is preserved\n\nCloudflare's migration list is append-only. The compiler now reads your existing `wrangler.toml` (when present) and emits auto-generated DO `[[migrations]]` blocks in two phases: deployed entries first (preserving order), net-new entries appended last. Reordering DOs in the config array no longer reshuffles deployed migrations.\n\n### `quickback/public/` — static-asset passthrough\n\nAnything dropped under `quickback/public/` is copied verbatim into `src/apps/` on every compile and served by the wrangler `[assets]` binding. Use for favicons, `robots.txt`, OG images, `.well-known/` files, marketing PDFs — anything that needs to ride past the compiler as bytes.\n\n- Optional. Missing folder is a no-op.\n- Stale-cleaned. Files removed from `quickback/public/` disappear on the next compile.\n- Hidden entries (`.DS_Store`, dotfiles) are skipped.\n- Collisions with compiler-emitted manifest paths fail the compile loudly.\n\n### Minor\n\n- Standalone-action wrapper skips the org gate when the access tree references any pseudo-role.\n- Queue handler emit no longer drops the `queue` export when there are no embeddings.\n\n---\n\n## v0.14.7 — May 7, 2026\n\n### Codegen fixes for projects with non-`id` primary keys and DO-only features\n\nFour surgical fixes to the generated output:\n\n- Duplicate table imports in relationship-role routes are deduplicated.\n- `db` references in single-record and bulk action handlers now resolve correctly during pre-fetch.\n- PartyServer auth gates pass the in-scope `db` handle into firewall calls.\n- Durable-object-only features keep their `lib/` files in the output.\n\n### `emailOtp` + AWS SES is OTP-only\n\n`auth.emailOtp` with the AWS SES email provider no longer auto-wires the magic-link companion. Mail-client URL prefetching can burn the one-time code before the human sees it; the Account SPA's `/email-otp` route is the single canonical entry point. Projects that explicitly want the magic-link arm can wire `sendVerificationOTP` directly.\n\n---\n\n## v0.14.6 — May 7, 2026\n\n### MCP transport correctness\n\nFour fixes to the MCP-over-HTTP path:\n\n- `tools/call` URLs are no longer double-prefixed for action tools.\n- Auth middleware accepts API keys via `Authorization: Bearer` in addition to `x-api-key` and query parameters — the channel MCP clients use exclusively.\n- `auth.roleHierarchy` is expanded for runtime role checks across api-key, JWT, and session auth paths. A higher role inherits the privileges of every lower role.\n- Team-scoped firewall predicates degrade gracefully when no team is active (org scoping continues to apply; team scoping is optional).\n\n---\n\n## v0.14.5 — May 7, 2026\n\n### MCP environment threading\n\nThe generated MCP server's `tools/call` dispatch threads `env` and `executionCtx` into the inner request, so action tools that touch Cloudflare bindings (D1, KV, R2, Queues) no longer crash with `undefined` env access.\n\n---\n\n## v0.14.4 — May 7, 2026\n\n### `via:` firewall predicates pull required imports\n\nThe relationship-role generator emits `inArray` and `sql` imports when the firewall has any `via:` predicate, and `buildFirewallConditions` accepts `(ctx, db)` so the relationship subquery has a Drizzle client to evaluate against. Every CRUD and action call site passes `db` through automatically.\n\n---\n\n## v0.14.3 — May 7, 2026\n\n### Relationship-role table re-exports\n\nGenerated `<table>.resource.ts` files now re-export their Drizzle table binding. Cross-feature relationship subqueries that import the binding from the resource file (rather than the schema) resolve correctly.\n\n---\n\n## v0.14.2 — May 7, 2026\n\n### Historical DO `[[migrations]]` are preserved\n\nA new `bindings.durableObjectMigrations` config slot carries forward `deleted_classes`, `renamed_classes`, and `transferred_classes` lifecycle entries across recompiles. Cloudflare's migration list is append-only; entries declared here are emitted first in `wrangler.toml`, then auto-generated current-class entries follow:\n\n```ts\nbindings: {\n durableObjects: [{ name: 'NOTEPAD', className: 'Notepad', from: 'lib/Notepad' }],\n durableObjectMigrations: [\n { tag: 'qb-do-deleted-legacy-notes-2026-05-05', deletedClasses: ['LegacyNotes'] },\n ],\n}\n```\n\nAll four lifecycle shapes are supported. User-declared entries can override auto-emit by reusing the same tag.\n\n---\n\n## v0.14.1 — May 7, 2026\n\n### Bulk action variants in `openapi.json`\n\nRecord-based actions with `bulkVariant: true` are now emitted as sibling operations in the OpenAPI spec, with the documented `{ ids, input, failFast? }` request shape, 200/207/400 responses, and a separate `<Resource><Action>Bulk` `operationId` so typed-client codegen distinguishes single from bulk.\n\n### Cross-tenant \"my events\" patterns\n\nThe access docs now include a worked example for the cross-tenant aggregation pattern (e.g. `GET /my-events` returning resources across all tenants a caller is invited to). See [Access → Cross-tenant dashboards](/compiler/definitions/access#cross-tenant-my-events-dashboards-are-not-this).\n\n---\n\n## v0.14.0 — May 7, 2026\n\n### Relationship-based authorization\n\nRoles can now be bound to a domain-table membership (\"user is a confirmed guest of this event\") rather than an org membership or a pseudo-role. Declare the relationship once and reference it from `firewall:` or `access.roles:`:\n\n```ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n },\n },\n roles: {\n guest: { via: 'guestOf' },\n eventStaff: { or: [{ via: 'guestOf' }, { roles: ['admin', 'owner'] }] },\n },\n}\n\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' },\n],\nread: { access: { roles: ['admin', 'member', 'guest'] } },\ncreate: { access: { roles: ['admin', 'guest'] } },\nupdate: { access: { roles: ['admin'] } },\n```\n\nThe compiler emits an inline Drizzle subquery against the relationship table and AND-composes it as the outermost firewall clause. The relationship table's own firewall (tenant scope, soft-delete) is honored inside the subquery; cross-tenant grants are impossible because the resource's tenant filter sits outermost.\n\nSupported surfaces: row-level scoping via `firewall: [{ field, via }]`, role gates on writes and reads, view access. Masking and action access reject relationship-roles at compile time with pointers to the working pattern (gate the row at the firewall layer, gate the role at the access layer).\n\nCross-tenant aggregation dashboards aren't solved by relationship-roles — the tenant firewall remains the outermost AND. For that pattern, use a user-scoped firewall or function-form access on a dedicated route.\n\nSee [Firewall → Relationship-based scoping](/compiler/definitions/firewall#relationship-based-scoping-via) and [Access → Relationship-based authorization](/compiler/definitions/access#relationship-based-authorization).\n\n### Bulk variants on record-based actions\n\n`defineAction({ bulkVariant: true })` emits `POST /:resource/batch/{action}` alongside the per-record route. The bulk handler loops the same access + transition + execute pipeline over a `{ ids, input, failFast? }` body:\n\n```ts\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n bulkVariant: true,\n transition: { field: \"status\", via: \"nextStatus\", fromTo: { /* ... */ } },\n async execute({ db, record, input, whereTransition }) {\n // exact same body — runs once per id\n },\n});\n```\n\nPer-record outcomes return as 207 Multi-Status. `failFast: true` aborts on the first failure and wraps the loop in `db.transaction()` on tx-supporting providers; D1 fails fast without rollback. Max 100 IDs per request. Rejected on standalone actions and `unsafe` actions.\n\n### Aggregations on read views\n\nRead views can declare pre-computed metrics that surface alongside the row payload:\n\n```ts\nread: {\n views: {\n pipeline: {\n fields: [\"id\", \"jobId\", \"candidateId\", \"status\", \"appliedAt\"],\n aggregations: {\n totalApplications: { fn: \"count\" },\n byStatus: { fn: \"groupBy\", field: \"status\" },\n },\n },\n },\n}\n```\n\nAggregations run over the same firewalled, filtered set as the row query; pagination is intentionally ignored. Supported functions: `sum`, `avg`, `min`, `max`, `count`, `count_distinct`, `groupBy`. See [Views → Aggregations](/compiler/definitions/views#aggregations).\n\n---\n\n## v0.13.5 — May 6, 2026\n\n### Object-form `auth.plugins` config is honored\n\nThe documented `plugins: { oauthProvider: {...} }`, `plugins: { organization: { teams: { enabled: true } } }` shapes now flow through the compiler unchanged. Per-plugin options reach the generated `auth.ts` as written.\n\n### `roles: [\"PUBLIC\"]` allowed on writes and actions\n\n`PUBLIC` is the explicit, uppercase opt-in for unauthenticated access on every access node — reads, writes, views, and actions. The runtime trusts the marker; row-level safety comes from firewall, masking, and the action's own validation. `PUBLIC` actions continue to receive mandatory audit logging.\n\nCommon pattern: pair `roles: [\"PUBLIC\"]` with `firewall: { exception: true }` on the resource so the row predicate doesn't reject every unauthenticated caller.\n\n---\n\n## v0.12.0 — May 5, 2026\n\n### Per-room authorization for PartyServer\n\n`bindings.durableObjects[].access` declares a path-scoped gate that runs the declared resource's firewall and `read.access` pipeline before the WebSocket upgrade:\n\n```ts\ndurableObjects: [\n // Single-resource: roomId IS the chat row id.\n { name: 'Chat', className: 'Chat', from: 'lib/Chat',\n access: { resource: 'chats' } },\n\n // Multi-resource: regex dispatches kind → resource.\n { name: 'Notepad', className: 'Notepad', from: 'lib/Notepad',\n access: {\n roomId: { pattern: '^(day-note|interaction|record):([A-Za-z0-9_-]+)$', kindGroup: 1, idGroup: 2 },\n resources: {\n 'day-note': { resource: 'day-notes' },\n 'interaction': { resource: 'interactions' },\n 'record': { resource: 'records' },\n },\n } },\n\n // Anonymous lobbies / public pads: explicit opt-out.\n { name: 'PublicLobby', className: 'PublicLobby', from: 'lib/PublicLobby',\n access: 'public' },\n]\n```\n\nThe gate 401s unauthenticated callers, 403s when the firewall hides the row, 404s when the row is missing. Resource references are validated against feature names at compile time. See [PartyServer Rooms → Per-room authorization](/stack/realtime/partyserver-rooms#per-room-authorization-via-access-v012).\n\n---\n\n## v0.11.1 — May 5, 2026\n\n### PartyServer auto-mount is secure by default\n\nThe `/realtime/*` auto-mount now wraps `partyserverMiddleware` in an auth check. Unauthenticated upgrades return 401; the four auth mechanisms (session cookie, JWT bearer, `x-api-key` header, query parameter) all unlock connections. Per-room access remains the `Server` class's responsibility in `onConnect`.\n\n---\n\n## v0.11.0 — May 5, 2026\n\n### OAuth Provider (MCP-ready)\n\nQuickback can act as a standards-compliant OAuth 2.1 + OIDC authorization server via [`@better-auth/oauth-provider`](https://better-auth.com/docs/plugins/oauth-provider). Enable with `plugins: [\"oauthProvider\"]`. The compiler auto-includes Better Auth's `jwt` plugin and the Account SPA gains a `/consent` page for the standard authorization-code flow.\n\nThis replaces Better Auth's deprecated `mcp` plugin and gives every MCP client (Cursor, Claude Desktop, claude.ai connectors, custom tooling) RFC 7591 dynamic client registration plus the discovery documents they need to bootstrap. See [Auth Plugins → OAuth Provider](/stack/auth/plugins#oauth-provider-mcp-ready).\n\n### API keys via query parameter\n\nThe auth middleware now accepts API keys as `?api_key=…` or `?key=…` query parameters. The `x-api-key` header takes precedence when both are sent. Prefer the header whenever the client supports it — query parameters land in access logs and `Referer` headers.\n\n### PartyServer rooms + realtime URL split\n\nThe realtime URL space is reorganized so names match what each primitive does:\n\n- **`/realtime/v1/*` → `/broadcast/v1/*`** — the org-wide Broadcaster moves to its semantically accurate prefix.\n- **`/realtime/<binding>/<room-id>`** — new mount for [PartyServer](/stack/realtime/partyserver-rooms) rooms. Per-room Durable Objects with presence and lifecycle hooks. Auto-mounted whenever a project declares any in-worker DO.\n\n**Breaking** — recompile + redeploy required:\n\n- `REALTIME_URL` env var renamed to `BROADCAST_URL`.\n- SPA helpers `getRealtimeWsUrl()` / `getRealtimeTicketUrl()` renamed to `getBroadcastWsUrl()` / `getBroadcastTicketUrl()`.\n- `appConfig.routes.api.realtime` renamed to `appConfig.routes.api.broadcast`.\n\n`partyserver`, `partysocket`, and `hono-party` are pre-installed in the compiler image; collab projects compile without an extra `npm install` step.\n\n---\n\n## v0.10.20 — May 4, 2026\n\n### In-worker Durable Objects\n\n`bindings.durableObjects[].from` flips a DO binding into in-worker mode and emits the export, the `[[migrations]]` block, and the `CloudflareBindings` type all together:\n\n```ts\ndurableObjects: [{\n name: \"ITEM_STREAM\",\n className: \"ItemStream\",\n from: \"features/loops/lib/ItemStream\",\n}]\n```\n\nDO class files live under `quickback/lib/` or `quickback/features/<feature>/lib/` — both copy verbatim into the generated `src/` tree on every compile. `from` and `scriptName` are mutually exclusive; cross-worker DOs (`scriptName` set) skip the re-export and migration block.\n\n`migrationTag` (default `qb-do-${className}`) is stable across regenerations and must never be removed or renamed once deployed. `useSqlite` defaults to `true`. See [Bindings → Durable Objects](/compiler/config/bindings#durableobjects).\n\n---\n\n## v0.10.18 — May 2, 2026\n\n### `experimentalRemote` — share deployed D1 with `wrangler dev`\n\nPer-binding `experimental_remote = true` lets `wrangler dev` read/write deployed D1 for selected bindings:\n\n```ts\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n splitDatabases: true,\n experimentalRemote: { auth: true, features: false },\n }),\n}\n```\n\nUseful for \"share prod auth in dev, keep feature writes sandboxed.\" Off by default.\n\n### Google OAuth + signup ToS\n\nThe Account SPA wires Google OAuth end-to-end when configured under `auth.config.socialProviders.google.enabled`. The signup flow gains a Terms-of-Service checkbox gate (configurable via the Account SPA branding).\n\n### CLI compile auth gate\n\n`quickback compile` now requires authentication for cloud-compiler runs. Device-flow `?redirect=` parameters are standardized across the login + signup pages so a user clicking \"Create one\" no longer loses their return URL.\n\n---\n\n## v0.10.15–v0.10.17 — May 2, 2026\n\n### CSP auto-config\n\nWhen `security.csp` is set, the compiler widens directives additively based on the project's enabled features:\n\n| Trigger | Auto-added | Directive |\n|---|---|---|\n| `cms: true` OR `account: true` | `'unsafe-inline'`, `https://fonts.googleapis.com` | `styleSrc` |\n| `cms: true` OR `account: true` | `https://fonts.gstatic.com` | `fontSrc` |\n| `csp` set (always) | `@trustedOrigins` | `connectSrc` |\n| Bundled SPA enabled | SPA-baked API origin (`config.domain`, `quickback.{baseDomain}`, `cms.domain`, `account.domain`) | `connectSrc` |\n\nAnything you already wrote stays — auto-config never removes or overrides. Each applied addition is logged to stderr. Opt out with `security: { cspAutoConfig: false }`.\n\nMost projects can write the minimal:\n\n```ts\nsecurity: {\n csp: {\n defaultSrc: ['@self'],\n scriptSrc: ['@self'],\n objectSrc: ['@none'],\n upgradeInsecureRequests: true,\n },\n}\n```\n\n…and the compiler fills in font hosts, trusted origins, and SPA-baked URLs.\n\nWhen a target directive is missing, auto-config scaffolds it from `default-src` baseline rather than widening `default-src` itself — CSP3 fall-back semantics would otherwise leak the addition to every directive that falls back to `default-src`.\n\n---\n\n## v0.10.14 — May 1, 2026\n\n### `auth.jwt` config\n\nThe bearer-token JWT used by the auth fast-path is configurable. Tune `expiresIn` to bound the post-revocation replay window without affecting browser SPAs (which auto-refresh on every authed call):\n\n```ts\nauth: {\n jwt: {\n expiresIn: 30,\n issuer: 'my-api',\n audience: 'partner-svc',\n secretEnv: 'CUSTOM_JWT_SECRET',\n },\n}\n```\n\n### Admin MCP endpoints filtered\n\nBetter Auth admin endpoints (`/admin/list-users`, `/admin/ban-user`, etc.) now carry `x-access: { userRole: ['admin'] }` in the generated OpenAPI spec. The MCP `tools/list` access-filter drops them for non-admin callers.\n\n### Declarative `security` config\n\nEvery security response header (`Content-Security-Policy`, COOP, COEP, CORP, HSTS, `X-Frame-Options`, `Referrer-Policy`, `Permissions-Policy`) is configurable from `quickback.config.ts`. `@`-prefixed sentinels (`@self`, `@none`, `@unsafe-inline`, `@trustedOrigins`, etc.) replace awkward `\"'self'\"` quoting.\n\nThe compiler lints the resolved config for known footguns: `@unsafe-inline` in `script-src`, wildcard sources, missing `default-src`, HSTS preload-list misconfiguration.\n\n### HSTS skipped on localhost\n\nGenerated middleware skips `Strict-Transport-Security` when the request hostname is `localhost`, `127.0.0.1`, or `*.localhost`. Without this gate, `wrangler dev` would pin a developer's browser to HTTPS across every project on that machine.\n\n---\n\n## v0.10.13 — May 1, 2026\n\n### Clickjacking defence on every Worker\n\nEvery Worker emits `Content-Security-Policy: frame-ancestors 'self' <TRUSTED_ORIGINS…>` and `X-Frame-Options: SAMEORIGIN` on every response. The CSP allowlist is sourced from the same `TRUSTED_ORIGINS` constant that gates CORS.\n\n---\n\n## v0.10.11 — May 1, 2026\n\n### MCP `tools/list` is access-filtered\n\nEach MCP tool now carries sanitised access metadata. `tools/list` filters against the caller's `ctx`: unauthenticated callers see only `PUBLIC` tools, authenticated callers see only role-gated tools they pass.\n\n- Wildcard CORS removed from the MCP endpoint.\n- Unauthenticated `GET /mcp` no longer enumerates tool names.\n- Internal flavor text is removed; `annotations.destructiveHint` and `_unsafe` remain — those are the spec-correct signals for clients.\n\n`tools/call` continues to re-enter the Hono app and run every middleware (auth, firewall, access, guards, masking), so hiding a tool from list never weakens the underlying gate.\n\n---\n\n## v0.10.10 — April 29, 2026\n\n### Reserved keys in `access.record` are rejected\n\n`access.record` is a flat field map evaluated as implicit AND between entries — keys must be column names. The compiler now rejects reserved keys (`and`, `or`, `roles`, `userRole`) inside `record` with migration guidance pointing at the working pattern (top-level siblings with their own `record:` blocks).\n\n---\n\n## v0.10.8 — April 29, 2026\n\n### Audit logging on Postgres targets\n\n`audit_events` previously only existed on `cloudflare-d1`. The audit table now lives in a dedicated `audit` schema (`drizzle.pgSchema('audit')`) on Postgres targets. The `hasSecurityAudit` gate accepts D1 or any PG dialect; `auditDatabaseId` remains a D1-only requirement.\n\n### `auditDatabaseId` is a compile-time requirement\n\nProjects with unsafe or `PUBLIC` actions that previously produced a placeholder `database_id = \"local-audit\"` in production now fail at compile time with the exact `wrangler d1 create <project>-audit` command and the config key where the returned ID goes.\n\n### Action input → OpenAPI / MCP\n\n`defineAction({ input: z.object({...}) })` schemas flow into the OpenAPI `requestBody` and the MCP tool's `inputSchema.properties`. Simple `z.object` shapes are extracted at compile time; discriminated unions, refinements, recursive schemas, and bare-identifier references run through Zod's native `z.toJSONSchema()` for full-fidelity output.\n\n### OpenAPI fidelity\n\n- Response schemas emit `required[]` for every non-nullable column.\n- `text(_, { enum: [...] })` columns emit as closed `{ type: \"string\", enum: [...] }`.\n- `id` claims `format: \"uuid\"` only when the project's `generateId` actually produces UUIDs. cuid2 / prefixed / nanoid / serial generators emit plain `{ type: \"string\" }`.\n\n### Minor\n\n- Auto-mask predicate verifies the resolved owner column exists before emitting an `or: 'owner'` clause; falls back to roles-only with a warning otherwise.\n- Generated CRUD errors emit canonical `QuickbackErrorCode` enum values (`DB_NOT_NULL_VIOLATION`, `DB_UNIQUE_VIOLATION`, etc.) so generated SDKs can exhaustively switch on `code`. See [API errors](/compiler/targets/hono-api/using-the-api/errors#database).\n\n---\n\n## DSL: one file per action, multi-table per feature\n\n### One file per action\n\nAction authoring is one file per action under `<feature>/actions/<name>.ts`. The filename is the action name and the URL segment:\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: { applied: [\"screening\"], screening: [\"interview\"], interview: [\"offer\"] },\n },\n async execute({ db, record, input, auditFields, whereTransition }) { /* … */ },\n});\n```\n\n`defineAction` is imported from a generated per-feature helper at `<feature>/.quickback/define-action.ts` — `record`, `input`, and audit fields are typed without manual annotations.\n\n**Discovery rules:**\n- `actions/<name>.ts` binds to the feature's primary table.\n- `actions/<table>/<name>.ts` binds to the sibling table file.\n- Setting `path:` makes the action standalone (custom URL, no record fetch).\n- Tableless features require every action to be standalone.\n\n**Retired** (rejected at load time with migration guidance): `actions.ts` (bundled multi-action file), `_feature.ts`, `handlers/` directory + `handler:` string ref, `defineActions(table, {…})`, colocated `defineActions` inside table files, `standalone: true` flag, `*-actions.ts` / `*.actions.ts` filename patterns.\n\nSee [Actions docs](/compiler/definitions/actions).\n\n### Multi-table actions per feature\n\nOne feature directory can own actions on multiple tables. Three discovery modes:\n\n- **Colocated** (canonical) — `<table>.ts` containing both `defineTable` and `defineActions(<table>, …)`. One file per entity.\n- **`actions.ts`** — single primary-table actions file at feature root.\n- **`actions/<table>.ts`** — per-table action files for strict schema/behavior separation.\n\nPlus a universal `_feature.ts` slot for non-table-bound feature-level actions and shared Zod schemas.\n\nAction names are unique per `(bindTable, name)` pair. Sibling-bound `actions/episodes/publish.ts` and `actions/shows/publish.ts` mount at `/episodes/:id/publish` and `/shows/:id/publish` and compile cleanly.\n\n---\n\n## Firewall: named-scope shape\n\nThe named-scope firewall shape is a co-equal user-facing input alongside the predicate array:\n\n```typescript\nfirewall: { organization: { column: 'tenant_id' } } // named-scope (compact)\nfirewall: { owner: { column: 'account_user_id' } }\nfirewall: { exception: true }\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n] // predicate array (explicit)\n```\n\nPick the form that reads better — named-scope for the common one-line case, predicate array when you need custom `in`-lists or non-scope predicates.\n\n**Auto-detection synonyms.** When `firewall:` is omitted, the compiler scans the schema for an isolation column. The org-scope list accepts `organizationId`, `organisationId`, `orgId`, `organization`, `organisation`, `org` (American + British). User-scope accepts `userId`.\n\n**`ownerId` is a targeted error signal.** When a table carries `ownerId` but no isolation column and no explicit `firewall:`, the compiler raises a specific error — `ownerId` is business-logic ownership, not access control. Use `userId` for access control, declare an explicit `firewall:`, or add a separate isolation column.\n\n---\n\n## v0.10.0 — April 26, 2026\n\n### `q.scope()` — single-declaration tenant scoping\n\n`q.scope(kind)` replaces the three-place pattern (column declaration + firewall predicate + ownership-guard) with one column:\n\n```typescript\ncolumns: {\n organizationId: q.scope('organization'), // → ctx.activeOrgId\n ownerId: q.scope('owner'), // → ctx.userId\n teamId: q.scope('team'), // → ctx.activeTeamId\n}\n```\n\n`q.scope()` columns auto-derive the firewall predicate, register with the guards layer as `systemManaged` (client input rejected), and auto-populate from `ctx` on create / upsert. The systemManaged extension generalises beyond `q.scope()`: any firewall predicate whose `equals` references `ctx.*` registers its `field` automatically.\n\nSee [`q.scope()`](/compiler/definitions/schema#qscope--tenant-scope-columns).\n\n### `masking[col].query.roles` — unified filter / sort / search gate\n\nThe three legacy per-capability flags (`filterable`, `searchable`, `sortable`) are replaced by a single `query.roles` allowlist:\n\n```typescript\nmasking: {\n email: {\n type: 'email',\n show: { roles: ['admin'] },\n query: { roles: ['admin'] }, // defaults to show.roles when omitted\n },\n}\n```\n\nA view's own `query.{filterable,searchable,sortable}` allowlist is the opt-in for higher-privileged roles; the existing intersection validator gates it at compile time.\n\n**Breaking:** `masking[col].filterable / .searchable / .sortable` is rejected at compile time with a migration hint. Replace with `query.roles` (or delete the flags — `query` defaults to `show.roles`).\n\n---\n\n## v0.9.0 — April 25, 2026\n\n### Unified `read:` pipeline\n\nThe read side of every resource has its own block — `read:` — that owns the collection-level `GET /` endpoint, single-record `GET /:id`, and named view projections.\n\n**Breaking changes** (compile-time errors with migration hints):\n\n- `crud.list` → `read.access` (plus `read.pageSize` / `read.maxPageSize`)\n- `crud.get` → `read.access` (single-record GET inherits automatically)\n- Top-level `views: {...}` → `read.views: {...}`\n- `crud.list.fields` / `crud.get.fields` → declare a named view under `read.views` and call `/views/{name}`\n\n### Pre-record access ordering\n\nHandlers on `/:id` run a role-only access check before the firewall query. A caller without a matching role gets 403 before the database is touched. This closes the 404-vs-403 ID-probe channel — an unauthorized caller can no longer distinguish \"row exists in another tenant\" from \"row doesn't exist.\" See [Access evaluation order](/compiler/definitions/access#evaluation-order).\n\n### Transactional batch operations\n\nBatch endpoints expose `failFast` and a `meta.transactional` response field. On tx-supporting providers (postgres, supabase, neon, libsql, better-sqlite3, bun-sqlite), `failFast: true` wraps the per-record loop in `db.transaction(...)` so any failure rolls back the entire batch. On Cloudflare D1 (no `db.transaction`), `failFast: true` stops on the first error but prior writes stay committed.\n\nEmbedding queue messages and realtime broadcasts emit after the transaction commits — rolled-back batches produce no orphan jobs.\n\nSee [Batch Operations → Transactional semantics](/compiler/targets/hono-api/using-the-api/batch-operations#transactional-semantics).\n\n---\n\n## v0.8.7 — April 17, 2026\n\n### Hono CVE bump\n\nHono is bumped to `^4.12.14` across the monorepo, the compiler Docker image's pre-installed deps, and every generator path that emits Hono into compiled projects. Older ranges covered the vulnerable window. Recompile to pick up the fix in your generated project's `package.json`.\n\n### Cloudflare Email Sending in public beta\n\nQuickback defaults to the Workers `send_email` binding for Cloudflare deploys. Cloudflare Email Sending has graduated to public beta — production-ready with zero-config. AWS SES remains a fully supported opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes. See [Email Configuration](/compiler/config#email-configuration).\n\n### Dependency sweep\n\n`wrangler@^4.83.0`, `drizzle-orm@^0.45.2`, `drizzle-kit@^0.31.10`, `zod@^4.3.6`, `@cloudflare/workers-types@^4.20260417.1`.\n\n---\n\n## v0.8.5 — April 15, 2026\n\n### `userRole` access primitive\n\nA new `userRole?: string[]` field in the declarative `Access` config evaluates against `ctx.userRole` (the Better Auth admin-plugin `user.role` column). Distinct from `roles`, which matches `ctx.roles` (org membership).\n\n```typescript\n// Org owner OR platform admin\naccess: { or: [{ roles: ['owner'] }, { userRole: ['admin'] }] }\n\n// Platform admins see SSNs across every org\nmasking: { ssn: { type: 'ssn', show: { userRole: ['admin'] } } }\n```\n\n`userRole` works everywhere `Access` is accepted — CRUD, actions, views, masking, and inside `or` / `and` combinators. See [Access → userRole vs roles](/compiler/definitions/access#userrole-vs-roles).\n\n### CMS admin gate enforced server-side\n\n`cms: { access: \"admin\" }` previously only hid the CMS link in Account UI and rendered an \"Access Denied\" screen inside the SPA. Server-side enforcement now applies at every CMS-facing surface: the SPA shell, `/api/v1/schema`, and `custom_view` CRUD.\n\n### Better Auth 1.5 + `@cloudflare/workers-types` compatibility\n\nGenerated API code typechecks against the new versions. The org-member role-change broadcast hook is emitted via `organizationHooks.afterUpdateMemberRole` (the supported shape after the 1.5 deprecation of `databaseHooks.member.update.after`). `REALTIME_URL` and `ACCESS_TOKEN` are always emitted as optional bindings when the organization plugin is active.\n\n---\n\n## v0.8.4 — April 14, 2026\n\n### `generateId: \"short\"` strategy\n\nA compact ID option for tables where short, shareable codes matter more than collision resistance at scale:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", { generateId: \"short\" }),\n}\n```\n\nGenerates 6-character alphanumeric IDs (e.g. `a3F9xK`) using nanoid's `customAlphabet` with the full 62-char alphabet (`0-9A-Za-z`). Requires the `nanoid` package.\n\n**When to use:** room codes, invite links, share URLs, ephemeral records.\n\n**When not to use:** high-volume tables. 62^6 ≈ 56.8B combinations means ~238K rows before a 50% collision probability. For large tables stick with `\"uuid\"`, `\"cuid\"`, or `\"prefixed\"`. See [Providers → ID Generation Options](/compiler/config/providers#id-generation-options).\n\n---\n\n## v0.8.2 — April 11, 2026\n\n### Catch-all `VITE_QUICKBACK_URL`\n\nA single Quickback origin can be set in place of four separate URL env vars:\n\n```bash\nVITE_QUICKBACK_URL=https://secure.example.com\n```\n\n| Individual var (explicit) | Fallback when unset |\n|---|---|\n| `VITE_QUICKBACK_API_URL` | `${VITE_QUICKBACK_URL}` |\n| `VITE_QUICKBACK_ACCOUNT_URL` | `${VITE_QUICKBACK_URL}/account` |\n| `VITE_QUICKBACK_CMS_URL` | `${VITE_QUICKBACK_URL}/cms` |\n\n`VITE_QUICKBACK_APP_URL` stays independent — it points at the tenant's own frontend. Non-breaking; individual vars take precedence when set. Library users can set `__QUICKBACK_URL__` on `globalThis`. See [Environment Variables](/stack/account-ui/environment-variables).\n\n---\n\n## v0.8.1 — April 9, 2026\n\n### Role hierarchy with `+` suffix\n\nDefine a hierarchy and use `+` to mean \"this role and above\":\n\n```typescript\nauth: { roleHierarchy: ['member', 'admin', 'owner'] }\n\ncrud: {\n list: { access: { roles: [\"member+\"] } }, // member, admin, owner\n create: { access: { roles: [\"admin+\"] } }, // admin, owner\n delete: { access: { roles: [\"owner\"] } }, // owner only\n}\n```\n\nRoles are expanded at compile time. No `+` = exact match. See [Access → Role Hierarchy](/compiler/definitions/access#role-hierarchy).\n\n---\n\n## v0.8.0 — April 9, 2026\n\n### Breaking: VITE URL environment variables namespaced\n\nAll Quickback-generated URL environment variables are namespaced under `VITE_QUICKBACK_*` to avoid collisions with other Vite projects.\n\n| Old | New |\n|-----|-----|\n| `VITE_API_URL` | `VITE_QUICKBACK_API_URL` |\n| `VITE_ACCOUNT_URL` | `VITE_QUICKBACK_ACCOUNT_URL` |\n| `VITE_APP_URL` | `VITE_QUICKBACK_APP_URL` |\n| `VITE_CMS_URL` | `VITE_QUICKBACK_CMS_URL` |\n\nNon-URL variables are unchanged (`VITE_ENABLE_*`, branding vars, `VITE_STRIPE_PUBLISHABLE_KEY`).\n\n**Action required:**\n- Compiled projects: re-run `quickback compile`.\n- Standalone deploys: update `.env`, `.env.production`, and `wrangler.toml` files manually.\n- Library users: `__QUICKBACK_API_URL__` / `__QUICKBACK_APP_URL__` globals are unchanged.\n\n### CMS access control\n\n`cms.access: \"admin\"` enforces access at the CMS level, not just link visibility. Non-admin users (`user.role !== \"admin\"`) see an \"Access Denied\" screen with a sign-out button.\n\n---\n\n## v0.5.11 — February 24, 2026\n\n### Mandatory unsafe action audit trail\n\nStructured `unsafe` config (`unsafe: { reason, adminOnly, crossTenant, targetScope }`). Cross-tenant unsafe actions require Better Auth authentication plus platform admin role (`ctx.userRole === \"admin\"`). Mandatory audit logging on success, denial, and error paths. Cloudflare output includes `AUDIT_DB` wiring, `drizzle.audit.config.ts`, and `db:migrate:audit:*` scripts when unsafe actions are present.\n\nCompile-time raw SQL guard for actions and handlers (`allowRawSql: true` required per action).\n\n### Security contract report artifacts\n\nGenerated security contract artifacts: `reports/security-contracts.report.json`, `reports/security-contracts.report.sig.json`. Config-driven signing controls (`compiler.securityContracts.report.signature.*`). Missing required signing keys fail loudly with explicit remediation.\n\n### Headless Drizzle rename hints\n\n`compiler.migrations.renames` configuration for CI/CD environments where Drizzle's interactive rename prompts block compilation. See [Configuration](/compiler/config).\n\n### Minor\n\n- Email OTP magic links work correctly.\n- Auth is required for all API routes when running locally.\n- Single-file multi-table exports alongside `defineTable()` produce a clear error.\n\n---\n\n## v0.5.8 — February 14, 2026\n\n### Quickback CMS\n\nA schema-driven admin panel that connects to your generated API. The compiler now outputs a JSON schema registry consumed by the CMS at runtime. Firewall error modes (`reveal` for 403 with details, `hide` for opaque 404) are configurable per resource for security-sensitive deployments.\n\n---\n\n## v0.5.7 — February 12, 2026\n\n### Scoped database for actions\n\nActions receive a security-scoped database instead of a raw Drizzle instance. The compiler generates a proxy wrapper that automatically enforces org isolation, owner filtering, and soft-delete visibility — the same protections that CRUD routes have always had.\n\nDuck-typed column detection at runtime:\n\n| Column Detected | SELECT / UPDATE / DELETE | INSERT |\n|---|---|---|\n| `organizationId` | Adds `WHERE organizationId = ?` | Auto-injects `organizationId` from context |\n| `ownerId` | Adds `WHERE ownerId = ?` | Auto-injects `ownerId` from context |\n| `deletedAt` | Adds `WHERE deletedAt IS NULL` | — |\n\nEvery action is secure by default — no manual `WHERE` clauses needed.\n\nActions that intentionally need to bypass security (admin reports, cross-org queries, migrations) can declare `unsafe: true` to receive a raw, unscoped database handle via `rawDb`:\n\n```typescript\ndefineActions(analytics, {\n globalReport: {\n unsafe: true,\n execute: async ({ db, rawDb, ctx, input }) => {\n // db → still scoped (safety net)\n // rawDb → bypasses all security filters\n const allOrgs = await rawDb.select().from(organizations);\n },\n },\n});\n```\n\nWithout `unsafe: true`, `rawDb` is `undefined`. See [Actions](/compiler/definitions/actions).\n\n### Cascading soft delete\n\nSoft-deleting a parent record automatically cascades to child and junction tables within the same feature. The compiler detects foreign key references at build time and generates cascade `UPDATE` statements.\n\nRules:\n- Applies to soft delete only. Hard delete relies on database-level `ON DELETE CASCADE`.\n- Cascades within the same feature only — cross-feature references are not affected.\n- Child tables must have `deletedAt` / `deletedBy` columns (auto-added by the compiler).\n\nSee [Actions API → Cascading Soft Delete](/compiler/targets/hono-api/using-the-api/actions-api#cascading-soft-delete).\n\n### Advanced query parameters\n\nNew capabilities for all list endpoints:\n\n- **Field selection** — `?fields=id,name,status`\n- **Multi-sort** — `?sort=status:asc,createdAt:desc`\n- **Total count** — `?count=true` returns total matching records in `X-Total-Count`\n- **Full-text search** — `?search=keyword` searches across all text columns\n\nSee [Query Parameters](/compiler/targets/hono-api/using-the-api/query-params).\n\n---\n\n## v0.5.5 — February 5, 2026\n\n### OpenAPI spec generation\n\nGenerated APIs include a full OpenAPI specification at `/openapi.json`. Better Auth endpoints are included in the spec.\n\n### Better Auth plugins\n\nPublished `@quickback-dev/better-auth-upgrade-anonymous` (post-passkey email collection flow), `@quickback-dev/better-auth-combo-auth` (combined email + password + OTP), and `@quickback-dev/better-auth-aws-ses` (AWS SES email provider).\n\n### Security headers\n\nGlobal error handler prevents leaking internal error details. Security headers middleware (CSP, HSTS, X-Frame-Options, X-Content-Type-Options). `BETTER_AUTH_SECRET` properly passed to generated config.\n\n---\n\n## v0.5.4 — January 30, 2026\n\n### Account UI\n\nPre-built authentication UI deployed as Cloudflare Workers. Sessions, organizations, passkeys, passwordless, admin panel, API keys. Dual-mode: standalone (degit template) or embedded with Quickback projects.\n\n### Webhook system\n\nInbound webhook endpoints with signature verification. Outbound webhooks via Cloudflare Queues with automatic retries. Configurable per-feature webhook events.\n\n### Realtime & vector search\n\nDurable Objects + WebSocket realtime subscriptions. Vector embeddings via Cloudflare Vectorize. KV and R2 storage integrations.\n\n---\n\n## v0.5.0 — January 2026\n\n### Initial release\n\n- **Quickback Compiler** — TypeScript-first backend compiler.\n- **Four security pillars** — Firewall, Access, Guards, Masking.\n- **`defineTable()`** — schema + security configuration in a single file.\n- **Templates** — Cloudflare Workers, B2B SaaS.\n- **Cloud compiler** — remote compilation via `compiler.quickback.dev`.\n- **CLI** — `quickback create`, `quickback compile`.\n- **Better Auth integration** — organizations, roles, sessions.\n- **Drizzle ORM** — schema-first with automatic migrations.\n- **Cloudflare D1** — split database support (auth + features)."
|
|
6
|
+
"content": "## Unreleased\n\n### Realtime: identity-gated Durable Object rooms (`roomIdEquals`)\n\nPer-user Durable Object entrypoints (gateway / presence / inbox) can now declare\nan identity gate on the binding — `access: { roomIdEquals: 'ctx.userId' }` (or\n`'ctx.activeOrgId'`). The compiler emits a Worker-edge gate at\n`/realtime/<kebab>/*` that 401s anonymous callers, 400s a missing segment, and\n403s unless the decoded room segment equals the server-resolved `ctx` id — a\nstring compare with no backing table or DB query. See\n[PartyServer rooms → Per-room authorization](/stack/realtime/partyserver-rooms).\n\n- Closes the cross-user hole that \"no `access` declared\" leaves open: a per-user\n room without a gate falls through to the authenticated-only catchall, so any\n authenticated user could open another user's room by guessing the id.\n- The gate lives at the edge, not in the DO — a Durable Object has no session\n and only sees client-settable headers, so it must never re-authorize from\n request data (trusting an `x-user-id` header was the original spoof hole).\n- Only `'ctx.userId'` and `'ctx.activeOrgId'` are accepted; anything else is a\n compile-time error (fail-closed Zod + generator validation).\n\n### OAuth provider: spurious authorization-server warning silenced by default\n\nThe generated `oauthProvider({...})` now emits\n`silenceWarnings: { oauthAuthServerConfig: true }` by default. The compiler\nalways serves the `/.well-known/oauth-authorization-server` discovery route when\nthe provider is enabled, so `@better-auth/oauth-provider`'s\n\"please ensure … exists\" boot warning was always spurious. Override or extend it\nvia `plugins.oauthProvider.silenceWarnings`.\n\n### `defineSchedule` — cron jobs from a single source\n\nDeclare a cron schedule in `services/schedules/*.ts` and the compiler emits the\nWorker's `scheduled()` handler + the matching `[triggers] crons` in\n`wrangler.toml` — the trigger-side mirror of `defineQueue`. No separate cron\nWorker, no hand-patching the generated entry (which a recompile would strip).\nSee [Schedules](/stack/schedules).\n\n```typescript\n// services/schedules/sweepDigests.ts\nexport default defineSchedule({\n name: \"sweepDigests\",\n cron: \"* * * * *\",\n execute: async ({ db, env, services }) => { await runDigestSweep(db, env, services); },\n});\n```\n\n- One `scheduled(event, env, ctx)` dispatcher runs every schedule whose cron\n matches `event.cron`; failures are isolated per-schedule.\n- The execute context (`{ db, env, services, cron, scheduledTime }`) runs\n server-internal with `ctx.internal = true` and an audit actor of\n `system:cron-<name>`, plus a `withInternalContext` helper for\n `roles: ['INTERNAL']`-gated rows.\n\n### Rate limiting — the fifth security pillar\n\nPer-operation request caps on every CRUD endpoint, backed by Cloudflare's\nnative [Rate Limiting binding](/compiler/definitions/rate-limit) — no extra\nstorage, no third-party libraries. Applied to every resource by default\n(read 1000/60s, write 200/60s), overridable per-op, per-resource, or\nproject-wide; `false` opts out at any scope.\n\n- One middleware per feature router maps method→op, keys the limit by\n `<resource>:<op>:<userId>` (falling back to the client IP for anonymous\n callers), and returns `429` + `Retry-After` when over the cap.\n- Unique `(limit, period)` tuples collapse onto shared bindings — a project\n that never declares `rateLimit` ships exactly two (`RL_1000_60`,\n `RL_200_60`), emitted as GA `[[ratelimits]]` blocks in `wrangler.toml` and\n typed `RateLimit` on `CloudflareBindings`.\n- `period` is compile-time constrained to `10` or `60` (Cloudflare binding\n limit); the check no-ops when a binding is absent, so local dev never\n hard-depends on it.\n\n### Envelope encryption — `q.text().encrypted()` (encryption pillar, Phase 1)\n\nMark a text column `.encrypted()` and it is AES-256-GCM-encrypted at rest\nunder a **per-organization key**: a database breach (backup, export, leaked\ntoken, SQL injection, insider read) yields only ciphertext for that column.\nSee [Encryption](/compiler/definitions/encryption).\n\n- Per-org DEKs live wrapped under the `ENCRYPTION_KEK` worker secret in a\n compiler-owned `org_data_keys` table (lazily created, versioned for\n rotation). Deleting an org's row **crypto-shreds** every value it wrote.\n- One write chokepoint: CRUD, batch, and action-layer `db.insert/update`\n all encrypt through the audit wrapper — audit snapshots, webhook\n payloads, and realtime deltas carry ciphertext by construction.\n- Reads decrypt behind the firewall then apply masking; encrypted columns\n are compile-time excluded from `?search`/`?filter`/`?sort`, view query\n allowlists, and embedding sources.\n- `ctx.crypto.encrypt/decrypt` for explicit server-side processing in\n actions; boot guard refuses to serve without the KEK (503 `MISSING_ENV`);\n scaffolded `.dev.vars` now includes a generated `ENCRYPTION_KEK`.\n- The sealed (E2EE) and vault tiers remain compile-gated until built —\n roadmap in `apps/compiler/research/encryption-vault-spec.md`.\n\n### Postgres-style table triggers (`defineTable` / `feature` `triggers:`)\n\nTables can now declare `before`/`after` triggers on `insert`/`update`/\n`delete`, with two lowering lanes and a per-trigger compile report. See\n[Triggers](/compiler/definitions/triggers) for the full reference.\n\n- **`sql:` entries** compile to real SQLite `CREATE TRIGGER` statements,\n shipped in the journaled features migration (content-addressed — an\n unchanged trigger set appends nothing; removing a trigger drops it on the\n next migrate). They fire for **every** write path including raw SQL, run\n atomically with the triggering statement (the only transactional option\n on D1), support `when:` guards and `RAISE(ABORT, ...)` rejection, and\n `OLD.`/`NEW.` column references are validated at compile time. The\n compiler owns the `BEGIN`/`END` frame — emitted uppercase, since\n lowercase `begin` breaks remote D1's statement splitter. On soft-delete\n tables, `*Delete` events map to the `deleted_at` transition (plus a\n hard-delete variant) and `*Update` events exclude it, so a soft delete\n fires delete triggers exactly once. D1 only.\n- **`handler:` entries** run as application hooks at the audit-wrapper\n write chokepoint (REST CRUD + actions). `before*` hooks are synchronous\n and can mutate the payload or throw to reject — the write never executes\n and the request gets `TRIGGER_REJECTED` (422); audit fields are\n re-stamped after hooks and cannot be forged. `after*` hooks run once per\n returned row and are **awaited** — a throw surfaces as\n `TRIGGER_AFTER_FAILED` (500) with `details.committed: true` since the\n write already persisted. Handlers get `{ table, op, values|row, ctx, db,\n env }`; the `db` is audit-wrapped at cascade depth + 1, so hook writes\n stamp audit fields, emit live-view deltas, and fire nested triggers,\n bounded by a depth cap of 5. Each table's drizzle object is auto-imported\n into the generated registry under its authored name, and handler imports\n are usage-filtered and hoisted.\n\nThe compile output includes a lowering/coverage report and fail-closed\nwarnings: `handler:` triggers do **not** fire for queue handlers, cron, or\nraw SQL — guards that must hold universally should use `sql:` +\n`RAISE(ABORT)`. `async: true` (queue-dispatched after-hooks) and\n`withOld: true` (previous-row access) are reserved and rejected at compile\ntime until they ship.\n\nAlso in this change:\n\n- New `trigger` error layer with `TRIGGER_REJECTED` / `TRIGGER_AFTER_FAILED`\n codes in the generated error catalog, OpenAPI spec, and SDK types.\n- Parser: function-valued properties in `defineTable`/`feature` configs now\n parse as compile-time source carriers instead of failing the whole config\n with \"no dynamic expressions\" — unblocks trigger handlers (and\n function-form `access:` / custom masks) through the CLI source path.\n- Fixed a column-injection bug where a comment merely mentioning a column\n name (e.g. `\"deleted_at\"` in a docblock) suppressed audit/soft-delete\n column injection for the table.\n- Fixed a silent no-op: a project declaring `services/queues/*.ts` handlers\n without embeddings or `additionalQueues` deployed a wired `queue` export\n with no `[[queues.consumers]]` to feed it — the handlers were dead code.\n The primary queue (and its typed env binding) is now emitted for\n handlers-only projects, with a compile notice that Cloudflare Queues\n requires the paid Workers plan. Queue emission remains strictly opt-in by\n usage: projects with no queue-backed features (embeddings, queue\n handlers, `additionalQueues`, webhooks) emit no queue configuration and\n deploy on the free plan.\n## v0.47.0 — June 11, 2026\n\n### Breaking: zero-false-positive analyzer checks are now compile errors\n\nThe authz/authn analyzer (v0.37) shipped warn-only. After a release cycle of\ndata, the checks whose every trip is a definite misconfiguration — never a\nlegitimate config — are **promoted to compile errors**. Warnings nobody is\nforced to read are documentation; the pillar guarantees are now enforced.\n\n**Breaking** — a config that previously compiled with one of these warnings\nnow fails the compile:\n\n- `AUTHZ_EMPTY_PERMISSION` — a permission that is structurally unsatisfiable\n (`allOf(a, not(a))`: a fact AND its exact negation at the same AND-level).\n- `AUTHZ_CAPABILITY_CEILING` — a resource's firewall grants a\n `scope:<kind>:<role>` role access beyond its capability profile (or the\n role has no profile at all). This is the M0.2 pillar guarantee — it was\n authored as an error all along and is now enforced.\n- `AUTHN_ROUTE_COVERAGE`, `AUTHN_SURFACE_INVARIANT`,\n `AUTHN_SECRET_CONSISTENCY`, `AUTHN_CREDENTIAL_DELIVERY`,\n `AUTHN_CLAIM_PROVENANCE` — the structural-authn set (route auth coverage,\n bearer-only `/mcp`/agent surfaces + INTERNAL unreachability, mint↔verify\n key/issuer/audience pairing, anchored credential delivery, verifier-only\n identity claims). These still run against empty route/credential metadata\n on a real compile (no-ops until the generators emit it), but the severity\n contract is locked in now — they fail the build the moment they can fire.\n\nThe heuristic/advisory checks are unchanged: `AUTHZ_SHADOWED_ARM`,\n`AUTHZ_UNREACHABLE_ROLE`, `AUTHZ_UNREACHABLE_VIEW`, and\n`AUTHZ_NOT_OVER_RESOURCE` stay warnings; `AUTHZ_PUSHDOWN_COST` stays an info\nreport. `QUICKBACK_AUTHZ_STRICT=true` still promotes those warnings too.\n\n**The override escape hatch** — every promoted finding can be explicitly\naccepted, per finding, with a required reason:\n\n```ts\nauthz: {\n analyzer: {\n allow: [\n {\n check: 'AUTHZ_CAPABILITY_CEILING',\n target: 'sessions/scope:event:organizer', // from the rendered finding\n reason: 'organizer grant profile lands with the v2 rollout (TICKET-123)',\n },\n ],\n },\n}\n```\n\nAn override downgrades that exact `(check, target)` finding back to a warning\nthat cites the reason — even under strict mode (it's an explicit, reasoned\nacceptance). Every rendered error prints its exact override recipe. Guard\nrails: `check` must be one of the promoted ids (unknown or keep-warn ids are\nrejected at config validation), `reason` is required, and an `allow` entry\nthat matches no current finding is itself a compile error — no dead\noverrides accumulating after the underlying issue is fixed.\n\nAnalyzer-internal defects are still fail-open: a bug in the analyzer itself\ndowngrades to a single warning and the compile continues. Only real findings\nfail builds.\n\n### CLI: live views now compile through the CLI\n\n`defineView` files under `quickback/services/views/` were never loaded by\nthe CLI — the compile payload simply omitted them, so\n[live views](/stack/realtime/live-views) (v0.35) only worked when driving\nthe compiler API directly. The CLI now discovers and ships them like every\nother service definition, and the compile summary counts them\n(`Loaded services: … 1 live view(s)`). If you declared views and wondered\nwhy no surface ever went live: upgrade the CLI and recompile.\n\n### CLI: deterministic compile output across machines\n\nFeature and service discovery used raw `readdir` order, which differs\nbetween macOS and Linux — route registration order, schema re-exports,\nOpenAPI paths, and the Neon RLS document's content hash could all churn when\nthe same project was recompiled on a different machine. All discovery sites\nnow sort by codepoint, so the same input compiles to the same bytes\neverywhere. Expect a one-time diff on the first recompile if your previous\noutput was generated in a different filesystem order.\n\n### Fixes\n\n- Read-only resources (no `crud` block) generated routes importing a\n `CRUD_ACCESS` symbol their resource file never exported — a tsc/bundle\n break. The export is now unconditional.\n- The `blog` starter template gated writes on the removed `ADMIN`\n pseudo-role, which hard-fails current compiles; it now uses the\n org-membership `admin` role.\n- `reports/operations.manifest.json` and `reports/conformance.manifest.json`\n now also cover the realtime (`/broadcast/v1`), storage (`/storage/v1`),\n and FGA (`/fga/v1`) surfaces.\n- The dead free/pro tier plumbing is gone: no Tier row in\n `quickback whoami`, no upsell copy at login. Compiling complete projects\n requires login, exactly as before — there was never a paid gate behind it.\n- The CLI is published to npm via trusted publishing (GitHub OIDC) — signed\n provenance, no long-lived npm token in the pipeline.\n\n## v0.46.0 — June 11, 2026\n\n### Breaking: \"no organization context\" responses unified on HTTP 403\n\nGenerated APIs used to answer the same semantic condition — *the caller has no\nactive organization context* — with two different statuses: `400 ORG_REQUIRED`\nfrom the collection list guard and the create/PUT/batch org validation, but\n`403 ACCESS_NO_ORG` from standalone actions and `403\nACCESS_TENANT_SCOPE_REQUIRED` from unsafe org-scoped actions. Clients and SDKs\nhad to special-case the split.\n\n**Breaking** — recompile + redeploy required; every \"no org context\" denial is\nnow **403**:\n\n- `GET /api/v1/<resource>` (and views) without an active org or\n `?organizationId=` → `403 ORG_REQUIRED` (was 400).\n- `POST /`, `PUT /:id`, `POST /batch`, `PUT /batch` without an active org →\n `403 ORG_REQUIRED` (was 400).\n- Standalone actions (`403 ACCESS_NO_ORG`) and unsafe org-scoped actions\n (`403 ACCESS_TENANT_SCOPE_REQUIRED`) were already 403 and are unchanged.\n\nError **codes are unchanged** — `ORG_REQUIRED`, `ACCESS_NO_ORG`, and\n`ACCESS_TENANT_SCOPE_REQUIRED` keep their identities, so clients that\ndiscriminate on `code` need no changes. Only clients that branch on the raw\n`400` status for these responses must update to `403`.\n\n### Breaking: root-mounted actions lose their nested alias URLs\n\nA standalone action whose declared `path:` lives outside its feature prefix\n(e.g. `path: \"/reports/orders\"` in the `orders` feature) mounts at the root:\n`/api/v1/reports/orders`. That root URL is the one the OpenAPI spec, the MCP\nsurface, and the operations manifest have always advertised — but the\ngenerated per-feature routes file *also* carried an undocumented, fully-gated\ncopy at the nested `/api/v1/<feature><path>` URL (e.g.\n`/api/v1/orders/reports/orders`).\n\n**Breaking** — the nested alias is no longer emitted. One URL per operation:\na root-mounted action exists only at its advertised `/api/v1<path>` mount.\nAnything calling the unadvertised nested URL gets a 404 after recompile +\nredeploy; switch to the documented root URL. Actions declared *under* the\nfeature prefix are untouched, and a feature whose standalone actions are all\nroot-mounted no longer emits an (empty) feature actions routes file.\n\n### Behavior change: `PUBLIC` inside `or:` arms admits anonymous callers\n\n[Access](/compiler/definitions/access) has always documented `PUBLIC` as\nworking on every access node, but the emitted auth gate only honored it in a\nflat `roles: [...]` list. A tree like\n\n```ts\naccess: {\n or: [\n { roles: [\"PUBLIC\"] },\n { roles: [\"admin\"] },\n ],\n}\n```\n\nstill answered anonymous callers with `401`. The auth gate is now tree-aware\nand matches the documented semantics: a `PUBLIC` `or:` arm admits anonymous\ncallers past the authentication gate (an `and:` group admits them only when\n*every* arm does), and the access / org / firewall layers still evaluate the\nfull tree. One shared predicate now drives the emitted gates, the OpenAPI\n`security` blocks, and view routes (which gate per view on the\nview-effective access).\n\n**Worth a loud note:** if you have a nested `PUBLIC` arm that was silently\n401-ing, that endpoint becomes anonymously reachable after recompile —\nexactly what the config declares, but verify it's what you meant. `PUBLIC`\naudit logging applies to the newly-admitted routes as usual.\n\n### Realtime broadcasts now enforce `requiredRoles` and masking\n\nA table's declared realtime gates weren't being applied to the generated\nCRUD broadcasts: `realtime: { requiredRoles: [...] }` and column masking were\nhonored on the HTTP surface but not on the WebSocket fanout. The docs\npromised per-role, masked realtime delivery; the generated broadcasts now\nmatch it. **Recompile and redeploy** any project using realtime on\nrole-gated or masked tables.\n\nGenerated `realtime.insert / update / delete` calls now carry:\n\n- **`targetRoles`** — the table's `realtime.requiredRoles` (post role-\n hierarchy `+` expansion), enforced per subscriber at fanout.\n- **`maskingConfig`** — serialized from the same effective masking\n (declared + auto-detected sensitive columns) the HTTP mask functions are\n generated from. What HTTP masks is what the WebSocket wire masks.\n\nLive-view `view_changes` deltas honor the same table-level `requiredRoles`\nat fanout, so a role-gated table can't leak through a\n[live view](/stack/realtime/live-views) subscription either.\n\nNotes:\n\n- Recompile suffices — no config change needed.\n- If you worked around this with hand-written `realtime.*` calls passing\n `targetRoles` / `maskingConfig`, those workaround broadcasts can be\n removed.\n- `type: 'custom'` mask functions can't ride the wire — the Broadcaster\n fails closed and broadcasts `[REDACTED]` for those columns.\n- Tables without `requiredRoles` or masking are byte-identical: the open\n broadcast default is unchanged.\n\n### Batch operations inherit the base operation's access\n\nWhen a batch operation was declared without its own `access`, it didn't pick\nup the base operation's role requirement:\n\n```ts\ncrud: {\n update: { access: { roles: [\"admin\"] } },\n batchUpdate: { maxBatchSize: 25 }, // ← no access of its own\n}\n```\n\nA batch config declared without `access` now inherits the base operation's\naccess at compile time — fail closed, so runtime, the OpenAPI spec, and the\ngenerated code all agree. Explicit batch `access` still wins (including\nper-side on upserts); a base op without access still yields an\nauthenticated-only batch op. The flat `update: { batch: true }` shape and\nauto-promoted batch ops were never affected. **Recompile and redeploy** if\nyou use the explicit-batch shape without per-batch access.\n\n### Record actions, PUT upserts, and legacy firewall arms fail closed\n\nThree fail-closed hardening fixes, found and verified against the new\nconformance catalog (route × principal expectations derived from the\ncompiler's own IR — see the\n[conformance manifest](/compiler/targets/hono-api/using-the-api/openapi#operations-manifest)).\nAll apply on recompile + redeploy; no config change needed:\n\n- **Record actions evaluate the role gate before fetching the record**, so\n the denial response no longer varies with record state — a uniform\n `403 ACCESS_ROLE_REQUIRED`. (Bulk actions already had this order; unsafe\n actions write their audit row on the pre-record denial.)\n- **PUT upsert treats an out-of-scope id as a firewall miss** (`403` reveal /\n `404` hide, per your firewall error mode; a standard 207 miss entry on\n `PUT /batch`) instead of routing it into the create path. Genuinely new\n ids keep the create path.\n- **Legacy (array-form) firewall arms deny cleanly when a bound context\n claim is absent at runtime** (e.g. no active org), rather than surfacing a\n database error — the same deny-when-absent behavior the explicit `all:` /\n `any:` group forms already had.\n\n### Root-mounted standalone actions use the standard gate stack\n\nStandalone actions mounted outside their feature prefix\n(`path: \"/reports/orders\"`) were emitted through a separate code path that\ndid not apply the full access / audit / scoped-database treatment that\nin-feature standalone actions receive. They now render through the same\ngenerator, so the same access checks, security-audit writes, and\ntenant-scoped database wrapping apply everywhere. If you use root-mounted\nstandalone actions, recompile and redeploy. (Unifying the two code paths is\nalso what surfaced the two breaking changes above.)\n\n### Namespace routing fixes\n\n- An action whose declared `path` exactly equals its namespace prefix is now\n claimed by the namespace like any nested action (Hono's `/x/*` mount\n already matched the bare `/x`) — it's served through the namespace's gate\n instead of carrying a second inline copy of the resolver.\n- A namespace with zero claimed standalone actions (e.g. record-based-only)\n no longer mounts its middleware at all — a dead gate can no longer\n intercept requests under its prefix.\n\n### Custom org roles work with Better Auth member management\n\nCustom roles referenced in access trees (e.g. `roles: [\"support\"]`) are now\nauto-registered with the Better Auth organization plugin. They were already\nenforceable on routes but unprovisionable through Better Auth —\n`invite-member` / `update-member-role` rejected them with\n`400 ROLE_NOT_FOUND`, so there was no supported way to actually give a\nmember the role. Auto-registered roles carry member-equivalent permissions\n(this is about assignability; your access trees remain the authorization\nmodel). If you pass your own `roles` / `ac` to the organization plugin\noptions, those win and auto-registration is skipped. Built-in, pseudo, and\n`scope:` roles are excluded; projects with no custom roles emit\nbyte-identical output.\n\n### snake_case tables: dropped record actions and broken helpers fixed\n\nTwo fixes for tables declared with snake_case names (`event_notes`):\n\n- The generated `.quickback/define-action.ts` helpers imported the camelCase\n identifier while the generated alias file exports the verbatim declared\n name (`export { event_notes }`) — a TS2724 compile failure for any\n snake_case table with action files. The helpers now import the real export\n aliased to the camelCase local.\n- Record actions on a snake-declared table living in a kebab-named feature\n file (`event-notes/actions/pin.ts`) were not emitted — missing from both\n the generated routes and OpenAPI. They now emit and document consistently.\n\nIf you have snake_case tables with record actions, recompiling **adds routes\nthat previously didn't exist** — review the new surface.\n\n### First-class MCP OAuth config: `auth.oauth`\n\nThe OAuth 2.1 surface behind `agents.mcp.requireAuth` (v0.42.0) gains a\nfirst-class config block — env-resolvable issuer / login / consent URLs,\nscopes, RFC 8707 audiences, and a dynamic-client-registration toggle:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n oauth: {\n enabled: true,\n issuerUrl: { env: \"OAUTH_ISSUER_URL\", fallback: \"http://localhost:8787/auth/v1\" },\n loginPage: { env: \"OAUTH_LOGIN_URL\", fallback: \"http://localhost:8787/account/login\" },\n consentPage: { env: \"OAUTH_CONSENT_URL\", fallback: \"http://localhost:8787/account/consent\" },\n scopes: [\"openid\", \"profile\", \"email\", \"offline_access\"],\n audiences: [{ env: \"OAUTH_MCP_AUDIENCE\", fallback: \"http://localhost:8787/mcp\" }],\n allowDynamicClientRegistration: true,\n },\n}),\n```\n\nSetting it auto-enables the `oauthProvider`, `jwt`, and `bearer` plugins,\nemits the RFC 8414 / RFC 9728 discovery documents, and accepts the\nprovider's JWKS-signed access tokens in the standard auth middleware. A new\nproject hook, `quickback/hooks/resolve-oauth-context.ts`, lets you derive\ntenant fields (`activeOrgId` / `activeTeamId` / roles) from the validated\nOAuth identity. On Neon, the auth schema is now owned by the Better Auth CLI\nend to end (the compiler no longer emits its placeholder `src/auth/schema.ts`\nor `src/lib/neon.ts`). See\n[OAuth Provider (MCP-ready)](/stack/auth/plugins#oauth-provider-mcp-ready)\nand [Auth Hooks](/stack/account-ui/hooks#oauth-context-resolver).\n\n### Neon RLS covers force-enabled plugin tables\n\nOn Neon, row-level-security policies are generated for the Better Auth\ntables. The list of tables receiving policies was derived from your declared\nauth config and didn't account for plugins the compiler force-enables\nautomatically — so some auth-owned tables could be created without RLS\npolicies. The list now derives from the fully resolved plugin set, so every\ngenerated auth table receives appropriate policies (self-scoped where there\nis a clear owner, service-role-only otherwise — fail closed). The RLS\nmigration is content-addressed, so the update arrives as a new journaled\nentry on the next recompile + `db:migrate`. **Neon projects should recompile\nand run `db:migrate`.**\n\n### New compile reports: operations + conformance manifests\n\nEvery compile now writes two machine-readable reports next to\n`openapi.json`:\n\n- **`reports/operations.manifest.json`** — a stable, sorted index of every\n operation: `{ operationId, method, path, auth, feature, kind }`, covering\n the resource, action, view, auth, realtime, storage, and FGA surfaces. An\n extend-only public contract — the recommended integration point for\n scripting against the generated surface.\n- **`reports/conformance.manifest.json`** — for each route × principal\n class, the expected outcome (allow / 401 / 403 / cross-tenant miss …),\n derived from the same IR the emitters consume. This is the artifact the\n conformance fixes above were found and verified against.\n\nThe OpenAPI generator itself now reads the same IR as the route emitters, so\nthe spec follows the emitted surface by construction — including four\naccuracy fixes: `PUT /{id}` is documented only when actually enabled, the\nbatch surface documents the emitter's auto-promotion + access inheritance,\nand views document their effective (view-level, falling back to read-level)\naccess. See\n[Operations manifest](/compiler/targets/hono-api/using-the-api/openapi#operations-manifest).\n\n## v0.45.0 — June 9, 2026\n\n### `auth.jwt.revocationCheck: 'kv'` — sub-TTL JWT revocation\n\nThe JWT fast-path trusts signed claims for their full lifetime — that's what\nmakes it a fast-path. Until now the only revocation bounds were the TTL\n(plain claims) and the carry-forward cap (scope claims, v0.44.0). The\nlong-promised `'kv'` mode is now real on the **Cloudflare runtime**:\n\n```ts\nauth: { jwt: { revocationCheck: 'kv' } }\n```\n\n- **Per-principal revocation timestamps, not per-token denylists.** A\n revocation event writes \"everything for this principal minted before now is\n dead\" to the project's **existing `KV` binding** (keys prefixed `qbrev:`) —\n nothing extra to provision. Entries self-expire after the maximum token\n lifetime, so the store never accumulates.\n- **The bearer fast-path checks before trusting.** A verified token whose\n `iat` (or `sct`, for the relationship-scope claim) predates the stored\n timestamp is rejected and falls through to session auth, which re-checks\n membership and re-mints — an active legitimate session recovers\n transparently. Costs 2+ edge-cached KV reads per bearer verify; the\n explicit trade the opt-in buys.\n- **Written automatically where revocation actually happens:** org-member\n removal and role change (Better Auth `organizationHooks`), and\n UPDATE/DELETE of scope-conferring relationship rows — through the same\n audit-wrapper write chokepoint Live Views uses, plus the single DELETE\n route (which has the row in hand but no `.returning()`). Revoke-on-touch:\n a false positive just forces a cheap re-prove.\n- **User bans flip automatically.** The Better Auth admin plugin's ban lands\n as a user-row update, so a generated `databaseHooks.user.update.after` hook\n stamps the user-level revocation the moment `banned` flips — every\n outstanding JWT dies on its next use, and the cookie/session path already\n rejects banned sessions, completing the lockout. When outbound webhooks are\n configured, the same hook emits a `user.banned` event so subscribed\n endpoints are notified.\n- **App-code helpers** for everything else: `src/lib/jwt-revocation.ts`\n exports `revokeUserTokens` / `revokeMemberTokens` / `revokeScopeTokens`\n (e.g. call `revokeUserTokens` from a custom revoke-all flow).\n- **Fails open.** A KV outage degrades revocation to the TTL /\n carry-forward-cap bound — it never locks every bearer out.\n\nBun/Node + `'kv'` fails at compile time with a clear message (the store rides\nthe Cloudflare KV binding; those runtimes own immediate-revoke via the\ncookie/session path). Default remains `'none'`; without the flag the emitted\nmiddleware is byte-identical to v0.44.0.\n\n### Neon: `npm run db:migrate` now applies the RLS layer\n\nThe RLS SQL (helper functions, policies, triggers) used to be emitted as\norphaned `drizzle/migrations/0099–0102` files that no tool ever applied —\n`db:migrate` ran the schema migrations and silently skipped the security\nlayer. The RLS document now rides the journaled drizzle set in\n`quickback/drizzle/` as a content-addressed migration\n(`<idx>_quickback_rls_<hash>`), so one `npm run db:migrate` applies schema\n**and** security, in dependency order. The migration is idempotent\n(`DROP POLICY IF EXISTS` + re-create), so it converges over databases where\nthe old files were applied by hand; an unchanged security config appends\nnothing (the journal stays byte-stable across recompiles), and a changed one\nappends a new content-addressed entry — append-only, like every other\nmigration. Existing Neon projects: recompile + `db:migrate`, nothing breaks.\n\n### Neon: `user_sessions` is real, and the SQL layer speaks TEXT ids\n\n`get_active_org_id()` — the helper every org-scoped RLS policy reads — was\nquerying a `public.user_sessions` table that **no migration created**, and\nthe helper layer was typed `uuid` against Better Auth's TEXT ids\n(`org_abc123`), which would throw on first contact. Now:\n\n- `user_sessions` is compiler-owned migration state\n (`src/db/rls-support.schema.ts`), created by the normal journaled flow\n with a FK to the users table — outside `src/auth/schema.ts`, which the\n Better Auth CLI rewrites.\n- Generated Better Auth session hooks mirror the session's active\n organization (and team, in teams mode) into it on create/update.\n Switching to \"no org\" nulls it through — SQL-side access revokes, fail\n closed.\n- The RLS helper layer (`get_active_org_id`, `get_active_team_id`,\n `is_owner`, the audit helpers) is TEXT-typed to match Better Auth ids.\n- Policies for Better Auth's own tables use the plural physical names the\n BA CLI actually generates on Neon, and BA tables no longer get Quickback\n audit triggers for columns they don't have.\n\n### Hard deletes wire into the audit pipeline correctly\n\nTwo codegen bugs around `delete: { mode: 'hard' }`:\n\n- Firewall auto-detection emitted an `isNull(deletedAt)` predicate for\n tables with no soft-delete column — every read on a hard-delete table\n referenced a column that doesn't exist.\n- Hard-delete routes import the `logHardDelete` audit helper, but the helper\n file was only emitted when the project also had unsafe or `PUBLIC` actions\n — a project with hard deletes and neither failed at deploy time. Hard\n deletes are now a first-class trigger of the security-audit pipeline\n (helper file, `AUDIT_DB` binding, env types, audit migration); on D1 that\n means [`auditDatabaseId`](/compiler/config/providers) is required, and the\n compile error says so.\n\n### Generated output is now typechecked — with the first crop of fixes\n\nEvery compiler change now compiles a matrix of fixture projects and runs\n`tsc` + `wrangler deploy --dry-run` against the **generated output** — the\nclass of bug where the compiler emits syntactically valid TypeScript that\nfails downstream. The first runs caught real ones, all fixed here:\n\n- **Neon:** `src/db/org.schema.ts` re-exported tables that don't exist after\n the Better Auth CLI's plural rewrite; a missing `AuthDatabase` type\n export; transaction callbacks typed bare `(tx)` failing `noImplicitAny`;\n the auth middleware's member-table fallback hardcoded the singular name.\n- **Embeddings:** the queue consumer's `Ai.run` result and the optional\n `EMBEDDINGS_QUEUE` binding both failed strict checks — the route now\n returns a structured `503` when the producer binding is missing instead\n of crashing.\n- **snake_case relationship tables:** relationship/arrow emitters imported\n the camelCase identifier where the generated file exports the verbatim\n table name (`export { event_guests }`) — TS2724 for any snake_case\n relationship table. Imports now alias the real export\n (`event_guests as eventGuests`).\n\n## v0.44.0 — June 9, 2026\n\n### Scope carry-forward is now bounded (revocation fix)\n\nThe auth middleware's rolling refresh re-signs a verified `scope` claim on\nevery authed call without re-probing the relationship — that's what lets a\nscoped session ride past the short JWT TTL with zero per-request DB cost. But\nunbounded, it defeated the revocation model the docs promised: a removed\nguest/staff who kept polling got a fresh TTL on every request, so \"removal\ntakes effect within one TTL\" only held for *idle* clients, and the refresh\nalso bypassed the ≤180s scope-token ceiling (it re-signed with the raw\n`auth.jwt.expiresIn`).\n\nScope tokens now carry a proof timestamp (`sct`), stamped exclusively by the\nproven mint sites (`POST /scope/v1/enter` and the namespace resolver, via the\nshared mint helper). The rolling refresh:\n\n- **refuses once the claim's proof is older than the carry-forward cap\n (15 minutes)** — past it, the token expires within one TTL and the client\n re-proves via `enter` or any minting namespace route, which won't re-mint a\n revoked role. Worst-case post-revocation window for an active client:\n **cap + one TTL** from the last real proof, instead of unbounded.\n- **carries `sct` forward verbatim** — the refresh can never restart the\n window without an actual relationship probe. Claims without `sct`\n (pre-0.44 tokens) fail closed and simply stop refreshing.\n- **signs through the same ≤180s ceiling as the mint sites** — an\n `auth.jwt.expiresIn` above the ceiling no longer leaks into scope-bearing\n tokens via the refresh path.\n\nNo client changes needed: tokens renew exactly as before inside the window,\nand re-entering is the existing flow. For tables where even the capped window\nis too wide, gate with a `via` arm (live relationship subquery per request)\ninstead of a bare `ctx.scope.<kind>` arm; immediate revocation\n(`auth.jwt.revocationCheck: 'kv'`) remains on the roadmap.\n\n## v0.43.0 — June 4, 2026\n\n### Better Auth 1.6\n\nGenerated projects are now pinned to Better Auth **1.6**. The `agents.mcp.requireAuth` work in 0.42.0 surfaced a long-standing version drift: the compiler emitted `better-auth: ^1.5.0`, but `@better-auth/oauth-provider` resolves a tree that requires `@better-auth/core ^1.6.14` and imports `@better-auth/core/utils/host` + `/redirect-uri` — subpaths that only exist in 1.6.x. The result was a `wrangler deploy` that failed at bundle time with `Could not resolve …` and never uploaded.\n\nThis release aligns the **entire** Better Auth dependency set to a coherent 1.6.9 floor so npm resolves one consistent tree:\n\n- `better-auth`, `@better-auth/drizzle-adapter`, `@better-auth/api-key`, `@better-auth/passkey`, `@better-auth/oauth-provider` → `^1.6.9` (generated projects, the baked Docker deps, and the bundled CMS/Account SPAs).\n- Added an explicit `kysely ^0.28.16` pin: Better Auth 1.6's migrator imports `DEFAULT_MIGRATION_TABLE` / `DEFAULT_MIGRATION_LOCK_TABLE` from kysely but doesn't *declare* kysely, so the Worker bundle needs it pinned directly.\n\nNo code migration was required — Quickback already uses `@better-auth/oauth-provider` (not the now-deprecated OIDC Provider plugin), and emits no `freshAge`/SAML usage affected by 1.6's behavioral changes. Verified end to end: a `requireAuth` project and a normal project both `npm install` a clean 1.6.14 tree and bundle with `wrangler deploy --dry-run` with zero resolution errors.\n\n### Larger migration histories no longer hit the upload ceiling\n\nLong-lived projects accumulate one full-schema drizzle snapshot per migration, and the whole cumulative meta payload (snapshots + journals + `.sql`, across both the auth and features dirs) is re-sent on **every** compile — even a no-schema-change one. Projects with deep migration histories were hitting the compiler's `existingFiles` size limit and failing to compile, with no schema drift and nothing to fix on their end.\n\nThe server-side ceilings are raised so this is no longer the binding constraint:\n\n- `existingFiles` payload: **4 MiB → 16 MiB**\n- total request body: **8 MiB → 32 MiB** (kept above the per-category limits so it doesn't trip first)\n\nThis is enforced entirely on the compiler, so no CLI upgrade is needed — the new headroom applies as soon as `compiler.quickback.dev` is on this release.\n\n### Custom response headers (`security.headers`)\n\nThe generated Worker emitted a fixed set of security headers (CSP, HSTS,\n`X-Content-Type-Options`, …) with no supported way to add your own — teams that\nwanted, say, an `X-Server-Version` build stamp on every response had to\npost-patch the generated middleware after each compile.\n\nNew `security.headers` sets arbitrary response headers natively. Values are\nstatic strings or templates interpolating per-deploy Worker env vars via the\n`{{env.VAR_NAME}}` token:\n\n```ts\nsecurity: {\n headers: {\n // Both vars must be set, or the header is omitted entirely.\n 'X-Server-Version': '{{env.SERVER_VERSION}}+{{env.SERVER_BUILD}}',\n 'X-Powered-By': 'Quickback',\n },\n}\n```\n\n- **Omit-if-unset** — a header that references env vars is emitted only when\n *every* referenced var is set (non-empty) at runtime. A Worker that forgot to\n inject the var emits no header, never `X-Server-Version: undefined`. Static\n headers are always emitted.\n- The value is read from `c.env` per request, so it picks up whatever Worker\n var is injected at deploy time — nothing is baked at compile time.\n- **Managed headers are rejected** — names owned by a dedicated `security` field\n (CSP, HSTS, `X-Frame-Options`, `Referrer-Policy`, …) error at compile so the\n two emitters can't race. Malformed `{{env…}}` tokens error too, rather than\n leaking literal braces into the wire header.\n\nSurvives a clean `quickback compile` with no post-processing. See\n[Security Headers → Custom response headers](/compiler/config/security#custom-response-headers).\n\n## v0.42.0 — June 4, 2026\n\n### Interactive OAuth for the generated MCP server\n\nMCP connectors (Claude, Cursor, …) could only connect to a generated `/mcp`\nendpoint **anonymously** — they never launched a sign-in flow, so auth-gated\ntools stayed invisible. The OAuth machinery was already present (Better Auth's\n`oauth-provider` ships `/oauth2/authorize`, `/token`, `/register` + PKCE under\n`/auth/v1`); the compiler just never let a connector discover or trigger it.\n\nNew `agents.mcp.requireAuth` makes the MCP surface authenticated-only:\n\n```ts\nagents: { mcp: { requireAuth: true } },\n```\n\nWhen enabled, the compiler:\n\n- **Challenges unauthenticated `/mcp`** with `401` + `WWW-Authenticate: Bearer\n resource_metadata=\"…\"` ([RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) §5.1) — the signal connectors use to start OAuth.\n- **Force-enables `oauthProvider` + `bearer`**, so `/oauth2/authorize`, `/token`,\n and `/register` ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591) dynamic client registration) exist with PKCE.\n- **Delegates `/.well-known/oauth-authorization-server`** to Better Auth's real\n metadata instead of a hand-rolled stub that advertised a non-existent\n authorization endpoint.\n- Adds the `<origin>/mcp` resource to `validAudiences`\n ([RFC 8707](https://datatracker.ietf.org/doc/html/rfc8707)) so the connector's access token isn't rejected.\n\nLogin and consent are served by your Account SPA, so users authenticate with\nwhatever methods you already enabled. Default is unchanged (anonymous public\ntools); set `requireAuth: true` for servers meant for authenticated users.\n\n## v0.40.2 — June 3, 2026\n\n### Passwordless plugins can no longer bypass the signup gate\n\nBetter Auth's `emailOtp` and `magicLink` plugins auto-create an account when a\ncode/link is verified for an unknown email — and that path is independent of\n`emailAndPassword.disableSignUp`. As a result, `account.auth.signup: false`\nclosed `POST /auth/v1/sign-up/email` but left OTP / magic-link verification as an\nopen back-door for account creation.\n\nThe compiler now emits each plugin's own `disableSignUp` flag, and new\nper-plugin options expose it directly:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: {\n emailOtp: { disableSignUp: true }, // OTP sign-in only; unknown emails rejected\n magicLink: { disableSignUp: true }, // same for magic links\n },\n}),\n```\n\nBoth default to following the global gate: setting `account.auth.signup: false`\n(→ `emailAndPassword.disableSignUp: true`) now also gates the OTP and magic-link\npaths automatically. Set `{ disableSignUp: false }` on a plugin explicitly to\nkeep its sign-up open while password sign-up stays closed.\n\n## v0.40.1 — June 2, 2026\n\n- The generated `wrangler.toml` and `Env` type now emit the `ASSETS` binding\n type for projects that mount SPAs (CMS / Account), so handler code that\n references `c.env.ASSETS` typechecks.\n- Compiler Docker builds preserve their layer cache across rebuilds, cutting\n local recompile time.\n\n## v0.40.0 — June 2, 2026\n\nR2 file storage is now **presign-only by default**. Adding\n`defineFileStorage(\"cloudflare-r2\")` emits just the `ctx.storage` signer — no\nFILES_DB database, no `/storage/v1/*` endpoints, no files worker. You sign\npresigned URLs against a bucket and store references in your own table. The\nturnkey managed subsystem is still available, now behind `managed: true`.\n\nThis decouples the lightweight primitive from the heavyweight subsystem so you\ncan add uploads without standing up a metadata database you don't use.\n\n### Presign-only by default; managed is opt-in\n\n```ts\n// Presign-only (default) — ctx.storage against a bucket, nothing else\ndefineFileStorage(\"cloudflare-r2\", { bucketName: \"my-app-media\" })\n\n// Managed subsystem — FILES_DB + /storage/v1/* + files worker\ndefineFileStorage(\"cloudflare-r2\", { managed: true })\n```\n\n- New projects can omit `bucketName` — it defaults to `<project>-media`, so\n setup is one `wrangler r2 bucket create` plus the R2 API-token secrets.\n- Existing projects set `bucketName` to a bucket they already have. Presign-only\n emits **no** R2 bucket binding and **no** FILES_DB binding — nothing to\n provision, nothing to migrate.\n\n### Per-call bucket + custom secret names\n\n```ts\n// Sign against a different bucket than the configured default\nawait storage.signPutUrl(key, { bucket: \"my-app-public\", contentType });\n```\n\nIf your project already stores R2 credentials under different env-var names,\nmap them so the signer reads yours:\n\n```ts\ndefineFileStorage(\"cloudflare-r2\", {\n bucketName: \"my-app-media\",\n presign: { accountIdEnv: \"CF_ACCOUNT_ID\", accessKeyIdEnv: \"S3_KEY\", secretAccessKeyEnv: \"S3_SECRET\" },\n})\n```\n\n### Fixes\n\n- `maxFileSize` now accepts a human string (`\"100mb\"`, `\"5gb\"`) as well as a\n number of bytes — previously a string emitted invalid TypeScript.\n- Presign-only no longer emits a stray `FILES_DB` `[[d1_databases]]` block (with\n an invalid `database_id = \"local-files\"`) into `wrangler.toml`, which would\n have made `wrangler deploy` reject the worker.\n\n## v0.39.1 — June 2, 2026\n\nDeduplicate colliding OpenAPI `operationId`s. The auto-generated list id\n`list\n</Button>\n```\n\n`ResponsiveModal` survived the migration unchanged — it composes the higher-level Dialog + Drawer wrappers (preserved public API), not the underlying primitives.\n\n#### Caller-side API changes worth noting\n\nBase-ui ships some real behavioural changes the Radix variants didn't:\n\n- `<Select onValueChange>` now receives `(value: string | null, eventDetails) => void` (was `(value: string) => void`). Existing `Dispatch<SetStateAction<string>>` setters reject `null` — wrap callbacks defensively: `onValueChange={(v) => v != null && setX(v)}`.\n- `<DropdownMenuContent forceMount>` removed (base-ui has no `forceMount`). Use base-ui's `keepMounted` on the Popup/Positioner if you need to preserve unmounted state.\n- Component sub-names shifted (`Dialog.Content` → `Dialog.Popup`, `Dialog.Overlay` → `Dialog.Backdrop`). Data attributes are now `data-open` / `data-closed` (no more `data-state=\"open\"`).\n\n#### Adding a new primitive after this release\n\n```bash\ncd packages/ui\npnpm dlx shadcn@latest add <component> --overwrite --yes\n# Sweep generated `@/` imports to relative paths — the SPAs' vite-tsconfig-paths\n# plugin doesn't see packages/ui's @/* mapping at bundle time:\nsed -i.bak \\\n -e 's|\"@/lib/utils\"|\"../lib/utils\"|g' \\\n -e 's|\"@/components/|\"./|g' \\\n -e 's|\"@/hooks/|\"../hooks/|g' \\\n components/<component>.tsx && rm components/<component>.tsx.bak\n```\n\nIf the new primitive pulls in fresh deps, mirror them into `apps/compiler/deps-spa-{cms,account}-package.json` per the SPA build pipeline or Docker SPA builds will fail.\n\n---\n\n## v0.18.1 — May 18, 2026\n\n### Account SPA — teams, active-team picker, permission-aware UI\n\nThe Account SPA's organization surface is now feature-parity with Better Auth's `organization` plugin for the basic team workflow, and replaces the long-standing hardcoded `role === 'owner' || 'admin'` checks with `checkRolePermission` so projects that ship custom roles get a UI that respects them.\n\n#### Teams (opt-in)\n\nWhen the BA config enables teams — `organization({ teams: { enabled: true } })` — the compiler emits `VITE_ENABLE_ORG_TEAMS=true` and the Account SPA exposes a Teams tab on each organization:\n\n- **Teams index** (`/$slug/teams`) — splits into \"Your teams\" (from `listUserTeams`) and \"Other teams\" so non-admins land on what's relevant. Create / rename / delete from the list, gated on `team:create` / `team:update` / `team:delete`.\n- **Team detail** (`/$slug/teams/$teamId`) — member roster with add / remove, joining `listTeamMembers` against the org's full member list for display.\n- **Active-team picker** in the org header — calls `setActiveTeam` and exposes the choice via `OrganizationContext.activeTeamId` so downstream routes (and the BA `session.activeTeamId` server-side) stay in sync.\n- **Team-aware invites** — `InviteMemberDialog` shows an optional team picker when teams are on and forwards `teamId` to `inviteMember`, so accepting the invite drops the new member straight into the right team.\n\nTeams are loaded once by the `$slug` layout (`listTeams` + `listUserTeams`) and exposed via `OrganizationContext.teams` / `userTeamIds` / `refreshTeams`, so individual team routes don't re-fetch the list.\n\n#### Permission-aware UI via `checkRolePermission`\n\n`OrganizationContext.isOwnerOrAdmin` is gone. Routes now read `can(resource, action)` from context, which delegates to `authClient.organization.checkRolePermission` — synchronous, no roundtrip, and aware of any custom roles registered via the BA `ac` option. Multi-role users (BA stores multiple roles comma-separated) are handled by checking each role; the action is allowed if any role grants it.\n\nMigrated sites:\n\n- `$slug.tsx` tab gates → `can('invitation', 'create')`, `can('organization', 'update')`\n- `members.tsx` action menu → `can('member', 'update' | 'delete')`; the owner-hierarchy guard (non-owners can't touch owner-role members) is preserved as a client-side mirror of BA's server enforcement\n- `invitations.tsx` → `can('invitation', 'create' | 'cancel')` gates the Invite button, resend, and cancel separately\n- `settings.tsx` → `can('organization', 'update')` for the form, `can('organization', 'delete')` for the danger zone (was owner-only)\n- `teams.tsx` / `teams.$teamId.tsx` → `can('team', 'create' | 'update' | 'delete')`\n\nProjects on the default three-role hierarchy see no behaviour change; projects that defined `admin`/`member` overrides via BA's access-control API now get a UI that matches what the server will actually authorize.\n\n#### Editable slug + metadata on organization settings\n\nThe `$slug/settings.tsx` form now edits two more `organization.update` fields:\n\n- **URL slug** — full debounced `checkSlug` flow (mirroring the create-org form); on rename, the SPA navigates to `/${newSlug}/settings` and the layout re-fetches with the new slug.\n- **Metadata** — single `Record<string, any> | null` JSON textarea, parsed on submit with inline error messaging. Empty clears the field.\n\nSlug rename is non-breaking for the SPA itself, but every external link / bookmark that references the old slug becomes a 404 — the form warns about this before saving.\n\n#### Auth client wiring\n\nWhen `VITE_ENABLE_ORG_TEAMS=true`, the SPA's `organizationClient(...)` is instantiated with `teams: { enabled: true }` so the team APIs are typed end-to-end. When the flag is off, team methods aren't surfaced — and the Teams tab is hidden — keeping the bundle and UI honest about what the server actually supports.\n\n---\n\n## v0.18.0 — May 17, 2026\n\n### `config.apps` — mount user-authored SPAs on dedicated hostnames\n\nThe compiler now generates per-hostname Worker middleware for arbitrary user SPAs alongside the built-in CMS and Account UIs. Previously the only way to host a product app next to a Quickback API was a second Worker; `config.apps` brings the full stack — API, account, and product UI — onto one deployment with same-origin auth.\n\n```ts\napps: {\n www: {\n domain: \"www.example.com\",\n aliasDomains: [\"example.com\"], // apex serves the same SPA\n },\n}\n```\n\nEach entry binds one or more hostnames to a directory under `src/apps/<name>/` and inherits the Account-domain pass-through behavior — `/api/`, `/auth/`, `/admin/`, `/storage/`, and `/health` route to Hono so the SPA fetches its API without CORS. The compiler:\n\n- emits a `custom_domain = true` route in `wrangler.toml` for the primary hostname and every alias\n- adds each hostname to Better Auth's `TRUSTED_ORIGINS` (when `trustedOrigins` is left unset)\n- widens the CSP `connect-src` to cover the SPA-baked origins\n- folds the new hostnames into shared-parent detection for `crossSubDomainCookies`\n\nDrop the prebuilt SPA bundle at `quickback/apps/<name>/` — the existing source-apps passthrough copies it byte-for-byte into `src/apps/<name>/`. The compiler doesn't build the SPA; it only emits routing for whatever's already there. The names `cms`, `account`, and `public` are reserved; hostname collisions with `cms.domain` / `account.domain` / `account.adminDomain` or between two `apps[*]` entries fail at compile time.\n\nWhen `cms` and `account` are both configured, the multi-domain catchall now explicitly skips app hostnames — an API miss on an app host returns the standard 404 JSON via `app.notFound` instead of stray-serving a sibling SPA's HTML shell.\n\n### Cross-subdomain cookie inference handles apex aliases\n\nThe shared-parent detection that drives `advanced.crossSubDomainCookies` previously reduced any hostname by stripping the leftmost label — `'example.com'` collapsed to `'com'`, which broke equality against sibling subdomains. Apex hostnames (exactly two dot-segments) are now treated as already being the parent, so apex aliases (`example.com` listed alongside `www.example.com`) coexist cleanly with `auth.example.com` / `cms.example.com` and the compiler still emits `crossSubDomainCookies: { enabled: true, domain: '.example.com' }`.\n\n---\n\n## v0.17.2 — May 15, 2026\n\n### `customPlugins` escape hatch on `defineAuth(\"better-auth\", …)`\n\nThe Better Auth provider now accepts `customPlugins` alongside the named-plugin registry — a path to ship third-party plugins (`@better-auth-kit/audit`, …), unregistered built-ins, or one-off project-local plugins without forking the compiler.\n\nEach entry is an explicit import descriptor:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: { passkey: true, organization: true },\n customPlugins: [\n // (1) Project-local plugin file at quickback/plugins/long-session.ts\n { from: \"./plugins/long-session\", export: \"longSessionPlugin\" },\n // (2) Third-party npm package\n {\n from: \"@better-auth-kit/audit\",\n export: \"auditPlugin\",\n args: { events: [\"sign-in\"] },\n dependencies: { \"@better-auth-kit/audit\": \"^1.0.0\" },\n },\n ],\n}),\n```\n\n`from` is either a relative path under `./plugins/` (the CLI auto-uploads matching files from `quickback/plugins/`; the compiler copies them into `src/plugins/<name>.ts` and rewrites the emitted import) or a bare npm specifier (emitted verbatim; declare `dependencies` so the package lands in the generated `package.json`). Omit `args` to emit the symbol uncalled (plugin instance); provide `args` to emit a JSON-serialized factory call.\n\nThe descriptor is validated with Zod — typos in `from`/`export`, paths that escape `./plugins/`, and references to files the CLI didn't ship all fail at compile time with a targeted message.\n\n---\n\n## v0.17.1 — May 14, 2026\n\n### `quickback start` — interactive onboarding\n\n```bash\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n```\n\n`start` walks new users through template selection, scaffolds the project on disk, and only prompts for an account when it's ready to compile. Cancelling at the login prompt leaves the scaffold intact — sign in and run `quickback compile` whenever you're ready.\n\nThe same deferred-auth flow applies to `quickback create`. Scaffolding and (optional) Cloudflare D1 setup run before authentication, so you can preview the project on disk before committing to an account.\n\n### Named views on the free tier\n\nThe `todos` template now ships a `dashboard` named view, exposing a projected response at `GET /api/v1/todos/views/dashboard`. Named views support per-view access rules and per-view field selection while inheriting the table's firewall and masking — the canonical way to ship list-view payloads that are cheaper to fetch and easier to cache than a full collection read.\n\n### `quickback init` removed\n\nFolded into `start` and `create`. The legacy command name prints a deprecation notice pointing at its replacements.\n\n### Minor\n\n- `quickback whoami` reads the stored tier from your credentials.\n- Pro upsell copy in `quickback login` is shown only when the server returns an explicit free-tier subscription.\n- Bare scaffolds (`cloudflare`, `empty`) report accurately when there are no features to generate migrations for.\n\n---\n\n## v0.16.10 — May 14, 2026\n\n### D1-specific safety pass on generated migrations\n\nThe `cloudflare-d1` provider now runs a post-generation pass over every Drizzle migration directory (auth, features, webhooks, audit) before the compile finishes. Better Auth cleanup for retired managed tables is stripped from raw `DROP TABLE` statements. Drop-only cleanup migrations are reordered child-first when foreign-key dependencies require it. Every generated D1 migration directory is replayed against SQLite during compile, so a D1-breaking migration fails at compile time rather than at `wrangler d1 migrations apply`.\n\n---\n\n## v0.16.9 — May 13, 2026\n\n### Resource-scoped realtime tickets\n\n`providers.database.config.realtime` accepts an object form for projects whose WebSocket subscribers aren't org members:\n\n```ts\nrealtime: {\n wsTicket: {\n role: \"attendee\",\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n}\n```\n\nThe generated `/broadcast/v1/ws-ticket` route authenticates the caller, evaluates the declared relationship role against the request, and mints a short-lived WebSocket ticket scoped to the resolved resource. `realtime: true` continues to enable the org-scoped broadcaster.\n\n### Unified broadcast targeting\n\nThe realtime helper and Broadcaster now route by `scopeKey || organizationId || userId`. String targets remain shorthand for `organizationId`; explicit targets can scope a broadcast to a resource or a single user:\n\n```ts\nawait realtime.broadcast(\"event-page-updated\", payload, { scopeKey: \"events:evt_123\" });\nawait realtime.broadcast(\"dm\", payload, { userId: recipientId });\n```\n\nWebSocket tickets are Quickback-minted (signed with `BETTER_AUTH_SECRET`), not Better Auth tokens — Better Auth remains the front-door auth check; Quickback signs the upgrade ticket after authorization succeeds.\n\n---\n\n## v0.16.8 — May 13, 2026\n\n### One auth transport per request\n\nGenerated middleware treats `Cookie`, `Authorization: Bearer`, and `x-api-key` as distinct auth methods and rejects mixed requests with `400 AUTH_METHOD_CONFLICT`. Query-string API keys (`?api_key=` / `?key=`) are no longer accepted. Machine-to-machine auth is explicit; precedence rules between transports are gone.\n\n### Cookie-backed CSRF gate\n\nGenerated apps now block cross-site `POST` / `PUT` / `PATCH` / `DELETE` requests from cookie-relying callers. The middleware skips explicit `Authorization` clients, requires a trusted `Origin` or `Referer`, and blocks `Sec-Fetch-Site: cross-site`. This matters most for cross-subdomain session setups where `SameSite=None` is intentional.\n\n### First-class Wrangler observability\n\n`providers.runtime.config.observability` now supports nested `logs` / `traces` blocks for `headSamplingRate`, `destinations`, `persist`, and `logs.invocationLogs`, emitting matching `[observability]`, `[observability.logs]`, and `[observability.traces]` TOML.\n\n---\n\n## v0.16.7 — May 12, 2026\n\n### Bearer wins over cookie\n\nA request carrying both `Authorization` and a session `Cookie` resolves entirely from the bearer; the cookie is dropped before `getSession()` runs. All three Bearer flavors (API key, JWT, session-token) now behave consistently — no more silent cookie precedence on session-token bearers.\n\n### Bearer plugin defaults to `requireSignature: true`\n\nBetter Auth's `bearer` plugin defaults to unsigned tokens; Quickback now emits `bearer({ requireSignature: true })`. Tokens emitted in the CORS-exposed `set-auth-token` header are server-signed with `BETTER_AUTH_SECRET` and verified on every request. Projects that genuinely need unsigned bearers can override via `providers.auth.config.plugins.bearer`.\n\nSee [Authentication Security → Bearer Tokens and Cookie Precedence](/stack/auth/security#bearer-tokens-and-cookie-precedence).\n\n---\n\n## v0.16.5 — May 12, 2026\n\n### Flat write DSL\n\nResource write operations are now declared at the table level alongside `read`, replacing the nested `crud` block:\n\n```ts\ndefineTable(customers, {\n read: { ... },\n create: { access: { roles: [\"admin\"] } },\n update: { access: { roles: [\"admin\"] } },\n delete: { access: { roles: [\"admin\"] }, mode: \"soft\" },\n upsert: { access: { roles: [\"admin\"] } },\n guards: { ... },\n});\n```\n\n`crud` and top-level `put` still compile as deprecated compatibility aliases. Mixed usage on the same resource is rejected. `schema-registry.json` emits both shapes during the transition.\n\n### CMS placement for multi-table feature actions\n\nStandalone actions on multi-table features have an explicit placement model:\n\n- `cms.placement: \"feature\"` shows the action on every table toolbar in the feature\n- `cms.placement: \"tables\"` with `cms.tables` scopes it to specific tables\n- `cms.hidden: true` keeps it API-only\n\nFeature-root standalone actions are emitted under a new `featureActions` bucket in `schema-registry.json`. Ambiguous multi-table standalone actions without placement compile with a warning.\n\n### `openapi.types` accepts a string array\n\nOne compile can write the generated types file to multiple locations, keeping colocated SPA clients in sync:\n\n```ts\nopenapi: { types: ['api-types.gen.ts', 'apps/web/src/lib/api-types.gen.ts'] }\n```\n\n### Stable artifact ordering\n\nGenerated route files and `schema-registry.json` are emitted in a stable order across runs. Identical logical input produces identical artifacts.\n\n---\n\n## v0.16.4 — May 12, 2026\n\n### Drizzle snapshot integrity\n\nDrizzle metadata files (`<n>_snapshot.json`) are no longer stamped with a Quickback warning key. The warning is now journal-only. Projects whose snapshots were corrupted by an earlier release self-heal on the next compile — the stripped header is removed during staging and the rewritten snapshot is clean.\n\n### `account.auth.*` drives the server, not just the SPA\n\nThe Account UI's auth flags (`signup`, `password`, `passkey`, `emailOTP`, `emailVerification`) now configure the Better Auth server alongside the SPA bundle. A normalizer maps them into the server config:\n\n- `signup → emailAndPassword.disableSignUp` (inverted)\n- `password → emailAndPassword.enabled`\n- `emailVerification → emailAndPassword.requireEmailVerification`\n- `passkey` / `emailOTP` → plugin additions\n\nThe SPA's `VITE_ENABLE_*` flags are derived from the same canonicalized server config, so the bundle and the server cannot drift. Two new flags ride along: `VITE_ENABLE_API_KEYS` and `VITE_ENABLE_MAGIC_LINK`.\n\n**Breaking** for projects that implicitly relied on the SPA-only behaviour: `account.auth.signup: false` now actually disables `POST /auth/v1/sign-up/email` on the server. Set `providers.auth.config.emailAndPassword.disableSignUp: false` explicitly to keep server signup open while hiding the SPA screen.\n\n---\n\n## v0.16.3 — May 9, 2026\n\n### Standalone action mount order\n\nFeature-level standalone action routers now register before sibling CRUD routers when both mount at the exact same prefix. A literal path like `GET /api/v1/records/today-bundle` resolves to the standalone handler instead of falling through to `GET /:id` and treating `\"today-bundle\"` as a record ID.\n\n---\n\n## v0.16.1 — May 9, 2026\n\n### Cloudflare ASSETS canonicalization\n\nWorker SPA fallbacks now request `/<dir>/` instead of `/<dir>/index.html`. Cloudflare's static-assets binding rewrites `/index.html` requests as 307 redirects to the trailing-slash path under the default `html_handling=auto-trailing-slash`, which previously caused redirect loops in SPA fallback handlers. Affects CMS, Account, admin, and the multi-domain catchall.\n\n### `account.customLogin`\n\nSet `account: { customLogin: true }` to drop a project-branded sign-in page in front of the bundled SPA. Place the page at `quickback/public/account/login/index.html` (as a directory) and the existing public passthrough serves it. The route registers before the `/account/*` SPA catch-all so the static handler wins; everything else under `/account/` continues to route through the bundled SPA.\n\n### Project-level realtime defaults\n\n`providers.database.config.realtime: true` now treats every resource as realtime-enabled by default. Per-resource `realtime: { enabled: false }` still wins.\n\n### Compile-time validators\n\nTwo new compile-time errors over silent runtime failures:\n\n- `AUTHENTICATED` + org-scoped firewall is rejected. The combination silently returned empty lists to sign-in-only callers who lacked an active org; the validator names three valid resolutions (drop the org scope, use `USER`, or split the route).\n- `createRealtime` imports without `realtime: true` enabled in the config are rejected at compile.\n\n### Drizzle metadata hardening\n\nDrizzle journal files carry a \"do not edit\" header. The compiler warns when the journal entry count exceeds the snapshot file count (typically the trace of a hand-deleted snapshot).\n\n### Minor\n\n- `SYSADMIN` is now recognised by the standalone-action org gate's pseudo-role matcher.\n- Apex `/` and `/account/login` get fallback redirects to `auth.loginUrl` when neither bundled SPA is enabled.\n- Record-based action URLs are kebab-case to match the OpenAPI spec (e.g. `/api/v1/widgets/:id/send-invite`).\n\n---\n\n## v0.16.0 — May 9, 2026\n\n### Agent Auth Protocol\n\nQuickback ships a server implementation of the [Agent Auth Protocol](https://agentauthprotocol.com) via `@better-auth/agent-auth`. Enable with `auth.plugins.agentAuth: true` and the compiler emits the full agent-auth surface: discovery at `/.well-known/agent-configuration`, capability projection from the project's OpenAPI spec, a device-authorization approval page in the Account SPA at `/agents/approve`, and the four agent-auth tables added to the auth schema automatically.\n\n**OpenAPI capability projection runs by default.** Every operation with an `operationId` becomes an agent capability. Default `approvalStrength` map: `GET → \"session\"`, `POST/PUT/PATCH/DELETE → \"webauthn\"`. The proxy `onExecute` makes a self-fetch with a Better Auth JWT minted for the agent session, so the inner request hits the existing JWT fast-path and runs the full firewall + access + masking pipeline. Opt out of OpenAPI projection with `agentAuth: { fromOpenAPI: false }` and wire `capabilities` + `onExecute` by hand.\n\n### Bearer-only on `/mcp` and the agent-auth surface\n\n`/mcp` forwards only `Authorization: Bearer …` into the inner request. Cookie and `x-api-key` forwarding are removed. Three Bearer flavors land on the same header — Better Auth session token (via the `bearer` plugin), OAuth access token (via OAuth Provider), and agent JWT (via `@better-auth/agent-auth`).\n\n### Auth DSL gains first-class plugin entries\n\n`bearer`, `oauthProvider`, and `agentAuth` are now typed entries in both the array-form union and the `BetterAuthPlugins` interface, with their own options shapes (`OAuthProviderOptions`, `AgentAuthOptions`). Existing `as any` casts can come out.\n\nAuto-enable rule: turning on `agentAuth` force-adds `bearer` + `oauthProvider`. No useful agent-auth deployment ships without those two.\n\n### `queue-consumer.ts` gating\n\nThe queue consumer is emitted when any of the following are true: embeddings are configured, queue handlers exist under `services/queues/*`, or `additionalQueues` is declared. Previously the third case left projects with a wrangler binding pointing at a missing handler.\n\n---\n\n## v0.15.0 — May 7, 2026\n\n### Sysadmin tier for the CMS\n\nA new opt-in `cms: { sysadmin: true }` flag turns the CMS into a cross-tenant DB-admin tool gated by `user.role === 'sysadmin'`. Distinct from the Better Auth `'admin'` plugin role, so user-management powers and DB-admin powers stay decoupled. Off by default.\n\nWhen enabled, the compiler emits a `SYSADMIN` pseudo-role (a fifth marker alongside `PUBLIC` / `AUTHENTICATED` / `USER` / `ADMIN`), a firewall escape hatch that drops tenant scopes for sysadmins while preserving soft-delete, a true cross-tenant `/admin/v1/sysadmin/organizations` endpoint, and a relaxed cross-tenant guard for list routes.\n\nThe CMS SPA gains a two-mode design: org admins keep the existing membership-based switcher, sysadmins get an \"All organizations\" selector that pins tenants via `?organizationId=` on every API call.\n\n### Durable Object `[[migrations]]` order is preserved\n\nCloudflare's migration list is append-only. The compiler now reads your existing `wrangler.toml` (when present) and emits auto-generated DO `[[migrations]]` blocks in two phases: deployed entries first (preserving order), net-new entries appended last. Reordering DOs in the config array no longer reshuffles deployed migrations.\n\n### `quickback/public/` — static-asset passthrough\n\nAnything dropped under `quickback/public/` is copied verbatim into `src/apps/` on every compile and served by the wrangler `[assets]` binding. Use for favicons, `robots.txt`, OG images, `.well-known/` files, marketing PDFs — anything that needs to ride past the compiler as bytes.\n\n- Optional. Missing folder is a no-op.\n- Stale-cleaned. Files removed from `quickback/public/` disappear on the next compile.\n- Hidden entries (`.DS_Store`, dotfiles) are skipped.\n- Collisions with compiler-emitted manifest paths fail the compile loudly.\n\n### Minor\n\n- Standalone-action wrapper skips the org gate when the access tree references any pseudo-role.\n- Queue handler emit no longer drops the `queue` export when there are no embeddings.\n\n---\n\n## v0.14.7 — May 7, 2026\n\n### Codegen fixes for projects with non-`id` primary keys and DO-only features\n\nFour surgical fixes to the generated output:\n\n- Duplicate table imports in relationship-role routes are deduplicated.\n- `db` references in single-record and bulk action handlers now resolve correctly during pre-fetch.\n- PartyServer auth gates pass the in-scope `db` handle into firewall calls.\n- Durable-object-only features keep their `lib/` files in the output.\n\n### `emailOtp` + AWS SES is OTP-only\n\n`auth.emailOtp` with the AWS SES email provider no longer auto-wires the magic-link companion. Mail-client URL prefetching can burn the one-time code before the human sees it; the Account SPA's `/email-otp` route is the single canonical entry point. Projects that explicitly want the magic-link arm can wire `sendVerificationOTP` directly.\n\n---\n\n## v0.14.6 — May 7, 2026\n\n### MCP transport correctness\n\nFour fixes to the MCP-over-HTTP path:\n\n- `tools/call` URLs are no longer double-prefixed for action tools.\n- Auth middleware accepts API keys via `Authorization: Bearer` in addition to `x-api-key` and query parameters — the channel MCP clients use exclusively.\n- `auth.roleHierarchy` is expanded for runtime role checks across api-key, JWT, and session auth paths. A higher role inherits the privileges of every lower role.\n- Team-scoped firewall predicates degrade gracefully when no team is active (org scoping continues to apply; team scoping is optional).\n\n---\n\n## v0.14.5 — May 7, 2026\n\n### MCP environment threading\n\nThe generated MCP server's `tools/call` dispatch threads `env` and `executionCtx` into the inner request, so action tools that touch Cloudflare bindings (D1, KV, R2, Queues) no longer crash with `undefined` env access.\n\n---\n\n## v0.14.4 — May 7, 2026\n\n### `via:` firewall predicates pull required imports\n\nThe relationship-role generator emits `inArray` and `sql` imports when the firewall has any `via:` predicate, and `buildFirewallConditions` accepts `(ctx, db)` so the relationship subquery has a Drizzle client to evaluate against. Every CRUD and action call site passes `db` through automatically.\n\n---\n\n## v0.14.3 — May 7, 2026\n\n### Relationship-role table re-exports\n\nGenerated `<table>.resource.ts` files now re-export their Drizzle table binding. Cross-feature relationship subqueries that import the binding from the resource file (rather than the schema) resolve correctly.\n\n---\n\n## v0.14.2 — May 7, 2026\n\n### Historical DO `[[migrations]]` are preserved\n\nA new `bindings.durableObjectMigrations` config slot carries forward `deleted_classes`, `renamed_classes`, and `transferred_classes` lifecycle entries across recompiles. Cloudflare's migration list is append-only; entries declared here are emitted first in `wrangler.toml`, then auto-generated current-class entries follow:\n\n```ts\nbindings: {\n durableObjects: [{ name: 'NOTEPAD', className: 'Notepad', from: 'lib/Notepad' }],\n durableObjectMigrations: [\n { tag: 'qb-do-deleted-legacy-notes-2026-05-05', deletedClasses: ['LegacyNotes'] },\n ],\n}\n```\n\nAll four lifecycle shapes are supported. User-declared entries can override auto-emit by reusing the same tag.\n\n---\n\n## v0.14.1 — May 7, 2026\n\n### Bulk action variants in `openapi.json`\n\nRecord-based actions with `bulkVariant: true` are now emitted as sibling operations in the OpenAPI spec, with the documented `{ ids, input, failFast? }` request shape, 200/207/400 responses, and a separate `<Resource><Action>Bulk` `operationId` so typed-client codegen distinguishes single from bulk.\n\n### Cross-tenant \"my events\" patterns\n\nThe access docs now include a worked example for the cross-tenant aggregation pattern (e.g. `GET /my-events` returning resources across all tenants a caller is invited to). See [Access → Cross-tenant dashboards](/compiler/definitions/access#cross-tenant-my-events-dashboards-are-not-this).\n\n---\n\n## v0.14.0 — May 7, 2026\n\n### Relationship-based authorization\n\nRoles can now be bound to a domain-table membership (\"user is a confirmed guest of this event\") rather than an org membership or a pseudo-role. Declare the relationship once and reference it from `firewall:` or `access.roles:`:\n\n```ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n },\n },\n roles: {\n guest: { via: 'guestOf' },\n eventStaff: { or: [{ via: 'guestOf' }, { roles: ['admin', 'owner'] }] },\n },\n}\n\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' },\n],\nread: { access: { roles: ['admin', 'member', 'guest'] } },\ncreate: { access: { roles: ['admin', 'guest'] } },\nupdate: { access: { roles: ['admin'] } },\n```\n\nThe compiler emits an inline Drizzle subquery against the relationship table and AND-composes it as the outermost firewall clause. The relationship table's own firewall (tenant scope, soft-delete) is honored inside the subquery; cross-tenant grants are impossible because the resource's tenant filter sits outermost.\n\nSupported surfaces: row-level scoping via `firewall: [{ field, via }]`, role gates on writes and reads, view access. Masking and action access reject relationship-roles at compile time with pointers to the working pattern (gate the row at the firewall layer, gate the role at the access layer).\n\nCross-tenant aggregation dashboards aren't solved by relationship-roles — the tenant firewall remains the outermost AND. For that pattern, use a user-scoped firewall or function-form access on a dedicated route.\n\nSee [Firewall → Relationship-based scoping](/compiler/definitions/firewall#relationship-based-scoping-via) and [Access → Relationship-based authorization](/compiler/definitions/access#relationship-based-authorization).\n\n### Bulk variants on record-based actions\n\n`defineAction({ bulkVariant: true })` emits `POST /:resource/batch/{action}` alongside the per-record route. The bulk handler loops the same access + transition + execute pipeline over a `{ ids, input, failFast? }` body:\n\n```ts\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n bulkVariant: true,\n transition: { field: \"status\", via: \"nextStatus\", fromTo: { /* ... */ } },\n async execute({ db, record, input, whereTransition }) {\n // exact same body — runs once per id\n },\n});\n```\n\nPer-record outcomes return as 207 Multi-Status. `failFast: true` aborts on the first failure and wraps the loop in `db.transaction()` on tx-supporting providers; D1 fails fast without rollback. Max 100 IDs per request. Rejected on standalone actions and `unsafe` actions.\n\n### Aggregations on read views\n\nRead views can declare pre-computed metrics that surface alongside the row payload:\n\n```ts\nread: {\n views: {\n pipeline: {\n fields: [\"id\", \"jobId\", \"candidateId\", \"status\", \"appliedAt\"],\n aggregations: {\n totalApplications: { fn: \"count\" },\n byStatus: { fn: \"groupBy\", field: \"status\" },\n },\n },\n },\n}\n```\n\nAggregations run over the same firewalled, filtered set as the row query; pagination is intentionally ignored. Supported functions: `sum`, `avg`, `min`, `max`, `count`, `count_distinct`, `groupBy`. See [Views → Aggregations](/compiler/definitions/views#aggregations).\n\n---\n\n## v0.13.5 — May 6, 2026\n\n### Object-form `auth.plugins` config is honored\n\nThe documented `plugins: { oauthProvider: {...} }`, `plugins: { organization: { teams: { enabled: true } } }` shapes now flow through the compiler unchanged. Per-plugin options reach the generated `auth.ts` as written.\n\n### `roles: [\"PUBLIC\"]` allowed on writes and actions\n\n`PUBLIC` is the explicit, uppercase opt-in for unauthenticated access on every access node — reads, writes, views, and actions. The runtime trusts the marker; row-level safety comes from firewall, masking, and the action's own validation. `PUBLIC` actions continue to receive mandatory audit logging.\n\nCommon pattern: pair `roles: [\"PUBLIC\"]` with `firewall: { exception: true }` on the resource so the row predicate doesn't reject every unauthenticated caller.\n\n---\n\n## v0.12.0 — May 5, 2026\n\n### Per-room authorization for PartyServer\n\n`bindings.durableObjects[].access` declares a path-scoped gate that runs the declared resource's firewall and `read.access` pipeline before the WebSocket upgrade:\n\n```ts\ndurableObjects: [\n // Single-resource: roomId IS the chat row id.\n { name: 'Chat', className: 'Chat', from: 'lib/Chat',\n access: { resource: 'chats' } },\n\n // Multi-resource: regex dispatches kind → resource.\n { name: 'Notepad', className: 'Notepad', from: 'lib/Notepad',\n access: {\n roomId: { pattern: '^(day-note|interaction|record):([A-Za-z0-9_-]+)$', kindGroup: 1, idGroup: 2 },\n resources: {\n 'day-note': { resource: 'day-notes' },\n 'interaction': { resource: 'interactions' },\n 'record': { resource: 'records' },\n },\n } },\n\n // Anonymous lobbies / public pads: explicit opt-out.\n { name: 'PublicLobby', className: 'PublicLobby', from: 'lib/PublicLobby',\n access: 'public' },\n]\n```\n\nThe gate 401s unauthenticated callers, 403s when the firewall hides the row, 404s when the row is missing. Resource references are validated against feature names at compile time. See [PartyServer Rooms → Per-room authorization](/stack/realtime/partyserver-rooms#per-room-authorization-via-access-v012).\n\n---\n\n## v0.11.1 — May 5, 2026\n\n### PartyServer auto-mount is secure by default\n\nThe `/realtime/*` auto-mount now wraps `partyserverMiddleware` in an auth check. Unauthenticated upgrades return 401; the four auth mechanisms (session cookie, JWT bearer, `x-api-key` header, query parameter) all unlock connections. Per-room access remains the `Server` class's responsibility in `onConnect`.\n\n---\n\n## v0.11.0 — May 5, 2026\n\n### OAuth Provider (MCP-ready)\n\nQuickback can act as a standards-compliant OAuth 2.1 + OIDC authorization server via [`@better-auth/oauth-provider`](https://better-auth.com/docs/plugins/oauth-provider). Enable with `plugins: [\"oauthProvider\"]`. The compiler auto-includes Better Auth's `jwt` plugin and the Account SPA gains a `/consent` page for the standard authorization-code flow.\n\nThis replaces Better Auth's deprecated `mcp` plugin and gives every MCP client (Cursor, Claude Desktop, claude.ai connectors, custom tooling) RFC 7591 dynamic client registration plus the discovery documents they need to bootstrap. See [Auth Plugins → OAuth Provider](/stack/auth/plugins#oauth-provider-mcp-ready).\n\n### API keys via query parameter\n\nThe auth middleware now accepts API keys as `?api_key=…` or `?key=…` query parameters. The `x-api-key` header takes precedence when both are sent. Prefer the header whenever the client supports it — query parameters land in access logs and `Referer` headers.\n\n### PartyServer rooms + realtime URL split\n\nThe realtime URL space is reorganized so names match what each primitive does:\n\n- **`/realtime/v1/*` → `/broadcast/v1/*`** — the org-wide Broadcaster moves to its semantically accurate prefix.\n- **`/realtime/<binding>/<room-id>`** — new mount for [PartyServer](/stack/realtime/partyserver-rooms) rooms. Per-room Durable Objects with presence and lifecycle hooks. Auto-mounted whenever a project declares any in-worker DO.\n\n**Breaking** — recompile + redeploy required:\n\n- `REALTIME_URL` env var renamed to `BROADCAST_URL`.\n- SPA helpers `getRealtimeWsUrl()` / `getRealtimeTicketUrl()` renamed to `getBroadcastWsUrl()` / `getBroadcastTicketUrl()`.\n- `appConfig.routes.api.realtime` renamed to `appConfig.routes.api.broadcast`.\n\n`partyserver`, `partysocket`, and `hono-party` are pre-installed in the compiler image; collab projects compile without an extra `npm install` step.\n\n---\n\n## v0.10.20 — May 4, 2026\n\n### In-worker Durable Objects\n\n`bindings.durableObjects[].from` flips a DO binding into in-worker mode and emits the export, the `[[migrations]]` block, and the `CloudflareBindings` type all together:\n\n```ts\ndurableObjects: [{\n name: \"ITEM_STREAM\",\n className: \"ItemStream\",\n from: \"features/loops/lib/ItemStream\",\n}]\n```\n\nDO class files live under `quickback/lib/` or `quickback/features/<feature>/lib/` — both copy verbatim into the generated `src/` tree on every compile. `from` and `scriptName` are mutually exclusive; cross-worker DOs (`scriptName` set) skip the re-export and migration block.\n\n`migrationTag` (default `qb-do-${className}`) is stable across regenerations and must never be removed or renamed once deployed. `useSqlite` defaults to `true`. See [Bindings → Durable Objects](/compiler/config/bindings#durableobjects).\n\n---\n\n## v0.10.18 — May 2, 2026\n\n### `experimentalRemote` — share deployed D1 with `wrangler dev`\n\nPer-binding `experimental_remote = true` lets `wrangler dev` read/write deployed D1 for selected bindings:\n\n```ts\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n splitDatabases: true,\n experimentalRemote: { auth: true, features: false },\n }),\n}\n```\n\nUseful for \"share prod auth in dev, keep feature writes sandboxed.\" Off by default.\n\n### Google OAuth + signup ToS\n\nThe Account SPA wires Google OAuth end-to-end when configured under `auth.config.socialProviders.google.enabled`. The signup flow gains a Terms-of-Service checkbox gate (configurable via the Account SPA branding).\n\n### CLI compile auth gate\n\n`quickback compile` now requires authentication for cloud-compiler runs. Device-flow `?redirect=` parameters are standardized across the login + signup pages so a user clicking \"Create one\" no longer loses their return URL.\n\n---\n\n## v0.10.15–v0.10.17 — May 2, 2026\n\n### CSP auto-config\n\nWhen `security.csp` is set, the compiler widens directives additively based on the project's enabled features:\n\n| Trigger | Auto-added | Directive |\n|---|---|---|\n| `cms: true` OR `account: true` | `'unsafe-inline'`, `https://fonts.googleapis.com` | `styleSrc` |\n| `cms: true` OR `account: true` | `https://fonts.gstatic.com` | `fontSrc` |\n| `csp` set (always) | `@trustedOrigins` | `connectSrc` |\n| Bundled SPA enabled | SPA-baked API origin (`config.domain`, `quickback.{baseDomain}`, `cms.domain`, `account.domain`) | `connectSrc` |\n\nAnything you already wrote stays — auto-config never removes or overrides. Each applied addition is logged to stderr. Opt out with `security: { cspAutoConfig: false }`.\n\nMost projects can write the minimal:\n\n```ts\nsecurity: {\n csp: {\n defaultSrc: ['@self'],\n scriptSrc: ['@self'],\n objectSrc: ['@none'],\n upgradeInsecureRequests: true,\n },\n}\n```\n\n…and the compiler fills in font hosts, trusted origins, and SPA-baked URLs.\n\nWhen a target directive is missing, auto-config scaffolds it from `default-src` baseline rather than widening `default-src` itself — CSP3 fall-back semantics would otherwise leak the addition to every directive that falls back to `default-src`.\n\n---\n\n## v0.10.14 — May 1, 2026\n\n### `auth.jwt` config\n\nThe bearer-token JWT used by the auth fast-path is configurable. Tune `expiresIn` to bound the post-revocation replay window without affecting browser SPAs (which auto-refresh on every authed call):\n\n```ts\nauth: {\n jwt: {\n expiresIn: 30,\n issuer: 'my-api',\n audience: 'partner-svc',\n secretEnv: 'CUSTOM_JWT_SECRET',\n },\n}\n```\n\n### Admin MCP endpoints filtered\n\nBetter Auth admin endpoints (`/admin/list-users`, `/admin/ban-user`, etc.) now carry `x-access: { userRole: ['admin'] }` in the generated OpenAPI spec. The MCP `tools/list` access-filter drops them for non-admin callers.\n\n### Declarative `security` config\n\nEvery security response header (`Content-Security-Policy`, COOP, COEP, CORP, HSTS, `X-Frame-Options`, `Referrer-Policy`, `Permissions-Policy`) is configurable from `quickback.config.ts`. `@`-prefixed sentinels (`@self`, `@none`, `@unsafe-inline`, `@trustedOrigins`, etc.) replace awkward `\"'self'\"` quoting.\n\nThe compiler lints the resolved config for known footguns: `@unsafe-inline` in `script-src`, wildcard sources, missing `default-src`, HSTS preload-list misconfiguration.\n\n### HSTS skipped on localhost\n\nGenerated middleware skips `Strict-Transport-Security` when the request hostname is `localhost`, `127.0.0.1`, or `*.localhost`. Without this gate, `wrangler dev` would pin a developer's browser to HTTPS across every project on that machine.\n\n---\n\n## v0.10.13 — May 1, 2026\n\n### Clickjacking defence on every Worker\n\nEvery Worker emits `Content-Security-Policy: frame-ancestors 'self' <TRUSTED_ORIGINS…>` and `X-Frame-Options: SAMEORIGIN` on every response. The CSP allowlist is sourced from the same `TRUSTED_ORIGINS` constant that gates CORS.\n\n---\n\n## v0.10.11 — May 1, 2026\n\n### MCP `tools/list` is access-filtered\n\nEach MCP tool now carries sanitised access metadata. `tools/list` filters against the caller's `ctx`: unauthenticated callers see only `PUBLIC` tools, authenticated callers see only role-gated tools they pass.\n\n- Wildcard CORS removed from the MCP endpoint.\n- Unauthenticated `GET /mcp` no longer enumerates tool names.\n- Internal flavor text is removed; `annotations.destructiveHint` and `_unsafe` remain — those are the spec-correct signals for clients.\n\n`tools/call` continues to re-enter the Hono app and run every middleware (auth, firewall, access, guards, masking), so hiding a tool from list never weakens the underlying gate.\n\n---\n\n## v0.10.10 — April 29, 2026\n\n### Reserved keys in `access.record` are rejected\n\n`access.record` is a flat field map evaluated as implicit AND between entries — keys must be column names. The compiler now rejects reserved keys (`and`, `or`, `roles`, `userRole`) inside `record` with migration guidance pointing at the working pattern (top-level siblings with their own `record:` blocks).\n\n---\n\n## v0.10.8 — April 29, 2026\n\n### Audit logging on Postgres targets\n\n`audit_events` previously only existed on `cloudflare-d1`. The audit table now lives in a dedicated `audit` schema (`drizzle.pgSchema('audit')`) on Postgres targets. The `hasSecurityAudit` gate accepts D1 or any PG dialect; `auditDatabaseId` remains a D1-only requirement.\n\n### `auditDatabaseId` is a compile-time requirement\n\nProjects with unsafe or `PUBLIC` actions that previously produced a placeholder `database_id = \"local-audit\"` in production now fail at compile time with the exact `wrangler d1 create <project>-audit` command and the config key where the returned ID goes.\n\n### Action input → OpenAPI / MCP\n\n`defineAction({ input: z.object({...}) })` schemas flow into the OpenAPI `requestBody` and the MCP tool's `inputSchema.properties`. Simple `z.object` shapes are extracted at compile time; discriminated unions, refinements, recursive schemas, and bare-identifier references run through Zod's native `z.toJSONSchema()` for full-fidelity output.\n\n### OpenAPI fidelity\n\n- Response schemas emit `required[]` for every non-nullable column.\n- `text(_, { enum: [...] })` columns emit as closed `{ type: \"string\", enum: [...] }`.\n- `id` claims `format: \"uuid\"` only when the project's `generateId` actually produces UUIDs. cuid2 / prefixed / nanoid / serial generators emit plain `{ type: \"string\" }`.\n\n### Minor\n\n- Auto-mask predicate verifies the resolved owner column exists before emitting an `or: 'owner'` clause; falls back to roles-only with a warning otherwise.\n- Generated CRUD errors emit canonical `QuickbackErrorCode` enum values (`DB_NOT_NULL_VIOLATION`, `DB_UNIQUE_VIOLATION`, etc.) so generated SDKs can exhaustively switch on `code`. See [API errors](/compiler/targets/hono-api/using-the-api/errors#database).\n\n---\n\n## DSL: one file per action, multi-table per feature\n\n### One file per action\n\nAction authoring is one file per action under `<feature>/actions/<name>.ts`. The filename is the action name and the URL segment:\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: { applied: [\"screening\"], screening: [\"interview\"], interview: [\"offer\"] },\n },\n async execute({ db, record, input, auditFields, whereTransition }) { /* … */ },\n});\n```\n\n`defineAction` is imported from a generated per-feature helper at `<feature>/.quickback/define-action.ts` — `record`, `input`, and audit fields are typed without manual annotations.\n\n**Discovery rules:**\n- `actions/<name>.ts` binds to the feature's primary table.\n- `actions/<table>/<name>.ts` binds to the sibling table file.\n- Setting `path:` makes the action standalone (custom URL, no record fetch).\n- Tableless features require every action to be standalone.\n\n**Retired** (rejected at load time with migration guidance): `actions.ts` (bundled multi-action file), `_feature.ts`, `handlers/` directory + `handler:` string ref, `defineActions(table, {…})`, colocated `defineActions` inside table files, `standalone: true` flag, `*-actions.ts` / `*.actions.ts` filename patterns.\n\nSee [Actions docs](/compiler/definitions/actions).\n\n### Multi-table actions per feature\n\nOne feature directory can own actions on multiple tables. Three discovery modes:\n\n- **Colocated** (canonical) — `<table>.ts` containing both `defineTable` and `defineActions(<table>, …)`. One file per entity.\n- **`actions.ts`** — single primary-table actions file at feature root.\n- **`actions/<table>.ts`** — per-table action files for strict schema/behavior separation.\n\nPlus a universal `_feature.ts` slot for non-table-bound feature-level actions and shared Zod schemas.\n\nAction names are unique per `(bindTable, name)` pair. Sibling-bound `actions/episodes/publish.ts` and `actions/shows/publish.ts` mount at `/episodes/:id/publish` and `/shows/:id/publish` and compile cleanly.\n\n---\n\n## Firewall: named-scope shape\n\nThe named-scope firewall shape is a co-equal user-facing input alongside the predicate array:\n\n```typescript\nfirewall: { organization: { column: 'tenant_id' } } // named-scope (compact)\nfirewall: { owner: { column: 'account_user_id' } }\nfirewall: { exception: true }\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n] // predicate array (explicit)\n```\n\nPick the form that reads better — named-scope for the common one-line case, predicate array when you need custom `in`-lists or non-scope predicates.\n\n**Auto-detection synonyms.** When `firewall:` is omitted, the compiler scans the schema for an isolation column. The org-scope list accepts `organizationId`, `organisationId`, `orgId`, `organization`, `organisation`, `org` (American + British). User-scope accepts `userId`.\n\n**`ownerId` is a targeted error signal.** When a table carries `ownerId` but no isolation column and no explicit `firewall:`, the compiler raises a specific error — `ownerId` is business-logic ownership, not access control. Use `userId` for access control, declare an explicit `firewall:`, or add a separate isolation column.\n\n---\n\n## v0.10.0 — April 26, 2026\n\n### `q.scope()` — single-declaration tenant scoping\n\n`q.scope(kind)` replaces the three-place pattern (column declaration + firewall predicate + ownership-guard) with one column:\n\n```typescript\ncolumns: {\n organizationId: q.scope('organization'), // → ctx.activeOrgId\n ownerId: q.scope('owner'), // → ctx.userId\n teamId: q.scope('team'), // → ctx.activeTeamId\n}\n```\n\n`q.scope()` columns auto-derive the firewall predicate, register with the guards layer as `systemManaged` (client input rejected), and auto-populate from `ctx` on create / upsert. The systemManaged extension generalises beyond `q.scope()`: any firewall predicate whose `equals` references `ctx.*` registers its `field` automatically.\n\nSee [`q.scope()`](/compiler/definitions/schema#qscope--tenant-scope-columns).\n\n### `masking[col].query.roles` — unified filter / sort / search gate\n\nThe three legacy per-capability flags (`filterable`, `searchable`, `sortable`) are replaced by a single `query.roles` allowlist:\n\n```typescript\nmasking: {\n email: {\n type: 'email',\n show: { roles: ['admin'] },\n query: { roles: ['admin'] }, // defaults to show.roles when omitted\n },\n}\n```\n\nA view's own `query.{filterable,searchable,sortable}` allowlist is the opt-in for higher-privileged roles; the existing intersection validator gates it at compile time.\n\n**Breaking:** `masking[col].filterable / .searchable / .sortable` is rejected at compile time with a migration hint. Replace with `query.roles` (or delete the flags — `query` defaults to `show.roles`).\n\n---\n\n## v0.9.0 — April 25, 2026\n\n### Unified `read:` pipeline\n\nThe read side of every resource has its own block — `read:` — that owns the collection-level `GET /` endpoint, single-record `GET /:id`, and named view projections.\n\n**Breaking changes** (compile-time errors with migration hints):\n\n- `crud.list` → `read.access` (plus `read.pageSize` / `read.maxPageSize`)\n- `crud.get` → `read.access` (single-record GET inherits automatically)\n- Top-level `views: {...}` → `read.views: {...}`\n- `crud.list.fields` / `crud.get.fields` → declare a named view under `read.views` and call `/views/{name}`\n\n### Pre-record access ordering\n\nHandlers on `/:id` run a role-only access check before the firewall query. A caller without a matching role gets 403 before the database is touched. This closes the 404-vs-403 ID-probe channel — an unauthorized caller can no longer distinguish \"row exists in another tenant\" from \"row doesn't exist.\" See [Access evaluation order](/compiler/definitions/access#evaluation-order).\n\n### Transactional batch operations\n\nBatch endpoints expose `failFast` and a `meta.transactional` response field. On tx-supporting providers (postgres, supabase, neon, libsql, better-sqlite3, bun-sqlite), `failFast: true` wraps the per-record loop in `db.transaction(...)` so any failure rolls back the entire batch. On Cloudflare D1 (no `db.transaction`), `failFast: true` stops on the first error but prior writes stay committed.\n\nEmbedding queue messages and realtime broadcasts emit after the transaction commits — rolled-back batches produce no orphan jobs.\n\nSee [Batch Operations → Transactional semantics](/compiler/targets/hono-api/using-the-api/batch-operations#transactional-semantics).\n\n---\n\n## v0.8.7 — April 17, 2026\n\n### Hono CVE bump\n\nHono is bumped to `^4.12.14` across the monorepo, the compiler Docker image's pre-installed deps, and every generator path that emits Hono into compiled projects. Older ranges covered the vulnerable window. Recompile to pick up the fix in your generated project's `package.json`.\n\n### Cloudflare Email Sending in public beta\n\nQuickback defaults to the Workers `send_email` binding for Cloudflare deploys. Cloudflare Email Sending has graduated to public beta — production-ready with zero-config. AWS SES remains a fully supported opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes. See [Email Configuration](/compiler/config#email-configuration).\n\n### Dependency sweep\n\n`wrangler@^4.83.0`, `drizzle-orm@^0.45.2`, `drizzle-kit@^0.31.10`, `zod@^4.3.6`, `@cloudflare/workers-types@^4.20260417.1`.\n\n---\n\n## v0.8.5 — April 15, 2026\n\n### `userRole` access primitive\n\nA new `userRole?: string[]` field in the declarative `Access` config evaluates against `ctx.userRole` (the Better Auth admin-plugin `user.role` column). Distinct from `roles`, which matches `ctx.roles` (org membership).\n\n```typescript\n// Org owner OR platform admin\naccess: { or: [{ roles: ['owner'] }, { userRole: ['admin'] }] }\n\n// Platform admins see SSNs across every org\nmasking: { ssn: { type: 'ssn', show: { userRole: ['admin'] } } }\n```\n\n`userRole` works everywhere `Access` is accepted — CRUD, actions, views, masking, and inside `or` / `and` combinators. See [Access → userRole vs roles](/compiler/definitions/access#userrole-vs-roles).\n\n### CMS admin gate enforced server-side\n\n`cms: { access: \"admin\" }` previously only hid the CMS link in Account UI and rendered an \"Access Denied\" screen inside the SPA. Server-side enforcement now applies at every CMS-facing surface: the SPA shell, `/api/v1/schema`, and `custom_view` CRUD.\n\n### Better Auth 1.5 + `@cloudflare/workers-types` compatibility\n\nGenerated API code typechecks against the new versions. The org-member role-change broadcast hook is emitted via `organizationHooks.afterUpdateMemberRole` (the supported shape after the 1.5 deprecation of `databaseHooks.member.update.after`). `REALTIME_URL` and `ACCESS_TOKEN` are always emitted as optional bindings when the organization plugin is active.\n\n---\n\n## v0.8.4 — April 14, 2026\n\n### `generateId: \"short\"` strategy\n\nA compact ID option for tables where short, shareable codes matter more than collision resistance at scale:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", { generateId: \"short\" }),\n}\n```\n\nGenerates 6-character alphanumeric IDs (e.g. `a3F9xK`) using nanoid's `customAlphabet` with the full 62-char alphabet (`0-9A-Za-z`). Requires the `nanoid` package.\n\n**When to use:** room codes, invite links, share URLs, ephemeral records.\n\n**When not to use:** high-volume tables. 62^6 ≈ 56.8B combinations means ~238K rows before a 50% collision probability. For large tables stick with `\"uuid\"`, `\"cuid\"`, or `\"prefixed\"`. See [Providers → ID Generation Options](/compiler/config/providers#id-generation-options).\n\n---\n\n## v0.8.2 — April 11, 2026\n\n### Catch-all `VITE_QUICKBACK_URL`\n\nA single Quickback origin can be set in place of four separate URL env vars:\n\n```bash\nVITE_QUICKBACK_URL=https://secure.example.com\n```\n\n| Individual var (explicit) | Fallback when unset |\n|---|---|\n| `VITE_QUICKBACK_API_URL` | `${VITE_QUICKBACK_URL}` |\n| `VITE_QUICKBACK_ACCOUNT_URL` | `${VITE_QUICKBACK_URL}/account` |\n| `VITE_QUICKBACK_CMS_URL` | `${VITE_QUICKBACK_URL}/cms` |\n\n`VITE_QUICKBACK_APP_URL` stays independent — it points at the tenant's own frontend. Non-breaking; individual vars take precedence when set. Library users can set `__QUICKBACK_URL__` on `globalThis`. See [Environment Variables](/stack/account-ui/environment-variables).\n\n---\n\n## v0.8.1 — April 9, 2026\n\n### Role hierarchy with `+` suffix\n\nDefine a hierarchy and use `+` to mean \"this role and above\":\n\n```typescript\nauth: { roleHierarchy: ['member', 'admin', 'owner'] }\n\ncrud: {\n list: { access: { roles: [\"member+\"] } }, // member, admin, owner\n create: { access: { roles: [\"admin+\"] } }, // admin, owner\n delete: { access: { roles: [\"owner\"] } }, // owner only\n}\n```\n\nRoles are expanded at compile time. No `+` = exact match. See [Access → Role Hierarchy](/compiler/definitions/access#role-hierarchy).\n\n---\n\n## v0.8.0 — April 9, 2026\n\n### Breaking: VITE URL environment variables namespaced\n\nAll Quickback-generated URL environment variables are namespaced under `VITE_QUICKBACK_*` to avoid collisions with other Vite projects.\n\n| Old | New |\n|-----|-----|\n| `VITE_API_URL` | `VITE_QUICKBACK_API_URL` |\n| `VITE_ACCOUNT_URL` | `VITE_QUICKBACK_ACCOUNT_URL` |\n| `VITE_APP_URL` | `VITE_QUICKBACK_APP_URL` |\n| `VITE_CMS_URL` | `VITE_QUICKBACK_CMS_URL` |\n\nNon-URL variables are unchanged (`VITE_ENABLE_*`, branding vars, `VITE_STRIPE_PUBLISHABLE_KEY`).\n\n**Action required:**\n- Compiled projects: re-run `quickback compile`.\n- Standalone deploys: update `.env`, `.env.production`, and `wrangler.toml` files manually.\n- Library users: `__QUICKBACK_API_URL__` / `__QUICKBACK_APP_URL__` globals are unchanged.\n\n### CMS access control\n\n`cms.access: \"admin\"` enforces access at the CMS level, not just link visibility. Non-admin users (`user.role !== \"admin\"`) see an \"Access Denied\" screen with a sign-out button.\n\n---\n\n## v0.5.11 — February 24, 2026\n\n### Mandatory unsafe action audit trail\n\nStructured `unsafe` config (`unsafe: { reason, adminOnly, crossTenant, targetScope }`). Cross-tenant unsafe actions require Better Auth authentication plus platform admin role (`ctx.userRole === \"admin\"`). Mandatory audit logging on success, denial, and error paths. Cloudflare output includes `AUDIT_DB` wiring, `drizzle.audit.config.ts`, and `db:migrate:audit:*` scripts when unsafe actions are present.\n\nCompile-time raw SQL guard for actions and handlers (`allowRawSql: true` required per action).\n\n### Security contract report artifacts\n\nGenerated security contract artifacts: `reports/security-contracts.report.json`, `reports/security-contracts.report.sig.json`. Config-driven signing controls (`compiler.securityContracts.report.signature.*`). Missing required signing keys fail loudly with explicit remediation.\n\n### Headless Drizzle rename hints\n\n`compiler.migrations.renames` configuration for CI/CD environments where Drizzle's interactive rename prompts block compilation. See [Configuration](/compiler/config).\n\n### Minor\n\n- Email OTP magic links work correctly.\n- Auth is required for all API routes when running locally.\n- Single-file multi-table exports alongside `defineTable()` produce a clear error.\n\n---\n\n## v0.5.8 — February 14, 2026\n\n### Quickback CMS\n\nA schema-driven admin panel that connects to your generated API. The compiler now outputs a JSON schema registry consumed by the CMS at runtime. Firewall error modes (`reveal` for 403 with details, `hide` for opaque 404) are configurable per resource for security-sensitive deployments.\n\n---\n\n## v0.5.7 — February 12, 2026\n\n### Scoped database for actions\n\nActions receive a security-scoped database instead of a raw Drizzle instance. The compiler generates a proxy wrapper that automatically enforces org isolation, owner filtering, and soft-delete visibility — the same protections that CRUD routes have always had.\n\nDuck-typed column detection at runtime:\n\n| Column Detected | SELECT / UPDATE / DELETE | INSERT |\n|---|---|---|\n| `organizationId` | Adds `WHERE organizationId = ?` | Auto-injects `organizationId` from context |\n| `ownerId` | Adds `WHERE ownerId = ?` | Auto-injects `ownerId` from context |\n| `deletedAt` | Adds `WHERE deletedAt IS NULL` | — |\n\nEvery action is secure by default — no manual `WHERE` clauses needed.\n\nActions that intentionally need to bypass security (admin reports, cross-org queries, migrations) can declare `unsafe: true` to receive a raw, unscoped database handle via `rawDb`:\n\n```typescript\ndefineActions(analytics, {\n globalReport: {\n unsafe: true,\n execute: async ({ db, rawDb, ctx, input }) => {\n // db → still scoped (safety net)\n // rawDb → bypasses all security filters\n const allOrgs = await rawDb.select().from(organizations);\n },\n },\n});\n```\n\nWithout `unsafe: true`, `rawDb` is `undefined`. See [Actions](/compiler/definitions/actions).\n\n### Cascading soft delete\n\nSoft-deleting a parent record automatically cascades to child and junction tables within the same feature. The compiler detects foreign key references at build time and generates cascade `UPDATE` statements.\n\nRules:\n- Applies to soft delete only. Hard delete relies on database-level `ON DELETE CASCADE`.\n- Cascades within the same feature only — cross-feature references are not affected.\n- Child tables must have `deletedAt` / `deletedBy` columns (auto-added by the compiler).\n\nSee [Actions API → Cascading Soft Delete](/compiler/targets/hono-api/using-the-api/actions-api#cascading-soft-delete).\n\n### Advanced query parameters\n\nNew capabilities for all list endpoints:\n\n- **Field selection** — `?fields=id,name,status`\n- **Multi-sort** — `?sort=status:asc,createdAt:desc`\n- **Total count** — `?count=true` returns total matching records in `X-Total-Count`\n- **Full-text search** — `?search=keyword` searches across all text columns\n\nSee [Query Parameters](/compiler/targets/hono-api/using-the-api/query-params).\n\n---\n\n## v0.5.5 — February 5, 2026\n\n### OpenAPI spec generation\n\nGenerated APIs include a full OpenAPI specification at `/openapi.json`. Better Auth endpoints are included in the spec.\n\n### Better Auth plugins\n\nPublished `@quickback-dev/better-auth-upgrade-anonymous` (post-passkey email collection flow), `@quickback-dev/better-auth-combo-auth` (combined email + password + OTP), and `@quickback-dev/better-auth-aws-ses` (AWS SES email provider).\n\n### Security headers\n\nGlobal error handler prevents leaking internal error details. Security headers middleware (CSP, HSTS, X-Frame-Options, X-Content-Type-Options). `BETTER_AUTH_SECRET` properly passed to generated config.\n\n---\n\n## v0.5.4 — January 30, 2026\n\n### Account UI\n\nPre-built authentication UI deployed as Cloudflare Workers. Sessions, organizations, passkeys, passwordless, admin panel, API keys. Dual-mode: standalone (degit template) or embedded with Quickback projects.\n\n### Webhook system\n\nInbound webhook endpoints with signature verification. Outbound webhooks via Cloudflare Queues with automatic retries. Configurable per-feature webhook events.\n\n### Realtime & vector search\n\nDurable Objects + WebSocket realtime subscriptions. Vector embeddings via Cloudflare Vectorize. KV and R2 storage integrations.\n\n---\n\n## v0.5.0 — January 2026\n\n### Initial release\n\n- **Quickback Compiler** — TypeScript-first backend compiler.\n- **Four security pillars** — Firewall, Access, Guards, Masking.\n- **`defineTable()`** — schema + security configuration in a single file.\n- **Templates** — Cloudflare Workers, B2B SaaS.\n- **Cloud compiler** — remote compilation via `compiler.quickback.dev`.\n- **CLI** — `quickback create`, `quickback compile`.\n- **Better Auth integration** — organizations, roles, sessions.\n- **Drizzle ORM** — schema-first with automatic migrations.\n- **Cloudflare D1** — split database support (auth + features)."
|
|
7
7
|
},
|
|
8
8
|
"compiler/claude-code-skill": {
|
|
9
9
|
"title": "AI Developer Tools",
|
|
@@ -51,7 +51,7 @@ export const DOCS = {
|
|
|
51
51
|
},
|
|
52
52
|
"compiler/config": {
|
|
53
53
|
"title": "Configuration",
|
|
54
|
-
"content": "The `quickback.config.ts` file configures your Quickback project. It defines which providers to use, which features to enable, and how the compiler generates code.\n\n```typescript\n\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## Discoverable options block\n\nAfter your first `quickback compile`, the file gets a managed block bracketed by sentinel comments:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: cloudflare({}),\n\n // [quickback:options-start]\n // ── Project ──\n //\n // Primary custom domain (auto-inferred from cms/account/api domains if unset).\n // domain: \"example.com\",\n //\n // ── Embedded UIs (CMS / Account) ──\n //\n // Login/signup/profile/orgs SPA. Set `true` for default, or object to customize.\n // account: {\n // fileUploads: false, // show the avatar upload UI on the profile page\n // auth: { passkey: false, emailOTP: false, ... },\n // ...\n // },\n //\n // ... every other option Quickback supports\n // [quickback:options-end]\n});\n```\n\nThis block is **regenerated on every compile** — the compiler is the source of truth, so newly added options surface automatically when you upgrade Quickback (no CLI bump needed).\n\n**To enable an option**, copy the line you care about *above* the `[quickback:options-start]` sentinel and uncomment it:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: cloudflare({}),\n\n account: {\n fileUploads: true, // ← lifted out of the managed block\n },\n\n // [quickback:options-start]\n // ... account is now omitted from this block on next compile\n // [quickback:options-end]\n});\n```\n\nQuickback notices that `account` is set above the marker and drops it from the managed block on the next compile to avoid duplicate definitions. Anything outside the marker block is yours and never touched.\n\nIf you ever want to opt out of the auto-managed block, run:\n\n```bash\nquickback compile --no-sync-config\n```\n\n## Required Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `name` | `string` | Project name |\n| `template` | `\"hono\"` | Application template (`\"nextjs\"` is experimental) |\n| `providers` | `object` | Runtime, database, and auth provider configuration |\n\n## Optional Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `features` | `object` | Feature flags such as `pinnedOrganizationId` — see [Pinned Organization Mode](/compiler/config/single-tenant) |\n| `build` | `object` | Build options (`outputDir`, `packageManager`, `dependencies`) |\n| `compiler` | `object` | Compiler options — `features.auditFields: false` disables audit field injection project-wide; `migrations.renames` provides rename hints for headless CI; `securityContracts` tunes the route/SQL invariants checker |\n| `openapi` | `object` | OpenAPI spec generation (`generate`, `publish`, `docs: 'scalar' \\| 'swagger'` for an in-browser API reference) — see [OpenAPI](/compiler/targets/hono-api/using-the-api/openapi) |\n| `schemaRegistry` | `object` | Schema registry generation for the CMS (enabled by default, `{ generate: false }` to disable) — see [Schema Registry](/stack/cms/schema-registry) |\n| `etag` | `object` | ETag caching for GET responses (enabled by default, `{ enabled: false }` to disable) — see [Caching & ETags](/compiler/targets/hono-api/using-the-api/caching) |\n| `cms` | `boolean \\| object` | Embed CMS in compiled Worker — see [CMS](/stack/cms) |\n| `account` | `boolean \\| object` | Embed Account UI in compiled Worker — see [Account UI](/stack/account-ui) |\n| `trustedOrigins` | `string[]` | CORS trusted origins for cross-domain auth |\n| `domain` | `string` | Primary API domain (auto-inferred from custom domains if not set) |\n| `dev` | `object` | Local development settings (`port`) |\n| `auth` | `object` | App-level auth settings (`roleHierarchy`) — see [Access](/compiler/definitions/access#role-hierarchy) |\n| `email` | `object` | Email delivery config (`provider`, `from`, `fromName`) |\n\n## Custom Dependencies\n\nAdd third-party npm packages to the generated `package.json` using `build.dependencies`. This is useful when your action handlers import external libraries.\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n build: {\n dependencies: {\n \"fast-xml-parser\": \"^4.5.0\",\n \"lodash-es\": \"^4.17.21\",\n },\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\nThese are merged into the generated `package.json` alongside Quickback's own dependencies. Run `npm install` after compiling to install them.\n\n## Headless Migration Rename Hints\n\nWhen `drizzle-kit generate` detects a potential rename, it normally prompts for confirmation. Cloud/CI compiles are non-interactive, so you must provide explicit rename hints.\n\nAdd hints in `compiler.migrations.renames`:\n\n```typescript\nexport default defineConfig({\n // ...\n compiler: {\n migrations: {\n renames: {\n // Keys are NEW names, values are OLD names\n tables: {\n events_v2: \"events\",\n },\n columns: {\n events: {\n summary_text: \"summary\",\n },\n },\n },\n },\n },\n});\n```\n\nRules:\n- `tables`: `new_table_name -> old_table_name`\n- `columns.<table>`: `new_column_name -> old_column_name`\n- Keys must match the names in your current schema (the new names)\n- Validation fails fast for malformed rename config, unsupported keys, or conflicting legacy/new rename paths.\n\n## Disable Audit Field Injection\n\nBy default, Quickback auto-injects four **audit fields** (`createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`) into every feature table, plus two **soft-delete fields** (`deletedAt`, `deletedBy`) into tables that use soft delete (the default delete mode). The audit fields drive record-provenance queries and the CMS audit panel; the soft-delete pair drives soft-delete filtering.\n\nTo opt out project-wide:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n compiler: {\n features: {\n auditFields: false, // skip audit-field injection globally\n },\n },\n providers: { /* ... */ },\n});\n```\n\nWhen disabled, you're responsible for supplying these columns yourself if you want soft delete, audit trails, or modifiedAt-based optimistic concurrency. See the [Schema → Audit Fields](/compiler/definitions/schema#audit-fields) section for the full list and what each field drives.\n\n## Security Contract Reports and Signing\n\nAfter generation, Quickback verifies machine-checkable security contracts for Hono routes and RLS SQL.\n\nIt also emits a report artifact and signature artifact by default:\n\n- `reports/security-contracts.report.json`\n- `reports/security-contracts.report.sig.json`\n\nYou can configure output paths and signing behavior:\n\n```typescript\nexport default defineConfig({\n // ...\n compiler: {\n securityContracts: {\n failMode: \"error\", // or \"warn\"\n report: {\n path: \"reports/security-contracts.report.json\",\n signature: {\n enabled: true,\n required: true,\n keyEnv: \"QUICKBACK_SECURITY_REPORT_SIGNING_KEY\",\n keyId: \"prod-k1\",\n path: \"reports/security-contracts.report.sig.json\",\n },\n },\n },\n },\n});\n```\n\nIf `signature.required: true` and no key is available, compilation fails with a clear error message (or warning in `failMode: \"warn\"`).\n\n## Hostname architecture (v0.33+)\n\nA modern Quickback project runs on **one Cloudflare Worker** that serves multiple URL surfaces. By default, everything lives under a single unified backend hostname (auto-inferred as `quickback.{baseDomain}` from your other configured subdomains, or overridable via `config.domain`). For larger deployments, you can opt-in to **dedicated hostnames** for specific surfaces — they're additive aliases, never replacements.\n\n### The unified backend contract\n\nWhen any subdomain is configured (`account.domain`, `cms.domain`, `auth.domain`, `api.domain`, `apps.<n>.domain`), the compiler always emits a unified backend host where **every compiler-emitted backend route** is reachable:\n\n- `/api/v1/*` — feature routes\n- `/auth/v1/*` — Better Auth\n- `/storage/*` — R2 file storage\n- `/health`, `/openapi.json` — monitoring/discovery\n- `/account/*`, `/cms/*` — bundled SPAs (when enabled)\n- `/broadcast/v1/*` (realtime), `/mcp` (MCP), etc.\n\nThe unified hostname is `quickback.{baseDomain}` by default (where baseDomain is extracted from your first configured subdomain). Override with `config.domain` if you prefer a different name.\n\nThis contract is forward-pointing: it gives a stable URL pattern for future management tooling — `https://quickback.{baseDomain}/...` will always reach a Quickback backend regardless of how the operator splits their surfaces.\n\n### Dedicated hostnames (optional, additive)\n\nFor branding or operational separation, you can opt specific surfaces onto their own hostnames:\n\n```ts\n{\n // Bundled SPAs on their own hosts (already-shipped pattern):\n cms: { domain: 'cms.example.com' },\n account: { domain: 'account.example.com' },\n\n // v0.33+ — backend surfaces on their own hosts:\n auth: { domain: 'auth.example.com' },\n api: { domain: 'api.example.com' },\n\n // User SPAs (existing pattern):\n apps: {\n www: { domain: 'app.example.com' },\n },\n}\n```\n\nOn a dedicated hostname, **the hostname IS the namespace** — the path drops the prefix that matches the hostname:\n\n| URL on dedicated host | Internally rewritten to | Notes |\n|---|---|---|\n| `https://api.example.com/v1/users` | `/api/v1/users` | Worker-entry rewriter prepends `/api` |\n| `https://auth.example.com/v1/sign-in/email` | `/auth/v1/sign-in/email` | Same shape with `/auth` |\n| `https://api.example.com/api/v1/users` | (unchanged) | Long form also accepted |\n| `https://api.example.com/auth/v1/sign-in` | **404** | Auth doesn't live on the API hostname |\n| `https://api.example.com/health` | (unchanged) | Explicit exception — monitoring agents expect `/health` everywhere |\n\nDual-reach is preserved on the unified host:\n\n| URL on unified host | Handler | Notes |\n|---|---|---|\n| `https://quickback.example.com/api/v1/users` | feature route | Works whether `api.domain` is set or not |\n| `https://quickback.example.com/auth/v1/sign-in/email` | Better Auth | Works whether `auth.domain` is set or not |\n| `https://quickback.example.com/v1/users` | **404** | Shortcut only applies on dedicated hostnames |\n\nEach dedicated hostname also:\n\n- Gets a `{ pattern, custom_domain: true }` route in `wrangler.toml` automatically\n- Joins `trustedOrigins` for CORS\n- Joins the cross-subdomain cookie inference (auto-enables `crossSubDomainCookies` when ≥2 same-parent subdomains are configured, so `auth.example.com` and `app.example.com` can share session cookies)\n- Joins CSP `connect-src` so SPAs can fetch from it\n\n### Why two URL shapes (Shape 1 vs Shape 2)\n\nIf you only want Better Auth to **advertise** itself on a different URL (e.g. so verification emails link to `auth.example.com` instead of the unified host), set the `BETTER_AUTH_URL` env var on the Worker — no code change required. BA generates outgoing URLs against that value. This is sufficient when the goal is branding email/OAuth callback URLs without changing where requests actually land.\n\n`auth.domain` (Shape 1, above) is the heavier option: it binds an actual hostname to the Worker, configures CORS/cookies/CSP for it, and adds the path-shortcut rewriter. Use it when you want the dedicated hostname as a real ingress, not just a label.\n\n## CMS Configuration\n\nEmbed the [Quickback CMS](/stack/cms) in your compiled Worker. The CMS reads your schema registry and renders a complete admin interface — zero UI code per table.\n\n```typescript\n// Simple — embed CMS at root\ncms: true,\n\n// With custom domain\ncms: { domain: \"cms.example.com\" },\n\n// With access control (only admins can access CMS)\ncms: { domain: \"cms.example.com\", access: \"admin\" },\n\n// Cross-tenant DB-admin tier — sysadmins see every tenant's data\ncms: { domain: \"cms.example.com\", sysadmin: true },\n```\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `domain` | `string` | — | Custom domain for CMS. Adds a `custom_domain` route to `wrangler.toml`. |\n| `access` | `\"user\" \\| \"admin\"` | `\"admin\"` | Controls who can access the CMS. When `\"admin\"`, platform control-plane users (`user.role === \"appmanager\"`) can enter; when `sysadmin` mode is also on, `user.role === \"sysadmin\"` is admitted too. The gate is enforced at the Worker level (SPA shell, `/api/v1/schema`, and `custom_view` CRUD all return 403 to callers outside those roles) and in the SPA. Also hides the CMS link in Account UI. See [CMS Connecting](/stack/cms/connecting) for the full enforcement model. |\n| `sysadmin` | `boolean` | `false` | Cross-tenant DB-admin tier. When `true`, opts into the `SYSADMIN` pseudo-role (`user.role === \"sysadmin\"`), the firewall escape hatch (sysadmins bypass tenant scopes, soft-delete still enforced), the cross-tenant `/auth/v1/admin/list-organizations` endpoint (sibling of Better Auth's `/auth/v1/admin/list-users`, gated to sysadmin only), and the SPA's \"All organizations\" sentinel. The CMS HTML gate admits `userRole === \"sysadmin\"` alongside `\"appmanager\"`. Off by default. See [`SYSADMIN` pseudo-role](/compiler/definitions/access#sysadmin--cross-tenant-db-admin-tier). |\n\n### Sysadmin tier (`cms.sysadmin: true`)\n\nQuickback's default model assumes every CMS user belongs to at least one organization (`member` row in the auth DB). For platforms that need a Supabase-style cross-tenant DB-admin tool — debugging a tenant's data, running cross-tenant queries, supporting a customer — that's a poor fit: a sysadmin without `member` rows would dead-end, and auto-filling their active org from \"first membership\" silently scopes them to a tenant they have no relationship with.\n\n`cms: { sysadmin: true }` introduces a separate role tier:\n\n- **Role**: `user.role === \"sysadmin\"` (set on the Better Auth user table). Distinct from `\"appmanager\"` — appmanagers keep platform control-plane access (CMS shell, Better Auth admin surfaces, support tooling), while sysadmins get true cross-tenant data access. `ADMIN` is now a rejected legacy pseudo-role; use `userRole: [\"appmanager\"]` for control-plane gates and `roles: [\"SYSADMIN\"]` for cross-tenant access.\n- **Firewall**: every `buildFirewallConditions()` emits an `if (ctx.userRole === \"sysadmin\") return undefined` (or just the soft-delete predicate when present) at the top, so sysadmins see every tenant's rows. See [Firewall escape hatch](/compiler/definitions/firewall#sysadmin-escape-hatch).\n- **Org listing**: a `GET /auth/v1/admin/list-organizations` endpoint selects directly from the auth-schema `organization` table — every row, every tenant. Sits under Better Auth's admin URL namespace (sibling of `/auth/v1/admin/list-users`) so the URL shape matches BA convention; the handler is Quickback-emitted and gated to `user.role === \"sysadmin\"` only. For the membership-bound caller's-orgs listing, use BA's own `/auth/v1/organization/list`.\n- **CMS SPA**: when the user is a sysadmin, the header switcher loads from the cross-tenant endpoint, defaults to \"All organizations\" (which omits `?organizationId=` and reaches the firewall escape), and pins selected tenants via `?organizationId=` on every API call. Org admins keep the existing membership-based switcher.\n- **CMS HTML gate**: admits `userRole === \"sysadmin\"` alongside `\"appmanager\"`. Org admins are not locked out when you set `cms.access: \"user\"`; `cms.access: \"admin\"` is specifically the platform control-plane gate.\n\nOff by default. Projects that don't enable it get zero behavior change; setting `cms.sysadmin: true` and granting a user `user.role = \"sysadmin\"` is the only way to unlock the cross-tenant view.\n\n## Account UI Configuration\n\nEmbed the [Account UI](/stack/account-ui) in your compiled Worker. Provides login, signup, profile management, organization management, and admin — all built from your config at compile time.\n\nFor post-signup logic — auto-provisioning a workspace, gating signup, setting an active organization — drop a file in `quickback/hooks/`. See [Auth Hooks](/stack/account-ui/hooks).\n\n```typescript\n// Simple — embed Account UI with defaults\naccount: true,\n\n// Full configuration\naccount: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n companyName: \"My Company\",\n auth: {\n password: true,\n emailOTP: false,\n passkey: true,\n organizations: true,\n admin: true,\n },\n},\n```\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `domain` | `string` | Custom domain for Account UI (e.g., `auth.example.com`) |\n| `adminDomain` | `string` | Custom domain for admin-only access (e.g., `admin.example.com`). Serves the same Account SPA — the client-side router handles admin routing. |\n| `appUrl` | `string` | URL of the tenant's main application — where users are redirected after login. Baked into the Account SPA as `VITE_QUICKBACK_APP_URL`. Independent from `domain`. |\n| `name` | `string` | App display name shown on login, profile, and email templates |\n| `companyName` | `string` | Company name for branding |\n| `tagline` | `string` | App tagline shown on login page |\n| `description` | `string` | App description |\n\n### Auth Feature Flags\n\nControl which authentication features are exposed. Disabled features are excluded from the Account UI bundle at compile time (routes removed before the Vite build, keeping bundle sizes minimal) **and** enforced on the server side via the Better Auth config — so \"signup off\" actually closes `POST /auth/v1/sign-up/email`, not just the SPA's signup screen.\n\n`account.auth.*` is a shorthand for `providers.auth.config` — the compiler maps each flag onto the Better Auth server config before any code is generated. You can write either side directly; setting both incompatibly (e.g. `account.auth.signup: false` and `emailAndPassword.disableSignUp: false`) fails the compile with a precise error rather than picking a silent winner.\n\n| Flag | Type | Default | Maps to (server) | Description |\n|------|------|---------|------------------|-------------|\n| `auth.password` | `boolean` | `true` | `emailAndPassword.enabled` | Email/password authentication — both server endpoint and UI |\n| `auth.emailOTP` | `boolean` | `false` | adds `emailOtp` plugin | Email one-time password login — adds plugin server-side, surfaces UI |\n| `auth.passkey` | `boolean` | `false` | adds `passkey` plugin | WebAuthn/FIDO2 passkey authentication — adds plugin server-side, surfaces UI |\n| `auth.signup` | `boolean` | `true` | `emailAndPassword.disableSignUp` (inverted) | Self-service account registration — false hides the UI **and** rejects the server endpoint with 403 |\n| `auth.organizations` | `boolean` | `true` | UI surface only | Organization management UI (dashboard, invitations, roles). Server-side organization support stays on regardless; set `features.pinnedOrganizationId` when you want one fixed org with no switching UI |\n| `auth.admin` | `boolean` | `false` | UI surface only | Admin panel for user management in the Account SPA. The Better Auth admin plugin is compiler-managed separately from this UI toggle |\n| `auth.emailVerification` | `boolean` | `false` | `emailAndPassword.requireEmailVerification` | Require email verification before sessions are issued. False = sessions usable immediately after signup |\n\n## Trusted Origins\n\nList of origins allowed to make cross-origin requests to your API. Required when your CMS, Account UI, or frontend app run on different domains.\n\n```typescript\ntrustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n \"https://cms.example.com\",\n \"https://app.example.com\",\n],\n```\n\n## Local Development\n\nConfigure local development URLs. These are automatically added to the trusted origins list for CORS and Better Auth, so authentication works out of the box during local development.\n\n```typescript\ndev: {\n port: 8787, // wrangler dev port (default: 8787)\n api: \"http://localhost:8787\", // API backend URL\n cms: \"http://localhost:8787/cms\", // CMS URL (path on same worker)\n account: \"http://localhost:8787/account\", // Account URL (path on same worker)\n},\n```\n\nIf you run a SPA standalone on its own Vite dev server, set its URL here so CORS allows it:\n\n```typescript\ndev: {\n port: 8787,\n api: \"http://localhost:8787\",\n account: \"http://localhost:5173\", // standalone Account dev server\n},\n```\n\n| Field | Type | Default | Description |\n|-------|------|---------|-------------|\n| `port` | `number` | `8787` | Local dev server port (sets `[dev].port` in wrangler.toml) |\n| `api` | `string` | `http://localhost:{port}` | API backend URL |\n| `cms` | `string` | — | CMS dev URL (added to trusted origins if set) |\n| `account` | `string` | — | Account dev URL (added to trusted origins if set) |\n\n## Email Configuration\n\nConfigure email delivery for authentication emails (verification, password reset, invitations).\n\n> **Cloudflare Email Sending is now in public beta** and is Quickback's default transport for Cloudflare deploys. The Workers `send_email` binding is zero-config — no API keys, no third-party accounts. AWS SES remains supported as an explicit opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes or existing SES setups.\n\n```typescript\n// Cloudflare Email Service (default) — uses send_email binding, no API keys needed\nemail: {\n from: \"noreply@example.com\",\n fromName: \"My App\",\n},\n\n// AWS SES — requires AWS credentials set as Wrangler secrets\nemail: {\n provider: \"aws-ses\",\n region: \"us-east-2\",\n from: \"noreply@example.com\",\n fromName: \"My App\",\n},\n```\n\n| Field | Type | Default | Description |\n|-------|------|---------|-------------|\n| `provider` | `\"cloudflare\" \\| \"aws-ses\"` | `\"cloudflare\"` | Email transport |\n| `from` | `string` | `\"noreply@example.com\"` | Sender email address |\n| `fromName` | `string` | `\"{name} \\| Account Services\"` | Sender display name |\n| `region` | `string` | `\"us-east-2\"` | AWS SES region (aws-ses only) |\n\n### Auto-wiring\n\nFor the Cloudflare provider (the default), the compiler automatically:\n- Emits `[[send_email]] EMAIL` into `wrangler.toml`\n- Generates `src/lib/cloudflare-email.ts`\n- Wires `sendResetPassword`, `sendVerificationEmail`, `sendInvitationEmail`, etc. into Better Auth\n\n…whenever any auth surface needs to send mail — `emailAndPassword.enabled`, the `emailOtp` / `magicLink` / `organization` plugins — or you set the top-level `email: {…}` config. You don't need to add `bindings.sendEmail` by hand for the standard cases.\n\n> **Cloudflare Email Routing setup is required.** The binding alone does not deliver mail. Enable Email Routing on the sending zone and add at least one verified destination address ([Cloudflare docs](https://developers.cloudflare.com/email-routing/get-started/)). Otherwise sends fail at runtime even with the binding present and the `/auth/v1/ses/status` check passing locally.\n\n## Multi-Domain Example\n\nA complete config with CMS, Account UI, and Admin on separate subdomains:\n\n```typescript\nexport default {\n name: \"my-app\",\n template: \"hono\",\n cms: { domain: \"cms.example.com\", access: \"admin\" },\n account: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n companyName: \"Example Inc.\",\n auth: {\n password: true,\n emailOTP: false,\n passkey: true,\n organizations: false,\n admin: true,\n },\n },\n email: {\n from: \"noreply@example.com\",\n fromName: \"My App\",\n },\n trustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n \"https://cms.example.com\",\n \"https://example.com\",\n ],\n providers: {\n runtime: { name: \"cloudflare\", config: {\n routes: [{ pattern: \"api.example.com\", custom_domain: true }],\n }},\n database: { name: \"cloudflare-d1\", config: { binding: \"DB\" } },\n auth: { name: \"better-auth\", config: { plugins: [\"admin\"] } },\n },\n};\n```\n\nThis produces a single Cloudflare Worker serving five domains. See [Multi-Domain Architecture](/compiler/config/domains) for details on hostname routing, cross-subdomain cookies, and the unified fallback domain.\n\n---\n\nSee the sub-pages for detailed reference on each section:\n- [Providers](/compiler/config/providers) — Runtime, database, and auth options\n- [Variables](/compiler/config/variables) — Environment variables and flags\n- [Output](/compiler/config/output) — Generated file structure\n- [Pinned Organization Mode](/compiler/config/single-tenant) — Fixed-org deployments without org switching UI\n- [Multi-Domain Architecture](/compiler/config/domains) — Custom domains, hostname routing, and cross-subdomain auth"
|
|
54
|
+
"content": "The `quickback.config.ts` file configures your Quickback project. It defines which providers to use, which features to enable, and how the compiler generates code.\n\n```typescript\n\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## Discoverable options block\n\nAfter your first `quickback compile`, the file gets a managed block bracketed by sentinel comments:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: cloudflare({}),\n\n // [quickback:options-start]\n // ── Project ──\n //\n // Primary custom domain (auto-inferred from cms/account/api domains if unset).\n // domain: \"example.com\",\n //\n // ── Embedded UIs (CMS / Account) ──\n //\n // Login/signup/profile/orgs SPA. Set `true` for default, or object to customize.\n // account: {\n // fileUploads: false, // show the avatar upload UI on the profile page\n // auth: { passkey: false, emailOTP: false, ... },\n // ...\n // },\n //\n // ... every other option Quickback supports\n // [quickback:options-end]\n});\n```\n\nThis block is **regenerated on every compile** — the compiler is the source of truth, so newly added options surface automatically when you upgrade Quickback (no CLI bump needed).\n\n**To enable an option**, copy the line you care about *above* the `[quickback:options-start]` sentinel and uncomment it:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: cloudflare({}),\n\n account: {\n fileUploads: true, // ← lifted out of the managed block\n },\n\n // [quickback:options-start]\n // ... account is now omitted from this block on next compile\n // [quickback:options-end]\n});\n```\n\nQuickback notices that `account` is set above the marker and drops it from the managed block on the next compile to avoid duplicate definitions. Anything outside the marker block is yours and never touched.\n\nIf you ever want to opt out of the auto-managed block, run:\n\n```bash\nquickback compile --no-sync-config\n```\n\n## Required Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `name` | `string` | Project name |\n| `template` | `\"hono\"` | Application template (`\"nextjs\"` is experimental) |\n| `providers` | `object` | Runtime, database, and auth provider configuration |\n\n## Optional Fields\n\nEvery optional top-level key the config accepts is listed below. You never have to memorize them — after your first compile, the [discoverable options block](#discoverable-options-block) lists each one (minus the ones you've set) right inside your `quickback.config.ts`. This table is the human reference; follow the links for detailed pages.\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `domain` | `string` | Primary custom domain (auto-inferred from `cms`/`account`/`api` domains if unset) — see [Domains](/compiler/config/domains) |\n| `api` | `object` | Dedicated hostname for the feature API surface (`/api/v1/*`); additive alias — see [Domains](/compiler/config/domains) |\n| `auth` | `object` | App-level auth settings (`roleHierarchy`, `jwt`, `loginUrl`/`profileUrl`, `domain`) — see [Access](/compiler/definitions/access#role-hierarchy) |\n| `authz` | `object` | Relationship-based authorization (`relationships`, `roles`, `permissions`, `arrows`) — see [Permissions](/compiler/definitions/permissions) |\n| `trustedOrigins` | `string[]` | CORS trusted origins for cross-domain auth |\n| `features` | `object` | Feature flags such as `organizations` / `pinnedOrganizationId` — see [Pinned Organization Mode](/compiler/config/single-tenant) |\n| `cms` | `boolean \\| object` | Embed CMS in compiled Worker (`domain`, `access`, `sysadmin`) — see [CMS](/stack/cms) |\n| `account` | `boolean \\| object` | Embed Account UI in compiled Worker (`domain`, `name`, `auth.*`, branding) — see [Account UI](/stack/account-ui) |\n| `apps` | `object` | Mount hand-authored SPAs on their own hostname or path prefix — see [Domains](/compiler/config/domains) |\n| `agents` | `boolean \\| object` | AI/agent discovery surface (`robots.txt`, `llms.txt`, MCP, OAuth discovery) — see [Agents](/compiler/config/agents) |\n| `security` | `object \\| false` | HTTP response security headers (CSP, HSTS, COOP/COEP, Referrer/Permissions-Policy) — see [Security Headers](/compiler/config/security) |\n| `openapi` | `object` | OpenAPI spec generation (`generate`, `publish`, `docs: 'scalar' \\| 'swagger'`, `types`) — see [OpenAPI](/compiler/targets/hono-api/using-the-api/openapi) |\n| `schemaRegistry` | `object` | Schema registry generation for the CMS (`{ generate: false }` to disable) — see [Schema Registry](/stack/cms/schema-registry) |\n| `etag` | `object` | ETag caching for GET responses (`{ enabled: false }` to disable) — see [Caching & ETags](/compiler/targets/hono-api/using-the-api/caching) |\n| `email` | `object` | Email delivery config (`provider`, `from`, `fromName`, `region`) — see [Email Configuration](#email-configuration) |\n| `bindings` | `object` | Extra Cloudflare bindings (durable objects, queues, R2, services, `vars`, AI) — see [Bindings](/compiler/config/bindings) |\n| `compiler` | `object` | Compiler internals — `features.auditFields: false`, `migrations.renames` (headless CI), `securityContracts`, `injectId`, `routes` |\n| `build` | `object` | Build options (`outputDir`, `packageManager`, `dependencies`) — see [Custom Dependencies](#custom-dependencies) |\n| `dev` | `object` | Local development settings (`port`, `api`, `cms`, `account`, `hostnames`) — see [Variables](/compiler/config/variables) |\n| `preset` | `string` | Inherit defaults from a named preset |\n\n## Custom Dependencies\n\nAdd third-party npm packages to the generated `package.json` using `build.dependencies`. This is useful when your action handlers import external libraries.\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n build: {\n dependencies: {\n \"fast-xml-parser\": \"^4.5.0\",\n \"lodash-es\": \"^4.17.21\",\n },\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\nThese are merged into the generated `package.json` alongside Quickback's own dependencies. Run `npm install` after compiling to install them.\n\n## Headless Migration Rename Hints\n\nWhen `drizzle-kit generate` detects a potential rename, it normally prompts for confirmation. Cloud/CI compiles are non-interactive, so you must provide explicit rename hints.\n\nAdd hints in `compiler.migrations.renames`:\n\n```typescript\nexport default defineConfig({\n // ...\n compiler: {\n migrations: {\n renames: {\n // Keys are NEW names, values are OLD names\n tables: {\n events_v2: \"events\",\n },\n columns: {\n events: {\n summary_text: \"summary\",\n },\n },\n },\n },\n },\n});\n```\n\nRules:\n- `tables`: `new_table_name -> old_table_name`\n- `columns.<table>`: `new_column_name -> old_column_name`\n- Keys must match the names in your current schema (the new names)\n- Validation fails fast for malformed rename config, unsupported keys, or conflicting legacy/new rename paths.\n\n## Disable Audit Field Injection\n\nBy default, Quickback auto-injects four **audit fields** (`createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`) into every feature table, plus two **soft-delete fields** (`deletedAt`, `deletedBy`) into tables that use soft delete (the default delete mode). The audit fields drive record-provenance queries and the CMS audit panel; the soft-delete pair drives soft-delete filtering.\n\nTo opt out project-wide:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n compiler: {\n features: {\n auditFields: false, // skip audit-field injection globally\n },\n },\n providers: { /* ... */ },\n});\n```\n\nWhen disabled, you're responsible for supplying these columns yourself if you want soft delete, audit trails, or modifiedAt-based optimistic concurrency. See the [Schema → Audit Fields](/compiler/definitions/schema#audit-fields) section for the full list and what each field drives.\n\n## Security Contract Reports and Signing\n\nAfter generation, Quickback verifies machine-checkable security contracts for Hono routes and RLS SQL.\n\nIt also emits a report artifact and signature artifact by default:\n\n- `reports/security-contracts.report.json`\n- `reports/security-contracts.report.sig.json`\n\nYou can configure output paths and signing behavior:\n\n```typescript\nexport default defineConfig({\n // ...\n compiler: {\n securityContracts: {\n failMode: \"error\", // or \"warn\"\n report: {\n path: \"reports/security-contracts.report.json\",\n signature: {\n enabled: true,\n required: true,\n keyEnv: \"QUICKBACK_SECURITY_REPORT_SIGNING_KEY\",\n keyId: \"prod-k1\",\n path: \"reports/security-contracts.report.sig.json\",\n },\n },\n },\n },\n});\n```\n\nIf `signature.required: true` and no key is available, compilation fails with a clear error message (or warning in `failMode: \"warn\"`).\n\n## Hostname architecture (v0.33+)\n\nA modern Quickback project runs on **one Cloudflare Worker** that serves multiple URL surfaces. By default, everything lives under a single unified backend hostname (auto-inferred as `quickback.{baseDomain}` from your other configured subdomains, or overridable via `config.domain`). For larger deployments, you can opt-in to **dedicated hostnames** for specific surfaces — they're additive aliases, never replacements.\n\n### The unified backend contract\n\nWhen any subdomain is configured (`account.domain`, `cms.domain`, `auth.domain`, `api.domain`, `apps.<n>.domain`), the compiler always emits a unified backend host where **every compiler-emitted backend route** is reachable:\n\n- `/api/v1/*` — feature routes\n- `/auth/v1/*` — Better Auth\n- `/storage/*` — R2 file storage\n- `/health`, `/openapi.json` — monitoring/discovery\n- `/account/*`, `/cms/*` — bundled SPAs (when enabled)\n- `/broadcast/v1/*` (realtime), `/mcp` (MCP), etc.\n\nThe unified hostname is `quickback.{baseDomain}` by default (where baseDomain is extracted from your first configured subdomain). Override with `config.domain` if you prefer a different name.\n\nThis contract is forward-pointing: it gives a stable URL pattern for future management tooling — `https://quickback.{baseDomain}/...` will always reach a Quickback backend regardless of how the operator splits their surfaces.\n\n### Dedicated hostnames (optional, additive)\n\nFor branding or operational separation, you can opt specific surfaces onto their own hostnames:\n\n```ts\n{\n // Bundled SPAs on their own hosts (already-shipped pattern):\n cms: { domain: 'cms.example.com' },\n account: { domain: 'account.example.com' },\n\n // v0.33+ — backend surfaces on their own hosts:\n auth: { domain: 'auth.example.com' },\n api: { domain: 'api.example.com' },\n\n // User SPAs (existing pattern):\n apps: {\n www: { domain: 'app.example.com' },\n },\n}\n```\n\nOn a dedicated hostname, **the hostname IS the namespace** — the path drops the prefix that matches the hostname:\n\n| URL on dedicated host | Internally rewritten to | Notes |\n|---|---|---|\n| `https://api.example.com/v1/users` | `/api/v1/users` | Worker-entry rewriter prepends `/api` |\n| `https://auth.example.com/v1/sign-in/email` | `/auth/v1/sign-in/email` | Same shape with `/auth` |\n| `https://api.example.com/api/v1/users` | (unchanged) | Long form also accepted |\n| `https://api.example.com/auth/v1/sign-in` | **404** | Auth doesn't live on the API hostname |\n| `https://api.example.com/health` | (unchanged) | Explicit exception — monitoring agents expect `/health` everywhere |\n\nDual-reach is preserved on the unified host:\n\n| URL on unified host | Handler | Notes |\n|---|---|---|\n| `https://quickback.example.com/api/v1/users` | feature route | Works whether `api.domain` is set or not |\n| `https://quickback.example.com/auth/v1/sign-in/email` | Better Auth | Works whether `auth.domain` is set or not |\n| `https://quickback.example.com/v1/users` | **404** | Shortcut only applies on dedicated hostnames |\n\nEach dedicated hostname also:\n\n- Gets a `{ pattern, custom_domain: true }` route in `wrangler.toml` automatically\n- Joins `trustedOrigins` for CORS\n- Joins the cross-subdomain cookie inference (auto-enables `crossSubDomainCookies` when ≥2 same-parent subdomains are configured, so `auth.example.com` and `app.example.com` can share session cookies)\n- Joins CSP `connect-src` so SPAs can fetch from it\n\n### Why two URL shapes (Shape 1 vs Shape 2)\n\nIf you only want Better Auth to **advertise** itself on a different URL (e.g. so verification emails link to `auth.example.com` instead of the unified host), set the `BETTER_AUTH_URL` env var on the Worker — no code change required. BA generates outgoing URLs against that value. This is sufficient when the goal is branding email/OAuth callback URLs without changing where requests actually land.\n\n`auth.domain` (Shape 1, above) is the heavier option: it binds an actual hostname to the Worker, configures CORS/cookies/CSP for it, and adds the path-shortcut rewriter. Use it when you want the dedicated hostname as a real ingress, not just a label.\n\n## CMS Configuration\n\nEmbed the [Quickback CMS](/stack/cms) in your compiled Worker. The CMS reads your schema registry and renders a complete admin interface — zero UI code per table.\n\n```typescript\n// Simple — embed CMS at root\ncms: true,\n\n// With custom domain\ncms: { domain: \"cms.example.com\" },\n\n// With access control (only admins can access CMS)\ncms: { domain: \"cms.example.com\", access: \"admin\" },\n\n// Cross-tenant DB-admin tier — sysadmins see every tenant's data\ncms: { domain: \"cms.example.com\", sysadmin: true },\n```\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `domain` | `string` | — | Custom domain for CMS. Adds a `custom_domain` route to `wrangler.toml`. |\n| `access` | `\"user\" \\| \"admin\"` | `\"admin\"` | Controls who can access the CMS. When `\"admin\"`, platform control-plane users (`user.role === \"appmanager\"`) can enter; when `sysadmin` mode is also on, `user.role === \"sysadmin\"` is admitted too. The gate is enforced at the Worker level (SPA shell, `/api/v1/schema`, and `custom_view` CRUD all return 403 to callers outside those roles) and in the SPA. Also hides the CMS link in Account UI. See [CMS Connecting](/stack/cms/connecting) for the full enforcement model. |\n| `sysadmin` | `boolean` | `false` | Cross-tenant DB-admin tier. When `true`, opts into the `SYSADMIN` pseudo-role (`user.role === \"sysadmin\"`), the firewall escape hatch (sysadmins bypass tenant scopes, soft-delete still enforced), the cross-tenant `/auth/v1/admin/list-organizations` endpoint (sibling of Better Auth's `/auth/v1/admin/list-users`, gated to sysadmin only), and the SPA's \"All organizations\" sentinel. The CMS HTML gate admits `userRole === \"sysadmin\"` alongside `\"appmanager\"`. Off by default. See [`SYSADMIN` pseudo-role](/compiler/definitions/access#sysadmin--cross-tenant-db-admin-tier). |\n\n### Sysadmin tier (`cms.sysadmin: true`)\n\nQuickback's default model assumes every CMS user belongs to at least one organization (`member` row in the auth DB). For platforms that need a Supabase-style cross-tenant DB-admin tool — debugging a tenant's data, running cross-tenant queries, supporting a customer — that's a poor fit: a sysadmin without `member` rows would dead-end, and auto-filling their active org from \"first membership\" silently scopes them to a tenant they have no relationship with.\n\n`cms: { sysadmin: true }` introduces a separate role tier:\n\n- **Role**: `user.role === \"sysadmin\"` (set on the Better Auth user table). Distinct from `\"appmanager\"` — appmanagers keep platform control-plane access (CMS shell, Better Auth admin surfaces, support tooling), while sysadmins get true cross-tenant data access. `ADMIN` is now a rejected legacy pseudo-role; use `userRole: [\"appmanager\"]` for control-plane gates and `roles: [\"SYSADMIN\"]` for cross-tenant access.\n- **Firewall**: every `buildFirewallConditions()` emits an `if (ctx.userRole === \"sysadmin\") return undefined` (or just the soft-delete predicate when present) at the top, so sysadmins see every tenant's rows. See [Firewall escape hatch](/compiler/definitions/firewall#sysadmin-escape-hatch).\n- **Org listing**: a `GET /auth/v1/admin/list-organizations` endpoint selects directly from the auth-schema `organization` table — every row, every tenant. Sits under Better Auth's admin URL namespace (sibling of `/auth/v1/admin/list-users`) so the URL shape matches BA convention; the handler is Quickback-emitted and gated to `user.role === \"sysadmin\"` only. For the membership-bound caller's-orgs listing, use BA's own `/auth/v1/organization/list`.\n- **CMS SPA**: when the user is a sysadmin, the header switcher loads from the cross-tenant endpoint, defaults to \"All organizations\" (which omits `?organizationId=` and reaches the firewall escape), and pins selected tenants via `?organizationId=` on every API call. Org admins keep the existing membership-based switcher.\n- **CMS HTML gate**: admits `userRole === \"sysadmin\"` alongside `\"appmanager\"`. Org admins are not locked out when you set `cms.access: \"user\"`; `cms.access: \"admin\"` is specifically the platform control-plane gate.\n\nOff by default. Projects that don't enable it get zero behavior change; setting `cms.sysadmin: true` and granting a user `user.role = \"sysadmin\"` is the only way to unlock the cross-tenant view.\n\n## Account UI Configuration\n\nEmbed the [Account UI](/stack/account-ui) in your compiled Worker. Provides login, signup, profile management, organization management, and admin — all built from your config at compile time.\n\nFor post-signup logic — auto-provisioning a workspace, gating signup, setting an active organization — drop a file in `quickback/hooks/`. See [Auth Hooks](/stack/account-ui/hooks).\n\n```typescript\n// Simple — embed Account UI with defaults\naccount: true,\n\n// Full configuration\naccount: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n companyName: \"My Company\",\n auth: {\n password: true,\n emailOTP: false,\n passkey: true,\n organizations: true,\n admin: true,\n },\n},\n```\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `domain` | `string` | Custom domain for Account UI (e.g., `auth.example.com`) |\n| `adminDomain` | `string` | Custom domain for admin-only access (e.g., `admin.example.com`). Serves the same Account SPA — the client-side router handles admin routing. |\n| `appUrl` | `string` | URL of the tenant's main application — where users are redirected after login. Baked into the Account SPA as `VITE_QUICKBACK_APP_URL`. Independent from `domain`. |\n| `name` | `string` | App display name shown on login, profile, and email templates |\n| `companyName` | `string` | Company name for branding |\n| `tagline` | `string` | App tagline shown on login page |\n| `description` | `string` | App description |\n\n### Auth Feature Flags\n\nControl which authentication features are exposed. Disabled features are excluded from the Account UI bundle at compile time (routes removed before the Vite build, keeping bundle sizes minimal) **and** enforced on the server side via the Better Auth config — so \"signup off\" actually closes `POST /auth/v1/sign-up/email`, not just the SPA's signup screen.\n\n`account.auth.*` is a shorthand for `providers.auth.config` — the compiler maps each flag onto the Better Auth server config before any code is generated. You can write either side directly; setting both incompatibly (e.g. `account.auth.signup: false` and `emailAndPassword.disableSignUp: false`) fails the compile with a precise error rather than picking a silent winner.\n\n| Flag | Type | Default | Maps to (server) | Description |\n|------|------|---------|------------------|-------------|\n| `auth.password` | `boolean` | `true` | `emailAndPassword.enabled` | Email/password authentication — both server endpoint and UI |\n| `auth.emailOTP` | `boolean` | `false` | adds `emailOtp` plugin | Email one-time password login — adds plugin server-side, surfaces UI |\n| `auth.passkey` | `boolean` | `false` | adds `passkey` plugin | WebAuthn/FIDO2 passkey authentication — adds plugin server-side, surfaces UI |\n| `auth.signup` | `boolean` | `true` | `emailAndPassword.disableSignUp` (inverted) | Self-service account registration — false hides the UI **and** rejects the server endpoint with 403 |\n| `auth.organizations` | `boolean` | `true` | UI surface only | Organization management UI (dashboard, invitations, roles). Server-side organization support stays on regardless; set `features.pinnedOrganizationId` when you want one fixed org with no switching UI |\n| `auth.admin` | `boolean` | `false` | UI surface only | Admin panel for user management in the Account SPA. The Better Auth admin plugin is compiler-managed separately from this UI toggle |\n| `auth.emailVerification` | `boolean` | `false` | `emailAndPassword.requireEmailVerification` | Require email verification before sessions are issued. False = sessions usable immediately after signup |\n\n## Trusted Origins\n\nList of origins allowed to make cross-origin requests to your API. Required when your CMS, Account UI, or frontend app run on different domains.\n\n```typescript\ntrustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n \"https://cms.example.com\",\n \"https://app.example.com\",\n],\n```\n\n## Local Development\n\nConfigure local development URLs. These are automatically added to the trusted origins list for CORS and Better Auth, so authentication works out of the box during local development.\n\n```typescript\ndev: {\n port: 8787, // wrangler dev port (default: 8787)\n api: \"http://localhost:8787\", // API backend URL\n cms: \"http://localhost:8787/cms\", // CMS URL (path on same worker)\n account: \"http://localhost:8787/account\", // Account URL (path on same worker)\n},\n```\n\nIf you run a SPA standalone on its own Vite dev server, set its URL here so CORS allows it:\n\n```typescript\ndev: {\n port: 8787,\n api: \"http://localhost:8787\",\n account: \"http://localhost:5173\", // standalone Account dev server\n},\n```\n\n| Field | Type | Default | Description |\n|-------|------|---------|-------------|\n| `port` | `number` | `8787` | Local dev server port (sets `[dev].port` in wrangler.toml) |\n| `api` | `string` | `http://localhost:{port}` | API backend URL |\n| `cms` | `string` | — | CMS dev URL (added to trusted origins if set) |\n| `account` | `string` | — | Account dev URL (added to trusted origins if set) |\n\n## Email Configuration\n\nConfigure email delivery for authentication emails (verification, password reset, invitations).\n\n> **Cloudflare Email Sending is now in public beta** and is Quickback's default transport for Cloudflare deploys. The Workers `send_email` binding is zero-config — no API keys, no third-party accounts. AWS SES remains supported as an explicit opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes or existing SES setups.\n\n```typescript\n// Cloudflare Email Service (default) — uses send_email binding, no API keys needed\nemail: {\n from: \"noreply@example.com\",\n fromName: \"My App\",\n},\n\n// AWS SES — requires AWS credentials set as Wrangler secrets\nemail: {\n provider: \"aws-ses\",\n region: \"us-east-2\",\n from: \"noreply@example.com\",\n fromName: \"My App\",\n},\n```\n\n| Field | Type | Default | Description |\n|-------|------|---------|-------------|\n| `provider` | `\"cloudflare\" \\| \"aws-ses\"` | `\"cloudflare\"` | Email transport |\n| `from` | `string` | `\"noreply@example.com\"` | Sender email address |\n| `fromName` | `string` | `\"{name} \\| Account Services\"` | Sender display name |\n| `region` | `string` | `\"us-east-2\"` | AWS SES region (aws-ses only) |\n\n### Auto-wiring\n\nFor the Cloudflare provider (the default), the compiler automatically:\n- Emits `[[send_email]] EMAIL` into `wrangler.toml`\n- Generates `src/lib/cloudflare-email.ts`\n- Wires `sendResetPassword`, `sendVerificationEmail`, `sendInvitationEmail`, etc. into Better Auth\n\n…whenever any auth surface needs to send mail — `emailAndPassword.enabled`, the `emailOtp` / `magicLink` / `organization` plugins — or you set the top-level `email: {…}` config. You don't need to add `bindings.sendEmail` by hand for the standard cases.\n\n> **Cloudflare Email Routing setup is required.** The binding alone does not deliver mail. Enable Email Routing on the sending zone and add at least one verified destination address ([Cloudflare docs](https://developers.cloudflare.com/email-routing/get-started/)). Otherwise sends fail at runtime even with the binding present and the `/auth/v1/ses/status` check passing locally.\n\n## Multi-Domain Example\n\nA complete config with CMS, Account UI, and Admin on separate subdomains:\n\n```typescript\nexport default {\n name: \"my-app\",\n template: \"hono\",\n cms: { domain: \"cms.example.com\", access: \"admin\" },\n account: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n companyName: \"Example Inc.\",\n auth: {\n password: true,\n emailOTP: false,\n passkey: true,\n organizations: false,\n admin: true,\n },\n },\n email: {\n from: \"noreply@example.com\",\n fromName: \"My App\",\n },\n trustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n \"https://cms.example.com\",\n \"https://example.com\",\n ],\n providers: {\n runtime: { name: \"cloudflare\", config: {\n routes: [{ pattern: \"api.example.com\", custom_domain: true }],\n }},\n database: { name: \"cloudflare-d1\", config: { binding: \"DB\" } },\n auth: { name: \"better-auth\", config: { plugins: [\"admin\"] } },\n },\n};\n```\n\nThis produces a single Cloudflare Worker serving five domains. See [Multi-Domain Architecture](/compiler/config/domains) for details on hostname routing, cross-subdomain cookies, and the unified fallback domain.\n\n---\n\nSee the sub-pages for detailed reference on each section:\n- [Providers](/compiler/config/providers) — Runtime, database, and auth options\n- [Variables](/compiler/config/variables) — Environment variables and flags\n- [Output](/compiler/config/output) — Generated file structure\n- [Pinned Organization Mode](/compiler/config/single-tenant) — Fixed-org deployments without org switching UI\n- [Multi-Domain Architecture](/compiler/config/domains) — Custom domains, hostname routing, and cross-subdomain auth"
|
|
55
55
|
},
|
|
56
56
|
"compiler/config/output": {
|
|
57
57
|
"title": "Output Structure",
|
|
@@ -115,7 +115,7 @@ export const DOCS = {
|
|
|
115
115
|
},
|
|
116
116
|
"compiler/definitions": {
|
|
117
117
|
"title": "Definitions Overview",
|
|
118
|
-
"content": "Before diving into specific features, let's understand how Quickback's pieces connect. This page gives you the mental model for everything that follows.\n\n## The Big Picture\n\nQuickback is a **backend compiler**. You write definition files, and Quickback compiles them into a production-ready API.\n\n1. **You write definitions** - Table files with schema and security config using `defineTable`\n2. **Quickback compiles them** - Analyzes your definitions at build time\n3. **You get a production API** - `GET /jobs`, `POST /jobs`, `PATCH /jobs/:id`, `DELETE /jobs/:id`, batch operations, plus custom actions\n\n## File Structure\n\nYour definitions live in a `quickback/features/` folder organized by feature:\n\n```\nmy-app/\n├── quickback/\n│ ├── quickback.config.ts # Compiler configuration\n│ └── features/\n│ └── {feature-name}/\n│ ├── candidates.ts # Table + config (defineTable)\n│ ├── applications.ts # Secondary table + config\n│ ├── interview-scores.ts # Internal table (no routes)\n│ ├── actions.ts # Custom actions (optional)\n│ └── handlers/ # Action handlers (optional)\n│ └── advance-stage.ts\n├── src/ # Generated code (output)\n└── package.json\n```\n\n**Table files** use `defineTable` to combine schema and security config:\n\n```typescript\n// features/candidates/candidates.ts\n\nexport const candidates = sqliteTable(\"candidates\", {\n id: text(\"id\").primaryKey(),\n organizationId: text(\"organization_id\").notNull(),\n name: text(\"name\").notNull(),\n email: text(\"email\").notNull(),\n phone: text(\"phone\"),\n source: text(\"source\"),\n});\n\nexport default defineTable(candidates, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"name\", \"email\", \"phone\", \"source\"],\n updatable: [\"name\", \"phone\"],\n },\n masking: {\n email: { type: 'email', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n});\n\nexport type Candidate = typeof candidates.$inferSelect;\n```\n\n**Key points:**\n- Tables with `export default defineTable(...)` → resource routes generated\n- Tables without default export → internal/junction tables (no routes)\n- Route path derived from filename: `applications.ts` → `/api/v1/applications`\n\n## The Four Security Layers\n\nEvery API request passes through four security layers, in order:\n\n```\nRequest → Firewall → Access → Guards → Masking → Response\n │ │ │ │\n │ │ │ └── Hide sensitive fields\n │ │ └── Block field modifications\n │ └── Check roles & conditions\n └── Isolate data by owner/org/team\n```\n\n### 1. Firewall (Data Isolation)\n\nThe firewall controls **which records** a user can see. It automatically adds WHERE clauses to every query based on your schema columns:\n\n| Column in Schema | What happens |\n|------------------|--------------|\n| `organization_id` | Data isolated by organization |\n| `user_id` | Data isolated by user (personal data) |\n\nNo manual configuration needed - Quickback applies smart rules based on your schema.\n\nFor relationship-based row visibility (e.g. \"user can see this event because they have a confirmed `event_guests` row pointing at it\"), declare the relationship under `authz.relationships` and reference it from the firewall with a `via:` predicate. See [Firewall → Relationship-based scoping](/compiler/definitions/firewall#relationship-based-scoping-via).\n\n[Learn more about Firewall →](/compiler/definitions/firewall)\n\n### 2. Access (CRUD Permissions)\n\nAccess controls **which operations** a user can perform. It checks roles and record conditions. Reads (`GET /` and `GET /:id`) live under `read:`; writes live under top-level `create:`, `update:`, `delete:`, and `upsert:`.\n\n```typescript\nread: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n},\ncreate: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\nupdate: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\ndelete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n```\n\n[Learn more about Access →](/compiler/definitions/access)\n\n### 3. Guards (Field Modification Rules)\n\nGuards control **which fields** can be modified in each operation.\n\n| Guard Type | What it means |\n|------------|---------------|\n| `createable` | Fields that can be set when creating |\n| `updatable` | Fields that can be changed when updating |\n| `protected` | Fields that can only be changed via specific actions |\n| `immutable` | Fields that can never be changed after creation |\n\n[Learn more about Guards →](/compiler/definitions/guards)\n\n### 4. Masking (Data Redaction)\n\nMasking hides sensitive fields from users who shouldn't see them.\n\n```typescript\nmasking: {\n email: { type: 'email' }, // Shows: j***@e******.com\n phone: { type: 'phone' }, // Shows: ******4567\n salary: { type: 'redact' }, // Shows: [REDACTED]\n}\n```\n\n[Learn more about Masking →](/compiler/definitions/masking)\n\n## How They Work Together\n\n**Scenario:** An interviewer requests `GET /candidates/cnd_123`\n\n1. **Firewall** checks: Is candidate `cnd_123` in the user's organization?\n - Yes → Continue\n - No → 404 Not Found (as if it doesn't exist)\n\n2. **Access** checks: Can interviewers perform GET?\n - Yes → Continue\n - No → 403 Forbidden\n\n3. **Guards** don't apply to GET (they're for writes)\n\n4. **Masking** applies: User is an `interviewer`, not `recruiter` or `hiring-manager`\n - Email: `jane@company.com` → `j***@c******.com`\n - Phone: `555-123-4567` → `******4567`\n\n5. **Response** sent with masked data\n\n## Locked Down by Default\n\nQuickback is **secure by default**. Nothing is accessible until you explicitly allow it.\n\n| Layer | Default | What you must do |\n|-------|---------|------------------|\n| Firewall | AUTO | Auto-detects from `organization_id`/`user_id` columns. Only configure for exceptions. |\n| Access | DENIED | Explicitly define `access` rules with roles |\n| Guards | LOCKED | Explicitly list `createable`, `updatable` fields |\n| Actions | BLOCKED | Explicitly define `access` for each action |\n\n**You must deliberately open each door.** This prevents accidental data exposure.\n\n## Other Resource Options\n\nBeyond the four security layers, `defineTable` accepts a handful of declarative hints that shape the generated API and the CMS without touching your security posture.\n\n| Option | What it does | Full reference |\n|---|---|---|\n| `views` | Named column projections — `GET /resource/views/{name}` returns a subset of columns under its own access rule. | [Views](/compiler/definitions/views) |\n| `references` | Explicit FK target table for columns that don't follow the \"Id\"-stripped convention (e.g. `vendorId → contact`). | [CMS Schema Registry](/stack/cms/schema-registry) |\n| `displayColumn` | Column to use as the human-readable label in FK resolutions and CMS list views (auto-detected as `name`/`title`/`label` if not set). | [CMS Table Views](/stack/cms/table-views) |\n| `defaultSort` | Default sort order for CMS list rendering (`{ field, order: \"asc\" \\| \"desc\" }`). | [CMS Table Views](/stack/cms/table-views) |\n| `inputHints` | Per-column CMS input type: `select`, `richtext`, `textarea`, `lookup`, `currency`, etc. Pure CMS hint, no runtime effect. | [CMS Record Layouts](/stack/cms/record-layouts) |\n| `layouts` | Named record-page layouts — group fields into sections (collapsed, multi-column). Falls back to auto-grouping if unset. | [CMS Record Layouts](/stack/cms/record-layouts) |\n| `embeddings` | Auto-generate vector embeddings for specified fields on insert/update. | [Stack → Embeddings](/stack/vector/using-embeddings) |\n| `realtime` | Per-table broadcast config (`enabled`, `onInsert`, `onUpdate`, `onDelete`, `requiredRoles`, `fields`). | [Stack → Realtime](/stack/realtime/using-realtime) |\n| `path` | Override the route base path (defaults to feature name). | — |\n\nAll options are optional — omit them and Quickback uses sensible defaults (auto-detected display column, auto-grouped layout, no embeddings, no realtime).\n\n## Next Steps\n\n1. [Database Schema](/compiler/definitions/schema) — Define your tables\n2. [Firewall](/compiler/definitions/firewall) — Set up data isolation\n3. [Access](/compiler/definitions/access) — Configure read and write permissions\n4. [Guards](/compiler/definitions/guards) — Control field modifications\n5. [Masking](/compiler/definitions/masking) — Hide sensitive data\n6. [Views](/compiler/definitions/views) — Column-level security\n7. [Validation](/compiler/definitions/validation) — Field validation rules\n8. [Actions](/compiler/definitions/actions) — Add custom business logic"
|
|
118
|
+
"content": "Before diving into specific features, let's understand how Quickback's pieces connect. This page gives you the mental model for everything that follows.\n\n## The Big Picture\n\nQuickback is a **backend compiler**. You write definition files, and Quickback compiles them into a production-ready API.\n\n1. **You write definitions** - Table files with schema and security config using `defineTable`\n2. **Quickback compiles them** - Analyzes your definitions at build time\n3. **You get a production API** - `GET /jobs`, `POST /jobs`, `PATCH /jobs/:id`, `DELETE /jobs/:id`, batch operations, plus custom actions\n\n## File Structure\n\nYour definitions live in a `quickback/features/` folder organized by feature:\n\n```\nmy-app/\n├── quickback/\n│ ├── quickback.config.ts # Compiler configuration\n│ └── features/\n│ └── {feature-name}/\n│ ├── candidates.ts # Table + config (defineTable)\n│ ├── applications.ts # Secondary table + config\n│ ├── interview-scores.ts # Internal table (no routes)\n│ ├── actions.ts # Custom actions (optional)\n│ └── handlers/ # Action handlers (optional)\n│ └── advance-stage.ts\n├── src/ # Generated code (output)\n└── package.json\n```\n\n**Table files** use `defineTable` to combine schema and security config:\n\n```typescript\n// features/candidates/candidates.ts\n\nexport const candidates = sqliteTable(\"candidates\", {\n id: text(\"id\").primaryKey(),\n organizationId: text(\"organization_id\").notNull(),\n name: text(\"name\").notNull(),\n email: text(\"email\").notNull(),\n phone: text(\"phone\"),\n source: text(\"source\"),\n});\n\nexport default defineTable(candidates, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"name\", \"email\", \"phone\", \"source\"],\n updatable: [\"name\", \"phone\"],\n },\n masking: {\n email: { type: 'email', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n});\n\nexport type Candidate = typeof candidates.$inferSelect;\n```\n\n**Key points:**\n- Tables with `export default defineTable(...)` → resource routes generated\n- Tables without default export → internal/junction tables (no routes)\n- Route path derived from filename: `applications.ts` → `/api/v1/applications`\n\n## The Five Security Layers\n\nEvery API request passes through five security layers, in order:\n\n```\nRequest → Rate Limit → Firewall → Access → Guards → Masking → Response\n │ │ │ │ │\n │ │ │ │ └── Hide sensitive fields\n │ │ │ └── Block field modifications\n │ │ └── Check roles & conditions\n │ └── Isolate data by owner/org/team\n └── Cap requests per user / op\n```\n\n### 1. Firewall (Data Isolation)\n\nThe firewall controls **which records** a user can see. It automatically adds WHERE clauses to every query based on your schema columns:\n\n| Column in Schema | What happens |\n|------------------|--------------|\n| `organization_id` | Data isolated by organization |\n| `user_id` | Data isolated by user (personal data) |\n\nNo manual configuration needed - Quickback applies smart rules based on your schema.\n\nFor relationship-based row visibility (e.g. \"user can see this event because they have a confirmed `event_guests` row pointing at it\"), declare the relationship under `authz.relationships` and reference it from the firewall with a `via:` predicate. See [Firewall → Relationship-based scoping](/compiler/definitions/firewall#relationship-based-scoping-via).\n\n[Learn more about Firewall →](/compiler/definitions/firewall)\n\n### 2. Access (CRUD Permissions)\n\nAccess controls **which operations** a user can perform. It checks roles and record conditions. Reads (`GET /` and `GET /:id`) live under `read:`; writes live under top-level `create:`, `update:`, `delete:`, and `upsert:`.\n\n```typescript\nread: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n},\ncreate: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\nupdate: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\ndelete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n```\n\n[Learn more about Access →](/compiler/definitions/access)\n\n### 3. Guards (Field Modification Rules)\n\nGuards control **which fields** can be modified in each operation.\n\n| Guard Type | What it means |\n|------------|---------------|\n| `createable` | Fields that can be set when creating |\n| `updatable` | Fields that can be changed when updating |\n| `protected` | Fields that can only be changed via specific actions |\n| `immutable` | Fields that can never be changed after creation |\n\n[Learn more about Guards →](/compiler/definitions/guards)\n\n### 4. Masking (Data Redaction)\n\nMasking hides sensitive fields from users who shouldn't see them.\n\n```typescript\nmasking: {\n email: { type: 'email' }, // Shows: j***@e******.com\n phone: { type: 'phone' }, // Shows: ******4567\n salary: { type: 'redact' }, // Shows: [REDACTED]\n}\n```\n\n[Learn more about Masking →](/compiler/definitions/masking)\n\n### 5. Rate Limiting (Request Caps)\n\nRate limiting caps **how often** an operation can be called, backed by Cloudflare's native Rate Limiting binding — no extra storage, no third-party libraries. Unlike the other four layers, it's applied to **every resource by default** (read `1000/60s`, writes `200/60s`) and runs first, before any data is touched.\n\n```typescript\nrateLimit: {\n delete: { limit: 5, period: 60 }, // tighter than the 200/60s default\n},\n// read / create / update keep shipped defaults\n```\n\nOverride per-op, per-resource, or project-wide; set `false` at any scope to opt out. Limits are keyed by `<resource>:<op>:<userId>` (falling back to client IP for anonymous callers), and over-cap requests get a `429` with `Retry-After`.\n\n[Learn more about Rate Limiting →](/compiler/definitions/rate-limit)\n\n## How They Work Together\n\n**Scenario:** An interviewer requests `GET /candidates/cnd_123`\n\n1. **Rate Limit** checks: Is this user under their `read` cap on `candidates`?\n - Yes → Continue\n - No → 429 Too Many Requests (with `Retry-After`)\n\n2. **Firewall** checks: Is candidate `cnd_123` in the user's organization?\n - Yes → Continue\n - No → 404 Not Found (as if it doesn't exist)\n\n3. **Access** checks: Can interviewers perform GET?\n - Yes → Continue\n - No → 403 Forbidden\n\n4. **Guards** don't apply to GET (they're for writes)\n\n5. **Masking** applies: User is an `interviewer`, not `recruiter` or `hiring-manager`\n - Email: `jane@company.com` → `j***@c******.com`\n - Phone: `555-123-4567` → `******4567`\n\n6. **Response** sent with masked data\n\n## Locked Down by Default\n\nQuickback is **secure by default**. Nothing is accessible until you explicitly allow it.\n\n| Layer | Default | What you must do |\n|-------|---------|------------------|\n| Firewall | AUTO | Auto-detects from `organization_id`/`user_id` columns. Only configure for exceptions. |\n| Access | DENIED | Explicitly define `access` rules with roles |\n| Guards | LOCKED | Explicitly list `createable`, `updatable` fields |\n| Rate Limit | ON | Applied to every resource (read 1000/60s, write 200/60s). Override or set `false` to opt out. |\n| Actions | BLOCKED | Explicitly define `access` for each action |\n\n**You must deliberately open each door.** This prevents accidental data exposure.\n\n## Other Resource Options\n\nBeyond the five security layers, `defineTable` accepts a handful of declarative hints that shape the generated API and the CMS without touching your security posture.\n\n| Option | What it does | Full reference |\n|---|---|---|\n| `views` | Named column projections — `GET /resource/views/{name}` returns a subset of columns under its own access rule. | [Views](/compiler/definitions/views) |\n| `references` | Explicit FK target table for columns that don't follow the \"Id\"-stripped convention (e.g. `vendorId → contact`). | [CMS Schema Registry](/stack/cms/schema-registry) |\n| `displayColumn` | Column to use as the human-readable label in FK resolutions and CMS list views (auto-detected as `name`/`title`/`label` if not set). | [CMS Table Views](/stack/cms/table-views) |\n| `defaultSort` | Default sort order for CMS list rendering (`{ field, order: \"asc\" \\| \"desc\" }`). | [CMS Table Views](/stack/cms/table-views) |\n| `inputHints` | Per-column CMS input type: `select`, `richtext`, `textarea`, `lookup`, `currency`, etc. Pure CMS hint, no runtime effect. | [CMS Record Layouts](/stack/cms/record-layouts) |\n| `layouts` | Named record-page layouts — group fields into sections (collapsed, multi-column). Falls back to auto-grouping if unset. | [CMS Record Layouts](/stack/cms/record-layouts) |\n| `embeddings` | Auto-generate vector embeddings for specified fields on insert/update. | [Stack → Embeddings](/stack/vector/using-embeddings) |\n| `realtime` | Per-table broadcast config (`enabled`, `onInsert`, `onUpdate`, `onDelete`, `requiredRoles`, `fields`). | [Stack → Realtime](/stack/realtime/using-realtime) |\n| `path` | Override the route base path (defaults to feature name). | — |\n\nAll options are optional — omit them and Quickback uses sensible defaults (auto-detected display column, auto-grouped layout, no embeddings, no realtime).\n\n## Next Steps\n\n1. [Database Schema](/compiler/definitions/schema) — Define your tables\n2. [Firewall](/compiler/definitions/firewall) — Set up data isolation\n3. [Access](/compiler/definitions/access) — Configure read and write permissions\n4. [Guards](/compiler/definitions/guards) — Control field modifications\n5. [Masking](/compiler/definitions/masking) — Hide sensitive data\n6. [Rate Limit](/compiler/definitions/rate-limit) — Per-operation request caps\n7. [Views](/compiler/definitions/views) — Column-level security\n8. [Validation](/compiler/definitions/validation) — Field validation rules\n9. [Actions](/compiler/definitions/actions) — Add custom business logic"
|
|
119
119
|
},
|
|
120
120
|
"compiler/definitions/masking": {
|
|
121
121
|
"title": "Masking - Field Redaction",
|
|
@@ -147,7 +147,7 @@ export const DOCS = {
|
|
|
147
147
|
},
|
|
148
148
|
"compiler/definitions/triggers": {
|
|
149
149
|
"title": "Triggers - Postgres-Style Table Triggers",
|
|
150
|
-
"content": "Run logic when rows change — Postgres-style `before`/`after` triggers on `insert`/`update`/`delete`, declared per table.\n\nEach trigger lowers one of two ways, and the compiler reports which:\n\n| You write | Lowers to | Fires on |\n|---|---|---|\n| `sql:` | A real SQLite `CREATE TRIGGER` in your migrations | **Every** write path — REST, actions, queue handlers, cron, raw SQL. Atomic with the write. |\n| `handler:` | An application hook at the audit-wrapper write chokepoint | Writes through the wrapped `db` — REST CRUD and actions. **Not** queue handlers, cron, or raw SQL. |\n\nThere is no auto-translation between the lanes: SQL bodies stay SQL, functions stay functions. Pick the lane by what the trigger must guarantee.\n\n## Basic Usage\n\n```typescript\n// features/invoices/invoices.ts\n\nexport default feature('invoices', {\n columns: {\n id: q.id(),\n title: q.text({ maxLength: 200 }).required(),\n notes: q.text({ maxLength: 2000 }).optional(),\n total: q.int().default(0).required(),\n status: q.enum(['draft', 'sent', 'paid']).default('draft').required(),\n organizationId: q.scope('organization'),\n },\n read: { access: { roles: ['member'] } },\n create: { access: { roles: ['member'] } },\n update: { access: { roles: ['member'] } },\n delete: { access: { roles: ['member'] }, mode: 'soft' },\n\n triggers: {\n beforeInsert: [\n {\n name: 'guardTotals',\n handler: ({ values }) => {\n if (values.total < 0) throw new Error('total must be >= 0');\n return { notes: values.notes ?? 'created' }; // merge into the write\n },\n },\n ],\n afterInsert: [\n {\n // SQL lane — fires for raw SQL too, atomic with the insert\n name: 'stampNotes',\n sql: `UPDATE invoices SET notes = NEW.title WHERE id = NEW.id;`,\n },\n ],\n beforeUpdate: [\n {\n // The universal-enforcement shape: WHEN guard + RAISE(ABORT)\n name: 'lockPaid',\n when: `OLD.status = 'paid' AND NEW.status != 'paid'`,\n sql: `SELECT RAISE(ABORT, 'paid invoices cannot be reopened');`,\n },\n ],\n },\n});\n```\n\nEvents: `beforeInsert`, `afterInsert`, `beforeUpdate`, `afterUpdate`, `beforeDelete`, `afterDelete`. Each event takes an array of named triggers; names must be unique per event.\n\n## SQL triggers (`sql:`)\n\nThe compiler wraps your statements in a `CREATE TRIGGER` named\n`qb_trg_<table>_<event>_<name>` and ships it in the journaled features\nmigration — content-addressed, so an unchanged trigger set produces no new\nmigration, and removing a trigger from config drops it from the database on\nthe next migrate.\n\n- Write **bare, `;`-terminated statements** — the compiler owns the\n `BEGIN`/`END` frame. (It emits the frame uppercase; lowercase `begin`\n breaks remote D1's statement splitter even though local D1 accepts it.)\n- `OLD.column` / `NEW.column` references use **SQL column names**\n (`deleted_at`, not `deletedAt`) and are validated against the table at\n compile time.\n- Optional `when:` is a SQL expression guard (`WHEN` clause).\n- To reject a write, `SELECT RAISE(ABORT, 'message');` — this is the only\n trigger form that blocks *every* write path, including raw SQL.\n- SQL triggers run inside the triggering statement — the only\n transactional option on D1, which has no `db.transaction()`.\n\nCurrently supported on `cloudflare-d1` only; declaring `sql:` triggers on\nanother database provider is a compile error.\n\n### Soft-delete mapping\n\nOn soft-delete tables (the default), `*Delete` events map to the\nsoft-delete *transition* — the compiler emits an\n`AFTER UPDATE OF \"deleted_at\" ... WHEN NEW.\"deleted_at\" IS NOT NULL AND\nOLD.\"deleted_at\" IS NULL` trigger, plus a plain `AFTER DELETE` variant so\nraw-SQL hard deletes are still covered. `*Update` events get the inverse\nguard, so a soft delete fires delete triggers exactly once and never\ndouble-fires as an update.\n\n## Handler triggers (`handler:`)\n\nHandlers run at the same write chokepoint that powers audit stamping and\nLive Views, with full application context:\n\n```typescript\nhandler: ({ table, op, values /* before */, row /* after */, ctx, db, env }) => { ... }\n```\n\n- **`before*` hooks are synchronous.** Return a partial object to merge\n into the write payload, or throw to reject — the write never executes and\n the request gets a structured `TRIGGER_REJECTED` (422) error. Audit\n fields (`createdBy`, `modifiedAt`, …) are re-stamped after hooks run and\n cannot be forged.\n- **`after*` hooks run once per affected row and are awaited** before the\n write's promise resolves. They may be `async`. A throw surfaces as\n `TRIGGER_AFTER_FAILED` (500) with `details.committed: true` — the row was\n already persisted (no transactions on D1), so clients must not blind-retry.\n- Handlers must be **inline arrow/function expressions**. Imports they\n reference are hoisted into the generated registry, and each table's\n drizzle object is auto-imported under its authored name — so this works\n as written:\n\n```typescript\n\n// ...\nafterUpdate: [\n {\n name: 'syncNotes',\n handler: async ({ row, db }) => {\n await db.update(invoices)\n .set({ notes: `updated: ${row.title}` })\n .where(eq(invoices.id, row.id));\n },\n },\n],\n```\n\n`after*` hooks only receive rows when the write chain used `.returning()`\n— generated CRUD routes and actions do.\n\n### Recursion\n\nTrigger cascades are bounded in every lane:\n\n- **Handler hooks**: the `db` a hook receives is re-wrapped at depth + 1.\n A cascade deeper than 5 levels (a hook's write firing hooks that write\n again, …) throws with the table/op that exceeded the cap.\n- **SQL triggers**: SQLite's `recursive_triggers` pragma defaults off — a\n trigger cannot re-enter itself, directly or through a cycle.\n\n### Coverage — read the compile report\n\nHandler hooks do **not** fire for queue handlers, cron jobs, or raw SQL.\nThe compiler emits a per-trigger lowering report and warns at compile time\nwhen a `before*` handler is used as a guard — if a rule must hold for every\nwrite path, use the `sql:` lane with `RAISE(ABORT)`.\n\n## Choosing a lane\n\n| Need | Use |\n|---|---|\n| Invariant that must hold universally (raw SQL included) | `sql:` with `RAISE(ABORT)` |\n| Denormalized columns, counters, tombstones | `sql:` |\n| Validation/derivation with application logic | `before*` `handler:` |\n| Side-effects after a write (notify, write related rows) | `after*` `handler:` |\n| Atomic with the write (D1 has no transactions) | `sql:` only |\n\nPlanned (not yet available — declaring them is a compile error rather than\na silent no-op): `async: true` queue-dispatched after-hooks with retries,\nand `withOld: true` previous-row access on update/delete hooks."
|
|
150
|
+
"content": "Run logic when rows change — Postgres-style `before`/`after` triggers on `insert`/`update`/`delete`, declared per table.\n\nEach trigger lowers one of two ways, and the compiler reports which:\n\n| You write | Lowers to | Fires on |\n|---|---|---|\n| `sql:` | A real SQLite `CREATE TRIGGER` in your migrations | **Every** write path — REST, actions, queue handlers, cron, raw SQL. Atomic with the write. |\n| `handler:` | An application hook at the audit-wrapper write chokepoint | Writes through the wrapped `db` — REST CRUD and actions. **Not** queue handlers, cron, or raw SQL. |\n\nThere is no auto-translation between the lanes: SQL bodies stay SQL, functions stay functions. Pick the lane by what the trigger must guarantee.\n\n## Basic Usage\n\n```typescript\n// features/invoices/invoices.ts\n\nexport default feature('invoices', {\n columns: {\n id: q.id(),\n title: q.text({ maxLength: 200 }).required(),\n notes: q.text({ maxLength: 2000 }).optional(),\n total: q.int().default(0).required(),\n status: q.enum(['draft', 'sent', 'paid']).default('draft').required(),\n organizationId: q.scope('organization'),\n },\n read: { access: { roles: ['member'] } },\n create: { access: { roles: ['member'] } },\n update: { access: { roles: ['member'] } },\n delete: { access: { roles: ['member'] }, mode: 'soft' },\n\n triggers: {\n beforeInsert: [\n {\n name: 'guardTotals',\n handler: ({ values }) => {\n if (values.total < 0) throw new Error('total must be >= 0');\n return { notes: values.notes ?? 'created' }; // merge into the write\n },\n },\n ],\n afterInsert: [\n {\n // SQL lane — fires for raw SQL too, atomic with the insert\n name: 'stampNotes',\n sql: `UPDATE invoices SET notes = NEW.title WHERE id = NEW.id;`,\n },\n ],\n beforeUpdate: [\n {\n // The universal-enforcement shape: WHEN guard + RAISE(ABORT)\n name: 'lockPaid',\n when: `OLD.status = 'paid' AND NEW.status != 'paid'`,\n sql: `SELECT RAISE(ABORT, 'paid invoices cannot be reopened');`,\n },\n ],\n },\n});\n```\n\nEvents: `beforeInsert`, `afterInsert`, `beforeUpdate`, `afterUpdate`, `beforeDelete`, `afterDelete`. Each event takes an array of named triggers; names must be unique per event.\n\n## SQL triggers (`sql:`)\n\nThe compiler wraps your statements in a `CREATE TRIGGER` named\n`qb_trg_<table>_<event>_<name>` and ships it in the journaled features\nmigration — content-addressed, so an unchanged trigger set produces no new\nmigration, and removing a trigger from config drops it from the database on\nthe next migrate.\n\n- Write **bare, `;`-terminated statements** — the compiler owns the\n `BEGIN`/`END` frame. (It emits the frame uppercase; lowercase `begin`\n breaks remote D1's statement splitter even though local D1 accepts it.)\n- `OLD.column` / `NEW.column` references use **SQL column names**\n (`deleted_at`, not `deletedAt`) and are validated against the table at\n compile time.\n- Optional `when:` is a SQL expression guard (`WHEN` clause).\n- To reject a write, `SELECT RAISE(ABORT, 'message');` — this is the only\n trigger form that blocks *every* write path, including raw SQL.\n- SQL triggers run inside the triggering statement — the only\n transactional option on D1, which has no `db.transaction()`.\n\nCurrently supported on `cloudflare-d1` only; declaring `sql:` triggers on\nanother database provider is a compile error.\n\n### Soft-delete mapping\n\nOn soft-delete tables (the default), `*Delete` events map to the\nsoft-delete *transition* — the compiler emits an\n`AFTER UPDATE OF \"deleted_at\" ... WHEN NEW.\"deleted_at\" IS NOT NULL AND\nOLD.\"deleted_at\" IS NULL` trigger, plus a plain `AFTER DELETE` variant so\nraw-SQL hard deletes are still covered. `*Update` events get the inverse\nguard, so a soft delete fires delete triggers exactly once and never\ndouble-fires as an update.\n\n## Handler triggers (`handler:`)\n\nHandlers run at the same write chokepoint that powers audit stamping and\nLive Views, with full application context:\n\n```typescript\nhandler: ({ table, op, values /* before */, row /* after */, ctx, db, env }) => { ... }\n```\n\n- **`before*` hooks are synchronous.** Return a partial object to merge\n into the write payload, or throw to reject — the write never executes and\n the request gets a structured `TRIGGER_REJECTED` (422) error. Audit\n fields (`createdBy`, `modifiedAt`, …) are re-stamped after hooks run and\n cannot be forged.\n- **`after*` hooks run once per affected row and are awaited** before the\n write's promise resolves. They may be `async`. A throw surfaces as\n `TRIGGER_AFTER_FAILED` (500) with `details.committed: true` — the row was\n already persisted (no transactions on D1), so clients must not blind-retry.\n- Handlers must be **inline arrow/function expressions**. Imports they\n reference are hoisted into the generated registry, and each table's\n drizzle object is auto-imported under its authored name — so this works\n as written:\n\n```typescript\n\n// ...\nafterUpdate: [\n {\n name: 'syncNotes',\n handler: async ({ row, db }) => {\n await db.update(invoices)\n .set({ notes: `updated: ${row.title}` })\n .where(eq(invoices.id, row.id));\n },\n },\n],\n```\n\n`after*` hooks only receive rows when the write chain used `.returning()`\n— generated CRUD routes and actions do.\n\n### Recursion\n\nTrigger cascades are bounded in every lane:\n\n- **Handler hooks**: the `db` a hook receives is re-wrapped at depth + 1.\n A cascade deeper than 5 levels (a hook's write firing hooks that write\n again, …) throws with the table/op that exceeded the cap.\n- **SQL triggers**: SQLite's `recursive_triggers` pragma defaults off — a\n trigger cannot re-enter itself, directly or through a cycle.\n\n### Coverage — read the compile report\n\nHandler hooks do **not** fire for queue handlers, cron jobs, or raw SQL.\nThe compiler emits a per-trigger lowering report and warns at compile time\nwhen a `before*` handler is used as a guard — if a rule must hold for every\nwrite path, use the `sql:` lane with `RAISE(ABORT)`.\n\n> Cron jobs themselves are first-class — declare them with\n> [`defineSchedule`](/stack/schedules) and the compiler emits the Worker\n> `scheduled()` handler + `wrangler.toml` triggers. This note is only about\n> the table-trigger `handler:` lane not firing inside them.\n\n## Choosing a lane\n\n| Need | Use |\n|---|---|\n| Invariant that must hold universally (raw SQL included) | `sql:` with `RAISE(ABORT)` |\n| Denormalized columns, counters, tombstones | `sql:` |\n| Validation/derivation with application logic | `before*` `handler:` |\n| Side-effects after a write (notify, write related rows) | `after*` `handler:` |\n| Atomic with the write (D1 has no transactions) | `sql:` only |\n\nPlanned (not yet available — declaring them is a compile error rather than\na silent no-op): `async: true` queue-dispatched after-hooks with retries,\nand `withOld: true` previous-row access on update/delete hooks."
|
|
151
151
|
},
|
|
152
152
|
"compiler/definitions/validation": {
|
|
153
153
|
"title": "Validation",
|
|
@@ -415,7 +415,7 @@ export const DOCS = {
|
|
|
415
415
|
},
|
|
416
416
|
"stack": {
|
|
417
417
|
"title": "Quickback Stack",
|
|
418
|
-
"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| [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\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"
|
|
418
|
+
"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"
|
|
419
419
|
},
|
|
420
420
|
"stack/queues/handlers": {
|
|
421
421
|
"title": "Custom Queue Handlers",
|
|
@@ -443,12 +443,16 @@ export const DOCS = {
|
|
|
443
443
|
},
|
|
444
444
|
"stack/realtime/partyserver-rooms": {
|
|
445
445
|
"title": "PartyServer Rooms",
|
|
446
|
-
"content": "When you need **client↔client** state — presence, live cursors, shared notes, concurrent editing — Quickback exposes [PartyServer](https://github.com/cloudflare/partykit) rooms at `/realtime/<binding>/<room-id>`. Each room is its own Durable Object instance, so isolation between rooms is automatic and the runtime hibernates idle rooms for free.\n\nThis is **separate from `/broadcast/v1/*`** (the org-wide server fan-out documented in [Using Realtime](/stack/realtime/using-realtime)). They share the worker and the auth model but solve different problems:\n\n| Concern | `/broadcast/v1/*` | `/realtime/<binding>/<room-id>` |\n|---|---|---|\n| Direction | Server → clients | Client ↔ clients |\n| Sharding | One DO per org | One DO per room |\n| Use case | Postgres-changes, app-wide events | Live cursors, shared edits, presence |\n| Catchup | Ephemeral | Per-room state survives reconnects |\n\n## When to use rooms vs broadcast\n\nReach for rooms when **the messages flow between users in the same context** (interview, document, game match). Reach for broadcast when **the server is publishing facts** that any client in the org may want to react to (a record was updated, a webhook fired, a role changed).\n\nYou can use both in the same project. Cost is the same.\n\n## Define a room class\n\nThe PartyServer `Server` class extends `DurableObject`, so any in-worker DO you wire up via `bindings.durableObjects` qualifies. The lifecycle hooks below are what PartyServer adds on top:\n\n```ts\n// quickback/features/interviews/lib/InterviewRoom.ts\n\nexport class InterviewRoom extends Server {\n static options = { hibernate: true };\n\n presence = new Map<string, { userId?: string; name?: string }>();\n\n onConnect(connection: Connection) {\n this.presence.set(connection.id, {});\n this.broadcastPresence();\n }\n\n onMessage(connection: Connection, message: WSMessage) {\n if (typeof message !== 'string') return;\n const parsed = JSON.parse(message);\n if (parsed.type === 'note') {\n this.broadcast(JSON.stringify({ type: 'note', from: connection.id, body: parsed.body }), [connection.id]);\n }\n }\n\n onClose(connection: Connection) {\n this.presence.delete(connection.id);\n this.broadcastPresence();\n }\n\n private broadcastPresence() {\n const peers = Array.from(this.presence.entries()).map(([id, meta]) => ({ id, ...meta }));\n this.broadcast(JSON.stringify({ type: 'presence', peers }));\n }\n}\n```\n\n## Wire it into your config\n\nOne entry under `bindings.durableObjects` is everything the compiler needs. The Server class lives under a `lib/` directory inside the feature (the same path the compiler uses for any in-worker shared code) — author it at `quickback/features/interviews/lib/InterviewRoom.ts`. The `from` value is the corresponding module path, no extension.\n\n```ts\n// quickback/quickback.config.ts\nexport default defineConfig({\n // ...\n bindings: {\n durableObjects: [\n {\n name: 'INTERVIEW_ROOM',\n className: 'InterviewRoom',\n from: 'features/interviews/lib/InterviewRoom',\n },\n ],\n },\n build: {\n dependencies: {\n partyserver: '^0.5.5',\n partysocket: '^1.1.18',\n },\n },\n});\n```\n\nThe compiler emits the `[[durable_objects.bindings]]` block, the `[[migrations]]` entry (SQLite-backed by default), and the class re-export from `src/index.ts`. **It also auto-mounts the `hono-party` middleware at `/realtime/*`** the moment any in-worker DO is declared, so URL routing follows PartyServer's own convention.\n\n## Connect from the client\n\nThe `partysocket` package handles reconnection, buffering, and resilience. The `party` field is the kebab-cased binding name (`INTERVIEW_ROOM` → `interview-room`); the `room` field is any opaque ID.\n\n```ts\n\nconst socket = new PartySocket({\n host: window.location.host,\n party: 'interview-room',\n room: 'interview-abc123',\n prefix: 'realtime',\n});\n\nsocket.addEventListener('message', (e) => {\n const msg = JSON.parse(e.data);\n if (msg.type === 'presence') updatePresence(msg.peers);\n if (msg.type === 'note') appendNote(msg.from, msg.body);\n});\n\nsocket.send(JSON.stringify({ type: 'note', body: 'asked about tenure' }));\n```\n\n## Authentication\n\nThe auto-mounted middleware is **secure by default** — anonymous WebSocket upgrades are rejected with `401 Unauthorized` before `partyserverMiddleware` sees the request. The four auth mechanisms the rest of the worker honors all unlock connections:\n\n- session cookie\n- `Authorization: Bearer <jwt>`\n- `x-api-key` header\n- `?api_key=` / `?key=` query parameter\n\n(For the hand-written mount form below, you can also accept signed `?ws_ticket=` query params using the same issuer the Broadcaster exposes at `/broadcast/v1/ws-ticket`.)\n\nThe default gate only checks **whether** the caller is authenticated, not whether they're allowed in *this* room. For per-room authorization, the `access` field on the binding lets the compiler emit a path-scoped gate that runs your existing resource firewall + `read.access` pipeline before the WebSocket upgrade — no hand-written code, same status semantics as `GET /api/v1/<resource>/:id`.\n\n### Per-room authorization via `access` (v0.12+)\n\n```ts\n// quickback/quickback.config.ts\nbindings: {\n durableObjects: [\n // Single-resource: roomId IS the row id of `chats`.\n // Auto-emits a gate at /realtime/chat/* that runs `chats`'s firewall.\n {\n name: 'Chat', className: 'Chat', from: 'lib/Chat',\n access: { resource: 'chats' },\n },\n\n // Multi-resource: roomId pattern dispatches kind → resource.\n // Auto-emits a gate at /realtime/notepad/* that parses\n // `day-note:<rowId>` | `interaction:<rowId>` | `record:<rowId>`\n // and runs the matched resource's firewall on the rowId.\n {\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\n // Multi-table feature: pin the gate to a specific table so the\n // firewall + id query is unambiguous (v0.16.1+).\n {\n name: 'NotepadInteractions', className: 'NotepadInteractions', from: 'lib/NotepadInteractions',\n access: { resource: { feature: 'interactions', table: 'interactions' } },\n },\n\n // Room keyed by a unique non-PK column (v0.36+). A Yjs page editor is\n // addressed by `event_pages.yjsRoomId`, not the row id — `key` tells the\n // gate which column the roomId matches.\n {\n name: 'PageRoom', className: 'PageRoom', from: 'lib/PageRoom',\n access: { resource: { feature: 'event-pages', table: 'eventPages', key: 'yjsRoomId' } },\n },\n\n // Genuinely public room (no auth, no row lookup) — opt out explicitly.\n { name: 'PublicLobby', className: 'PublicLobby', from: 'lib/PublicLobby',\n access: 'public' },\n ],\n}\n```\n\nWhat the compiler emits:\n\n- **`access: { resource: 'chats' }`** — `app.use('/realtime/chat/*', …)` that 401s anonymous, parses the URL segment as a row id, queries `chats` with the resource's `buildFirewallConditions(ctx)` and `eq(chats.id, rowId)`, and 403s when the row is invisible to the caller (out-of-org, soft-deleted, etc.). The DO's `onLoad` / `onConnect` then runs only for rows the user can already read.\n- **`access: { resource: { feature, table } }`** — same gate, but the schema import + firewall alias are keyed off the pinned `table` instead of the feature name. Required when a feature owns more than one resourceful table; the access gate emit can't pick which table's firewall to query otherwise.\n- **`access: { resource: { feature, table, key } }`** — same gate, but it matches the roomId against `table.<key>` instead of `table.id`. Use it when the room is addressed by a unique non-PK column — e.g. a Yjs editor keyed by `event_pages.yjsRoomId` (`ns.idFromName(row.yjsRoomId)`). `key` defaults to `'id'`, so existing pins are unchanged. The compiler validates the column exists at compile time. `key` also works inside each multi-resource branch.\n- **Multi-resource form** — same gate but with a regex parser dispatching to per-kind firewall lookups. Unknown kinds 400 at the gate. Each `resources[kind].resource` accepts either form (string shorthand or `{ feature, table, key? }`).\n- **`access: 'public'`** — `app.use('/realtime/<kebab>/*', …)` that just passes through. Use for anonymous game lobbies / public collab pads where the room itself is the unit of access.\n- **No `access` declared** — falls through to the catchall `/realtime/*` gate that just checks `ctx.authenticated`. (v0.11.1 behavior.)\n\nCompile-time validation: every `resource` / `resources[].resource` value is checked against the project's feature names so typos surface as build errors, not as runtime 400s on the first WS upgrade. The string shorthand requires the feature to have exactly one resourceful table; multi-table features must use the long form `{ feature, table }` to pin a specific table. When `key` is set, the column is checked against the pinned table's schema.\n\n### Migrating a hand-rolled `onConnect` room to a declarative gate\n\nIf a room currently enforces access by hand inside `onConnect` / `onBeforeConnect` — typically because the room sits on a multi-table feature and an earlier compiler refused the ambiguous string shorthand — you can almost always replace it with a declarative `access` block. The decision is just \"what is the roomId?\":\n\n1. **roomId is a table's row id** → `access: { resource: { feature, table } }`.\n2. **roomId is a unique non-PK column** (a slug, a `yjsRoomId`) → add `key`: `access: { resource: { feature, table, key: 'yjsRoomId' } }`.\n3. **one DO class serves several room kinds** (e.g. `conv-<id>` / `ticket-<id>`) → the multi-resource form with a `pattern` that captures the kind and id.\n4. **access depends on membership, not just tenant** (e.g. \"is this user an attendee of the event that owns this page\") → you do **not** need hand-written code. Declare the pinned table's firewall with a `via:` relationship; the gate runs the table's *full* `buildFirewallConditions`, relationship subqueries included.\n\nThe declarative gate runs the exact firewall the CRUD `GET /:id` handler enforces, with the same 401/403 semantics, *before* the WebSocket upgrade — so by the time `onConnect` fires the caller is already authorized. Dropping the hand-rolled check also closes a common gap: a room with no `access` block is reachable by **any** authenticated user who can guess a room id, regardless of tenant.\n\n### Hand-written mount with `onBeforeConnect`\n\nPartyServer also accepts an `onBeforeConnect` hook that runs before the WebSocket upgrade. Reject the upgrade by returning a `Response`; otherwise return `undefined` (or a modified `Request`) and the connection proceeds. Use this when you want a different auth shape than the default — for example, requiring `?ws_ticket=` exclusively (and rejecting raw header / query api-keys), or running per-room checks at the gate instead of in `onConnect`:\n\n```ts\n\napp.use('/realtime/*', partyserverMiddleware({\n options: {\n prefix: 'realtime',\n onBeforeConnect: async (req) => {\n const token = new URL(req.url).searchParams.get('ws_ticket');\n if (!token || !await verifyTicket(token)) {\n return new Response('Unauthorized', { status: 401 });\n }\n },\n },\n}));\n```\n\nThe matching `ws_ticket` issuer is the same one the Broadcaster already uses at `/broadcast/v1/ws-ticket` — generate a ticket from your authenticated UI, pass it as a query param on the WebSocket URL, and verify it inside `onBeforeConnect`. To use this hand-written form, declare a custom route at `/realtime/*` *before* the auto-mount runs (Hono dispatches the first matching middleware) — that lets you opt out of the default auth gate or layer per-room access checks at the upgrade step.\n\n## CRDT-grade document collab (Yjs)\n\nDrop in [`Y-PartyServer`](https://github.com/cloudflare/partykit) when you need true concurrent text/document editing. It's a `Server` subclass that wraps Yjs's sync protocol; everything else above stays the same.\n\n```ts\n\nexport class DocumentRoom extends YServer {\n // Yjs doc lives on `this.doc`; sync protocol is automatic.\n // Override `onLoad()` / `onSave()` to persist to R2 / KV / your DB.\n}\n```\n\n## Why this and not the Broadcaster\n\nThe Broadcaster is a one-DO-per-org fan-out. It can't shard by document, and it doesn't model client→client messages. PartyServer's per-room model is the right primitive for collab; the Broadcaster's per-org model is the right primitive for \"tell everyone in this org that X happened.\" Run both."
|
|
446
|
+
"content": "When you need **client↔client** state — presence, live cursors, shared notes, concurrent editing — Quickback exposes [PartyServer](https://github.com/cloudflare/partykit) rooms at `/realtime/<binding>/<room-id>`. Each room is its own Durable Object instance, so isolation between rooms is automatic and the runtime hibernates idle rooms for free.\n\nThis is **separate from `/broadcast/v1/*`** (the org-wide server fan-out documented in [Using Realtime](/stack/realtime/using-realtime)). They share the worker and the auth model but solve different problems:\n\n| Concern | `/broadcast/v1/*` | `/realtime/<binding>/<room-id>` |\n|---|---|---|\n| Direction | Server → clients | Client ↔ clients |\n| Sharding | One DO per org | One DO per room |\n| Use case | Postgres-changes, app-wide events | Live cursors, shared edits, presence |\n| Catchup | Ephemeral | Per-room state survives reconnects |\n\n## When to use rooms vs broadcast\n\nReach for rooms when **the messages flow between users in the same context** (interview, document, game match). Reach for broadcast when **the server is publishing facts** that any client in the org may want to react to (a record was updated, a webhook fired, a role changed).\n\nYou can use both in the same project. Cost is the same.\n\n## Define a room class\n\nThe PartyServer `Server` class extends `DurableObject`, so any in-worker DO you wire up via `bindings.durableObjects` qualifies. The lifecycle hooks below are what PartyServer adds on top:\n\n```ts\n// quickback/features/interviews/lib/InterviewRoom.ts\n\nexport class InterviewRoom extends Server {\n static options = { hibernate: true };\n\n presence = new Map<string, { userId?: string; name?: string }>();\n\n onConnect(connection: Connection) {\n this.presence.set(connection.id, {});\n this.broadcastPresence();\n }\n\n onMessage(connection: Connection, message: WSMessage) {\n if (typeof message !== 'string') return;\n const parsed = JSON.parse(message);\n if (parsed.type === 'note') {\n this.broadcast(JSON.stringify({ type: 'note', from: connection.id, body: parsed.body }), [connection.id]);\n }\n }\n\n onClose(connection: Connection) {\n this.presence.delete(connection.id);\n this.broadcastPresence();\n }\n\n private broadcastPresence() {\n const peers = Array.from(this.presence.entries()).map(([id, meta]) => ({ id, ...meta }));\n this.broadcast(JSON.stringify({ type: 'presence', peers }));\n }\n}\n```\n\n## Wire it into your config\n\nOne entry under `bindings.durableObjects` is everything the compiler needs. The Server class lives under a `lib/` directory inside the feature (the same path the compiler uses for any in-worker shared code) — author it at `quickback/features/interviews/lib/InterviewRoom.ts`. The `from` value is the corresponding module path, no extension.\n\n```ts\n// quickback/quickback.config.ts\nexport default defineConfig({\n // ...\n bindings: {\n durableObjects: [\n {\n name: 'INTERVIEW_ROOM',\n className: 'InterviewRoom',\n from: 'features/interviews/lib/InterviewRoom',\n },\n ],\n },\n build: {\n dependencies: {\n partyserver: '^0.5.5',\n partysocket: '^1.1.18',\n },\n },\n});\n```\n\nThe compiler emits the `[[durable_objects.bindings]]` block, the `[[migrations]]` entry (SQLite-backed by default), and the class re-export from `src/index.ts`. **It also auto-mounts the `hono-party` middleware at `/realtime/*`** the moment any in-worker DO is declared, so URL routing follows PartyServer's own convention.\n\n## Connect from the client\n\nThe `partysocket` package handles reconnection, buffering, and resilience. The `party` field is the kebab-cased binding name (`INTERVIEW_ROOM` → `interview-room`); the `room` field is any opaque ID.\n\n```ts\n\nconst socket = new PartySocket({\n host: window.location.host,\n party: 'interview-room',\n room: 'interview-abc123',\n prefix: 'realtime',\n});\n\nsocket.addEventListener('message', (e) => {\n const msg = JSON.parse(e.data);\n if (msg.type === 'presence') updatePresence(msg.peers);\n if (msg.type === 'note') appendNote(msg.from, msg.body);\n});\n\nsocket.send(JSON.stringify({ type: 'note', body: 'asked about tenure' }));\n```\n\n## Authentication\n\nThe auto-mounted middleware is **secure by default** — anonymous WebSocket upgrades are rejected with `401 Unauthorized` before `partyserverMiddleware` sees the request. The four auth mechanisms the rest of the worker honors all unlock connections:\n\n- session cookie\n- `Authorization: Bearer <jwt>`\n- `x-api-key` header\n- `?api_key=` / `?key=` query parameter\n\n(For the hand-written mount form below, you can also accept signed `?ws_ticket=` query params using the same issuer the Broadcaster exposes at `/broadcast/v1/ws-ticket`.)\n\nThe default gate only checks **whether** the caller is authenticated, not whether they're allowed in *this* room. For per-room authorization, the `access` field on the binding lets the compiler emit a path-scoped gate that runs your existing resource firewall + `read.access` pipeline before the WebSocket upgrade — no hand-written code, same status semantics as `GET /api/v1/<resource>/:id`.\n\n### Per-room authorization via `access` (v0.12+)\n\n```ts\n// quickback/quickback.config.ts\nbindings: {\n durableObjects: [\n // Single-resource: roomId IS the row id of `chats`.\n // Auto-emits a gate at /realtime/chat/* that runs `chats`'s firewall.\n {\n name: 'Chat', className: 'Chat', from: 'lib/Chat',\n access: { resource: 'chats' },\n },\n\n // Multi-resource: roomId pattern dispatches kind → resource.\n // Auto-emits a gate at /realtime/notepad/* that parses\n // `day-note:<rowId>` | `interaction:<rowId>` | `record:<rowId>`\n // and runs the matched resource's firewall on the rowId.\n {\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\n // Multi-table feature: pin the gate to a specific table so the\n // firewall + id query is unambiguous (v0.16.1+).\n {\n name: 'NotepadInteractions', className: 'NotepadInteractions', from: 'lib/NotepadInteractions',\n access: { resource: { feature: 'interactions', table: 'interactions' } },\n },\n\n // Room keyed by a unique non-PK column (v0.36+). A Yjs page editor is\n // addressed by `event_pages.yjsRoomId`, not the row id — `key` tells the\n // gate which column the roomId matches.\n {\n name: 'PageRoom', className: 'PageRoom', from: 'lib/PageRoom',\n access: { resource: { feature: 'event-pages', table: 'eventPages', key: 'yjsRoomId' } },\n },\n\n // Identity-gated room — the roomId IS the caller's own id, with no backing\n // table. A per-user gateway / presence / inbox keyed on `ctx.userId`:\n // auto-emits a gate at /realtime/user-gateway/* that 403s unless the room\n // segment equals the authenticated user's id. Use `ctx.activeOrgId` for a\n // per-org room. No DB query — it's a string compare against ctx.\n {\n name: 'UserGateway', className: 'UserGateway', from: 'lib/UserGateway',\n access: { roomIdEquals: 'ctx.userId' },\n },\n\n // Genuinely public room (no auth, no row lookup) — opt out explicitly.\n { name: 'PublicLobby', className: 'PublicLobby', from: 'lib/PublicLobby',\n access: 'public' },\n ],\n}\n```\n\nWhat the compiler emits:\n\n- **`access: { resource: 'chats' }`** — `app.use('/realtime/chat/*', …)` that 401s anonymous, parses the URL segment as a row id, queries `chats` with the resource's `buildFirewallConditions(ctx)` and `eq(chats.id, rowId)`, and 403s when the row is invisible to the caller (out-of-org, soft-deleted, etc.). The DO's `onLoad` / `onConnect` then runs only for rows the user can already read.\n- **`access: { resource: { feature, table } }`** — same gate, but the schema import + firewall alias are keyed off the pinned `table` instead of the feature name. Required when a feature owns more than one resourceful table; the access gate emit can't pick which table's firewall to query otherwise.\n- **`access: { resource: { feature, table, key } }`** — same gate, but it matches the roomId against `table.<key>` instead of `table.id`. Use it when the room is addressed by a unique non-PK column — e.g. a Yjs editor keyed by `event_pages.yjsRoomId` (`ns.idFromName(row.yjsRoomId)`). `key` defaults to `'id'`, so existing pins are unchanged. The compiler validates the column exists at compile time. `key` also works inside each multi-resource branch.\n- **Multi-resource form** — same gate but with a regex parser dispatching to per-kind firewall lookups. Unknown kinds 400 at the gate. Each `resources[kind].resource` accepts either form (string shorthand or `{ feature, table, key? }`).\n- **`access: { roomIdEquals: 'ctx.userId' }`** — an **identity gate** for rooms with no backing table, where the roomId *is* the caller's own id. Emits `app.use('/realtime/<kebab>/*', …)` that 401s anonymous, 400s a missing segment, and 403s unless the decoded room segment equals `ctx.userId`. No schema import, no firewall, no DB query — a string compare against the server-resolved `ctx`. Use `'ctx.activeOrgId'` for a per-org room. This is the right gate for per-user gateways, presence, or inbox DOs keyed on `ns.idFromName(ctx.userId)`. Only `'ctx.userId'` and `'ctx.activeOrgId'` are accepted (validated at compile time); anything else is a build error. Distinct from `resource` because there's no row to firewall — it closes the cross-user hole that \"no `access` declared\" leaves open (any authenticated user could otherwise open another user's room via the catchall).\n- **`access: 'public'`** — `app.use('/realtime/<kebab>/*', …)` that just passes through. Use for anonymous game lobbies / public collab pads where the room itself is the unit of access.\n- **No `access` declared** — falls through to the catchall `/realtime/*` gate that just checks `ctx.authenticated`. (v0.11.1 behavior.)\n\nCompile-time validation: every `resource` / `resources[].resource` value is checked against the project's feature names so typos surface as build errors, not as runtime 400s on the first WS upgrade. The string shorthand requires the feature to have exactly one resourceful table; multi-table features must use the long form `{ feature, table }` to pin a specific table. When `key` is set, the column is checked against the pinned table's schema.\n\n### Migrating a hand-rolled `onConnect` room to a declarative gate\n\nIf a room currently enforces access by hand inside `onConnect` / `onBeforeConnect` — typically because the room sits on a multi-table feature and an earlier compiler refused the ambiguous string shorthand — you can almost always replace it with a declarative `access` block. The decision is just \"what is the roomId?\":\n\n1. **roomId is a table's row id** → `access: { resource: { feature, table } }`.\n2. **roomId is a unique non-PK column** (a slug, a `yjsRoomId`) → add `key`: `access: { resource: { feature, table, key: 'yjsRoomId' } }`.\n3. **one DO class serves several room kinds** (e.g. `conv-<id>` / `ticket-<id>`) → the multi-resource form with a `pattern` that captures the kind and id.\n4. **access depends on membership, not just tenant** (e.g. \"is this user an attendee of the event that owns this page\") → you do **not** need hand-written code. Declare the pinned table's firewall with a `via:` relationship; the gate runs the table's *full* `buildFirewallConditions`, relationship subqueries included.\n5. **roomId is the caller's own identity** (a per-user gateway/presence/inbox where the room *is* `ctx.userId`, with no backing table) → `access: { roomIdEquals: 'ctx.userId' }` (or `'ctx.activeOrgId'`). Do **not** enforce this inside the DO from request data — a Durable Object has no session and only sees client-settable headers, so trusting an `x-user-id` header lets any authenticated user open another user's room. The gate belongs at the Worker edge, which is exactly what this arm emits.\n\nThe declarative gate runs the exact firewall the CRUD `GET /:id` handler enforces, with the same 401/403 semantics, *before* the WebSocket upgrade — so by the time `onConnect` fires the caller is already authorized. Dropping the hand-rolled check also closes a common gap: a room with no `access` block is reachable by **any** authenticated user who can guess a room id, regardless of tenant.\n\n### Hand-written mount with `onBeforeConnect`\n\nPartyServer also accepts an `onBeforeConnect` hook that runs before the WebSocket upgrade. Reject the upgrade by returning a `Response`; otherwise return `undefined` (or a modified `Request`) and the connection proceeds. Use this when you want a different auth shape than the default — for example, requiring `?ws_ticket=` exclusively (and rejecting raw header / query api-keys), or running per-room checks at the gate instead of in `onConnect`:\n\n```ts\n\napp.use('/realtime/*', partyserverMiddleware({\n options: {\n prefix: 'realtime',\n onBeforeConnect: async (req) => {\n const token = new URL(req.url).searchParams.get('ws_ticket');\n if (!token || !await verifyTicket(token)) {\n return new Response('Unauthorized', { status: 401 });\n }\n },\n },\n}));\n```\n\nThe matching `ws_ticket` issuer is the same one the Broadcaster already uses at `/broadcast/v1/ws-ticket` — generate a ticket from your authenticated UI, pass it as a query param on the WebSocket URL, and verify it inside `onBeforeConnect`. To use this hand-written form, declare a custom route at `/realtime/*` *before* the auto-mount runs (Hono dispatches the first matching middleware) — that lets you opt out of the default auth gate or layer per-room access checks at the upgrade step.\n\n## CRDT-grade document collab (Yjs)\n\nDrop in [`Y-PartyServer`](https://github.com/cloudflare/partykit) when you need true concurrent text/document editing. It's a `Server` subclass that wraps Yjs's sync protocol; everything else above stays the same.\n\n```ts\n\nexport class DocumentRoom extends YServer {\n // Yjs doc lives on `this.doc`; sync protocol is automatic.\n // Override `onLoad()` / `onSave()` to persist to R2 / KV / your DB.\n}\n```\n\n## Why this and not the Broadcaster\n\nThe Broadcaster is a one-DO-per-org fan-out. It can't shard by document, and it doesn't model client→client messages. PartyServer's per-room model is the right primitive for collab; the Broadcaster's per-org model is the right primitive for \"tell everyone in this org that X happened.\" Run both."
|
|
447
447
|
},
|
|
448
448
|
"stack/realtime/using-realtime": {
|
|
449
449
|
"title": "Using Realtime",
|
|
450
450
|
"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 users whose role matches the broadcast's `targetRoles`. If a table's realtime config specifies `requiredRoles: [\"hiring-manager\", \"recruiter\"]`, only users with those roles receive the events. This applies to generated CRUD broadcasts and to [live view](/stack/realtime/live-views) `view_changes` deltas alike, enforced at fanout (v0.46+ — recompile and redeploy to pick up the enforcement).\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"
|
|
451
451
|
},
|
|
452
|
+
"stack/schedules": {
|
|
453
|
+
"title": "Schedules (Cron)",
|
|
454
|
+
"content": "`defineSchedule` is the trigger-side mirror of [`defineQueue`](/stack/queues). Drop a file in `services/schedules/` and the compiler emits a Worker `scheduled()` (cron) handler plus the matching `[triggers] crons` in `wrangler.toml` — no separate cron Worker, no hand-patching the generated entry.\n\n## Define a schedule\n\n```typescript\n// services/schedules/sweepDigests.ts\n\nexport default defineSchedule({\n name: \"sweepDigests\", // identifier + audit actor (system:cron-<name>)\n cron: \"* * * * *\", // Cloudflare cron syntax\n description: \"Send pending unread-email digests\",\n execute: async ({ db, env, services }) => {\n await runDigestSweep(db, env, services);\n },\n});\n```\n\nOne file per schedule under `services/schedules/*.ts`. Files prefixed with `_` are ignored. `name` must be a valid camelCase identifier (it's used as a generated symbol and the audit actor).\n\n## What the compiler emits\n\n1. **`scheduled(event, env, ctx)`** in the Worker's default export, dispatching to every schedule whose cron matches `event.cron`. Multiple schedules can share a cron; a failure in one is isolated from the others.\n2. **`[triggers] crons = [...]`** in `wrangler.toml` — one deduped, sorted list across all schedules.\n3. **`src/lib/schedules.ts`** — the generated runner. Regenerated on every `quickback compile`, so there's nothing to hand-maintain.\n\n## Execute context\n\n| Field | Type | Notes |\n|-------|------|-------|\n| `db` | Drizzle instance | The same DB the queue handlers get |\n| `env` | `CloudflareBindings` | All worker bindings |\n| `services` | `Services` | The services layer (`createServices(env)`) |\n| `cron` | `string` | The cron pattern that fired |\n| `scheduledTime` | `number` | `event.scheduledTime` (ms epoch) |\n| `withInternalContext` | helper | Opt into the `INTERNAL` trust zone for `roles: ['INTERNAL']`-gated rows |\n\n## Audit & trust\n\nCron runs are **server-internal**: there's no authenticated user, no request, no org scope. A fired tick gets a plain `db` (unscoped Drizzle) plus a `withInternalContext` helper:\n\n```typescript\nexecute: async ({ db, withInternalContext }) => {\n // `db` here is unscoped — no firewall WHERE, no audit actor.\n\n // Opt into the INTERNAL trust zone for cross-tenant work:\n await withInternalContext(async ({ ctx, db, services }) => {\n // ctx.internal = true, ctx.userId = \"system:cron-<name>\"\n // audited writes are attributable to e.g. system:cron-sweepDigests\n });\n},\n```\n\n`withInternalContext` builds a context with `internal: true` and `userId: \"system:cron-<name>\"`, so audited writes made through it are attributable to the schedule (e.g. `system:cron-sweepDigests`) and can reach `roles: ['INTERNAL']`-gated rows. Reach for it whenever the schedule legitimately operates across tenants.\n\n## Failure isolation\n\nThe generated `scheduled()` dispatcher runs every schedule whose cron matches `event.cron` concurrently (`Promise.all`), and each handler's errors are caught individually — one failing schedule logs `[Cron] Schedule error` and the others still run to completion. A cron with no registered handler logs `[Cron] No schedule registered` and returns.\n\n## Cron syntax\n\nStandard Cloudflare cron (`minute hour day-of-month month day-of-week`):\n\n| Pattern | Runs |\n|---------|------|\n| `* * * * *` | every minute |\n| `0 * * * *` | top of every hour |\n| `0 0 * * *` | daily at 00:00 UTC |\n| `*/5 * * * *` | every 5 minutes |\n\nSee Cloudflare's [Cron Triggers](https://developers.cloudflare.com/workers/configuration/cron-triggers/) docs for the full grammar and limits.\n\n## See also\n\n- [Queues](/stack/queues) — the async-message counterpart (`defineQueue`)\n- [Triggers](/compiler/definitions/triggers) — row-level lifecycle hooks (distinct from cron)"
|
|
455
|
+
},
|
|
452
456
|
"stack/storage": {
|
|
453
457
|
"title": "Storage",
|
|
454
458
|
"content": "The Quickback Stack uses Cloudflare's storage primitives for different use cases.\n\n## Storage Types\n\n| Service | Use Case | Pages |\n|---------|----------|-------|\n| **KV** | Sessions, caching, rate limiting | [Setup](/stack/storage/kv) · [Usage](/stack/storage/using-kv) |\n| **R2** | File uploads, avatars, attachments | [Setup](/stack/storage/r2) · [Usage](/stack/storage/using-r2) |\n\n## Getting Started\n\n- **[KV Setup](/stack/storage/kv)** — Namespace and bindings configuration\n- **[Using KV](/stack/storage/using-kv)** — Sessions, caching, rate limiting\n- **[R2 Setup](/stack/storage/r2)** — Bucket, bindings, CORS configuration\n- **[Using R2](/stack/storage/using-r2)** — Uploads, downloads, role-based access"
|
|
@@ -607,6 +611,7 @@ export const TOPIC_LIST = [
|
|
|
607
611
|
"stack/realtime/live-views",
|
|
608
612
|
"stack/realtime/partyserver-rooms",
|
|
609
613
|
"stack/realtime/using-realtime",
|
|
614
|
+
"stack/schedules",
|
|
610
615
|
"stack/storage",
|
|
611
616
|
"stack/storage/kv",
|
|
612
617
|
"stack/storage/r2",
|