@quickback-dev/cli 0.14.2 → 0.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/commands/compile.d.ts.map +1 -1
  2. package/dist/commands/compile.js +40 -2
  3. package/dist/commands/compile.js.map +1 -1
  4. package/dist/docs/content.d.ts.map +1 -1
  5. package/dist/docs/content.js +12 -7
  6. package/dist/docs/content.js.map +1 -1
  7. package/dist/index.js +1 -1
  8. package/dist/lib/copy-public-assets.d.ts +34 -0
  9. package/dist/lib/copy-public-assets.d.ts.map +1 -0
  10. package/dist/lib/copy-public-assets.js +118 -0
  11. package/dist/lib/copy-public-assets.js.map +1 -0
  12. package/dist/lib/copy-public-assets.test.d.ts +2 -0
  13. package/dist/lib/copy-public-assets.test.d.ts.map +1 -0
  14. package/dist/lib/copy-public-assets.test.js +151 -0
  15. package/dist/lib/copy-public-assets.test.js.map +1 -0
  16. package/dist/skill/docs/changelog.md +256 -0
  17. package/dist/skill/docs/compiler/config/index.md +18 -0
  18. package/dist/skill/docs/compiler/config/output.md +34 -0
  19. package/dist/skill/docs/compiler/definitions/access.md +17 -3
  20. package/dist/skill/docs/compiler/definitions/firewall.md +27 -0
  21. package/dist/skill/docs/compiler/definitions/schema.md +9 -0
  22. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/errors.md +84 -2
  23. package/dist/skill/docs/stack/auth/plugins/agent-auth.md +131 -0
  24. package/dist/skill/docs/stack/realtime/partyserver-rooms.md +10 -2
  25. package/package.json +1 -1
  26. package/src/skill/docs/changelog.md +256 -0
  27. package/src/skill/docs/compiler/config/index.md +18 -0
  28. package/src/skill/docs/compiler/config/output.md +34 -0
  29. package/src/skill/docs/compiler/definitions/access.md +17 -3
  30. package/src/skill/docs/compiler/definitions/firewall.md +27 -0
  31. package/src/skill/docs/compiler/definitions/schema.md +9 -0
  32. package/src/skill/docs/compiler/targets/hono-api/using-the-api/errors.md +84 -2
  33. package/src/skill/docs/stack/auth/plugins/agent-auth.md +131 -0
  34. package/src/skill/docs/stack/realtime/partyserver-rooms.md +10 -2
@@ -3,7 +3,7 @@
3
3
  export const DOCS = {
4
4
  "changelog": {
5
5
  "title": "Changelog",
6
- "content": "# Changelog\n\nRelease notes for the Quickback compiler, CLI, and platform.\n\n---\n\n## v0.14.2 — May 7, 2026\n\n### Wrangler `[[migrations]]` no longer drops historical Durable Object lifecycle entries\n\nCloudflare requires the `[[migrations]]` list in `wrangler.toml` to be **append-only**: once a tag has been deployed, removing it on a subsequent compile causes the next deploy to fail with `Cannot apply <new|deleted|renamed|transferred>-class migration to class <X>` — CF replays the full migrations log on every push and notices the tag is gone.\n\nPre-fix, the compiler regenerated the `[[migrations]]` blocks from scratch on every compile, emitting only entries for the *current* `durableObjects` bindings. Any historical lifecycle events the user had hand-maintained — `deleted_classes`, `renamed_classes`, `transferred_classes` — were silently dropped and the deploy then broke. AttendVIP hit this first: a `qb-do-deleted-legacy-notes-2026-05-05` deletion entry got dropped, and the next deploy tried to re-apply `qb-do-Notepad`'s `new_sqlite_classes` against the existing class.\n\nThe fix adds a new config slot — `bindings.durableObjectMigrations` — for historical entries that survive recompiles. Declared entries are emitted FIRST in the generated `wrangler.toml`'s migrations list (preserving chronological order), then the auto-generated current-class creation entries follow, deduplicated by tag so an explicit user entry wins over the auto-emit.\n\n```ts\n// quickback.config.ts\nbindings: {\n durableObjects: [\n { name: 'NOTEPAD', className: 'Notepad', from: 'lib/Notepad' },\n ],\n durableObjectMigrations: [\n // Carry forward across recompiles — Cloudflare's migration list is append-only.\n {\n tag: 'qb-do-deleted-legacy-notes-2026-05-05',\n deletedClasses: ['LegacyNotes'],\n },\n ],\n}\n```\n\nAll four lifecycle shapes are supported: `newClasses` / `newSqliteClasses` (creations), `deletedClasses` (removals), `renamedClasses` (`{ from, to }` inline-table-array), `transferredClasses` (`{ from, from_script, to }` for moves between workers). The user-declared entry can also override the auto-emit by reusing the same tag — useful when a DO started life as KV-backed before SQLite-DOs existed.\n\nThis is a config-side fix, not a wrangler.toml-merging one — Quickback doesn't read your existing `wrangler.toml`. The discipline is the same as for any append-only log: declare lifecycle events as you make them. Auto-detection of removed classes from the schema diff is on the roadmap; for now the compiler trusts your declaration.\n\n7 new tests covering deletion, rename, transfer, multi-entry ordering, override-via-same-tag, no-history bit-identical output, and the historical-only-no-current-DOs edge case.\n\n---\n\n## v0.14.1 — May 7, 2026\n\n### Bulk action variants now appear in `openapi.json`\n\nRecord-based actions with `bulkVariant: true` (introduced in v0.14.0) generate a working `POST /<base>/batch/<actionName>` route at runtime, but the OpenAPI generator wasn't aware of them — so the bulk endpoints were invisible to typed-client codegen (`api-types.gen.ts`) and to MCP-driven agents discovering operations from the spec. AttendVIP's v0.14.0 rollout (seven actions with `bulkVariant: true`: `approve`, `checkIn`, `checkOut`, `setVisibility`, `cancelInvite`, `sendInvite`, `sessionApprove`) found this within hours of shipping.\n\nThe OpenAPI generator now emits each bulk variant as a sibling operation to its per-record action, with the documented request shape (`{ ids: string[], input, failFast? }`), correct 200 / 207 / 400 responses, an `x-bulk-variant: true` marker, and a separate `<resource><Action>Bulk` `operationId` so client codegen can distinguish single from bulk. The fix also threads `bulkVariant` through `getAllActions` so any other downstream consumer of the action registry sees the flag — previously the parser captured it but the spec-emit path silently dropped it.\n\nNo changes required in user code. Re-running `quickback compile` regenerates `openapi.json` with both routes per `bulkVariant: true` action; downstream `api-types.gen.ts` builds pick up the new operations on the next codegen run.\n\n### Cross-tenant \"my events\" pattern documented with a worked example\n\nThe v0.14.0 docs noted that relationship-roles do **not** solve cross-tenant aggregation (\"a guest's view of events across all tenants they were invited to\") and pointed at function-form access as the workaround, but didn't show what that looked like in practice. The access docs now carry a full standalone-action example for `GET /my-events` — the canonical attendee-dashboard pattern — including the two security guardrails (always filter by `ctx.userId`; the action takes responsibility for soft-delete and other invariants the firewall would otherwise apply). Standalone actions are already mandatorily audit-logged in the runtime, so the cross-tenant traversal is recorded automatically.\n\nSee [Access → Cross-tenant \"my events\" 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 roles\n\nQuickback's role system now supports a third kind of role beyond Better Auth org membership and the four pseudo-roles (`PUBLIC`/`AUTHENTICATED`/`USER`/`ADMIN`): **relationship-roles** that bind to a domain-table membership (\"user is a confirmed guest of this event\") rather than an org/admin gate. The original ask was a B2B event-management app where logged-in users who aren't team members but ARE confirmed guests of an event need to see that event's sessions, pages, and tracks — same data, different access lane. The old workarounds (function-form access, hand-written actions, `firewall: { exception: true }`) all gave up some combination of OpenAPI/MCP visibility, CRUD code generation, or tenant safety.\n\nDeclare the relationship once in `quickback.config.ts`, then reference it from `firewall:` or `access.roles:`:\n\n```ts\n// quickback.config.ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests', // relationship table\n subject: { column: 'userId', equals: 'ctx.userId' }, // caller side\n resource: { column: 'eventId' }, // resource side\n where: { status: 'confirmed' }, // optional row filter\n },\n },\n roles: {\n guest: { via: 'guestOf' },\n eventStaff: {\n or: [{ via: 'guestOf' }, { roles: ['admin', 'owner'] }],\n },\n },\n}\n\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' }, // ← row scoping\n],\nread: { access: { roles: ['admin', 'member', 'guest'] } }, // ← OR-composed\ncrud: {\n create: { access: { roles: ['admin', 'guest'] } }, // inline async lookup\n update: { access: { roles: ['admin'] } },\n}\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 `buildFirewallConditions(ctx)` is called inside the subquery so soft-delete and tenant scope on the relationship row are always honored — soft-deleting an `event_guests` row revokes access immediately. Anonymous callers fail closed (the subquery short-circuits to `WHERE 1 = 0` when `ctx.userId` is null). Cross-tenant grants are impossible because the resource's tenant filter sits as the outermost AND, never folded into a role OR. See [Firewall → Relationship-based scoping](/compiler/definitions/firewall#relationship-based-scoping-via) and [Access → Relationship-based authorization](/compiler/definitions/access#relationship-based-authorization).\n\nWhat works in v0.14.0:\n\n| Surface | Status |\n|---|---|\n| `firewall: [{ field, via }]` row-level scoping | Full |\n| `crud.<op>.access` `roles: ['guest']` (inline emission) | Full |\n| `read.access` and `read.views.*.access` | Full |\n| `masking.<f>.show` `roles: ['guest']` | Compile-refused (workaround pointer) |\n| `actions.<n>.access` `roles: ['guest']` | Compile-refused (workaround pointer) |\n\nThe runtime evaluator fails closed on relationship arms regardless of which surface you hit, so silent grants are impossible everywhere. The two refused surfaces have clear compile-time errors pointing to the working pattern (gate the row at the firewall layer with `via:`, gate the role at the access layer with BA roles).\n\nCompile-time refusals also catch: unknown `via:` reference, cycles in role composition (`a → b → a`), reserved role-name shadowing (auth-provider-derived only — `guest`/`speaker`/`attendee` are free; `admin`/`owner`/`member` are reserved when the BA org plugin is on), unknown relationship `from` table, resource missing the `resource.column`, relationship table with `firewall: { exception: true }` (would let cross-tenant grants slip through), `lowering: 'session'` (reserved for v2 — staleness/invalidation ergonomics not yet shipped), and `+` hierarchy on relationship-roles (terminal, like pseudo-roles).\n\nCross-tenant \"my events\" dashboards (a logged-in user wants `GET /my-events` returning events they're a guest of *across all tenants*) are **not** solved by relationship-roles — the tenant firewall stays the outermost AND. For that pattern, use a user-scoped firewall (`firewall: { owner: { column: 'userId' } }`) or function-form access on a dedicated route. Documented prominently in [access.mdx](/compiler/definitions/access#cross-tenant-my-events-dashboards-are-not-this) so users don't reach for relationship-roles first and get confused.\n\nRoadmap: `lowering: 'session'` ergonomics, inline relationship emission for `actions.access` (needs `relationshipBindings` design), async/batched mask functions for `masking.show`. The schema slots are reserved so v2 lands non-breaking.\n\n### Bulk variants of record-based actions\n\nRecord-based actions can now opt into an auto-generated bulk route alongside the per-record route. Set `bulkVariant: true` on a `defineAction({...})` and the compiler emits `POST /:resource/batch/{action}` that loops the same access + transition + execute pipeline over a `{ ids: [...], input, failFast? }` body. The original ask was an event-management UX where every domain bulk operation (approve N guests, rescind N invites, advance N applications) became a hand-written standalone action that re-implemented a per-record action's transition + execute logic in a `for` loop — `PATCH /:resource/batch` couldn't do it because state lives on a protected field, which is the right call for safety.\n\n```ts\n// features/applications/actions/advance.ts\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n bulkVariant: true, // ← opt-in\n transition: { field: \"status\", via: \"nextStatus\", fromTo: { /* ... */ } },\n async execute({ db, record, input, whereTransition }) {\n // exact same body as before — runs once per id\n },\n});\n```\n\nPer-record outcomes return as 207 Multi-Status with the same `{ success, errors, meta }` shape as `PATCH /batch`. Each id flows through the firewall fetch, the per-record `evaluateAccessReason` split (403 role / 409 record-precondition), the transition pre-check, and the same `whereTransition` factory the single-record route uses — so a stale-state record fails for that id alone, not the whole batch. `failFast: true` aborts on the first failure and (on Postgres / Supabase / Neon / libsql / sqlite drivers) wraps the loop in `db.transaction()` so prior writes roll back; D1 is documented as fail-fast-without-rollback because it has no `db.transaction`.\n\nCompile-time refusals: `bulkVariant: true` is rejected on standalone actions (no record context to loop over) and on actions that declare `unsafe` (cross-tenant per-record audit not yet wired). Method is forced to POST regardless of the action's `method` setting — the one-row-to-many-rows asymmetry makes inheriting GET/DELETE confusing. Max batch size is 100 ids per request, mirroring the CRUD batch endpoints. See [Actions → Bulk variant](/compiler/definitions/actions#bulk-variant).\n\n### Aggregations on read views\n\nRead views can now declare pre-computed metrics that surface on the response next to the row payload, without a custom standalone action. Every dashboard tile that previously turned into a standalone action just for \"count of X grouped by Y\" now lives in the same view config that drives the rows.\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\nResponse carries `aggregations: { ... }` alongside `data`:\n\n```json\n{\n \"data\": [/* paginated rows */],\n \"view\": \"pipeline\",\n \"pagination\": { \"count\": 50, \"page\": 1, \"pageSize\": 50, \"hasMore\": true },\n \"aggregations\": {\n \"totalApplications\": 173,\n \"byStatus\": { \"applied\": 102, \"screening\": 41, \"interview\": 18, \"offer\": 7, \"rejected\": 5 }\n }\n}\n```\n\nAggregations always run over the **same firewalled, filtered set** as the row query — pagination is intentionally ignored, so `?status=applied&limit=10` returns the 10 paged rows AND the count over every applied row. Supported `fn`s: `sum`, `avg`, `min`, `max`, `count` (with or without `field` — `COUNT(*)` vs `COUNT(field)`), `count_distinct`, and `groupBy` (returns `{ value: count }`, NULLs bucket as `\"(none)\"`).\n\nCompile-time validation: `field` must reference a real column; `sum`/`avg` require numeric column types; the same masking opt-out gate that governs `query.{filterable, sortable, searchable}` applies to aggregations (a `sum(salary)` leaks structure even when the row payload is redacted); aggregation names cannot collide with the reserved response fields `data`, `pagination`, `view`. No raw SQL `expr:` form in v1 — column references only. See [Views → Aggregations](/compiler/definitions/views#aggregations).\n\n---\n\n## v0.13.5 — May 6, 2026\n\n### Object-form `auth.plugins` no longer crashes the compiler\n\nThe documented object form for per-plugin config — `plugins: { oauthProvider: {...} }`, `plugins: { organization: { teams: { enabled: true } } }`, etc. (see [Better Auth Plugins → Custom configuration](/stack/auth/plugins#oauth-provider-mcp-ready)) — was rejected by the compiler with `plugins.includes is not a function`. `hasCliAuthRoutes` called `.includes()` directly on `auth.config.plugins` to detect `deviceAuthorization`, and `generateAuthFiles` flattened plugins to a string array before handing them to the better-auth generator, silently dropping every per-plugin user option on the way through.\n\nBoth paths now run through a shared resolver that preserves the user's input format (object in → object out, array in → array out) and only adds the compiler's auto-included plugins (`organization`, `admin`, `apiKey`, plus `bearer` when `deviceAuthorization` is present) as `true` entries that don't clobber user config. Per-plugin options like `oauthProvider: { scopes: [...] }`, `organization: { teams: { enabled: true } }`, and `deviceAuthorization: { verificationUri: '...' }` now reach the generated `auth.ts` as written.\n\nBetter Auth's `ac` / `roles` access-control objects (the result of `createAccessControl(...)`) still require a custom `auth.ts` override — they're live runtime values that can't survive the JSON config trip from CLI → compiler. A declarative escape hatch for that is on the roadmap.\n\n### `roles: [\"PUBLIC\"]` is allowed on writes and actions again\n\nv0.10.17 added a compile-time block that rejected `roles: [\"PUBLIC\"]` on `crud.create` / `crud.update` / `crud.delete` and on every action. The intent — \"anonymous mutations are usually a misconfiguration\" — collided with the legitimate use cases the rest of Quickback was built around: Gmail one-click RSVP confirms, public RSVP forms, magic-link redemption, List-Unsubscribe-Post handlers, webhook ingest, captcha-gated contact forms. None of those carry a session, so `AUTHENTICATED` 401s the caller before the handler can validate its own token, and the suggested escape hatch (\"custom action that does its own auth + `firewall: { exception: true }`\") was itself blocked by the same validator.\n\nThe block is removed. `PUBLIC` is the explicit, uppercase opt-in for unauthenticated access on every access node — reads, CRUD writes, views, and actions. The compiler trusts the marker; row-level safety comes from firewall, masking, and the action's own token validation. `PUBLIC` actions continue to receive **mandatory audit logging** (IP, input, result, timing) in the runtime regardless. `crud.create`/`update`/`delete` typically pair `roles: [\"PUBLIC\"]` with `firewall: { exception: true }` on the resource so the row predicate doesn't reject every unauthenticated caller.\n\n`USER` and `ADMIN` keep their compile-time prerequisites (firewall must scope by `userId` / admin plugin must be enabled).\n\n---\n\n## v0.12.0 — May 5, 2026\n\n### Per-room authorization for PartyServer rooms\n\n`bindings.durableObjects[].access` lets the compiler emit a path-scoped gate that runs the declared resource's existing firewall + `read.access` pipeline before the WebSocket upgrade — same pillars `GET /api/v1/<resource>/:id` enforces, zero hand-written auth code.\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 game 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, and lets the upgrade proceed otherwise. DOs without an `access` declaration keep the v0.11.1 catchall (just `ctx.authenticated`). Resource references are validated against feature names at compile time so typos break the build, not the first WebSocket upgrade. See [PartyServer Rooms → Per-room authorization via access](/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 now secure by default\n\nThe `/realtime/*` auto-mount shipped in v0.11.0 didn't gate WebSocket upgrades — anyone who knew a room ID (CUID2, hard to guess but not a security boundary) could open a connection. `authMiddleware` populated the request context but `partyserverMiddleware` doesn't 401 anonymous upgrades on its own.\n\nThe auto-mount now wraps `partyserverMiddleware` in an auth check: `401 Unauthorized` if the caller has no resolved auth context, otherwise the upgrade proceeds. The four auth mechanisms the rest of the worker honors (session cookie, JWT bearer, `x-api-key` header, `?api_key=` / `?key=` query) all unlock connections automatically.\n\nPer-room access (e.g., \"is this user a member of the org that owns this room?\") is still your `Server` class's responsibility in `onConnect` — the auto-mount only enforces \"are you authenticated at all.\" Hand-written mounts with custom `onBeforeConnect` continue to work unchanged; declare them at `/realtime/*` before the auto-mount runs to opt out of the default gate.\n\nNo code changes required — `quickback compile` regenerates the gated mount automatically. Single-tenant alphas weren't exploitable in practice (room IDs aren't logged or surfaced); multi-tenant projects should redeploy to pick this up.\n\n---\n\n## v0.11.0 — May 5, 2026\n\n### OAuth Provider plugin (MCP-ready)\n\nQuickback can now 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 it with `plugins: [\"oauthProvider\"]` in your auth config — the compiler auto-includes Better Auth's `jwt` plugin (the OAuth provider delegates access-token signing to it) 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 future MCP client (Cursor, Claude Desktop, claude.ai connectors, custom tooling) RFC 7591 dynamic client registration + the well-known discovery documents they need to bootstrap themselves. See [Auth Plugins → OAuth Provider](/stack/auth/plugins#oauth-provider-mcp-ready).\n\n### API key auth via query parameter\n\nThe auth middleware now accepts API keys as `?api_key=...` or `?key=...` query parameters in addition to the `x-api-key` header. The header takes precedence when both are sent. This unblocks clients that can't inject custom headers — most notably claude.ai's MCP connector, which previously returned zero tools because every list/call attempt was unauthenticated.\n\nThe query-param form lands in access logs and `Referer` headers; prefer the header whenever the client supports it. See [Auth Plugins → API Keys](/stack/auth/plugins#api-keys).\n\n### PartyServer rooms + realtime URL split (breaking)\n\nThe realtime URL space is reorganized so the names match what each primitive does:\n\n- **`/realtime/v1/*` → `/broadcast/v1/*`** — the existing org-wide Broadcaster (Postgres-changes fan-out, ws-ticket auth) moves to its semantically accurate prefix. Same code, same behavior, just a different mount point.\n- **`/realtime/<binding>/<room-id>` is the new mount for [PartyServer](/stack/realtime/partyserver-rooms) rooms** — bidirectional, per-room (per-document) Durable Objects with presence and lifecycle hooks. Auto-mounted via `hono-party` whenever a project declares any in-worker DO via `bindings.durableObjects[].from`. Use these for collaborative editing, live cursors, and per-room state.\n\n**Breaking changes** — recompile + redeploy required:\n\n- The `REALTIME_URL` runtime env var is renamed to `BROADCAST_URL` (used by the org member-update broadcast hook in separate-mode realtime). If you set this via `wrangler secret put REALTIME_URL`, re-set it as `BROADCAST_URL`.\n- The auth-ui SPA helpers `getRealtimeWsUrl()` / `getRealtimeTicketUrl()` are renamed to `getBroadcastWsUrl()` / `getBroadcastTicketUrl()`. The `appConfig.routes.api.realtime` field is renamed to `appConfig.routes.api.broadcast`.\n- WebSocket subscribers that hardcoded `/realtime/v1/websocket` or `/realtime/v1/ws-ticket` need to be updated to `/broadcast/v1/...`. The bundled CMS and Account SPAs handle this automatically; custom clients need a one-line change.\n\n**Pre-installed deps in the compiler image:** `partyserver`, `partysocket`, and `hono-party` are now cached in `/deps/node_modules` so opt-in collab projects compile without an extra `npm install` step. `Y-PartyServer` (Yjs CRDT support) stays opt-in.\n\n**Recipe:** see the new [PartyServer Rooms](/stack/realtime/partyserver-rooms) doc page and the `examples/recruitment` interview-room demo for an end-to-end example with presence and live notes.\n\n---\n\n## v0.10.20 — May 4, 2026\n\n### In-worker Durable Objects via `bindings.durableObjects[].from`\n\n`bindings.durableObjects` previously only emitted the binding declaration — useful for cross-worker DOs (`scriptName: \"other-worker\"`), but not enough for app-owned classes that live in this worker's source. Authors had to hand-edit `src/index.ts` (to add `export { ItemStream } from './...'`) and `wrangler.toml` (to add the `[[migrations]]` block) on every compile.\n\nAdding `from` flips the entry into in-worker mode and the compiler does both:\n\n```ts\ndurableObjects: [\n {\n name: \"ITEM_STREAM\",\n className: \"ItemStream\",\n from: \"features/loops/lib/ItemStream\", // module path under src/\n },\n]\n```\n\nGenerates:\n- `src/index.ts`: `export { ItemStream } from './features/loops/lib/ItemStream';` — wrangler resolves the binding by class export.\n- `wrangler.toml`: a `[[migrations]]` block with `tag = \"qb-do-ItemStream\"` and `new_sqlite_classes = [\"ItemStream\"]`.\n- `CloudflareBindings`: `ITEM_STREAM: DurableObjectNamespace` so `c.env.ITEM_STREAM.idFromName(...)` typechecks.\n\nWhere the class file lives: in-worker DO classes go under `quickback/lib/` or `quickback/features/<feature>/lib/` — both copy verbatim into the generated `src/` tree on every compile (the rest of `src/` is wiped). The `from` value is the resulting `src/`-relative path with no `./` prefix and no `.ts` suffix.\n\n`from` and `scriptName` are mutually exclusive — the compiler rejects entries that set both. Cross-worker entries (`scriptName` set) skip the re-export and the migration block; the exporting worker owns its own migration table.\n\n`migrationTag` (default `qb-do-${className}`) is stable across regenerations and **must never be removed or renamed once deployed** — wrangler tracks applied tags and will reject deploys that try to walk them back. `useSqlite` defaults to `true`; set to `false` for legacy KV-backed DOs.\n\nSee [Bindings → Durable Objects](/compiler/config/bindings#durableobjects) for the full reference.\n\n---\n\n## v0.10.19 — May 4, 2026\n\n### Fix: bundled-SPA auth survives `wrangler dev` on custom_domain projects\n\n`wrangler dev` rewrites the configured `custom_domain` host in **every** response header value (Location, Content-Security-Policy, X-…) to the local hostname, with a case-sensitive substring matcher. That mangles the CSP `connect-src` for projects with `domain: \"api.example.com\"` + bundled CMS / Account SPAs:\n\n```\n# Compiled (correct)\nconnect-src 'self' https://api.example.com …\n\n# Served by wrangler dev (mangled)\nconnect-src 'self' https://localhost:8787 …\n```\n\nResult: the bundled SPA's hardcoded `VITE_QUICKBACK_API_URL` fetches get blocked in dev because the CSP only allows localhost. Reported by Loop on the 0.10.18 thread; verified end-to-end with a minimal `wrangler@4.85.0 dev --local` repro.\n\nThe compiler now emits the SPA-baked-origin literal in `connect-src` with the host's first letter capitalised (`https://Api.example.com`). CSP host-source matching is ASCII case-insensitive per CSP3, so browsers accept it for connections to `https://api.example.com`; wrangler's case-sensitive matcher misses it. The case-shift is applied at compile time and only to URLs whose host matches the configured `custom_domain` — other origins (localhost, third-party hosts) are unchanged.\n\n`TRUSTED_ORIGINS` keeps its lowercase prod entries: it's consumed by the CORS `isTrustedOrigin` check via `Array.includes()` against the browser-supplied Origin header (always lowercase). The CSP fix only needs to land on the SPA-baked literal — that's the entry the SPA's hardcoded fetch needs covered.\n\nIf wrangler ships a fix for the response-header rewrite, the case-shifted source remains a valid CSP entry that browsers match identically — no follow-up needed in user code.\n\n**Action required:** none. Recompile (`quickback compile`) to pick up the fix.\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` flag emitted into the generated `wrangler.toml`. Useful for \"share prod auth in dev, keep feature writes sandboxed\":\n\n```ts\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n splitDatabases: true,\n experimentalRemote: {\n auth: true, // wrangler dev reads/writes deployed AUTH_DB\n features: false, // (default) features stays local\n audit: false,\n webhooks: false,\n files: false,\n },\n }),\n}\n```\n\nKeys are logical binding names — `auth` flips the flag on the `AUTH_DB` binding, `features` flips it on `DB` (or the legacy single-DB binding), `audit` / `webhooks` / `files` follow the same pattern. Off by default; only enable for databases you intend to share.\n\n### Google OAuth + signup ToS\n\nThe Account SPA now wires Google OAuth end-to-end when `auth.providers.auth.config.socialProviders.google.enabled: true`. The compiler bakes the right `VITE_ENABLE_GOOGLE_OAUTH` flag into the SPA's `.env` so the social-login button renders only when the provider is enabled — no more dead buttons.\n\nSignup flow gains a Terms-of-Service checkbox gate (configurable via the Account SPA's branding config).\n\n### CLI compile auth gate + device-auth redirect fix\n\n- `quickback compile` now requires authentication for cloud-compiler runs (closes the unauth public-compile path).\n- The device-flow `/cli/authorize` page was sending `?returnTo=` to login, but `signup.tsx` and the `_authenticated` middleware only read `?redirect=` — so a user who clicked \"Create one\" from `/login` lost the return URL. Standardized on `?redirect=` everywhere.\n\n### Skill restructure (Claude Code skill)\n\nThe bundled Claude Code skill was reorganized for clarity:\n\n- `SKILL.md` is now a thin orientation pointer, not a 600-line dump\n- Reference docs split into `Compiler` and `Stack` sections\n- Docs bundled as **files** the model navigates with `Read` / `Glob` rather than via `quickback docs <topic>` shell calls — same content, fewer tool calls per lookup\n- Tightened against audit gaps surfaced by red-team review\n\nRun `quickback claude install` to pick up the new skill layout.\n\n---\n\n## v0.10.17 — May 2, 2026\n\n### Security fix: CSP auto-config no longer widens `default-src`\n\nWhen 0.10.15's auto-config was asked to add a value to a directive the user hadn't declared (e.g. `https://fonts.googleapis.com` → `style-src` when only `default-src` was set), it incorrectly pushed the value into `default-src` itself. Because CSP3 fall-back semantics make `default-src` the fallback for `script-src`, `img-src`, `media-src`, and others, this widened the attack surface to every directive that fell back to it — a `style-src`-only host became reachable from `script-src`.\n\n0.10.17 fixes the logic: missing target directives are now **scaffolded** with the user's `default-src` values as baseline, then extended with the auto-config addition. `default-src` stays clean. The new directive (e.g. `style-src`) covers exactly the styles the SPA needs and nothing else.\n\nBefore (0.10.16):\n```\ndefault-src 'self' https://fonts.googleapis.com https://fonts.gstatic.com @trustedOrigins https://api.example.com\n```\n\nAfter (0.10.17):\n```\ndefault-src 'self'\nstyle-src 'self' 'unsafe-inline' https://fonts.googleapis.com\nfont-src 'self' https://fonts.gstatic.com\nconnect-src 'self' @trustedOrigins https://api.example.com\n```\n\n**Action required:** recompile (`quickback compile`) to regenerate the security middleware with the corrected scaffolding. Configs that already declared each `*-src` directive explicitly were unaffected by the bug — the regression only surfaced when users wrote `defaultSrc: ['@self']` and let auto-config fill in the rest.\n\nThe user-side workaround from 0.10.16 (declaring each directive with `['@self']` to force scaffold) is no longer needed in 0.10.17 — the compiler does the right thing automatically.\n\n---\n\n## v0.10.16 — May 2, 2026\n\n### CSP auto-config now covers SPA-baked-in API origins\n\nWhen the bundled CMS or Account SPA is enabled, the compiler already inlines the API URL into the SPA bundle as a string literal at build time (`VITE_QUICKBACK_API_URL=https://${unifiedDomain}`). That hardcoded URL is what the SPA actually fetches — regardless of which origin is currently serving the page. CSP `connect-src` must allow it explicitly.\n\n0.10.16's auto-config picks up every domain the compiler already knows about — `config.domain`, the inferred `quickback.{baseDomain}`, `cms.domain`, `account.domain`, the admin domain — and adds `https://${each}` to `connectSrc` whenever a bundled SPA is enabled.\n\nThe motivating case: running the SPA on `localhost:5173` while it's still baked against `https://quickback.your-app.com`. Pre-0.10.16 the localhost CSP's `'self'` blocked the prod URL; users were patching it manually. Now it just works.\n\n```\n[security] auto-added https://quickback.loop.kardoe.com to csp.connectSrc — account: true → bundled Account SPA → SPA bundle hardcodes https://quickback.loop.kardoe.com as VITE_QUICKBACK_API_URL / etc.\n```\n\n`@trustedOrigins` (the CORS allowlist) is unchanged — it still gets added independently. The two cover different things: `@trustedOrigins` permits CORS-allowed sibling subdomains; the new SPA-baked addition permits the exact URL the SPA's compiled bundle hardcodes.\n\nCombined with 0.10.15's bundled-SPA defaults, most projects can now 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 styleSrc font hosts, fontSrc gstatic, connectSrc trusted origins, and connectSrc SPA-baked URLs.\n\n---\n\n## v0.10.15 — May 2, 2026\n\n### CSP auto-config — bundled-SPA origins added automatically\n\nWhen `security.csp` is set, the compiler now widens directives **additively** based on the project's enabled features. The four rules:\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\nAnything you already wrote stays — auto-config never removes or overrides. Every applied addition prints to stderr at compile so the magic is visible:\n\n```\n[security] auto-added 'unsafe-inline' to csp.styleSrc — account: true → bundled Account SPA → inline style attributes from Tailwind / TanStack Router\n[security] auto-added @trustedOrigins to csp.connectSrc — CORS-trusted origins must be reachable from XHR/fetch (matches cors() allowlist)\n```\n\nThe recipe in [the security docs](/compiler/config/security#example-paste-in-csp-for-a-quickback-spa-project) becomes ~5 lines shorter — most projects no longer need to list `fonts.googleapis.com` / `fonts.gstatic.com` / `@trustedOrigins` themselves. **Loop's CSP shrinks dramatically** after recompiling against this version.\n\n**Opt-out:** `security: { cspAutoConfig: false, csp: { ... } }` for projects fronted by a CDN that injects its own CSP, or teams that want strict from-scratch control.\n\n**Smart fallback:** if you set `defaultSrc` but omit the target directive (e.g. `defaultSrc: ['@self']` and nothing for `connectSrc`), the addition lands in `defaultSrc` rather than creating a sibling directive — CSP fall-back semantics mean a sibling would *narrow* your intent, so we preserve the broader fallback.\n\n### Troubleshooting table for CSP violations\n\nThe security docs page now includes a [Troubleshooting CSP violations](/compiler/config/security#troubleshooting-csp-violations) table mapping browser console errors back to the directive that needs widening. Useful when auto-config is disabled or the project has a non-bundled SPA hitting third-party origins.\n\n### Out of scope (deferred)\n\n- **Per-request CSP nonces** (`@nonce` sentinel implementation) — Phase 2 / 0.10.16. Sentinel still errors at compile in 0.10.15.\n- **`revocationCheck: 'kv'` for `auth.jwt`** — schema accepts it, runtime still errors at compile. Slipped from 0.10.15 to 0.10.16.\n- **Public R2 host auto-add to `imgSrc`** — most R2 access today goes through the worker so the SPA fetches from `'@self'`. Will revisit once we have a clean way to discover public-bucket hosts at compile.\n\n---\n\n## v0.10.14 — May 1, 2026\n\n### `auth.jwt` — JWT bearer-token fast-path config\n\nQuickback's bearer-token JWT (the one minted by the auth middleware and consumed by the fast-path on every subsequent request) is now configurable. The most-tuned knob is `expiresIn` — drop it to bound the post-revocation replay window without affecting browser SPAs, which auto-refresh via `set-auth-token` on every authed call:\n\n```ts\nauth: {\n jwt: {\n expiresIn: 30, // 30s post-revocation replay window\n issuer: 'my-api', // iss claim (verified on the way back in)\n audience: 'partner-svc', // aud claim\n secretEnv: 'CUSTOM_JWT_SECRET', // override BETTER_AUTH_SECRET if you need the JWT secret rotated independently\n },\n}\n```\n\n`revocationCheck: 'kv'` (KV-denylist consult on every fast-path verify, ~5-15ms edge-cached, no D1 hit) is reserved in the schema today but **deferred to 0.10.15** — setting it errors at compile so the migration path is explicit. `'none'` (today's behaviour, 0 cost, replay bound by TTL) stays the default.\n\nSee [the docs page](/compiler/config/auth) for the full knob list and tuning recommendations.\n\n### MCP admin endpoints hidden from non-admin `tools/list`\n\nBetter Auth admin endpoints (`/admin/list-users`, `/admin/ban-user`, `/admin/impersonate-user`, etc. — 9 in total) now carry `x-access: { userRole: ['admin'] }` in the generated OpenAPI spec, which means the MCP server's existing access-filter automatically drops them from `tools/list` for callers without an admin token. Anonymous and member-role callers no longer see admin tooling enumerated through MCP; admin endpoints still exist on the HTTP surface (Better Auth gates them server-side regardless).\n\n### Declarative `security` config block\n\nEvery security response-header (`Content-Security-Policy`, `Cross-Origin-Opener-Policy`, `Cross-Origin-Embedder-Policy`, `Cross-Origin-Resource-Policy`, `X-Frame-Options`, `Strict-Transport-Security`, `Referrer-Policy`, `Permissions-Policy`) is now configurable from `quickback.config.ts`. Loop's `postcompile-patch.mjs` (which re-injected a fuller CSP and COOP after every `quickback compile`) can now be deleted in favour of:\n\n```ts\nsecurity: {\n csp: {\n defaultSrc: ['@self'],\n scriptSrc: ['@self'],\n styleSrc: ['@self', '@unsafe-inline'],\n frameAncestors: ['@none'],\n objectSrc: ['@none'],\n upgradeInsecureRequests: true,\n },\n coop: 'same-origin',\n}\n```\n\n`@`-prefixed sentinels (`@self`, `@none`, `@unsafe-inline`, `@unsafe-eval`, `@trustedOrigins`, `@nonce`) save users from awkward `\"'self'\"` quoting and let `@trustedOrigins` resolve to the same allowlist `cors()` uses. Unknown sentinels throw at compile rather than silently stringify into the wire CSP.\n\nThe compiler runs lint rules over the resolved config — errors for `@nonce` (deferred to 0.10.15), `@unsafe-inline + @nonce` (silently broken), and sentinel-only directives that would resolve to nothing at runtime; warnings for `@unsafe-inline` in `script-src`, wildcard sources, missing `default-src`, HSTS preload-list misconfiguration, etc.\n\nDefaults preserve 0.10.13 behaviour byte-for-byte — adding the block without setting any field is a no-op.\n\nSee [the docs page](/compiler/config/security) for the full reference.\n\n### HSTS no longer pins `localhost` to HTTPS\n\nThe generated middleware now skips `Strict-Transport-Security` when the request hostname is `localhost`, `127.0.0.1`, or `*.localhost`. Without this gate, `wrangler dev` would pin the developer's browser to HTTPS for `max-age` seconds — observable across every project on that machine since HSTS keys on hostname, not port. Affects every project running locally.\n\n### Out of scope (deferred)\n\n- **Per-request CSP nonces** — Phase 2 / 0.10.15. Sentinel exists at config-validation level so users can author their final CSP today knowing it'll start working when nonces ship.\n- **Asset-hash CSP** for inline `<style>` and `<script>` blocks emitted by the bundled SPAs — Phase 3.\n- **Per-route CSP overrides** (e.g. one looser policy for `/admin`) — single global CSP for now.\n\n---\n\n## v0.10.13 — May 1, 2026\n\n### Clickjacking protection on every generated Worker\n\nEvery Worker now emits two clickjacking-defence headers on every\nresponse:\n\n- `Content-Security-Policy: frame-ancestors 'self' <TRUSTED_ORIGINS…>`\n- `X-Frame-Options: SAMEORIGIN`\n\nThe CSP allowlist is sourced from the same `TRUSTED_ORIGINS` constant\nthat gates CORS, so users configure their domains in one place\n(`auth.trustedOrigins` / `auth.trustedOriginDefaults` in\n`quickback.config.ts`) and both CORS and frame-ancestors stay in\nlockstep. `'self'` is always allowed so an app's own SPAs can frame\ntheir own routes (e.g. an account login popover hosted on the same\norigin).\n\nModern browsers obey `frame-ancestors` and ignore `X-Frame-Options`\nwhen both are set; the legacy header is included for clients that\ndon't speak CSP3. The CSP intentionally only sets `frame-ancestors` —\nadding `script-src` / `default-src` would need a much wider audit\nacross SPA assets, inline scripts, and third-party embeds, so that's\nleft as a follow-up.\n\nRecompile (`quickback compile`) and redeploy to pick this up — no\nconfig change needed unless you want to allow extra cross-origin\niframe embeds, in which case add them to `auth.trustedOrigins`.\n\n---\n\n## v0.10.12 — May 1, 2026\n\n### Bundled-docs sync for the MCP recon fix\n\nPatch release that re-bundles the CLI's offline docs (consulted by the\nClaude Code skill, Cursor rules, and other AI assistants) so they\nreflect the corrected `tools/list` access-filter behavior and CORS\nposture shipped in v0.10.11. The `compiler/config/agents.mdx` page\nitself was already corrected on the docs site immediately after the\n0.10.11 release; this bump propagates that text into the bundle inside\n`@quickback-dev/cli`.\n\nNo runtime or compiler behavior change — re-running `quickback compile`\nagainst this version produces the same output as v0.10.11.\n\n---\n\n## v0.10.11 — May 1, 2026\n\n### MCP `tools/list` is now access-filtered + recon-tightened\n\nThe generated MCP-over-HTTP server (`src/routes/mcp.ts`) had three holes\nthat turned a standard pentest into trivial recon:\n\n1. `tools/list` returned the entire tool catalogue to anyone — including\n admin-only endpoints — without checking auth or roles. Tool\n descriptions also leaked sentences like `[UNSAFE] bypasses tenant\n scoping and requires elevated access` verbatim.\n2. The endpoint set `Access-Control-Allow-Origin: *` so any origin could\n pull the catalogue from a browser.\n3. Unauthenticated `GET /mcp` enumerated every tool name in its\n discovery payload.\n\nFix:\n\n- Each tool now carries sanitised access metadata (`_access` covering\n `roles` / `userRole` / `or` / `and`, plus `_public` for `PUBLIC`\n pseudo-role or empty `security`). `tools/list` filters against the\n caller's `ctx` — unauth callers see only `_public` tools, authed\n callers see only role-gated tools they pass. Record predicates and\n function-form access (opaque at list time) are dropped.\n- Wildcard CORS removed entirely. The parent app's `cors()` middleware\n (origin allowlist via `TRUSTED_ORIGINS` + `BETTER_AUTH_URL`) now\n applies uniformly to `/mcp`, same as every other route.\n- `[UNSAFE] ... bypasses tenant scoping ...` flavour text is gone.\n `annotations.destructiveHint` and `_unsafe` remain — those are the\n spec-correct signals for clients to warn users.\n- Unauthenticated `GET /mcp` no longer lists tool names. Inventory is\n only available via the access-filtered `tools/list`.\n\nThis filter is recon-mitigation, not a security boundary: `tools/call`\nstill re-enters the Hono app and runs every middleware (auth, firewall,\naccess, guards, masking), so hiding a tool from list never weakens the\nunderlying gate.\n\nKnown follow-up: Better Auth admin endpoints (`ban-user`, `create-user`,\n`impersonate-user`, etc.) don't yet emit `x-access` in the OpenAPI spec,\nso any logged-in user still sees them in `tools/list` (the actual call\nis still gated by the admin plugin). Tracked separately.\n\n---\n\n## v0.10.10 — April 29, 2026\n\n### Reject reserved keys inside `access.record` at compile time\n\n`access.record` is a flat field map evaluated as implicit AND between\nentries — keys must be column names. Putting `and: [...]` (or `or` /\n`roles` / `userRole`) inside `record` was a real-world footgun: the\nruntime treated the literal string `\"and\"` as a column lookup, the\npredicate failed on every row, and the caller got a silent `403` /\nempty list with nothing pointing at the misuse. The TypeScript type\ncouldn't catch this — `RecordConditions` is an open-ended index\nsignature, so any key parses.\n\nThe compiler now walks every access node attached to a resource (CRUD\nops, `read.access`, view access, masking `show` / `query`, action\naccess) and throws a clear migration error when `record` contains a\nreserved key:\n\n- `and` / `or` inside `record` → use the top-level `and` / `or`\n sibling: `{ and: [{ record: { ... } }, { record: { ... } }] }`\n- `roles` / `userRole` inside `record` → put them at the access node\n alongside `record`: `{ roles: [...], record: { ... } }`\n\nThe error names the exact origin (`crud.update.access`,\n`actions.focus.access.or[1]`, etc.) so the fix lands in the right place.\n\n---\n\n## v0.10.9 — April 29, 2026\n\n### Role hierarchy now expands in record-based action access\n\n`auth.roleHierarchy: ['member', 'admin', 'owner']` plus\n`access: { roles: ['member+'] }` on a record-based action used to\nsilently 403 valid callers. The standalone-action route generator\ninlined the expanded role list as a JSON literal, but the\nrecord-based generator read the access config back through the\nruntime `actions['name'].access` import — the user's source, where\nthe unexpanded `'member+'` shorthand still lived. The runtime did\nliteral string matching against `ctx.roles`, so an `owner` calling\nthe action got `['member+'] !== 'owner'` and was rejected.\n\nFixed: record-based action routes now inline the expanded list the\nsame way standalone routes do. `input` and `execute` still flow\nthrough the runtime import (closures aren't serializable); only the\naccess config is lifted to a JSON literal so the compile-time\nexpansion actually reaches the matcher.\n\nA regression test (`role-hierarchy-action-routes.test.ts`) locks the\nbehavior in — it asserts that `member+` never reaches the route\noutput and that the access config is no longer read from\n`actions[name].access` at runtime.\n\n---\n\n## v0.10.8 — April 29, 2026\n\n### Audit support on postgres targets, plus a generated-API quality pass\n\n**Audit on PG.** Until this release, `audit_events` only existed on cloudflare-d1 — projects on Neon (or any postgres target) silently skipped audit logging on `unsafe:` and `PUBLIC`-role actions, and hard delete was hard-blocked. Postgres has no equivalent of D1's separate-database binding model, but it has native schemas — so the audit table now lives in a dedicated `audit` schema in the same database as features (`drizzle.pgSchema('audit')`). The `hasSecurityAudit` gate accepts D1 OR any PG dialect; the `auditDatabaseId` requirement only fires for D1 (which still uses the separate-binding model). The recruitment example wires `auditDatabaseId` so the recompile path stays green.\n\n**`auditDatabaseId` is now a compile-time requirement** (D1 only). Previously, projects with unsafe/PUBLIC actions but no audit id silently produced a `database_id = \"local-audit\"` placeholder in production `wrangler.toml`; Cloudflare's worker upload step then rejected it with code 10021 *after* assets and migrations had already run. The compile-time error names the exact `wrangler d1 create <project>-audit` command and the `auditDatabaseId` config key where the returned id goes.\n\n### Five fixes from a Loop integration ticket pass\n\n**Action input → OpenAPI / MCP.** `defineAction({ input: z.object({...}) })` schemas now flow into `requestBody` on the OpenAPI operation and `inputSchema.properties` / `_bodyFields` on the MCP tool list. Simple `z.object` shapes are extracted at compile time; for discriminated unions, refinements, recursive schemas, and bare-identifier references (`input: createPersonInput`), the compiler runs your action file through Zod 4's native `z.toJSONSchema()` during compilation — full-fidelity output with no static translator to maintain. Pre-fix, every action came out as a no-arg endpoint, which gutted typed SDK generation and made MCP useless for actions that take parameters.\n\n**OpenAPI fidelity.** Three surgical fixes that strict validators (zod, openapi-typescript, openapi-fetch) had been complaining about:\n- Response schemas now emit `required[]` for every non-nullable column, so generated SDKs treat them as guaranteed-present rather than optional.\n- `text(_, { enum: [...] })` columns emit as closed `{ type: \"string\", enum: [...] }`, narrowing to literal unions.\n- `id` only claims `format: \"uuid\"` when the project's `generateId` actually produces UUIDs. cuid2 / prefixed / nanoid / serial generators get plain `{ type: \"string\" }` — strict validators stop rejecting responses against their own spec.\n\n**Mask auto-detector now checks the column exists.** The auto-mask predicate used to be unconditionally `show: { or: 'owner', roles: ['admin'] }` — including for tables with no owner column at all (no `userId` / `ownerId` and no `q.scope('owner')`). The generated mask function would reference a non-existent column and fail under TypeScript checks. The auto-detector now verifies the resolved owner column exists in the parsed schema before emitting the `or` clause; when it doesn't, the rule falls back to roles-only and the compiler emits a warning so the behavior is transparent.\n\n**Error code consistency.** The generated CRUD layer was emitting raw codes (`'UNAUTHORIZED'`, `'NOT_NULL_VIOLATION'`, `'UNIQUE_VIOLATION'`, `'INSERT_FAILED'`, `'UPDATE_FAILED'`) that were never in the `QuickbackErrorCode` enum, so consumers couldn't switch exhaustively on `code`. New `database` layer + `DB_NOT_NULL_VIOLATION` / `DB_UNIQUE_VIOLATION` / `DB_INSERT_FAILED` / `DB_UPDATE_FAILED` / `NOT_FOUND` codes are now in the enum, the routes use `AuthErrors.missing()` / `DatabaseErrors.*()` helpers throughout, and the OpenAPI `Error` component emits `code` as a closed enum sourced from the canonical `QUICKBACK_ERROR_CODES` list. Generated SDKs can now `switch` on `code` without a default branch swallowing unknown values. See [API errors](/compiler/targets/hono-api/using-the-api/errors#database).\n\n**Dropped dead `auditFields` preamble from action route generators.** The audit wrapper's `Proxy` already hard-stamps `createdAt` / `createdBy` / `modifiedAt` / `modifiedBy` on every INSERT and `modifiedAt` / `modifiedBy` on every UPDATE — the `auditFields` const the route preamble built was never read. Dropped from `standalone.ts` / `record-based.ts` and from the `ActionExecutorParams` JSDoc. Migrated 7 example handlers (drop `modifiedAt: auditFields!.modifiedAt` from `.set` payloads — the wrapper handles it). Note: `.onConflictDoUpdate({ set })` is *not* intercepted by the wrapper, so `upsertBatch`-style handlers keep an explicit `modifiedAt: now`.\n\n---\n\n## One file per action: greenfield action authoring\n\nAction authoring collapses to a single shape. Each action is its own file under `<feature>/actions/<name>.ts` using `defineAction({...})`. 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` — types `record`, `input`, and audit fields without manual annotations. The directory says what `:id` mounts to; the imports say what the body reads or writes.\n\n**Discovery rules:**\n- `actions/<name>.ts` binds to the feature's primary table (the `<feature>.ts` file at the feature root).\n- `actions/<table>/<name>.ts` binds to the sibling table file `<table>.ts` — for multi-table features.\n- Setting `path:` makes the action standalone (custom URL, no record fetch, no firewall preload).\n- Tableless features (no top-level `*.ts` files) require every action to be standalone.\n- Action names are unique per `(bindTable, name)` pair — sibling-bound actions on different tables may share a verb (e.g. `actions/episodes/publish.ts` + `actions/shows/publish.ts` mount at `/episodes/:id/publish` and `/shows/:id/publish` and don't collide). Standalone actions are unique per `(method, path)`.\n- Files under `<feature>/lib/` are copied verbatim for feature-local helpers; `quickback/lib/` is exposed via the `~/lib/*` alias for cross-feature shared code (with a one-way import rule enforced at compile time).\n\n**Retired** (rejected at load time with migration guidance):\n\n- `actions.ts` (bundled multi-action file)\n- `_feature.ts` (shared preamble + tableless actions)\n- `handlers/` directory + `handler:` string ref\n- `defineActions(table, {…})` and `defineActions(null, {…})`\n- `export default { actions: {…} }`\n- Colocated `defineActions` inside table files\n- `standalone: true` flag (presence of `path:` is the new signal)\n- `*-actions.ts` / `*.actions.ts` filename patterns\n\nThe phantom-`unsafe` regex bug that flattened nested `unsafe: { … }` blocks into a fake top-level action is gone — the parser now reads action files as real TS modules with real imports, so type inference, jump-to-definition, and rename refactoring all work end-to-end.\n\nThe CLI loader rejects retired primitives at load time with batched migration errors. Existing projects need to be migrated by hand to the new shape before recompiling.\n\nSee the [Actions docs](/compiler/definitions/actions) for the full reference.\n\n---\n\n## Multi-table actions per feature\n\nFeatures used to support exactly one `defineActions(table, …)` call via `actions.ts`, which forced unnatural feature splits whenever multiple tables in the same feature needed actions (a podcast feature with `episodes`, `shows`, `seasons`, `collections`, etc.). One feature directory can now own actions on multiple tables across three discovery modes:\n\n- **Colocated** (canonical) — `<table>.ts` containing both `defineTable` and `defineActions(<table>, …)`. One file per entity. Default for new features.\n- **`actions.ts`** (existing) — single primary-table actions file at feature root. Unchanged behaviour.\n- **`actions/<table>.ts`** — per-table action files for teams that want strict schema/behavior separation or need to break an import cycle.\n\nPlus the universal `_feature.ts` slot (at feature root) for **non-table-bound feature-level actions** (`export default { actions: { … } }` shape) and **shared Zod schemas** that get prepended once to the merged actions module so every sibling action sees them. Allowed in any of the three modes — orthogonal to table binding.\n\nThe decision flowchart: *one table with actions → colocate. Multiple tables with actions → colocate each. Hit a cycle or want strict separation → `actions/<table>.ts`. Want schema/actions split for a single-table feature → `actions.ts`. Non-table actions → always `_feature.ts`.*\n\nConflicts are batched and printed once before the compiler aborts — no \"fix one, recompile, fix the next\" loop. The CLI hard-errors when a feature mixes `actions.ts` with table-bound mode, when the same table has its `defineActions` declared in two places, when an `actions/<x>.ts` first-arg doesn't match the basename, or when `_feature.ts` contains `defineActions(table, …)`. Legacy `*-actions.ts` / `*.actions.ts` filenames in a feature dir trigger a soft warning naming the offending paths.\n\nWithin the legacy bundled `actions.ts` DSL, action names had to be unique within a feature — the runtime module merged every source into one keyspace, so colliding `publish` actions on `episodes` and `shows` would have silently overwritten each other. The retired `actions.ts` shape is no longer accepted, so this constraint is gone: the current one-file-per-action layout keys uniqueness per `(bindTable, name)` pair, and the codegen aggregator mangles the JS map key per bind-table while keeping the URL segment bare. Sibling-bound `actions/episodes/publish.ts` and `actions/shows/publish.ts` mount at `/episodes/:id/publish` and `/shows/:id/publish` and compile cleanly.\n\nInline `execute:` bodies must be arrow functions (`execute: async (ctx) => { … }`). `async function` and plain `function` shapes were silently misparsed by the route emitter — they now hard-error at parse time pointing at the canonical arrow form, with a suggestion to use `handler:` for callers who genuinely need a named function declaration.\n\n`handlers/` walks recursively now — `handlers/<table>/<action>.ts` is the canonical layout. A new `lib/` directory under each feature gets copied verbatim into the output for feature-local helpers.\n\nMigration: existing `actions.ts` projects compile bit-identically — the legacy single-table path is unchanged. Legacy `*-actions.ts` filenames produce a soft warning and silently aren't picked up; rename to `<table>.ts` (colocated), `actions/<table>.ts`, or single `actions.ts`.\n\n---\n\n## Firewall: named-scope shape restored, auto-detection synonyms widened\n\nThe named-scope firewall shape (`firewall: { organization: { column: 'tenant_id' } }`) is back as a co-equal user-facing input alongside the predicate array. DSL v2 step 8 had walled it off, but the internal architecture still kept named-scope around for the route + scoped-db generators — so re-accepting it at the input boundary is a thin coercion layer, not an architectural change.\n\n```typescript\n// All three are now valid; all compile to the same predicate array internally.\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 expanded.** When `firewall:` is omitted entirely, the compiler scans the schema for an isolation column. The org-scope list now accepts `organizationId`, `organisationId`, `orgId`, `organization`, `organisation`, `org` (American + British). User-scope still accepts `userId` only.\n\n**`ownerId` is now 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 — Quickback won't auto-derive a firewall from it. Either rename to \\`userId\\` if this column controls access, add a separate \\`userId\\` / \\`organizationId\\` column, or specify \\`firewall:\\` explicitly.` This replaces the generic \"missing isolation column\" error in the `ownerId`-only case and preserves the documented distinction between RLS-style access control (`userId`) and business-logic ownership (`ownerId`).\n\nMigration: nothing breaks. Projects on the predicate-array shape compile bit-identically. Projects on the named-scope shape — including any test fixtures or example projects that were left on the legacy form — now compile cleanly again.\n\n---\n\n## v0.10.0 — April 26, 2026\n\n### `q.scope()` column DSL + unified `masking.query` gate\n\nTwo related DSL consolidations land. The `q.scope()` half is purely additive; the `masking.query` half rejects three legacy per-capability flags at compile time (migration is mechanical — see below).\n\n**`q.scope(kind)` — single-declaration tenant scoping.** Replaces the three-place pattern (column declaration + firewall predicate + implicit ownership-guard) with one column. `q.scope('organization')` compiles to `text(...).notNull()` and tells the compiler:\n\n1. Auto-derive the firewall predicate (`{ field: 'organizationId', equals: 'ctx.activeOrgId' }`) so the explicit `firewall:` block can be omitted entirely.\n2. Add the column to `GUARDS_CONFIG.systemManaged` so client input is rejected at the guard layer.\n3. Auto-populate from `ctx` on create / upsert.\n\nThe systemManaged extension generalises beyond `q.scope()`: any firewall predicate whose `equals` references `ctx.*` adds its `field` to the systemManaged set. So a hand-rolled `firewall: [{ field: 'tenantId', equals: 'ctx.activeOrgId' }]` gets the same treatment.\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\nThe auto-derived firewall also includes the soft-delete predicate (`{ field: 'deletedAt', isNull: true }`) when audit-field injection is on (the default). See [`q.scope()` in the schema docs](/compiler/definitions/schema#qscope--tenant-scope-columns).\n\n**`masking[col].query.roles` — unified role gate for filter / sort / search.** The three legacy per-capability flags (`filterable`, `searchable`, `sortable`) are replaced by a single allowlist that says \"these roles can query the column.\"\n\n```typescript\nmasking: {\n email: {\n type: 'email',\n show: { roles: ['admin'] },\n query: { roles: ['admin'] }, // optional — defaults to show.roles\n },\n}\n```\n\nWhen omitted, `query` inherits from `show.roles` (\"if you can see it, you can query it\") which is the right shape for almost all PII. A 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. See [Masking query gate](/compiler/definitions/masking#query-gate-filter--sort--search).\n\n**Breaking:** Setting `masking[col].filterable / .searchable / .sortable` is rejected at compile time with a migration hint. Replace with `query.roles` (or just delete the flags — `query` defaults to `show.roles`).\n\n---\n\n## v0.9.0 — April 25, 2026\n\n### DSL v2: unified `read:` pipeline, transactional batches, ID-probe defense\n\nStep 8 of the DSL v2 refactor lands. The headline shift is that the read\nside of every resource now has its own block — `read:` — that owns the\ncollection-level `GET /` endpoint, single-record `GET /:id`, and named view\nprojections. The legacy `crud.list` and `crud.get` shapes are rejected at\ncompile time. See the new [Read pipeline](/compiler/definitions/read) page\nfor the full reference and migration table.\n\n**Breaking changes** (compile-time errors with migration hints):\n\n- `crud.list` → [`read.access`](/compiler/definitions/read) (plus `read.pageSize` / `read.maxPageSize`)\n- `crud.get` → `read.access` (single-record GET inherits automatically; use record-level conditions on `read.access` for differentiated single-record gates)\n- Top-level `views: {...}` → [`read.views: {...}`](/compiler/definitions/read#views-under-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 on `/:id`**: handlers now run a role-only\naccess check **before** the firewall query, so a caller without a matching\nrole gets 403 before the database is touched. This closes the 404-vs-403\nID-probe channel — an unauthorized caller can no longer distinguish \"row\nexists in another tenant\" from \"row doesn't exist.\" See\n[Access evaluation order](/compiler/definitions/access#evaluation-order).\n\n**Transactional batch operations**: batch endpoints now expose a\n`failFast` option (replacing the old `atomic` naming) and a\n`meta.transactional` response field. On tx-supporting providers\n(postgres, supabase, neon, libsql, better-sqlite3, bun-sqlite), `failFast: true`\nwraps the per-record loop in `db.transaction(...)` so any failure rolls\nback the entire batch. On Cloudflare D1 (no `db.transaction`), `failFast: true`\nstill stops on the first error but prior writes stay committed; inspect\n`meta.transactional` to know which guarantee you got. Embedding queue\nmessages and realtime broadcasts are emitted **after** the transaction\ncommits, so a rolled-back batch produces no orphan jobs. See\n[Batch Operations: Transactional semantics](/compiler/targets/hono-api/using-the-api/batch-operations#transactional-semantics).\n\n**`firewallErrorMode` lifted off the firewall block**: the field that\ncontrols 403-vs-404 on firewall misses now lives at the resource top level\n(sibling to `firewall:`), since the firewall config is now a predicate\narray and this is a presentation-layer choice. Existing `firewall.errorMode`\nvalues should be lifted to `firewallErrorMode` at the resource level.\n\n**Read-only resources**: an empty `crud: {}` block (or omitting `crud:`\nentirely) is valid for read-only resources. `read:` alone is enough to\nexpose `GET /` and `GET /:id`.\n\n**Strict-mode top-level keys**: the strict allow-list now includes `dev` so\n`defineConfig({ dev: { ... } })` is accepted at the top level.\n\n---\n\n## v0.8.7 — April 17, 2026\n\n### Security: Hono CVE cluster fix\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 (`^4.0.0` / `^4.5.0` / `^4.6.0` / `^4.7.11`) covered the vulnerable window. Recompile to pick up the fix in your generated project's `package.json`.\n\n### Cloudflare Email Sending is now in public beta\n\nQuickback already defaults to the Workers `send_email` binding for Cloudflare deploys, and Cloudflare Email Sending has now graduated to public beta — production-ready with zero-config, no API keys, no third-party accounts. No action needed; recompiling any existing project continues to wire the default Cloudflare transport. AWS SES remains a fully supported opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes or existing SES setups. See [Email Configuration](/compiler/config#email-configuration).\n\n### Minor/patch dep sweep\n\nAligned the whole dep surface — monorepo, compiler Docker image, and generator emissions into compiled projects — so new compiles and existing recompiles converge on the same versions:\n\n- `wrangler@^4.83.0`\n- `drizzle-orm@^0.45.2`, `drizzle-kit@^0.31.10`\n- `zod@^4.3.6`\n- `@cloudflare/workers-types@^4.20260417.1` (also deduped — was accidentally declared in both `dependencies` and `devDependencies` in some paths)\n- `@tanstack/react-query@^5.99.0` (Account app)\n\n---\n\n## v0.8.5 — April 15, 2026\n\n### Fix: Better Auth 1.5 and `@cloudflare/workers-types` Compatibility\n\nGenerated API code failed to typecheck after Better Auth bumped to 1.5 and `@cloudflare/workers-types` tightened `BufferSource` to `ArrayBufferView<ArrayBuffer>`. Four unrelated surfaces broke:\n\n- **`databaseHooks.member.update.after` was removed** in Better Auth 1.5. The compiler now emits the member role-change broadcast hook as `organizationHooks.afterUpdateMemberRole` inside the `organization()` plugin call, which is the current supported shape.\n- **`REALTIME_URL` and `ACCESS_TOKEN`** are always emitted as optional `CloudflareBindings` fields when the organization plugin is active, so the broadcast hook typechecks even when `realtimeMode` is `\"inline\"` (or realtime isn't configured at all).\n- **`auth.api.listOrganizations` / `getFullOrganization` / `session.session.activeOrganizationId`** — third-party Better Auth plugins narrow the inferred `auth.api` type and hide organization-plugin endpoints. The generated middleware and `/admin/v1/organizations` route now cast through `any` for these calls.\n- **`crypto.subtle.sign` / `verify`** no longer accept `Uint8Array<ArrayBufferLike>` directly. Generated `jwt.ts` casts encoded payloads to `BufferSource`.\n\nNo config changes required — recompile to pick up the fixes.\n\n### CMS Admin Gate Now 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 — the static assets, `/api/v1/schema`, and `/api/v1/custom_view` CRUD were reachable by any authenticated user. A non-admin with an API token or cookie could bypass the UI and read schema metadata or saved CMS views directly.\n\nThis release adds server-side enforcement at every CMS-facing surface:\n\n- **CMS SPA shell** — the Worker checks `ctx.userRole === \"admin\"` before serving `index.html`. Unauthenticated requests redirect to login; authenticated non-admins get `403 Admin access required`. Static bundles (JS/CSS) remain reachable so browser caches aren't invalidated.\n- **`/api/v1/schema`** — returns `403` to non-admins.\n- **`custom_view` CRUD** — now gated on the new `userRole: [\"admin\"]` primitive rather than org membership.\n- **In-SPA gate** — unchanged; defense in depth behind the server-side gates.\n\nYour resource CRUD endpoints are unaffected — they keep their per-resource `crud.access.roles`.\n\n### New `userRole` Access Primitive\n\nAdded `userRole?: string[]` to the declarative `Access` config, evaluated against `ctx.userRole` (the Better Auth admin-plugin `user.role` column). This is distinct from `roles`, which matches `ctx.roles` (org membership).\n\n```typescript\n// Old: in multi-tenant this meant org-admin, not platform-admin\naccess: { roles: ['admin'] }\n\n// New: explicitly require user.role === 'admin' regardless of org membership\naccess: { userRole: ['admin'] }\n\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### Fix: `ReferenceError: customAlphabet is not defined` in generated POST handlers\n\nProjects with `providers.database.config.generateId: \"short\"` (or `\"nanoid\"` / `\"cuid\"`) compiled routes that called the ID helper but never imported it. Every generated `src/features/**/*.routes.ts` had `customAlphabet('0123...', 6)()` in its POST body but no matching `import { customAlphabet } from 'nanoid';` at the top of the file. Every `POST /api/v1/<resource>` and batch-create returned `500` with `ReferenceError: customAlphabet is not defined` on the first write.\n\nThe compiler now emits the correct import alongside the ID expression for all three modes: `nanoid`, `customAlphabet`, and `createId` from `@paralleldrive/cuid2`.\n\nNo config changes required — recompile to pick up the fix.\n\n### Fix: Dangling `export const` in generated `actions.ts` breaks `tsc`\n\nWhen a feature authored actions as `export const xActions = defineActions(...)` (instead of `export default defineActions(...)`), the compiler's preamble extractor leaked the assignment's left-hand side into the generated `src/features/<feature>/actions.ts`. The output contained a dangling `export const xActions =` with no right-hand side, and `tsc --noEmit` failed with `TS1109: Expression expected`. Runtime happened to work because the unused placeholder was never evaluated, but typecheck was red.\n\nThe preamble extractor now anchors its boundary to the start of the top-level statement containing `defineActions(...)`, covering `export default`, `export const X =`, `const X =`, and bare call forms. Local Zod helper declarations above the call continue to be preserved.\n\n### Fix: Files worker `database_id` reverted to `\"local-files\"` on every compile\n\nProjects using the two-worker R2 architecture had their files worker's `wrangler.toml` (`apps/backend/cloudflare-workers/files/wrangler.toml`) rewritten with `database_id = \"local-files\"` on every `quickback compile`, even when `providers.database.config.filesDatabaseId` was set to a real D1 UUID. The main worker's binding was correct — only the files worker fell through. Remote deploys of the files worker bound to a non-existent D1, so file serving and access-control reads failed with a binding error.\n\nThe files-worker wrangler generator now reads `filesDatabaseId` (and `filesDatabaseName`) from `providers.database.config` as a fallback when they aren't set on `providers.fileStorage.config`, matching the precedence chain already used by the main worker. Local dev is unaffected — `wrangler dev --local` uses `.wrangler/state/` regardless of the configured ID.\n\nNo config changes required — recompile and redeploy the files worker.\n\n---\n\n## v0.8.6 — April 16, 2026\n\n### Fix: Audit columns silently dropped from tables with a same-line index callback\n\nTables authored with the composite-index shape Drizzle / prettier produces —\n\n```ts\nexport const episodeTags = sqliteTable(\"episode_tags\", {\n id: text(\"id\").primaryKey(),\n episodeId: text(\"episode_id\").notNull(),\n tagId: text(\"tag_id\").notNull(),\n}, (t) => [ // <-- \"}, (t) =>\" on one line\n uniqueIndex(\"episode_tag_unique\").on(t.episodeId, t.tagId),\n]);\n```\n\nnever received audit field injection. A regex in `injectAuditFields` required a literal `\\n` between the columns-object `},` and the `(t) =>` index callback, so same-line closers were silently skipped and the function returned the source unchanged. drizzle-kit then diffed the audit-less schema against the previous snapshot and emitted `ALTER TABLE ... DROP COLUMN created_at/modified_at/deleted_at/created_by/modified_by/deleted_by` for every affected table. Any project that applied those migrations had production CRUD return `500` because the generated firewall helper still referenced `deletedAt`.\n\nThe regex is now whitespace-flexible and the identifier class accepts any valid JS identifier (`t`, `table`, `_t`, `tbl2`). A defensive guard throws at compile time if all three terminator patterns fail on a recognizable Drizzle table — no more silent drops.\n\n**Recovery path:**\n\n- Most projects: recompile. drizzle-kit will detect the audit columns are missing from the DB snapshot and emit an `ADD COLUMN` migration to restore them. Apply it.\n- Projects that already hand-patched their schema and ran a manual `ADD COLUMN` migration (like the `podcast-app` workaround in commit `98d8758`): the next compile will regenerate a matching `ADD COLUMN` migration that will fail with \"duplicate column name\" against a DB that already has the columns. Mark the new migration as applied without running it (e.g. `INSERT INTO __drizzle_migrations` in the features DB) or hand-edit the generated SQL to a no-op, then continue normally.\n\n### Fix: `firewall.exception` generated `isNull(<table>.deletedAt)` against a missing column\n\nResources with `firewall: { exception: true }` always emitted `return isNull(<table>.deletedAt);` inside `buildFirewallConditions()`, regardless of whether the table actually had a `deletedAt` column. Projects that disabled audit injection globally (`compiler.features.auditFields: false`) or authored a schema without `deletedAt` ended up with Drizzle resolving `<table>.deletedAt` to `undefined` at query time — every `GET /api/v1/<resource>` returned `500`.\n\nThe three concerns are now fully independent:\n\n- **`firewall.exception: true`** — only disables tenant scoping (org/user/team `WHERE` clauses). It does not gate audit fields or soft-delete.\n- **Audit fields** — always injected unless globally opted out. Unchanged.\n- **Soft-delete filter** — emitted only when the schema actually has `deletedAt` *or* the user explicitly set `firewall.softDelete`.\n\nIn the default configuration (audit injection on), behavior is unchanged: exception resources still filter `deletedAt IS NULL`. Only the broken case changes — exception resources on a schema without `deletedAt` now return `undefined` (no firewall), matching the column reality.\n\nNo config changes required — recompile to pick up the fix.\n\n---\n\n## v0.8.4 — April 14, 2026\n\n### New `generateId: \"short\"` Strategy\n\nAdded a 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\", {\n generateId: \"short\",\n }),\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 in your project (same as the existing `\"nanoid\"` strategy).\n\n**When to use:** room codes, invite links, share URLs, ephemeral records — anywhere the ID appears in a URL or needs to be human-typeable.\n\n**When not to use:** high-volume tables. 62^6 ≈ 56.8B combinations means ~238K rows before a 50% collision probability (birthday bound). For large tables stick with `\"uuid\"`, `\"cuid\"`, or `\"prefixed\"`.\n\nSee [Providers - ID Generation Options](/compiler/config/providers#id-generation-options) for the full list of strategies.\n\n---\n\n## v0.8.3 — April 14, 2026\n\n### Fix: `wrangler.toml` Route Placement and Binding IDs\n\nTwo bugs in the generated `wrangler.toml` that blocked production deployment without manual edits:\n\n**Routes were nested under `[dev]`.** The `routes = [...]` array was emitted after the `[dev]` section header, so TOML parsed it as `dev.routes` and wrangler ignored the custom domain (warning: `Unexpected fields found in dev field: \"routes\"`). Routes now emit as a top-level key.\n\n**D1 and KV bindings used placeholder IDs.** Despite `databaseId`, `filesDatabaseId`, and `kvId` being set in the quickback config, the generated `wrangler.toml` wrote `\"local-features\"`, `\"local-files\"`, and `\"local\"` instead of the real UUIDs. The compiler now resolves IDs from multiple config sources:\n\n| Binding | Config sources checked (in order) |\n|---------|-----------------------------------|\n| `AUTH_DB` | `database.config.authDatabaseId` |\n| `DB` | `database.config.featuresDatabaseId`, `database.config.databaseId` |\n| `FILES_DB` | `fileStorage.config.filesDatabaseId`, `database.config.filesDatabaseId` |\n| `KV` | `database.config.kvNamespaceId`, `storage.config.namespaceId`, `auth.config.kvId` |\n\nSee [Providers - Database Options](/compiler/config/providers#database-options) for the full list of supported ID properties.\n\n### Fix: Account SPA Post-Login Redirect on Unified Domain\n\nWhen the Account SPA was served at `/account/` on the unified quickback domain (e.g. `secure.example.com/account/`), post-login redirects dropped the basepath and sent users to `/dashboard` instead of `/account/dashboard`. Sign-out redirects had the same issue.\n\nThe SPA now shares a basepath module across the router and all raw `window.location.href` assignments, so login, signup, email OTP, welcome, and sign-out flows all stay under the correct path prefix regardless of whether the SPA is on the unified domain or its own dedicated auth subdomain.\n\nNo config changes required — recompile to pick up the fix.\n\n---\n\n## v0.8.2 — April 11, 2026\n\n### Catch-All `VITE_QUICKBACK_URL` Environment Variable\n\nInstead of setting four separate URL env vars, you can now point at a single Quickback origin:\n\n```bash\n# One variable — done.\nVITE_QUICKBACK_URL=https://secure.example.com\n```\n\nWhen set, it's used as a fallback for the individual URLs:\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, not the Quickback server.\n\n**Non-breaking.** Individual vars still take precedence when set, so existing configurations work unchanged. The compiler now also emits `VITE_QUICKBACK_URL` into the generated SPA `.env` files, and library users can set `__QUICKBACK_URL__` on `globalThis` for the same effect.\n\nSee [Environment Variables](/stack/account-ui/environment-variables) for the full reference.\n\n---\n\n## v0.8.1 — April 9, 2026\n\n### Role Hierarchy with `+` Suffix\n\nYou can now define a role hierarchy in your config and use the `+` suffix in access rules to mean \"this role and above\":\n\n```typescript\n// quickback.config.ts\nauth: {\n roleHierarchy: ['member', 'admin', 'owner'],\n}\n\n// In resource definitions\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) for details.\n\n---\n\n## v0.8.0 — April 9, 2026\n\n### Breaking: VITE URL Environment Variables Renamed\n\nAll Quickback-generated URL environment variables are now 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\n**Non-URL variables are unchanged:** `VITE_ENABLE_*` feature flags, branding vars (`VITE_APP_NAME`, etc.), and `VITE_STRIPE_PUBLISHABLE_KEY` stay as-is.\n\n**Action required:**\n- **Compiled projects** — re-run `quickback compile`. The compiler generates the new names automatically.\n- **Standalone deploys** — update `.env`, `.env.production`, and `wrangler.toml` files manually.\n- **Library users** — the `__QUICKBACK_API_URL__` / `__QUICKBACK_APP_URL__` globalThis names are unchanged, but if you pipe Vite env vars into them, update the var names.\n\nSee [Environment Variables](/stack/account-ui/environment-variables) for the full reference.\n\n### CMS Access Control\n\nThe `cms.access` config option now enforces access at the CMS level, not just link visibility in Account UI.\n\n```typescript\ncms: { access: \"admin\" }\n```\n\nWhen set to `\"admin\"`, non-admin users (`user.role !== \"admin\"`) see an \"Access Denied\" screen with a sign-out button instead of the CMS. When set to `\"user\"` (the default), any authenticated user can access the CMS.\n\nSee [CMS Connecting](/stack/cms/connecting) and [Compiler Config](/compiler/config) for details.\n\n### SPA Sub-Route Fix\n\nFixed a bug where hard-refreshing or directly navigating to SPA sub-routes (e.g., `/account/profile`, `/cms/tables/users`) returned a blank white screen. The Worker now correctly serves `index.html` for all SPA paths, allowing the client-side router to handle routing.\n\n---\n\n## v0.5.11 — February 24, 2026\n\n### Email OTP & Auth Fixes\n\n- Fixed email-OTP magic links not working correctly\n- Removed deprecated `/internal/validate` endpoint — use standard Better Auth session validation instead\n- Auth is now required for all API routes when running locally (previously some routes were unprotected in dev)\n\n### Multiple Table Exports Fix\n\n- Fixed a compiler error when a single file exports multiple Drizzle tables alongside a `defineTable()` default export\n- The CLI now properly detects and reports this with a clear error message pointing to the fix\n\n### Headless Drizzle Rename Hints\n\n- Added `compiler.migrations.renames` configuration for CI/CD environments where Drizzle's interactive rename prompts would block compilation\n- Compile errors now include explicit rename key paths and fail fast on malformed rename config keys\n- See [Configuration](/compiler/config) for details\n\n### Security Contract Report Artifacts\n\n- Added generated security contract artifacts to compiler output:\n - `reports/security-contracts.report.json`\n - `reports/security-contracts.report.sig.json`\n- Added config-driven signing controls:\n - `compiler.securityContracts.report.signature.enabled`\n - `compiler.securityContracts.report.signature.required`\n - `compiler.securityContracts.report.signature.key` / `keyEnv` / `keyId`\n- Missing required signing keys now fail loudly with explicit remediation guidance\n- Added strict config validation for report/signature paths and signing options\n\n### Mandatory Unsafe Action Audit Trail\n\n- Added structured unsafe action config (`unsafe: { reason, adminOnly, crossTenant, targetScope }`)\n- Cross-tenant unsafe actions now require Better Auth authentication plus platform admin role (`ctx.userRole === \"admin\"`)\n- Added mandatory audit logging for unsafe cross-tenant actions (success, denial, and error paths)\n- Cloudflare output now includes optional `AUDIT_DB` wiring, `drizzle.audit.config.ts`, and `db:migrate:audit:*` scripts when unsafe actions are present\n- Added compile-time raw SQL guard for actions and handlers (`allowRawSql: true` required per action)\n\n---\n\n## v0.5.10 — February 19, 2026\n\n### Compiler Page Parsing & CLI Output\n\n- Improved compiler page parsing for `definePage()` definitions\n- Better CLI output formatting during compilation\n- Added `apiPath` to schema registry for CMS integration\n\n### Bug Fixes\n\n- Fixed hyphenated action names not being properly quoted in generated code (e.g., `mark-complete` now generates valid JavaScript)\n- API key authentication (`x-api-key` header) is now handled separately from session tokens (`Bearer` header)\n\n---\n\n## v0.5.9 — February 16, 2026\n\n### CMS Pages & CLI Page Support\n\n- Added `definePage()` support for CMS-managed pages\n- Auth middleware improvements for page routes\n- CLI now supports page definitions alongside table and action definitions\n\n---\n\n## v0.5.8 — February 14, 2026\n\n### CMS App\n\n- Introduced the Quickback CMS — a schema-driven admin panel that connects to your generated API\n- CMS namespace added to actions for admin-specific operations\n- Fixed `guard` → `access` naming inconsistency in CMS action definitions\n\n### Schema Registry & Firewall Improvements\n\n- Added schema registry generator — the compiler now outputs a JSON schema registry used by the CMS\n- Firewall error modes: choose between `reveal` (403 with details) and `hide` (opaque 404) for security-sensitive deployments\n\n### Bug Fixes\n\n- Fixed anonymous user email format generation\n- Organization selector improvements in Account UI\n- Config validation now catches more errors at compile time\n- Better CRUD error handling with structured error responses\n- Fixed masking to use representative star counts instead of fixed formatting\n\n---\n\n## v0.5.7 — February 12, 2026\n\n### Scoped Database for Actions\n\nActions now 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\nThe scoped DB uses duck-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\nThis means **every action is secure by default** — no manual `WHERE` clauses needed.\n\n```typescript\ndefineActions(todos, {\n complete: {\n type: \"record\",\n execute: async ({ db, ctx, record, input }) => {\n // db is scoped — only sees records in user's org, excludes soft-deleted\n const siblings = await db.select().from(todos);\n // ↑ automatically filtered to ctx.activeOrgId + deletedAt IS NULL\n },\n },\n});\n```\n\n#### Unsafe Mode\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:\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`.\n\n**Related docs:** [Actions](/compiler/definitions/actions), [Actions API](/compiler/targets/hono-api/using-the-api/actions-api)\n\n---\n\n### Cascading Soft Delete\n\nSoft-deleting a parent record now **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\n```\nDELETE /api/v1/projects/:id\n```\n\nGenerated behavior:\n```typescript\n// 1. Soft delete the parent\nawait db.update(projects)\n .set({ deletedAt: now, deletedBy: userId })\n .where(eq(projects.id, id));\n\n// 2. Auto-cascade to children (compiler-generated)\nawait db.update(projectMembers)\n .set({ deletedAt: now, deletedBy: userId })\n .where(eq(projectMembers.projectId, id));\n\nawait db.update(projectTasks)\n .set({ deletedAt: now, deletedBy: userId })\n .where(eq(projectTasks.projectId, id));\n```\n\nRules:\n- Only applies to **soft delete** (the default). Hard delete relies on database-level `ON DELETE CASCADE`.\n- Only cascades within the **same feature** — cross-feature references are not affected.\n- Child tables must have `deletedAt` / `deletedBy` columns (auto-added by the compiler's audit fields).\n\n**Related docs:** [Actions API — Cascading Soft Delete](/compiler/targets/hono-api/using-the-api/actions-api#cascading-soft-delete)\n\n---\n\n### Advanced Query Parameters\n\nNew query parameter capabilities for all list endpoints:\n\n- **Field selection** — `?fields=id,name,status` returns only the columns you need\n- **Multi-sort** — `?sort=status:asc,createdAt:desc` sorts by multiple fields\n- **Total count** — `?count=true` returns total matching records in response headers (`X-Total-Count`)\n- **Full-text search** — `?search=keyword` searches across all text columns\n\n```bash\n# Get only names and statuses, sorted by status then date, with total count\nGET /api/v1/todos?fields=id,name,status&sort=status:asc,createdAt:desc&count=true\n\n# Search across all text fields\nGET /api/v1/todos?search=urgent\n```\n\n**Related docs:** [Query Parameters](/compiler/targets/hono-api/using-the-api/query-params)\n\n---\n\n### Audit Field Improvements\n\n- `deletedAt` and `deletedBy` fields are now **always injected** by the compiler for tables with soft delete enabled — no need to define them in your schema\n- All audit fields (`createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`, `deletedAt`, `deletedBy`) are auto-managed\n\n---\n\n## v0.5.6 — February 8, 2026\n\n### Database Naming Conventions\n\n- Default table and column naming changed to **snake_case** with `usePlurals: false`\n- Table names derived from generated Better Auth schema for consistency\n- Removed legacy single-database mode — split databases (auth + features) is now the standard\n\n### Auth Variable Shadowing Fix\n\n- Fixed `member` variable in auth middleware that shadowed the Drizzle `member` table import\n- Renamed to `sessionMember` to avoid conflicts in generated routes\n\n---\n\n## v0.5.5 — February 5, 2026\n\n### Better Auth Plugins\n\n- Published `@quickback-dev/better-auth-upgrade-anonymous` v1.1.0 — post-passkey email collection flow\n- Published `@quickback-dev/better-auth-combo-auth` — combined email + password + OTP authentication\n- Published `@quickback-dev/better-auth-aws-ses` — AWS SES email provider for Better Auth\n\n### OpenAPI Spec Generation\n\n- Generated APIs now include a full OpenAPI specification at `/openapi.json`\n- Better Auth endpoints included in the spec\n- Runtime route: `GET /openapi.json`\n\n### Security Hardening\n\n- Global error handler prevents leaking internal error details\n- Security headers middleware (CSP, HSTS, X-Frame-Options, X-Content-Type-Options)\n- `BETTER_AUTH_SECRET` properly passed to generated config\n\n---\n\n## v0.5.4 — January 30, 2026\n\n### Account UI\n\n- Pre-built authentication UI deployed as Cloudflare Workers\n- Features: sessions, organizations, passkeys, passwordless, admin panel, API keys\n- Dual-mode: standalone (degit template) or embedded with Quickback projects\n\n### Webhook System\n\n- Inbound webhook endpoints with signature verification\n- Outbound webhooks via Cloudflare Queues with automatic retries\n- Configurable per-feature webhook events\n\n### Realtime & Vector Search\n\n- Durable Objects + WebSocket realtime subscriptions\n- Vector embeddings via Cloudflare Vectorize\n- 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, Bun standalone, B2B SaaS\n- **Cloud Compiler** — Remote compilation via `compiler.quickback.dev`\n- **CLI** — `quickback create`, `quickback compile`, `quickback init`\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": "# Changelog\n\nRelease notes for the Quickback compiler, CLI, and platform.\n\n---\n\n## v0.16.1 — May 9, 2026\n\n### Cloudflare ASSETS canonicalization — worker SPA emits no longer 307-loop\n\nCloudflare's static-assets binding canonicalizes any request for `/<dir>/index.html` into a 307 redirect to `/<dir>/` (the default `html_handling=auto-trailing-slash`). When a worker subrequest issues `c.env.ASSETS.fetch(new Request(new URL('/<dir>/index.html', …)))`, the binding returns the 307; the worker forwards it; the browser re-requests `/<dir>/`; the same SPA-fallback handler (or hostname middleware) catches the directory request and re-fetches `/<dir>/index.html`. Infinite loop. Caught by AttendVIP writing custom `/admin/` and `/m/` host-routing patches on the deployed worker — the fix in their patches was switching to `/admin/` (trailing slash, no `index.html`), which Cloudflare resolves to the directory's `index.html` content with a 200.\n\nThe compiler had the same bug baked into every emit point. `cloudflare.ts` now fetches `/<dir>/` everywhere it previously asked for `/<dir>/index.html`: CMS hostname middleware, `/cms/*` SPA catchall, apex `/` handler, account/admin hostname middleware, `/account/*` SPA catchall, and the multi-domain catchall. Eight regression tests in `cf-assets-canonicalization-spa-fallback.test.ts` pin every emit so a future copy/paste can't sneak the literal back in.\n\n### `account.customLogin` — drop a project-branded sign-in page in front of the SPA\n\nA new `account: { customLogin: true }` flag emits an explicit `app.get('/account/login', …)` route that serves a project-supplied static page instead of letting the bundled Account SPA's client router handle the path. Drop the page at `quickback/public/account/login/index.html` (a *directory*, not a bare `login.html` — see the canonicalization note above) and the existing `quickback/public/` passthrough copies it into the asset binding. The route is registered before the `/account/*` SPA catch-all so the static handler wins; everything else under `/account/...` (profile, organizations, devices, …) keeps going through the React SPA. Same surface AttendVIP was hand-patching post-compile — promoting the flag means the next compile no longer wipes their override. Default `false`.\n\n### Project-level realtime auto-broadcasts every resource by default\n\n`dbConfig.realtime: true` now treats every resource as realtime-enabled unless its `realtime` block explicitly opts out. The previous behavior set `effectiveResourceRealtime` to `undefined` when a resource didn't declare its own block — so a project that flipped the project-level flag still had to add per-table `realtime: { enabled: true }` everywhere to actually get auto-broadcasts. Caught against AttendVIP after the v0.15.x auto-broadcast wiring landed but didn't fire. New default: project-level on with no per-resource override = `{ enabled: true }`. Per-resource `realtime: { enabled: false }` still wins.\n\n### Drizzle metadata gets a DO NOT EDIT header + journal drift warning\n\nTwo changes that protect the drizzle plumbing from quiet corruption.\n\n`compile-runner.ts:addJsonHeader` now stamps drizzle's generated JSON (`_journal.json`, `<n>_snapshot.json`) with a `$__quickback_warning__$` key explaining the file is regenerated by the compiler and should not be edited by hand. The disclaimer matches the one already on `.ts` outputs — the journal had been the one drizzle file users felt entitled to \"tidy up\" because nothing in it said otherwise.\n\nA new check in the same module compares the journal entry count against the snapshot file count. drizzle-kit only produces one snapshot per `generate` run, so `journal.entries.length > snapshots + 1` means the journal claims migrations the snapshot side has lost (typical cause: a manual delete of an `<n>_snapshot.json` that left the journal entry behind). The compiler logs a warning and lists the orphan entries. Detected directly out of AttendVIP's `Travel 500` triage — drizzle-kit was diffing against a stale `0002_snapshot.json` and emitting bogus full `CREATE TABLE` migrations for tables that had been added in subsequent (now-orphaned) journal entries.\n\n### Two new compile-time validators (LOUD failures over silent traps)\n\n**`AUTHENTICATED` + tenant-scoped firewall now refuses to compile.** `pseudo-role-validator.ts` rejects any access tree that admits `AUTHENTICATED` on a resource whose firewall scopes by `organizationId`. The combination is the silent-empty trap: a sign-in-only caller with no active org passes the role gate, the firewall WHERE clause filters every row out, and the API returns `[]` with a 200. The error message names three valid resolutions — drop the org scope (`firewall: { exception: true }`), tighten the role to `USER` or a role with implied org membership, or split the route into a token-auth branch and an org-membership branch.\n\n**`createRealtime` imports without `dbConfig.realtime: true` now throw.** Project lib + action + feature-lib files are scanned at compile time for `import { createRealtime }` (and the equivalent named binding). When the project hasn't enabled realtime, the compile fails with the offending file paths and remediation: either enable `dbConfig.realtime: true` so the runtime helper exists, or remove the import. Caught against AttendVIP — three handler files (`broadcastAnnouncement.ts`, `declineActivityForGuest.ts`, `applyRsvp.ts`) imported `createRealtime` after the v0.15 auto-broadcast wiring landed, but their config never set `realtime: true`. The Worker compiled, deployed, and 500'd at first call. The user's framing was \"config should be the source of truth\" — this validator enforces that. Five regression tests in `realtime-import-without-config-rejected.test.ts`.\n\n### Fixes\n\n**1. `SYSADMIN` was missing from the per-feature standalone gate's `allowsWithoutOrg` set.** The standalone-action wrapper skips its `if (!ctx.activeOrgId)` gate for any access tree referencing a pseudo-role (`PUBLIC`, `AUTHENTICATED`, `USER`, `ADMIN`) — but `SYSADMIN`, the v0.15.0 fifth marker, was missing from the matcher. Sysadmin actions on `cms.sysadmin: true` projects were 403'ing on cross-tenant calls (sysadmins have no member rows, so `ctx.activeOrgId` is unset by design). The matcher now includes `SYSADMIN`.\n\n**2. Apex `/` and `/account/login` get fallback redirects when neither CMS nor Account SPA is bundled.** Projects that opt out of both bundled SPAs still receive traffic at `/` (no apex handler, 404) and `/account/login` (no Account fallback, 404). Setting `auth.loginUrl` to an external sign-in host now activates two compiler-emitted redirects so those natural inbound URLs land somewhere useful: `/account/login → loginUrl?redirect=…` (preserves the bounce param) and `/ → loginUrl` (or `/account` when the Account SPA is bundled). Both opt in via `auth.loginUrl !== '/account/login'` so projects using the built-in `/account/login` keep the existing SPA-fallback behavior unchanged.\n\n**3. Record-based action URLs are now kebab-case to match OpenAPI.** `record-based.ts` was emitting URL paths from the camelCase action name (e.g. `/api/v1/widgets/:id/sendInvite`) while OpenAPI emit produced `/widgets/:id/send-invite`. Admin tooling and SDK consumers reading the OpenAPI spec hit 404s on every multi-word action. URL paths and OpenAPI emit now share a `urlPath = toKebabCase(urlSegment)` helper. Identifiers in audit `actionName`, error messages, and console logs stay camel — those are programmatic surfaces and breaking them would churn audit logs. Same fix shape as the v0.15.0 standalone-action URL casing.\n\n### Notes\n\nTest coverage: 1175 → 1183 (+8 across the canonicalization, customLogin, and createRealtime regression files). Verified end-to-end against AttendVIP — `quickback compile` produces a worker whose `/account/login`, hostname-routed account/admin SPAs, and apex / handler all return 200 with the right SPA shell on the deployed Cloudflare worker, no 307 loops.\n\nThe bundled docs (`packages/claude-skill/docs/changelog.md`, `packages/cli/src/skill/docs/changelog.md`) and the CLI's `packages/cli/src/docs/content.ts` are regenerated by `scripts/bundle-docs.ts` — run that before publishing the CLI bump.\n\n---\n\n## v0.16.0 — May 9, 2026\n\n### Agent Auth Protocol — first-class agent identity for AI callers\n\nQuickback now ships a server implementation of the [Agent Auth Protocol](https://agentauthprotocol.com) by way of `@better-auth/agent-auth`. Opt in with `auth.plugins.agentAuth: true` (or the array form `plugins: [\"agentAuth\"]`). When enabled, the compiler emits a complete 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 (`agent`, `agentHost`, `agentCapabilityGrant`, `approvalRequest`) added to the auth schema automatically by `auth generate`.\n\n**OpenAPI capability projection runs by default.** The compiler emits `src/lib/openapi-spec.ts` (the project's full OpenAPI spec inlined as a const) and wires `createFromOpenAPI(openapiSpec, { ... })` into the `agentAuth(...)` call. Every operation with an `operationId` becomes an agent capability. Default `approvalStrength` map: `GET → \"session\"`, `POST/PUT/PATCH/DELETE → \"webauthn\"`. Default `defaultHostCapabilities`: `[\"GET\", \"HEAD\"]`.\n\nThe proxy `onExecute` makes a self-fetch to the worker's own URL with a Better Auth JWT minted for `agentSession.user.id`, so the inner request hits the existing JWT fast-path, populates `ctx`, and the full firewall + access + masking pipeline runs on the proxied call. No new middleware code, no parallel security path — agent capability calls go through the same gates as regular REST traffic. The cost is one Cloudflare subrequest per capability call (~50ms); fine for typical agent traffic. Opt out of OpenAPI projection with `agentAuth: { fromOpenAPI: false }` and wire `capabilities` + `onExecute` by hand.\n\nThe Account SPA gains `/agents/approve` (`packages/account/app/routes/agents.approve.tsx`) — modeled on the existing `/cli/authorize` device-code page. Pastes the user code, fetches the pending request, lists the requested capabilities with a \"Step-up\" badge on any capability whose `approvalStrength` is `\"webauthn\"`, then approves or denies. WebAuthn step-up itself is a placeholder for v0.16.0 — the upstream agent-auth API for the escalation call is still settling, so capabilities tagged `\"webauthn\"` will fail server-side until that lands. The badge tells the user what's coming.\n\n### Bearer-only on `/mcp` and the agent-auth surface\n\n`/mcp` now forwards **only** `Authorization: Bearer …` into the inner `app.request()` re-entry. Cookie + `x-api-key` forwarding has been removed. The MCP surface is server-to-server by nature — there are no browser callers, no CSRF surface to defend, and no benefit to fragmenting the auth model across three header conventions. Three Bearer flavors all land on the same header, resolved by the inner Hono middleware chain:\n\n- Better Auth session token via the official `bearer` plugin\n- OAuth access token via the OAuth Provider plugin\n- Agent JWT via `@better-auth/agent-auth`\n\nIf a project still wants API-key auth here, configure the `apiKey` plugin to accept its key via `Authorization: Bearer` so everything stays one channel. The existing `mcp-server.test.ts` regression seal flips from \"forwards Cookie + x-api-key\" to \"forwards only Authorization (bearer-only surface)\".\n\n### Auth DSL: `bearer`, `oauthProvider`, `agentAuth` are now first-class plugin entries\n\nBoth the array-form union and the `BetterAuthPlugins` interface in `apps/compiler/src/define/auth.ts` gain `\"bearer\"`, `\"oauthProvider\"`, and `\"agentAuth\"`. `bearer` was previously in the runtime registry but missing from the TS type, so callsites had to use `as any` or `// @ts-expect-error` to set it. Both are gone now. New typed options interfaces — `OAuthProviderOptions` (audience, login/consent paths, dynamic registration) and `AgentAuthOptions` (providerName, providerDescription, modes, fromOpenAPI, approvalStrength, defaultHostCapabilities) — let users override defaults through the object form.\n\nAuto-enable rule lives in the canonical `computeAutoAddedPlugins` (`generators/auth.ts`): turning on `agentAuth` force-adds `bearer` + `oauthProvider`. There is no useful agent-auth deployment without those two — surfacing it as auto-add rather than a confusing \"missing dependency\" runtime error matches the existing pattern (`oauthProvider` already auto-adds `jwt`).\n\n### `queue-consumer.ts` now emitted for `additionalQueues` too\n\nPrior to this release, the queue consumer emit gated on `embeddingFeatures.length > 0 || queueHandlers.length > 0`. Projects that declared queue infrastructure via `dbConfig.additionalQueues` but had no embeddings + no `services/queues/*` handlers shipped a `wrangler.toml` with `[[queues.consumers]]` entries pointing at a missing worker `queue` export. The CLI's archive-restore step kept a stale `queue-consumer.ts` around, so the file appeared \"stuck\" across compiles — same class of bug as the v0.15.0 services/queues/* regression caught against AttendVIP, just one source removed.\n\nThe gate is now a three-way OR: `hasEmbeddings || hasQueueHandlers || hasAdditionalQueues`. When only `additionalQueues` is set, the compiler emits a stub `queue-consumer.ts` whose `queue` export acks every message with a warning — Cloudflare needs an export for every consumer binding, and a noisy-but-correct stub beats a silent deploy break. `MainAppOptions` and `CloudflareMainAppOptions` gain `hasAdditionalQueues`; `generateQueueImport` and `generateCloudflareExport` mirror the new gate. Regression test: `src/__tests__/queue-additional-queues-gate.test.ts`.\n\n### Fixes\n\n**1. `bearer` was missing from the `BetterAuthPlugins` TypeScript interface.** The runtime plugin registry has had `bearer` since the pre-1.0 cuts, but `apps/compiler/src/define/auth.ts` never declared it on the typed shape — so any `quickback.config.ts` using `plugins: { bearer: true }` had to `as any`-cast or sit behind a `@ts-expect-error`. Both `bearer` and `oauthProvider` (same gap, same workaround) are now first-class typed entries; `agentAuth` joins them. The array-form union also gains all three. No behavior change at runtime; existing casts can come out.\n\n**2. MCP `buildInternalRequest` no longer forwards Cookie or `x-api-key`.** The MCP surface is server-to-server — there are no browser callers, no CSRF surface to defend, and no benefit to fragmenting the auth model across three header conventions. The inner `app.request()` re-entry now forwards only `Authorization: Bearer …`. Three Bearer flavors all land on the same header (BA session token via the `bearer` plugin, OAuth access token via OAuth Provider, agent JWT via `@better-auth/agent-auth`). Existing `mcp-server.test.ts` regression flipped from \"forwards Cookie + x-api-key\" to \"forwards only Authorization (bearer-only surface)\".\n\n**3. `agentAuth` now auto-enables `bearer` + `oauthProvider`.** There is no useful agent-auth deployment without those two — the agent surface is bearer-only and MCP clients need OAuth to register. Auto-enable lives in the canonical `computeAutoAddedPlugins` (`generators/auth.ts`), so it propagates to every consumer (better-auth generator, schema generation, package-deps emission). Same pattern as the existing `oauthProvider` → `jwt` rule. Surfaced in `agent-auth.test.ts` with a regression seal that asserts both plugins land in the merged plugin list whether the user wrote the array form or the object form.\n\n**4. `OpenAPISpec` literal type rejected by tsc on inlined spec.** Quickback's OpenAPI emit produces `$ref`-style parameter entries (`{ \"$ref\": \"#/components/parameters/X\" }`) that the agent-auth plugin's stricter `OpenAPIParameter` type doesn't model — `tsc` fails the generated project with \"Type … is not assignable to OpenAPIParameter\". The plugin handles refs correctly at runtime; only the structural narrowing on the TS literal needed help. The generated `agentAuth({ ...createFromOpenAPI(openapiSpec as any, { ... }) })` call now carries an `as any` cast on the spec with an inline comment explaining why. Drop when upstream models `$ref` parameters.\n\n### Notes\n\n`@better-auth/agent-auth` 0.4.5 ships ESM-only exports without a `require` condition, so the Better Auth CLI's `auth generate` step (jiti / CJS resolver) bails with `ERR_PACKAGE_PATH_NOT_EXPORTED`. The compiler image patches the package's `package.json` at install time to add a matching `require` condition pointing at the same dist file (Node 22+ supports `require(esm)`). Remove the patch in `apps/compiler/Dockerfile` when upstream ships proper exports.\n\nTest coverage: 1136 → 1152 (+11 `agent-auth.test.ts`, +5 `queue-additional-queues-gate.test.ts`). Verified end-to-end against `examples/recruitment` with `agentAuth` enabled — `quickback compile` produces a project whose `npm run build` typechecks clean and whose generated schema includes all four agent-auth tables (`agent`, `agentHost`, `agentCapabilityGrant`, `approvalRequest`).\n\n---\n\n## v0.15.0 — May 7, 2026\n\n### Sysadmin tier — cross-tenant DB-admin role for the CMS\n\nA new opt-in `cms: { sysadmin: true }` flag turns the CMS into a Supabase-style cross-tenant DB-admin tool gated by `user.role === 'sysadmin'`. Distinct from `'admin'` so Better Auth admin-plugin powers (user management, impersonation) and DB-admin powers stay decoupled. Off by default — projects without the feature get zero behavior change.\n\nWhen enabled, the compiler emits a `SYSADMIN` pseudo-role (fifth marker alongside `PUBLIC` / `AUTHENTICATED` / `USER` / `ADMIN`); a firewall escape hatch in every `buildFirewallConditions` that drops tenant scopes for `ctx.userRole === 'sysadmin'` while preserving soft-delete; a true cross-tenant `/admin/v1/sysadmin/organizations` endpoint that selects directly from the auth-schema `organization` table; and a relaxed cross-tenant guard that skips the `ORG_REQUIRED` 400 for sysadmins on list routes — that's how the SPA's \"All organizations\" sentinel reaches the firewall escape end-to-end.\n\nThe CMS SPA gains a two-mode design: org admins keep the existing membership-based switcher (Better Auth's `setActiveOrganization`); sysadmins get a `SysadminOrgSelector` that loads from the cross-tenant endpoint, defaults to \"All organizations\" (omits the org filter on reads), and pins selected tenants via `?organizationId=` on every API call (sysadmins have no member rows, so `setActive` would 403). A new `OrgGate` component handles no-active-org cases for org users — auto-pick when there's exactly one membership, full-frame picker for multiple, empty state for zero — so sessions that lost their active org don't dead-end.\n\nRefusing to compile `roles: [\"SYSADMIN\"]` without `cms.sysadmin: true` keeps the role from sitting as dead code. RLS providers (Neon, Supabase) emit `false` for `SYSADMIN` today; per-table RLS policy emit is a follow-up.\n\n### Durable Object `[[migrations]]` order is now preserved across recompiles\n\nCloudflare's migration system is append-only — every deploy must include previously-deployed migration tags in their original order, with new ones appended last. CF rejects deploys with `code: 10061` when the order shifts. The compiler used to iterate `bindings.durableObjects` in config order at emit time, so a user inserting a new DO into the middle of the array bumped every later auto-migration into the wrong slot, breaking deploys for projects with multiple DOs (caught by AttendVIP).\n\nThe CLI now sends the project's existing `wrangler.toml` (when present) in `existingFiles` alongside the drizzle meta. The compiler parses migration tags from it via `parseExistingMigrationTags`, then emits auto-generated DO `[[migrations]]` blocks in two phases: deployed entries first (preserving the existing wrangler.toml order), net-new entries appended last in `bindings.durableObjects` config order. Reordering DOs in the config array no longer reshuffles deployed migrations; inserting a new DO anywhere in the array always appends its migration block last. First compiles (no existing wrangler.toml) keep the current config-order behavior — no behavior change for new projects. User-declared `bindings.durableObjectMigrations` (historical entries) are unaffected; they continue to emit first.\n\n### Standalone-action wrapper no longer 403s `AUTHENTICATED`-only routes on org-scoped projects\n\nStandalone actions (`standalone: true`) on org-scoped projects emitted an unconditional `if (!ctx.activeOrgId) return 403 ACCESS_NO_ORG` gate before role checking. For an action declared `access: { roles: [\"AUTHENTICATED\"] }`, this contradicted the access rule itself: a signed-in user with no active org (e.g. just signed up but not yet joined an organization, or a token-auth caller) was the exact caller `AUTHENTICATED` was supposed to admit. Found by AttendVIP — every recompile re-introduced the bug because the fix lived in handler-side patches, not the generator. The standalone wrapper now skips the org gate when the access tree references any pseudo-role anywhere, including under `or:`/`and:` arms.\n\n### Queue handler emit no longer drops the `queue` export when there are no embeddings\n\n`compiler.ts` emits `src/queue-consumer.ts` whenever `embeddingFeatures.length > 0 || queueHandlers.length > 0`, but the worker entry only checked `hasEmbeddings`. Projects with custom queue handlers under `services/queues/*` and no embeddings got the consumer file generated and then no entry-point wiring — wrangler bound the queue to a missing handler at deploy time. Caught against AttendVIP's `sendCancelEmail` queue handler. `MainAppOptions` and `CloudflareMainAppOptions` gain a `hasQueueHandlers` flag; `generateQueueImport` and `generateCloudflareExport` now gate on `hasEmbeddings || hasQueueHandlers`.\n\n### `quickback/public/` — static-asset passthrough into `src/apps/`\n\nA new opt-in folder. Anything you drop under `quickback/public/` is copied verbatim into `src/apps/` on every compile, where the wrangler `[assets]` binding (`directory = \"src/apps\"`) already serves it. So `quickback/public/robots.txt` becomes reachable at `https://your-domain/robots.txt`, `quickback/public/og/og-image.png` at `/og/og-image.png`, and so on. Favicons, `robots.txt`, OG images, marketing PDFs, sitemap fragments, `.well-known/` files — anything you'd previously have had to post-process into `src/apps/` after each compile.\n\nThe compiler does **not** parse, template, or otherwise touch these files. They ride past it as bytes — the CLI does the copy after `writeFilesWithMerge`, using `fs.copyFile` so binaries (PNGs, fonts, PDFs) stay byte-perfect rather than being corrupted by the utf-8 string channel the compiler manifest uses for source files. The compiler API contract is unchanged; nothing round-trips through `compile.quickback.dev`.\n\nRules:\n\n- **Optional.** If the folder doesn't exist, the step is a no-op.\n- **Stale-cleaned.** `src/` is wiped and rewritten each compile, so files removed from `quickback/public/` disappear from `src/apps/` automatically on the next run.\n- **Hidden entries skipped.** `.DS_Store`, `.git/`, dotfiles — none of these were intentional drops; including them would break worker asset bindings.\n- **Collisions fail loud.** A file in `quickback/public/` whose path would shadow a compiler-emitted manifest entry — e.g. `quickback/public/cms/index.html` against the SPA shell — fails the compile with the offending paths listed, rather than silently overwriting and producing a confused-looking SPA build. Move or rename the offending file.\n\nThe change is contained to the CLI: `packages/cli/src/lib/copy-public-assets.ts` (helper + `PublicAssetCollisionError`) and one block in `packages/cli/src/commands/compile.ts`. Test coverage in `copy-public-assets.test.ts` walks the missing-folder, single-file, nested-tree, binary-preservation, hidden-entry, single-collision, multi-collision, empty-folder, and split-output cases — nine tests, byte-level assertions on the binary path.\n\n---\n\n## v0.14.7 — May 7, 2026\n\n### Four more codegen bugs caught by AttendVIP — generated output now typechecks for projects with non-`id` PKs and DO-only features\n\nFiled after AttendVIP's `tsc` reported 230 errors against the generated `src/`. Triage split them into six patterns; four are surgical and ship here. The other two (TS2769 ×156 + TS2339 ×~50) trace to a deeper assumption — every queryable table has a string-typed `id` column — and are deferred to v0.14.8 along with the agreed `id` auto-inject design (see *Coming next* below).\n\n**1. Duplicate `guests` import in routes that use relationship-roles (`TS2300`).** The relationship-import injector (`generators/feature-generator.ts`) added `import { <table>, buildFirewallConditions as build<Table>FirewallConditions } from './<table>.resource'` whenever it detected a relationship-table reference in the routes file — without checking that the table binding was already imported from `./schema` upstream. So `guests.routes.ts` ended up with `guests` declared twice. Fix: scan the existing import block, only add identifiers that aren't already in scope (drop the binding from the new import line, or skip the line entirely if both binding and alias are imported).\n\n**2. `db` referenced before declaration in single-record + bulk action handlers (`TS2448` / `TS2304`).** `record-based.ts:195,541` baked `firewallClause = ...buildFirewallConditions(ctx, db)...` and used the same string in two places: (a) the outer pre-fetch `await unsafeDb.select().from(table).where(firewallClause)` — where `db` doesn't exist yet (`db = createScopedDb(unsafeDb, ctx)` is declared later for handler scope), and (b) inside `processBatch` where `db` is created from the tx/handle param. The outer use threw at typecheck (`'db' is used before its declaration`); at runtime it would have been a `ReferenceError`. Fix: pass `unsafeDb` (the in-scope handle) to `buildFirewallConditions` in both `firewallClause` definitions. The helper only uses its `db` arg for relationship-role subqueries (when `via:` is in play); either handle is a valid Drizzle client for that lookup.\n\n**3. PartyServer realtime gates passed 1 arg to a 2-arg `buildFirewall_X` (`TS2554`).** `optional-routes.ts` emitted `buildFirewall_<feature>(ctx as any)` in the WebSocket-upgrade gate for every Durable Object that declared `access: { resource }`. After v0.14.4 made `buildFirewallConditions(ctx, db)` 2-arg whenever the resource has any `via:` predicate, this gate stopped compiling for any DO whose target feature uses relationship-roles. AttendVIP's `event-pages` DO sits on `event_pages` (admin via `guestOf`), which is exactly that case. Fix: the gate already constructs `db = drizzle(c.env.<binding>)` for its own `db.select(...).limit(1)` — pass that same `db` into the firewall call. Mirrored in both the single-resource and multi-resource gate branches.\n\n**4. Durable-object-only features dropped their `lib/` files from output (`TS2307`).** `compiler.ts:546` only ran the feature-walker (and copied `featureLibFiles` to output) when the feature had at least one action file. AttendVIP's `user-profiles/` declares a single DO source under `lib/UserGateway.ts` and zero `actions/` — perfectly valid (per-user realtime gateway, the Slack/Linear pattern), but the walker skipped the feature entirely. The compile finished without error, then `index.ts` tried to import `./features/user-profiles/lib/UserGateway` and `tsc` 404'd the module. `event-pages/PageRoom.ts` worked only because that feature happens to also have `actions/`. Fix: run the discovery + lib-copy path whenever the feature has either actions OR lib files. Copying `lib/` files when the feature has at least one of either is the safe reading of the original intent.\n\n**Drops ~20 of the 230 attendvip errors** (TS2300 ×2, TS2448 ×11, TS2304 ×6, TS2554 ×2 from the realtime gate, TS2307 ×1 — depending on cache state). The remaining 210 are TS2769 (numeric-ID arrays where the column is `integer`, not `text`) and TS2339 (`.id` referenced on tables that have a non-`id` PK or a compound PK) — both downstream of the same root: `id` is currently *not* auto-injected, only audit columns are.\n\n### Account auth: emailOtp on AWS SES drops the magic-link companion (OTP-only)\n\nThe compiler used to auto-wire `createComboAuthSendVerificationOTP` from `@quickback-dev/better-auth-combo-auth` whenever a project used `emailOtp` with the `aws-ses` email provider — sign-in / sign-up / verify emails carried *both* a 6-digit OTP and a clickable magic link, with `useComboAuthEmail: true` in the SES config. This was on by default for every account-app project that picked AWS SES.\n\nTwo reasons to drop the magic-link half:\n\n1. **Mail-client URL prefetching can burn the OTP before the human sees the email.** Outlook Safe Links, Gmail mobile, corporate proxies, and security scanners all eagerly fetch URLs in incoming mail; the magic link's `?data=...` payload includes the OTP server-side, so the first GET completes the sign-in (consuming the one-time code) and the user clicking through 30 seconds later gets a \"code already used\" failure.\n2. **Two sign-in surfaces are harder to support.** The account SPA's `/welcome` and `/email-otp` routes only render the OTP form; the magic-link arm bypasses that UI entirely. One canonical entry point (enter the code) keeps the account flow legible.\n\nThe compiler now emits a plain `sendVerificationOTP` callback that calls `sendEmailWithSES` with `emailTemplates.emailOTP` directly — no combo wrapper, no magic-link URL. `useComboAuthEmail` is hardcoded to `false`. The `@quickback-dev/better-auth-combo-auth` package and the `magicLink` plugin are still available for users who explicitly opt in via a custom `sendVerificationOTP` in their config; the change here is just the auto-wired default.\n\nTest coverage: `auth-email-wiring.test.ts` was updated to assert the new shape — generated auth files for `emailOtp + aws-ses` now contain `emailTemplates.emailOTP` and `useComboAuthEmail: false`, and explicitly do not contain `createComboAuthSendVerificationOTP` or `better-auth-combo-auth`.\n\n### Coming next — `id` field auto-injection (v0.14.8)\n\nThe compiler treats `id` as load-bearing across CRUD/action route generators, FK probing, access checks, OpenAPI emission, and CMS — but doesn't add it for you the way it adds `createdAt`/`modifiedAt`/`createdBy`/`modifiedBy` (or `organizationId` in org-scoped features, or `deletedAt`/`deletedBy` for soft-delete tables). Tables that omit `id` (or use a non-`id` single PK like `userId.primaryKey()`, or a compound `primaryKey({ columns: [...] })` constraint) are accepted at parse time but produce broken output downstream. AttendVIP's `user_profiles`, `user_presence`, `user_notification_prefs`, `chat_reads`, and `chat_channel_members` all hit this.\n\n**Agreed direction:** mirror `injectAuditFields` with a new `injectIdField` that runs unconditionally — including on junction tables. Tables with no PK or a non-`id` PK get an `id` column auto-injected; existing column-level `.primaryKey()` on a non-`id` column gets demoted to `.notNull()`; `primaryKey({ columns: [...] })` constraints get rewritten to `uniqueIndex().on(...)`. The cost (one extra column per junction row) is minimal and closes the asymmetry — every table participating in routes gets a single string-typed `id`, just like every table gets `createdAt`. Migration tail (existing D1 databases need an ADD COLUMN + index rewrite per affected table) is generated alongside.\n\nNo user code changes required for the four fixes shipping in v0.14.7. Recompile and the affected features typecheck.\n\n---\n\n## v0.14.6 — May 7, 2026\n\n### Four more v0.14 compiler bugs caught by AttendVIP's MCP rollout\n\nFiled in `research/attendvip-v014-mcp-and-firewall-gaps.md` after AttendVIP patched these locally and asked us to upstream them. All four ride a single MCP `tools/call` against a team-scoped resource over a Bearer api-key — fix any one and the next bug surfaces. We're shipping them as one patch release with end-to-end coverage of the chain.\n\n**1. MCP `tools/call` URL is double-prefixed for action tools.** The OpenAPI spec emits action paths as `/api/v1/<action>` already-absolute, but the MCP request builder did `'/api/v1' + tool._path` unconditionally — so action tool calls hit `/api/v1/api/v1/<action>` and 404'd. CRUD tools (bare `_path: '/customers'`) were unaffected. Fix: prefix only when `_path` doesn't already start with `/api/v1/`.\n\n**2. Auth middleware ignored `Authorization: Bearer <api-key>`.** MCP clients (claude.ai, etc.) only set `Authorization: Bearer ...`. The api-key block read from `x-api-key` header / `?api_key=` / `?key=` query but not from `Authorization`; the JWT fast-path narrowly gated on `bearerToken.startsWith('eyJ')`. Non-JWT bearers fell through to BA session auth, which doesn't recognise api-keys, so the request authenticated as anonymous and `tools/list` returned only PUBLIC tools. Fix: api-key extraction now also accepts a non-JWT `Authorization: Bearer <token>` as the key candidate. Three transports for one credential — header / query / Bearer.\n\n**3. `auth.roleHierarchy` was silently inert for runtime role checks.** A user configured `auth.roleHierarchy: ['owner', 'admin', 'member']` and expected an `owner` to satisfy any check requiring `admin` or `member`. But the api-key + JWT fast-paths populated `ctx.roles` with the single org-member role, and the access checker did strict intersection — owner ∩ {admin, member} = ∅ → 403. Fix: at the api-key, JWT fast-path, AND BA session paths, expand the user's role via `auth.roleHierarchy` so a higher role inherits all lower-role privileges. The hierarchy is auto-normalized — users who write the array reversed (`['owner', 'admin', 'member']` instead of the documented `['member', 'admin', 'owner']`) now get the same correct expansion.\n\n**4. Team-firewall predicate hardcoded `eq(table.teamId, ctx.activeTeamId!)` even when no team was active.** The `!` non-null assertion lied at runtime — api-keys, JWTs, and sessions without an active team carry `undefined`. The resulting SQL was `team_id = NULL` which matches nothing, so api-key callers saw zero rows on team-scoped resources. Fix: emit the team predicate as `(ctx.activeTeamId ? eq(...) : undefined)` — drizzle's `and(...)` drops `undefined`, so the WHERE collapses to the org scope only. Org and owner predicates are deliberately NOT softened the same way (those are security boundaries, not optional scopes).\n\nAfter upstreaming, the AttendVIP one-shot verification passes:\n\n```bash\ncurl -fs -X POST https://attend.vip/mcp \\\n -H \"Authorization: Bearer $TOKEN\" -H 'Content-Type: application/json' \\\n -d '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"listEvents\",\"arguments\":{}}}' \\\n | jq '.result.content[0].text | fromjson | .data | length' # > 0\n```\n\nNo user code changes required for any of the four. Recompile and the MCP path works end-to-end against team-scoped, role-gated resources via Bearer api-key.\n\n---\n\n## v0.14.5 — May 7, 2026\n\n### MCP `tools/call` no longer crashes with `undefined (reading 'AUTH_DB')`\n\nThe generated MCP server's `tools/call` dispatch re-enters the same Hono app via `app.request(internalReq)` so every tool invocation runs through the full middleware chain (auth, firewall, access, guards, masking). But the call passed only the request — not `env` or `executionCtx` — so the sub-request handler ran with `c.env === undefined`. Any tool whose route touched a Cloudflare binding (e.g. the `AUTH_DB` D1, KV, R2, Queues) crashed with `Cannot read properties of undefined (reading 'AUTH_DB')`. Found by AttendVIP — every action that hit auth-side data (acceptInvite, etc.) failed.\n\n**Fix:** `mountMcp` now threads `c.env` and `c.executionCtx` through to `handle → handleRpc → callTool → app.request(internalReq, undefined, env, executionCtx)`. Hono's `request()` 3rd/4th args set the bindings + execution context for the sub-request, so the action handler sees the same env the outer worker received. Tools/list was unaffected — it reads ctx in-process and never re-enters the app.\n\nNo user code changes required. Recompile against v0.14.5 and the MCP endpoint dispatches actions correctly against all bindings.\n\n---\n\n## v0.14.4 — May 7, 2026\n\n### `via:` firewall predicates no longer crash with `ReferenceError: db is not defined`\n\nThe relationship-role generator (v0.14.0) emits a `buildFirewallConditions` body that references `db`, `inArray`, and `sql` at function scope when any predicate has `via:` — but the resource-file imports it generated only pulled in `eq, and, isNull, type SQL`. So every endpoint guarded by `firewall: [{ field, via }]` threw `ReferenceError: db is not defined` at the very first request, and the catch-all returned 500 before the firewall query ever ran. Found by AttendVIP on `/api/v1/event-pages` against v0.14.3 — none of the v0.14.0 → v0.14.3 unit tests exercised emitted-import resolution, so the bug rode through three patch releases.\n\nTwo fixes:\n\n1. **Imports in the generated resource file now include `inArray, sql`** when the firewall has any `via:` predicate. Hidden behind a flag so a no-via resource still gets the minimal import surface.\n2. **`buildFirewallConditions` now takes `(ctx, db)`** and the wrapper template (`WITH_FIREWALL_HELPER`) pulls `const db = c.get('db' as never) as any;` from the Hono context before invoking it. Every CRUD/action call site (single-record + batch + record-based-action) was updated to pass `db` through.\n\nRegression test added (`firewall-via-imports.test.ts`) that parses the generated resource file's top-level imports and asserts every free identifier referenced in `buildFirewallConditions` resolves to either an import or a function parameter — so a future generator change that introduces a new free identifier (`exists`, `not`, etc.) without importing it fails the unit suite instead of leaking to a real project.\n\nNo user code changes required — recompile and `via:` predicates work end-to-end.\n\n---\n\n## v0.14.3 — May 7, 2026\n\n### Relationship-role consumers now resolve the relationship-table binding at runtime\n\nPre-fix, the v0.14.0 relationship-role generator emitted imports like `import { eventGuests, buildFirewallConditions as buildEventGuestsFirewallConditions } from '../event-guests/event-guests.resource'` on every consuming resource — but the relationship-table's own `.resource.ts` file imported `event_guests` from `./schema` for its own use without re-exporting it. So the consuming file got `undefined` at runtime, every relationship subquery failed with `Cannot read properties of undefined`, and the whole authz layer was unreachable on real projects.\n\nFound by AttendVIP within minutes of recompiling against v0.14.2: the moment they hit any endpoint guarded by `firewall: [{ field, via }]` or `crud.<op>.access roles: ['guest']`, the request errored before the firewall query ran.\n\nThe fix is one line in `generateTableResourceHelpers` — re-export the Drizzle table binding from the `.resource` file alongside the existing import. The `.resource` file is the public surface of the table; the schema is an implementation detail. This decision was implicit in the relationship-import resolver's path choice but not enforced on the producer side.\n\n```ts\n// generated <table>.resource.ts (after fix)\n\nexport { event_guests }; // ← was missing\n```\n\nRegression test added (`authz-end-to-end.test.ts`) that asserts every `.resource` file re-exports its Drizzle binding, so this can't drift again. No user code changes required — recompile and the cross-feature relationship subqueries resolve correctly.\n\n---\n\n## v0.14.2 — May 7, 2026\n\n### Wrangler `[[migrations]]` no longer drops historical Durable Object lifecycle entries\n\nCloudflare requires the `[[migrations]]` list in `wrangler.toml` to be **append-only**: once a tag has been deployed, removing it on a subsequent compile causes the next deploy to fail with `Cannot apply <new|deleted|renamed|transferred>-class migration to class <X>` — CF replays the full migrations log on every push and notices the tag is gone.\n\nPre-fix, the compiler regenerated the `[[migrations]]` blocks from scratch on every compile, emitting only entries for the *current* `durableObjects` bindings. Any historical lifecycle events the user had hand-maintained — `deleted_classes`, `renamed_classes`, `transferred_classes` — were silently dropped and the deploy then broke. AttendVIP hit this first: a `qb-do-deleted-legacy-notes-2026-05-05` deletion entry got dropped, and the next deploy tried to re-apply `qb-do-Notepad`'s `new_sqlite_classes` against the existing class.\n\nThe fix adds a new config slot — `bindings.durableObjectMigrations` — for historical entries that survive recompiles. Declared entries are emitted FIRST in the generated `wrangler.toml`'s migrations list (preserving chronological order), then the auto-generated current-class creation entries follow, deduplicated by tag so an explicit user entry wins over the auto-emit.\n\n```ts\n// quickback.config.ts\nbindings: {\n durableObjects: [\n { name: 'NOTEPAD', className: 'Notepad', from: 'lib/Notepad' },\n ],\n durableObjectMigrations: [\n // Carry forward across recompiles — Cloudflare's migration list is append-only.\n {\n tag: 'qb-do-deleted-legacy-notes-2026-05-05',\n deletedClasses: ['LegacyNotes'],\n },\n ],\n}\n```\n\nAll four lifecycle shapes are supported: `newClasses` / `newSqliteClasses` (creations), `deletedClasses` (removals), `renamedClasses` (`{ from, to }` inline-table-array), `transferredClasses` (`{ from, from_script, to }` for moves between workers). The user-declared entry can also override the auto-emit by reusing the same tag — useful when a DO started life as KV-backed before SQLite-DOs existed.\n\nThis is a config-side fix, not a wrangler.toml-merging one — Quickback doesn't read your existing `wrangler.toml`. The discipline is the same as for any append-only log: declare lifecycle events as you make them. Auto-detection of removed classes from the schema diff is on the roadmap; for now the compiler trusts your declaration.\n\n7 new tests covering deletion, rename, transfer, multi-entry ordering, override-via-same-tag, no-history bit-identical output, and the historical-only-no-current-DOs edge case.\n\n---\n\n## v0.14.1 — May 7, 2026\n\n### Bulk action variants now appear in `openapi.json`\n\nRecord-based actions with `bulkVariant: true` (introduced in v0.14.0) generate a working `POST /<base>/batch/<actionName>` route at runtime, but the OpenAPI generator wasn't aware of them — so the bulk endpoints were invisible to typed-client codegen (`api-types.gen.ts`) and to MCP-driven agents discovering operations from the spec. AttendVIP's v0.14.0 rollout (seven actions with `bulkVariant: true`: `approve`, `checkIn`, `checkOut`, `setVisibility`, `cancelInvite`, `sendInvite`, `sessionApprove`) found this within hours of shipping.\n\nThe OpenAPI generator now emits each bulk variant as a sibling operation to its per-record action, with the documented request shape (`{ ids: string[], input, failFast? }`), correct 200 / 207 / 400 responses, an `x-bulk-variant: true` marker, and a separate `<resource><Action>Bulk` `operationId` so client codegen can distinguish single from bulk. The fix also threads `bulkVariant` through `getAllActions` so any other downstream consumer of the action registry sees the flag — previously the parser captured it but the spec-emit path silently dropped it.\n\nNo changes required in user code. Re-running `quickback compile` regenerates `openapi.json` with both routes per `bulkVariant: true` action; downstream `api-types.gen.ts` builds pick up the new operations on the next codegen run.\n\n### Cross-tenant \"my events\" pattern documented with a worked example\n\nThe v0.14.0 docs noted that relationship-roles do **not** solve cross-tenant aggregation (\"a guest's view of events across all tenants they were invited to\") and pointed at function-form access as the workaround, but didn't show what that looked like in practice. The access docs now carry a full standalone-action example for `GET /my-events` — the canonical attendee-dashboard pattern — including the two security guardrails (always filter by `ctx.userId`; the action takes responsibility for soft-delete and other invariants the firewall would otherwise apply). Standalone actions are already mandatorily audit-logged in the runtime, so the cross-tenant traversal is recorded automatically.\n\nSee [Access → Cross-tenant \"my events\" 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 roles\n\nQuickback's role system now supports a third kind of role beyond Better Auth org membership and the four pseudo-roles (`PUBLIC`/`AUTHENTICATED`/`USER`/`ADMIN`): **relationship-roles** that bind to a domain-table membership (\"user is a confirmed guest of this event\") rather than an org/admin gate. The original ask was a B2B event-management app where logged-in users who aren't team members but ARE confirmed guests of an event need to see that event's sessions, pages, and tracks — same data, different access lane. The old workarounds (function-form access, hand-written actions, `firewall: { exception: true }`) all gave up some combination of OpenAPI/MCP visibility, CRUD code generation, or tenant safety.\n\nDeclare the relationship once in `quickback.config.ts`, then reference it from `firewall:` or `access.roles:`:\n\n```ts\n// quickback.config.ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests', // relationship table\n subject: { column: 'userId', equals: 'ctx.userId' }, // caller side\n resource: { column: 'eventId' }, // resource side\n where: { status: 'confirmed' }, // optional row filter\n },\n },\n roles: {\n guest: { via: 'guestOf' },\n eventStaff: {\n or: [{ via: 'guestOf' }, { roles: ['admin', 'owner'] }],\n },\n },\n}\n\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' }, // ← row scoping\n],\nread: { access: { roles: ['admin', 'member', 'guest'] } }, // ← OR-composed\ncrud: {\n create: { access: { roles: ['admin', 'guest'] } }, // inline async lookup\n update: { access: { roles: ['admin'] } },\n}\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 `buildFirewallConditions(ctx)` is called inside the subquery so soft-delete and tenant scope on the relationship row are always honored — soft-deleting an `event_guests` row revokes access immediately. Anonymous callers fail closed (the subquery short-circuits to `WHERE 1 = 0` when `ctx.userId` is null). Cross-tenant grants are impossible because the resource's tenant filter sits as the outermost AND, never folded into a role OR. See [Firewall → Relationship-based scoping](/compiler/definitions/firewall#relationship-based-scoping-via) and [Access → Relationship-based authorization](/compiler/definitions/access#relationship-based-authorization).\n\nWhat works in v0.14.0:\n\n| Surface | Status |\n|---|---|\n| `firewall: [{ field, via }]` row-level scoping | Full |\n| `crud.<op>.access` `roles: ['guest']` (inline emission) | Full |\n| `read.access` and `read.views.*.access` | Full |\n| `masking.<f>.show` `roles: ['guest']` | Compile-refused (workaround pointer) |\n| `actions.<n>.access` `roles: ['guest']` | Compile-refused (workaround pointer) |\n\nThe runtime evaluator fails closed on relationship arms regardless of which surface you hit, so silent grants are impossible everywhere. The two refused surfaces have clear compile-time errors pointing to the working pattern (gate the row at the firewall layer with `via:`, gate the role at the access layer with BA roles).\n\nCompile-time refusals also catch: unknown `via:` reference, cycles in role composition (`a → b → a`), reserved role-name shadowing (auth-provider-derived only — `guest`/`speaker`/`attendee` are free; `admin`/`owner`/`member` are reserved when the BA org plugin is on), unknown relationship `from` table, resource missing the `resource.column`, relationship table with `firewall: { exception: true }` (would let cross-tenant grants slip through), `lowering: 'session'` (reserved for v2 — staleness/invalidation ergonomics not yet shipped), and `+` hierarchy on relationship-roles (terminal, like pseudo-roles).\n\nCross-tenant \"my events\" dashboards (a logged-in user wants `GET /my-events` returning events they're a guest of *across all tenants*) are **not** solved by relationship-roles — the tenant firewall stays the outermost AND. For that pattern, use a user-scoped firewall (`firewall: { owner: { column: 'userId' } }`) or function-form access on a dedicated route. Documented prominently in [access.mdx](/compiler/definitions/access#cross-tenant-my-events-dashboards-are-not-this) so users don't reach for relationship-roles first and get confused.\n\nRoadmap: `lowering: 'session'` ergonomics, inline relationship emission for `actions.access` (needs `relationshipBindings` design), async/batched mask functions for `masking.show`. The schema slots are reserved so v2 lands non-breaking.\n\n### Bulk variants of record-based actions\n\nRecord-based actions can now opt into an auto-generated bulk route alongside the per-record route. Set `bulkVariant: true` on a `defineAction({...})` and the compiler emits `POST /:resource/batch/{action}` that loops the same access + transition + execute pipeline over a `{ ids: [...], input, failFast? }` body. The original ask was an event-management UX where every domain bulk operation (approve N guests, rescind N invites, advance N applications) became a hand-written standalone action that re-implemented a per-record action's transition + execute logic in a `for` loop — `PATCH /:resource/batch` couldn't do it because state lives on a protected field, which is the right call for safety.\n\n```ts\n// features/applications/actions/advance.ts\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n bulkVariant: true, // ← opt-in\n transition: { field: \"status\", via: \"nextStatus\", fromTo: { /* ... */ } },\n async execute({ db, record, input, whereTransition }) {\n // exact same body as before — runs once per id\n },\n});\n```\n\nPer-record outcomes return as 207 Multi-Status with the same `{ success, errors, meta }` shape as `PATCH /batch`. Each id flows through the firewall fetch, the per-record `evaluateAccessReason` split (403 role / 409 record-precondition), the transition pre-check, and the same `whereTransition` factory the single-record route uses — so a stale-state record fails for that id alone, not the whole batch. `failFast: true` aborts on the first failure and (on Postgres / Supabase / Neon / libsql / sqlite drivers) wraps the loop in `db.transaction()` so prior writes roll back; D1 is documented as fail-fast-without-rollback because it has no `db.transaction`.\n\nCompile-time refusals: `bulkVariant: true` is rejected on standalone actions (no record context to loop over) and on actions that declare `unsafe` (cross-tenant per-record audit not yet wired). Method is forced to POST regardless of the action's `method` setting — the one-row-to-many-rows asymmetry makes inheriting GET/DELETE confusing. Max batch size is 100 ids per request, mirroring the CRUD batch endpoints. See [Actions → Bulk variant](/compiler/definitions/actions#bulk-variant).\n\n### Aggregations on read views\n\nRead views can now declare pre-computed metrics that surface on the response next to the row payload, without a custom standalone action. Every dashboard tile that previously turned into a standalone action just for \"count of X grouped by Y\" now lives in the same view config that drives the rows.\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\nResponse carries `aggregations: { ... }` alongside `data`:\n\n```json\n{\n \"data\": [/* paginated rows */],\n \"view\": \"pipeline\",\n \"pagination\": { \"count\": 50, \"page\": 1, \"pageSize\": 50, \"hasMore\": true },\n \"aggregations\": {\n \"totalApplications\": 173,\n \"byStatus\": { \"applied\": 102, \"screening\": 41, \"interview\": 18, \"offer\": 7, \"rejected\": 5 }\n }\n}\n```\n\nAggregations always run over the **same firewalled, filtered set** as the row query — pagination is intentionally ignored, so `?status=applied&limit=10` returns the 10 paged rows AND the count over every applied row. Supported `fn`s: `sum`, `avg`, `min`, `max`, `count` (with or without `field` — `COUNT(*)` vs `COUNT(field)`), `count_distinct`, and `groupBy` (returns `{ value: count }`, NULLs bucket as `\"(none)\"`).\n\nCompile-time validation: `field` must reference a real column; `sum`/`avg` require numeric column types; the same masking opt-out gate that governs `query.{filterable, sortable, searchable}` applies to aggregations (a `sum(salary)` leaks structure even when the row payload is redacted); aggregation names cannot collide with the reserved response fields `data`, `pagination`, `view`. No raw SQL `expr:` form in v1 — column references only. See [Views → Aggregations](/compiler/definitions/views#aggregations).\n\n---\n\n## v0.13.5 — May 6, 2026\n\n### Object-form `auth.plugins` no longer crashes the compiler\n\nThe documented object form for per-plugin config — `plugins: { oauthProvider: {...} }`, `plugins: { organization: { teams: { enabled: true } } }`, etc. (see [Better Auth Plugins → Custom configuration](/stack/auth/plugins#oauth-provider-mcp-ready)) — was rejected by the compiler with `plugins.includes is not a function`. `hasCliAuthRoutes` called `.includes()` directly on `auth.config.plugins` to detect `deviceAuthorization`, and `generateAuthFiles` flattened plugins to a string array before handing them to the better-auth generator, silently dropping every per-plugin user option on the way through.\n\nBoth paths now run through a shared resolver that preserves the user's input format (object in → object out, array in → array out) and only adds the compiler's auto-included plugins (`organization`, `admin`, `apiKey`, plus `bearer` when `deviceAuthorization` is present) as `true` entries that don't clobber user config. Per-plugin options like `oauthProvider: { scopes: [...] }`, `organization: { teams: { enabled: true } }`, and `deviceAuthorization: { verificationUri: '...' }` now reach the generated `auth.ts` as written.\n\nBetter Auth's `ac` / `roles` access-control objects (the result of `createAccessControl(...)`) still require a custom `auth.ts` override — they're live runtime values that can't survive the JSON config trip from CLI → compiler. A declarative escape hatch for that is on the roadmap.\n\n### `roles: [\"PUBLIC\"]` is allowed on writes and actions again\n\nv0.10.17 added a compile-time block that rejected `roles: [\"PUBLIC\"]` on `crud.create` / `crud.update` / `crud.delete` and on every action. The intent — \"anonymous mutations are usually a misconfiguration\" — collided with the legitimate use cases the rest of Quickback was built around: Gmail one-click RSVP confirms, public RSVP forms, magic-link redemption, List-Unsubscribe-Post handlers, webhook ingest, captcha-gated contact forms. None of those carry a session, so `AUTHENTICATED` 401s the caller before the handler can validate its own token, and the suggested escape hatch (\"custom action that does its own auth + `firewall: { exception: true }`\") was itself blocked by the same validator.\n\nThe block is removed. `PUBLIC` is the explicit, uppercase opt-in for unauthenticated access on every access node — reads, CRUD writes, views, and actions. The compiler trusts the marker; row-level safety comes from firewall, masking, and the action's own token validation. `PUBLIC` actions continue to receive **mandatory audit logging** (IP, input, result, timing) in the runtime regardless. `crud.create`/`update`/`delete` typically pair `roles: [\"PUBLIC\"]` with `firewall: { exception: true }` on the resource so the row predicate doesn't reject every unauthenticated caller.\n\n`USER` and `ADMIN` keep their compile-time prerequisites (firewall must scope by `userId` / admin plugin must be enabled).\n\n---\n\n## v0.12.0 — May 5, 2026\n\n### Per-room authorization for PartyServer rooms\n\n`bindings.durableObjects[].access` lets the compiler emit a path-scoped gate that runs the declared resource's existing firewall + `read.access` pipeline before the WebSocket upgrade — same pillars `GET /api/v1/<resource>/:id` enforces, zero hand-written auth code.\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 game 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, and lets the upgrade proceed otherwise. DOs without an `access` declaration keep the v0.11.1 catchall (just `ctx.authenticated`). Resource references are validated against feature names at compile time so typos break the build, not the first WebSocket upgrade. See [PartyServer Rooms → Per-room authorization via access](/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 now secure by default\n\nThe `/realtime/*` auto-mount shipped in v0.11.0 didn't gate WebSocket upgrades — anyone who knew a room ID (CUID2, hard to guess but not a security boundary) could open a connection. `authMiddleware` populated the request context but `partyserverMiddleware` doesn't 401 anonymous upgrades on its own.\n\nThe auto-mount now wraps `partyserverMiddleware` in an auth check: `401 Unauthorized` if the caller has no resolved auth context, otherwise the upgrade proceeds. The four auth mechanisms the rest of the worker honors (session cookie, JWT bearer, `x-api-key` header, `?api_key=` / `?key=` query) all unlock connections automatically.\n\nPer-room access (e.g., \"is this user a member of the org that owns this room?\") is still your `Server` class's responsibility in `onConnect` — the auto-mount only enforces \"are you authenticated at all.\" Hand-written mounts with custom `onBeforeConnect` continue to work unchanged; declare them at `/realtime/*` before the auto-mount runs to opt out of the default gate.\n\nNo code changes required — `quickback compile` regenerates the gated mount automatically. Single-tenant alphas weren't exploitable in practice (room IDs aren't logged or surfaced); multi-tenant projects should redeploy to pick this up.\n\n---\n\n## v0.11.0 — May 5, 2026\n\n### OAuth Provider plugin (MCP-ready)\n\nQuickback can now 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 it with `plugins: [\"oauthProvider\"]` in your auth config — the compiler auto-includes Better Auth's `jwt` plugin (the OAuth provider delegates access-token signing to it) 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 future MCP client (Cursor, Claude Desktop, claude.ai connectors, custom tooling) RFC 7591 dynamic client registration + the well-known discovery documents they need to bootstrap themselves. See [Auth Plugins → OAuth Provider](/stack/auth/plugins#oauth-provider-mcp-ready).\n\n### API key auth via query parameter\n\nThe auth middleware now accepts API keys as `?api_key=...` or `?key=...` query parameters in addition to the `x-api-key` header. The header takes precedence when both are sent. This unblocks clients that can't inject custom headers — most notably claude.ai's MCP connector, which previously returned zero tools because every list/call attempt was unauthenticated.\n\nThe query-param form lands in access logs and `Referer` headers; prefer the header whenever the client supports it. See [Auth Plugins → API Keys](/stack/auth/plugins#api-keys).\n\n### PartyServer rooms + realtime URL split (breaking)\n\nThe realtime URL space is reorganized so the names match what each primitive does:\n\n- **`/realtime/v1/*` → `/broadcast/v1/*`** — the existing org-wide Broadcaster (Postgres-changes fan-out, ws-ticket auth) moves to its semantically accurate prefix. Same code, same behavior, just a different mount point.\n- **`/realtime/<binding>/<room-id>` is the new mount for [PartyServer](/stack/realtime/partyserver-rooms) rooms** — bidirectional, per-room (per-document) Durable Objects with presence and lifecycle hooks. Auto-mounted via `hono-party` whenever a project declares any in-worker DO via `bindings.durableObjects[].from`. Use these for collaborative editing, live cursors, and per-room state.\n\n**Breaking changes** — recompile + redeploy required:\n\n- The `REALTIME_URL` runtime env var is renamed to `BROADCAST_URL` (used by the org member-update broadcast hook in separate-mode realtime). If you set this via `wrangler secret put REALTIME_URL`, re-set it as `BROADCAST_URL`.\n- The auth-ui SPA helpers `getRealtimeWsUrl()` / `getRealtimeTicketUrl()` are renamed to `getBroadcastWsUrl()` / `getBroadcastTicketUrl()`. The `appConfig.routes.api.realtime` field is renamed to `appConfig.routes.api.broadcast`.\n- WebSocket subscribers that hardcoded `/realtime/v1/websocket` or `/realtime/v1/ws-ticket` need to be updated to `/broadcast/v1/...`. The bundled CMS and Account SPAs handle this automatically; custom clients need a one-line change.\n\n**Pre-installed deps in the compiler image:** `partyserver`, `partysocket`, and `hono-party` are now cached in `/deps/node_modules` so opt-in collab projects compile without an extra `npm install` step. `Y-PartyServer` (Yjs CRDT support) stays opt-in.\n\n**Recipe:** see the new [PartyServer Rooms](/stack/realtime/partyserver-rooms) doc page and the `examples/recruitment` interview-room demo for an end-to-end example with presence and live notes.\n\n---\n\n## v0.10.20 — May 4, 2026\n\n### In-worker Durable Objects via `bindings.durableObjects[].from`\n\n`bindings.durableObjects` previously only emitted the binding declaration — useful for cross-worker DOs (`scriptName: \"other-worker\"`), but not enough for app-owned classes that live in this worker's source. Authors had to hand-edit `src/index.ts` (to add `export { ItemStream } from './...'`) and `wrangler.toml` (to add the `[[migrations]]` block) on every compile.\n\nAdding `from` flips the entry into in-worker mode and the compiler does both:\n\n```ts\ndurableObjects: [\n {\n name: \"ITEM_STREAM\",\n className: \"ItemStream\",\n from: \"features/loops/lib/ItemStream\", // module path under src/\n },\n]\n```\n\nGenerates:\n- `src/index.ts`: `export { ItemStream } from './features/loops/lib/ItemStream';` — wrangler resolves the binding by class export.\n- `wrangler.toml`: a `[[migrations]]` block with `tag = \"qb-do-ItemStream\"` and `new_sqlite_classes = [\"ItemStream\"]`.\n- `CloudflareBindings`: `ITEM_STREAM: DurableObjectNamespace` so `c.env.ITEM_STREAM.idFromName(...)` typechecks.\n\nWhere the class file lives: in-worker DO classes go under `quickback/lib/` or `quickback/features/<feature>/lib/` — both copy verbatim into the generated `src/` tree on every compile (the rest of `src/` is wiped). The `from` value is the resulting `src/`-relative path with no `./` prefix and no `.ts` suffix.\n\n`from` and `scriptName` are mutually exclusive — the compiler rejects entries that set both. Cross-worker entries (`scriptName` set) skip the re-export and the migration block; the exporting worker owns its own migration table.\n\n`migrationTag` (default `qb-do-${className}`) is stable across regenerations and **must never be removed or renamed once deployed** — wrangler tracks applied tags and will reject deploys that try to walk them back. `useSqlite` defaults to `true`; set to `false` for legacy KV-backed DOs.\n\nSee [Bindings → Durable Objects](/compiler/config/bindings#durableobjects) for the full reference.\n\n---\n\n## v0.10.19 — May 4, 2026\n\n### Fix: bundled-SPA auth survives `wrangler dev` on custom_domain projects\n\n`wrangler dev` rewrites the configured `custom_domain` host in **every** response header value (Location, Content-Security-Policy, X-…) to the local hostname, with a case-sensitive substring matcher. That mangles the CSP `connect-src` for projects with `domain: \"api.example.com\"` + bundled CMS / Account SPAs:\n\n```\n# Compiled (correct)\nconnect-src 'self' https://api.example.com …\n\n# Served by wrangler dev (mangled)\nconnect-src 'self' https://localhost:8787 …\n```\n\nResult: the bundled SPA's hardcoded `VITE_QUICKBACK_API_URL` fetches get blocked in dev because the CSP only allows localhost. Reported by Loop on the 0.10.18 thread; verified end-to-end with a minimal `wrangler@4.85.0 dev --local` repro.\n\nThe compiler now emits the SPA-baked-origin literal in `connect-src` with the host's first letter capitalised (`https://Api.example.com`). CSP host-source matching is ASCII case-insensitive per CSP3, so browsers accept it for connections to `https://api.example.com`; wrangler's case-sensitive matcher misses it. The case-shift is applied at compile time and only to URLs whose host matches the configured `custom_domain` — other origins (localhost, third-party hosts) are unchanged.\n\n`TRUSTED_ORIGINS` keeps its lowercase prod entries: it's consumed by the CORS `isTrustedOrigin` check via `Array.includes()` against the browser-supplied Origin header (always lowercase). The CSP fix only needs to land on the SPA-baked literal — that's the entry the SPA's hardcoded fetch needs covered.\n\nIf wrangler ships a fix for the response-header rewrite, the case-shifted source remains a valid CSP entry that browsers match identically — no follow-up needed in user code.\n\n**Action required:** none. Recompile (`quickback compile`) to pick up the fix.\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` flag emitted into the generated `wrangler.toml`. Useful for \"share prod auth in dev, keep feature writes sandboxed\":\n\n```ts\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n splitDatabases: true,\n experimentalRemote: {\n auth: true, // wrangler dev reads/writes deployed AUTH_DB\n features: false, // (default) features stays local\n audit: false,\n webhooks: false,\n files: false,\n },\n }),\n}\n```\n\nKeys are logical binding names — `auth` flips the flag on the `AUTH_DB` binding, `features` flips it on `DB` (or the legacy single-DB binding), `audit` / `webhooks` / `files` follow the same pattern. Off by default; only enable for databases you intend to share.\n\n### Google OAuth + signup ToS\n\nThe Account SPA now wires Google OAuth end-to-end when `auth.providers.auth.config.socialProviders.google.enabled: true`. The compiler bakes the right `VITE_ENABLE_GOOGLE_OAUTH` flag into the SPA's `.env` so the social-login button renders only when the provider is enabled — no more dead buttons.\n\nSignup flow gains a Terms-of-Service checkbox gate (configurable via the Account SPA's branding config).\n\n### CLI compile auth gate + device-auth redirect fix\n\n- `quickback compile` now requires authentication for cloud-compiler runs (closes the unauth public-compile path).\n- The device-flow `/cli/authorize` page was sending `?returnTo=` to login, but `signup.tsx` and the `_authenticated` middleware only read `?redirect=` — so a user who clicked \"Create one\" from `/login` lost the return URL. Standardized on `?redirect=` everywhere.\n\n### Skill restructure (Claude Code skill)\n\nThe bundled Claude Code skill was reorganized for clarity:\n\n- `SKILL.md` is now a thin orientation pointer, not a 600-line dump\n- Reference docs split into `Compiler` and `Stack` sections\n- Docs bundled as **files** the model navigates with `Read` / `Glob` rather than via `quickback docs <topic>` shell calls — same content, fewer tool calls per lookup\n- Tightened against audit gaps surfaced by red-team review\n\nRun `quickback claude install` to pick up the new skill layout.\n\n---\n\n## v0.10.17 — May 2, 2026\n\n### Security fix: CSP auto-config no longer widens `default-src`\n\nWhen 0.10.15's auto-config was asked to add a value to a directive the user hadn't declared (e.g. `https://fonts.googleapis.com` → `style-src` when only `default-src` was set), it incorrectly pushed the value into `default-src` itself. Because CSP3 fall-back semantics make `default-src` the fallback for `script-src`, `img-src`, `media-src`, and others, this widened the attack surface to every directive that fell back to it — a `style-src`-only host became reachable from `script-src`.\n\n0.10.17 fixes the logic: missing target directives are now **scaffolded** with the user's `default-src` values as baseline, then extended with the auto-config addition. `default-src` stays clean. The new directive (e.g. `style-src`) covers exactly the styles the SPA needs and nothing else.\n\nBefore (0.10.16):\n```\ndefault-src 'self' https://fonts.googleapis.com https://fonts.gstatic.com @trustedOrigins https://api.example.com\n```\n\nAfter (0.10.17):\n```\ndefault-src 'self'\nstyle-src 'self' 'unsafe-inline' https://fonts.googleapis.com\nfont-src 'self' https://fonts.gstatic.com\nconnect-src 'self' @trustedOrigins https://api.example.com\n```\n\n**Action required:** recompile (`quickback compile`) to regenerate the security middleware with the corrected scaffolding. Configs that already declared each `*-src` directive explicitly were unaffected by the bug — the regression only surfaced when users wrote `defaultSrc: ['@self']` and let auto-config fill in the rest.\n\nThe user-side workaround from 0.10.16 (declaring each directive with `['@self']` to force scaffold) is no longer needed in 0.10.17 — the compiler does the right thing automatically.\n\n---\n\n## v0.10.16 — May 2, 2026\n\n### CSP auto-config now covers SPA-baked-in API origins\n\nWhen the bundled CMS or Account SPA is enabled, the compiler already inlines the API URL into the SPA bundle as a string literal at build time (`VITE_QUICKBACK_API_URL=https://${unifiedDomain}`). That hardcoded URL is what the SPA actually fetches — regardless of which origin is currently serving the page. CSP `connect-src` must allow it explicitly.\n\n0.10.16's auto-config picks up every domain the compiler already knows about — `config.domain`, the inferred `quickback.{baseDomain}`, `cms.domain`, `account.domain`, the admin domain — and adds `https://${each}` to `connectSrc` whenever a bundled SPA is enabled.\n\nThe motivating case: running the SPA on `localhost:5173` while it's still baked against `https://quickback.your-app.com`. Pre-0.10.16 the localhost CSP's `'self'` blocked the prod URL; users were patching it manually. Now it just works.\n\n```\n[security] auto-added https://quickback.loop.kardoe.com to csp.connectSrc — account: true → bundled Account SPA → SPA bundle hardcodes https://quickback.loop.kardoe.com as VITE_QUICKBACK_API_URL / etc.\n```\n\n`@trustedOrigins` (the CORS allowlist) is unchanged — it still gets added independently. The two cover different things: `@trustedOrigins` permits CORS-allowed sibling subdomains; the new SPA-baked addition permits the exact URL the SPA's compiled bundle hardcodes.\n\nCombined with 0.10.15's bundled-SPA defaults, most projects can now 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 styleSrc font hosts, fontSrc gstatic, connectSrc trusted origins, and connectSrc SPA-baked URLs.\n\n---\n\n## v0.10.15 — May 2, 2026\n\n### CSP auto-config — bundled-SPA origins added automatically\n\nWhen `security.csp` is set, the compiler now widens directives **additively** based on the project's enabled features. The four rules:\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\nAnything you already wrote stays — auto-config never removes or overrides. Every applied addition prints to stderr at compile so the magic is visible:\n\n```\n[security] auto-added 'unsafe-inline' to csp.styleSrc — account: true → bundled Account SPA → inline style attributes from Tailwind / TanStack Router\n[security] auto-added @trustedOrigins to csp.connectSrc — CORS-trusted origins must be reachable from XHR/fetch (matches cors() allowlist)\n```\n\nThe recipe in [the security docs](/compiler/config/security#example-paste-in-csp-for-a-quickback-spa-project) becomes ~5 lines shorter — most projects no longer need to list `fonts.googleapis.com` / `fonts.gstatic.com` / `@trustedOrigins` themselves. **Loop's CSP shrinks dramatically** after recompiling against this version.\n\n**Opt-out:** `security: { cspAutoConfig: false, csp: { ... } }` for projects fronted by a CDN that injects its own CSP, or teams that want strict from-scratch control.\n\n**Smart fallback:** if you set `defaultSrc` but omit the target directive (e.g. `defaultSrc: ['@self']` and nothing for `connectSrc`), the addition lands in `defaultSrc` rather than creating a sibling directive — CSP fall-back semantics mean a sibling would *narrow* your intent, so we preserve the broader fallback.\n\n### Troubleshooting table for CSP violations\n\nThe security docs page now includes a [Troubleshooting CSP violations](/compiler/config/security#troubleshooting-csp-violations) table mapping browser console errors back to the directive that needs widening. Useful when auto-config is disabled or the project has a non-bundled SPA hitting third-party origins.\n\n### Out of scope (deferred)\n\n- **Per-request CSP nonces** (`@nonce` sentinel implementation) — Phase 2 / 0.10.16. Sentinel still errors at compile in 0.10.15.\n- **`revocationCheck: 'kv'` for `auth.jwt`** — schema accepts it, runtime still errors at compile. Slipped from 0.10.15 to 0.10.16.\n- **Public R2 host auto-add to `imgSrc`** — most R2 access today goes through the worker so the SPA fetches from `'@self'`. Will revisit once we have a clean way to discover public-bucket hosts at compile.\n\n---\n\n## v0.10.14 — May 1, 2026\n\n### `auth.jwt` — JWT bearer-token fast-path config\n\nQuickback's bearer-token JWT (the one minted by the auth middleware and consumed by the fast-path on every subsequent request) is now configurable. The most-tuned knob is `expiresIn` — drop it to bound the post-revocation replay window without affecting browser SPAs, which auto-refresh via `set-auth-token` on every authed call:\n\n```ts\nauth: {\n jwt: {\n expiresIn: 30, // 30s post-revocation replay window\n issuer: 'my-api', // iss claim (verified on the way back in)\n audience: 'partner-svc', // aud claim\n secretEnv: 'CUSTOM_JWT_SECRET', // override BETTER_AUTH_SECRET if you need the JWT secret rotated independently\n },\n}\n```\n\n`revocationCheck: 'kv'` (KV-denylist consult on every fast-path verify, ~5-15ms edge-cached, no D1 hit) is reserved in the schema today but **deferred to 0.10.15** — setting it errors at compile so the migration path is explicit. `'none'` (today's behaviour, 0 cost, replay bound by TTL) stays the default.\n\nSee [the docs page](/compiler/config/auth) for the full knob list and tuning recommendations.\n\n### MCP admin endpoints hidden from non-admin `tools/list`\n\nBetter Auth admin endpoints (`/admin/list-users`, `/admin/ban-user`, `/admin/impersonate-user`, etc. — 9 in total) now carry `x-access: { userRole: ['admin'] }` in the generated OpenAPI spec, which means the MCP server's existing access-filter automatically drops them from `tools/list` for callers without an admin token. Anonymous and member-role callers no longer see admin tooling enumerated through MCP; admin endpoints still exist on the HTTP surface (Better Auth gates them server-side regardless).\n\n### Declarative `security` config block\n\nEvery security response-header (`Content-Security-Policy`, `Cross-Origin-Opener-Policy`, `Cross-Origin-Embedder-Policy`, `Cross-Origin-Resource-Policy`, `X-Frame-Options`, `Strict-Transport-Security`, `Referrer-Policy`, `Permissions-Policy`) is now configurable from `quickback.config.ts`. Loop's `postcompile-patch.mjs` (which re-injected a fuller CSP and COOP after every `quickback compile`) can now be deleted in favour of:\n\n```ts\nsecurity: {\n csp: {\n defaultSrc: ['@self'],\n scriptSrc: ['@self'],\n styleSrc: ['@self', '@unsafe-inline'],\n frameAncestors: ['@none'],\n objectSrc: ['@none'],\n upgradeInsecureRequests: true,\n },\n coop: 'same-origin',\n}\n```\n\n`@`-prefixed sentinels (`@self`, `@none`, `@unsafe-inline`, `@unsafe-eval`, `@trustedOrigins`, `@nonce`) save users from awkward `\"'self'\"` quoting and let `@trustedOrigins` resolve to the same allowlist `cors()` uses. Unknown sentinels throw at compile rather than silently stringify into the wire CSP.\n\nThe compiler runs lint rules over the resolved config — errors for `@nonce` (deferred to 0.10.15), `@unsafe-inline + @nonce` (silently broken), and sentinel-only directives that would resolve to nothing at runtime; warnings for `@unsafe-inline` in `script-src`, wildcard sources, missing `default-src`, HSTS preload-list misconfiguration, etc.\n\nDefaults preserve 0.10.13 behaviour byte-for-byte — adding the block without setting any field is a no-op.\n\nSee [the docs page](/compiler/config/security) for the full reference.\n\n### HSTS no longer pins `localhost` to HTTPS\n\nThe generated middleware now skips `Strict-Transport-Security` when the request hostname is `localhost`, `127.0.0.1`, or `*.localhost`. Without this gate, `wrangler dev` would pin the developer's browser to HTTPS for `max-age` seconds — observable across every project on that machine since HSTS keys on hostname, not port. Affects every project running locally.\n\n### Out of scope (deferred)\n\n- **Per-request CSP nonces** — Phase 2 / 0.10.15. Sentinel exists at config-validation level so users can author their final CSP today knowing it'll start working when nonces ship.\n- **Asset-hash CSP** for inline `<style>` and `<script>` blocks emitted by the bundled SPAs — Phase 3.\n- **Per-route CSP overrides** (e.g. one looser policy for `/admin`) — single global CSP for now.\n\n---\n\n## v0.10.13 — May 1, 2026\n\n### Clickjacking protection on every generated Worker\n\nEvery Worker now emits two clickjacking-defence headers on every\nresponse:\n\n- `Content-Security-Policy: frame-ancestors 'self' <TRUSTED_ORIGINS…>`\n- `X-Frame-Options: SAMEORIGIN`\n\nThe CSP allowlist is sourced from the same `TRUSTED_ORIGINS` constant\nthat gates CORS, so users configure their domains in one place\n(`auth.trustedOrigins` / `auth.trustedOriginDefaults` in\n`quickback.config.ts`) and both CORS and frame-ancestors stay in\nlockstep. `'self'` is always allowed so an app's own SPAs can frame\ntheir own routes (e.g. an account login popover hosted on the same\norigin).\n\nModern browsers obey `frame-ancestors` and ignore `X-Frame-Options`\nwhen both are set; the legacy header is included for clients that\ndon't speak CSP3. The CSP intentionally only sets `frame-ancestors` —\nadding `script-src` / `default-src` would need a much wider audit\nacross SPA assets, inline scripts, and third-party embeds, so that's\nleft as a follow-up.\n\nRecompile (`quickback compile`) and redeploy to pick this up — no\nconfig change needed unless you want to allow extra cross-origin\niframe embeds, in which case add them to `auth.trustedOrigins`.\n\n---\n\n## v0.10.12 — May 1, 2026\n\n### Bundled-docs sync for the MCP recon fix\n\nPatch release that re-bundles the CLI's offline docs (consulted by the\nClaude Code skill, Cursor rules, and other AI assistants) so they\nreflect the corrected `tools/list` access-filter behavior and CORS\nposture shipped in v0.10.11. The `compiler/config/agents.mdx` page\nitself was already corrected on the docs site immediately after the\n0.10.11 release; this bump propagates that text into the bundle inside\n`@quickback-dev/cli`.\n\nNo runtime or compiler behavior change — re-running `quickback compile`\nagainst this version produces the same output as v0.10.11.\n\n---\n\n## v0.10.11 — May 1, 2026\n\n### MCP `tools/list` is now access-filtered + recon-tightened\n\nThe generated MCP-over-HTTP server (`src/routes/mcp.ts`) had three holes\nthat turned a standard pentest into trivial recon:\n\n1. `tools/list` returned the entire tool catalogue to anyone — including\n admin-only endpoints — without checking auth or roles. Tool\n descriptions also leaked sentences like `[UNSAFE] bypasses tenant\n scoping and requires elevated access` verbatim.\n2. The endpoint set `Access-Control-Allow-Origin: *` so any origin could\n pull the catalogue from a browser.\n3. Unauthenticated `GET /mcp` enumerated every tool name in its\n discovery payload.\n\nFix:\n\n- Each tool now carries sanitised access metadata (`_access` covering\n `roles` / `userRole` / `or` / `and`, plus `_public` for `PUBLIC`\n pseudo-role or empty `security`). `tools/list` filters against the\n caller's `ctx` — unauth callers see only `_public` tools, authed\n callers see only role-gated tools they pass. Record predicates and\n function-form access (opaque at list time) are dropped.\n- Wildcard CORS removed entirely. The parent app's `cors()` middleware\n (origin allowlist via `TRUSTED_ORIGINS` + `BETTER_AUTH_URL`) now\n applies uniformly to `/mcp`, same as every other route.\n- `[UNSAFE] ... bypasses tenant scoping ...` flavour text is gone.\n `annotations.destructiveHint` and `_unsafe` remain — those are the\n spec-correct signals for clients to warn users.\n- Unauthenticated `GET /mcp` no longer lists tool names. Inventory is\n only available via the access-filtered `tools/list`.\n\nThis filter is recon-mitigation, not a security boundary: `tools/call`\nstill re-enters the Hono app and runs every middleware (auth, firewall,\naccess, guards, masking), so hiding a tool from list never weakens the\nunderlying gate.\n\nKnown follow-up: Better Auth admin endpoints (`ban-user`, `create-user`,\n`impersonate-user`, etc.) don't yet emit `x-access` in the OpenAPI spec,\nso any logged-in user still sees them in `tools/list` (the actual call\nis still gated by the admin plugin). Tracked separately.\n\n---\n\n## v0.10.10 — April 29, 2026\n\n### Reject reserved keys inside `access.record` at compile time\n\n`access.record` is a flat field map evaluated as implicit AND between\nentries — keys must be column names. Putting `and: [...]` (or `or` /\n`roles` / `userRole`) inside `record` was a real-world footgun: the\nruntime treated the literal string `\"and\"` as a column lookup, the\npredicate failed on every row, and the caller got a silent `403` /\nempty list with nothing pointing at the misuse. The TypeScript type\ncouldn't catch this — `RecordConditions` is an open-ended index\nsignature, so any key parses.\n\nThe compiler now walks every access node attached to a resource (CRUD\nops, `read.access`, view access, masking `show` / `query`, action\naccess) and throws a clear migration error when `record` contains a\nreserved key:\n\n- `and` / `or` inside `record` → use the top-level `and` / `or`\n sibling: `{ and: [{ record: { ... } }, { record: { ... } }] }`\n- `roles` / `userRole` inside `record` → put them at the access node\n alongside `record`: `{ roles: [...], record: { ... } }`\n\nThe error names the exact origin (`crud.update.access`,\n`actions.focus.access.or[1]`, etc.) so the fix lands in the right place.\n\n---\n\n## v0.10.9 — April 29, 2026\n\n### Role hierarchy now expands in record-based action access\n\n`auth.roleHierarchy: ['member', 'admin', 'owner']` plus\n`access: { roles: ['member+'] }` on a record-based action used to\nsilently 403 valid callers. The standalone-action route generator\ninlined the expanded role list as a JSON literal, but the\nrecord-based generator read the access config back through the\nruntime `actions['name'].access` import — the user's source, where\nthe unexpanded `'member+'` shorthand still lived. The runtime did\nliteral string matching against `ctx.roles`, so an `owner` calling\nthe action got `['member+'] !== 'owner'` and was rejected.\n\nFixed: record-based action routes now inline the expanded list the\nsame way standalone routes do. `input` and `execute` still flow\nthrough the runtime import (closures aren't serializable); only the\naccess config is lifted to a JSON literal so the compile-time\nexpansion actually reaches the matcher.\n\nA regression test (`role-hierarchy-action-routes.test.ts`) locks the\nbehavior in — it asserts that `member+` never reaches the route\noutput and that the access config is no longer read from\n`actions[name].access` at runtime.\n\n---\n\n## v0.10.8 — April 29, 2026\n\n### Audit support on postgres targets, plus a generated-API quality pass\n\n**Audit on PG.** Until this release, `audit_events` only existed on cloudflare-d1 — projects on Neon (or any postgres target) silently skipped audit logging on `unsafe:` and `PUBLIC`-role actions, and hard delete was hard-blocked. Postgres has no equivalent of D1's separate-database binding model, but it has native schemas — so the audit table now lives in a dedicated `audit` schema in the same database as features (`drizzle.pgSchema('audit')`). The `hasSecurityAudit` gate accepts D1 OR any PG dialect; the `auditDatabaseId` requirement only fires for D1 (which still uses the separate-binding model). The recruitment example wires `auditDatabaseId` so the recompile path stays green.\n\n**`auditDatabaseId` is now a compile-time requirement** (D1 only). Previously, projects with unsafe/PUBLIC actions but no audit id silently produced a `database_id = \"local-audit\"` placeholder in production `wrangler.toml`; Cloudflare's worker upload step then rejected it with code 10021 *after* assets and migrations had already run. The compile-time error names the exact `wrangler d1 create <project>-audit` command and the `auditDatabaseId` config key where the returned id goes.\n\n### Five fixes from a Loop integration ticket pass\n\n**Action input → OpenAPI / MCP.** `defineAction({ input: z.object({...}) })` schemas now flow into `requestBody` on the OpenAPI operation and `inputSchema.properties` / `_bodyFields` on the MCP tool list. Simple `z.object` shapes are extracted at compile time; for discriminated unions, refinements, recursive schemas, and bare-identifier references (`input: createPersonInput`), the compiler runs your action file through Zod 4's native `z.toJSONSchema()` during compilation — full-fidelity output with no static translator to maintain. Pre-fix, every action came out as a no-arg endpoint, which gutted typed SDK generation and made MCP useless for actions that take parameters.\n\n**OpenAPI fidelity.** Three surgical fixes that strict validators (zod, openapi-typescript, openapi-fetch) had been complaining about:\n- Response schemas now emit `required[]` for every non-nullable column, so generated SDKs treat them as guaranteed-present rather than optional.\n- `text(_, { enum: [...] })` columns emit as closed `{ type: \"string\", enum: [...] }`, narrowing to literal unions.\n- `id` only claims `format: \"uuid\"` when the project's `generateId` actually produces UUIDs. cuid2 / prefixed / nanoid / serial generators get plain `{ type: \"string\" }` — strict validators stop rejecting responses against their own spec.\n\n**Mask auto-detector now checks the column exists.** The auto-mask predicate used to be unconditionally `show: { or: 'owner', roles: ['admin'] }` — including for tables with no owner column at all (no `userId` / `ownerId` and no `q.scope('owner')`). The generated mask function would reference a non-existent column and fail under TypeScript checks. The auto-detector now verifies the resolved owner column exists in the parsed schema before emitting the `or` clause; when it doesn't, the rule falls back to roles-only and the compiler emits a warning so the behavior is transparent.\n\n**Error code consistency.** The generated CRUD layer was emitting raw codes (`'UNAUTHORIZED'`, `'NOT_NULL_VIOLATION'`, `'UNIQUE_VIOLATION'`, `'INSERT_FAILED'`, `'UPDATE_FAILED'`) that were never in the `QuickbackErrorCode` enum, so consumers couldn't switch exhaustively on `code`. New `database` layer + `DB_NOT_NULL_VIOLATION` / `DB_UNIQUE_VIOLATION` / `DB_INSERT_FAILED` / `DB_UPDATE_FAILED` / `NOT_FOUND` codes are now in the enum, the routes use `AuthErrors.missing()` / `DatabaseErrors.*()` helpers throughout, and the OpenAPI `Error` component emits `code` as a closed enum sourced from the canonical `QUICKBACK_ERROR_CODES` list. Generated SDKs can now `switch` on `code` without a default branch swallowing unknown values. See [API errors](/compiler/targets/hono-api/using-the-api/errors#database).\n\n**Dropped dead `auditFields` preamble from action route generators.** The audit wrapper's `Proxy` already hard-stamps `createdAt` / `createdBy` / `modifiedAt` / `modifiedBy` on every INSERT and `modifiedAt` / `modifiedBy` on every UPDATE — the `auditFields` const the route preamble built was never read. Dropped from `standalone.ts` / `record-based.ts` and from the `ActionExecutorParams` JSDoc. Migrated 7 example handlers (drop `modifiedAt: auditFields!.modifiedAt` from `.set` payloads — the wrapper handles it). Note: `.onConflictDoUpdate({ set })` is *not* intercepted by the wrapper, so `upsertBatch`-style handlers keep an explicit `modifiedAt: now`.\n\n---\n\n## One file per action: greenfield action authoring\n\nAction authoring collapses to a single shape. Each action is its own file under `<feature>/actions/<name>.ts` using `defineAction({...})`. 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` — types `record`, `input`, and audit fields without manual annotations. The directory says what `:id` mounts to; the imports say what the body reads or writes.\n\n**Discovery rules:**\n- `actions/<name>.ts` binds to the feature's primary table (the `<feature>.ts` file at the feature root).\n- `actions/<table>/<name>.ts` binds to the sibling table file `<table>.ts` — for multi-table features.\n- Setting `path:` makes the action standalone (custom URL, no record fetch, no firewall preload).\n- Tableless features (no top-level `*.ts` files) require every action to be standalone.\n- Action names are unique per `(bindTable, name)` pair — sibling-bound actions on different tables may share a verb (e.g. `actions/episodes/publish.ts` + `actions/shows/publish.ts` mount at `/episodes/:id/publish` and `/shows/:id/publish` and don't collide). Standalone actions are unique per `(method, path)`.\n- Files under `<feature>/lib/` are copied verbatim for feature-local helpers; `quickback/lib/` is exposed via the `~/lib/*` alias for cross-feature shared code (with a one-way import rule enforced at compile time).\n\n**Retired** (rejected at load time with migration guidance):\n\n- `actions.ts` (bundled multi-action file)\n- `_feature.ts` (shared preamble + tableless actions)\n- `handlers/` directory + `handler:` string ref\n- `defineActions(table, {…})` and `defineActions(null, {…})`\n- `export default { actions: {…} }`\n- Colocated `defineActions` inside table files\n- `standalone: true` flag (presence of `path:` is the new signal)\n- `*-actions.ts` / `*.actions.ts` filename patterns\n\nThe phantom-`unsafe` regex bug that flattened nested `unsafe: { … }` blocks into a fake top-level action is gone — the parser now reads action files as real TS modules with real imports, so type inference, jump-to-definition, and rename refactoring all work end-to-end.\n\nThe CLI loader rejects retired primitives at load time with batched migration errors. Existing projects need to be migrated by hand to the new shape before recompiling.\n\nSee the [Actions docs](/compiler/definitions/actions) for the full reference.\n\n---\n\n## Multi-table actions per feature\n\nFeatures used to support exactly one `defineActions(table, …)` call via `actions.ts`, which forced unnatural feature splits whenever multiple tables in the same feature needed actions (a podcast feature with `episodes`, `shows`, `seasons`, `collections`, etc.). One feature directory can now own actions on multiple tables across three discovery modes:\n\n- **Colocated** (canonical) — `<table>.ts` containing both `defineTable` and `defineActions(<table>, …)`. One file per entity. Default for new features.\n- **`actions.ts`** (existing) — single primary-table actions file at feature root. Unchanged behaviour.\n- **`actions/<table>.ts`** — per-table action files for teams that want strict schema/behavior separation or need to break an import cycle.\n\nPlus the universal `_feature.ts` slot (at feature root) for **non-table-bound feature-level actions** (`export default { actions: { … } }` shape) and **shared Zod schemas** that get prepended once to the merged actions module so every sibling action sees them. Allowed in any of the three modes — orthogonal to table binding.\n\nThe decision flowchart: *one table with actions → colocate. Multiple tables with actions → colocate each. Hit a cycle or want strict separation → `actions/<table>.ts`. Want schema/actions split for a single-table feature → `actions.ts`. Non-table actions → always `_feature.ts`.*\n\nConflicts are batched and printed once before the compiler aborts — no \"fix one, recompile, fix the next\" loop. The CLI hard-errors when a feature mixes `actions.ts` with table-bound mode, when the same table has its `defineActions` declared in two places, when an `actions/<x>.ts` first-arg doesn't match the basename, or when `_feature.ts` contains `defineActions(table, …)`. Legacy `*-actions.ts` / `*.actions.ts` filenames in a feature dir trigger a soft warning naming the offending paths.\n\nWithin the legacy bundled `actions.ts` DSL, action names had to be unique within a feature — the runtime module merged every source into one keyspace, so colliding `publish` actions on `episodes` and `shows` would have silently overwritten each other. The retired `actions.ts` shape is no longer accepted, so this constraint is gone: the current one-file-per-action layout keys uniqueness per `(bindTable, name)` pair, and the codegen aggregator mangles the JS map key per bind-table while keeping the URL segment bare. Sibling-bound `actions/episodes/publish.ts` and `actions/shows/publish.ts` mount at `/episodes/:id/publish` and `/shows/:id/publish` and compile cleanly.\n\nInline `execute:` bodies must be arrow functions (`execute: async (ctx) => { … }`). `async function` and plain `function` shapes were silently misparsed by the route emitter — they now hard-error at parse time pointing at the canonical arrow form, with a suggestion to use `handler:` for callers who genuinely need a named function declaration.\n\n`handlers/` walks recursively now — `handlers/<table>/<action>.ts` is the canonical layout. A new `lib/` directory under each feature gets copied verbatim into the output for feature-local helpers.\n\nMigration: existing `actions.ts` projects compile bit-identically — the legacy single-table path is unchanged. Legacy `*-actions.ts` filenames produce a soft warning and silently aren't picked up; rename to `<table>.ts` (colocated), `actions/<table>.ts`, or single `actions.ts`.\n\n---\n\n## Firewall: named-scope shape restored, auto-detection synonyms widened\n\nThe named-scope firewall shape (`firewall: { organization: { column: 'tenant_id' } }`) is back as a co-equal user-facing input alongside the predicate array. DSL v2 step 8 had walled it off, but the internal architecture still kept named-scope around for the route + scoped-db generators — so re-accepting it at the input boundary is a thin coercion layer, not an architectural change.\n\n```typescript\n// All three are now valid; all compile to the same predicate array internally.\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 expanded.** When `firewall:` is omitted entirely, the compiler scans the schema for an isolation column. The org-scope list now accepts `organizationId`, `organisationId`, `orgId`, `organization`, `organisation`, `org` (American + British). User-scope still accepts `userId` only.\n\n**`ownerId` is now 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 — Quickback won't auto-derive a firewall from it. Either rename to \\`userId\\` if this column controls access, add a separate \\`userId\\` / \\`organizationId\\` column, or specify \\`firewall:\\` explicitly.` This replaces the generic \"missing isolation column\" error in the `ownerId`-only case and preserves the documented distinction between RLS-style access control (`userId`) and business-logic ownership (`ownerId`).\n\nMigration: nothing breaks. Projects on the predicate-array shape compile bit-identically. Projects on the named-scope shape — including any test fixtures or example projects that were left on the legacy form — now compile cleanly again.\n\n---\n\n## v0.10.0 — April 26, 2026\n\n### `q.scope()` column DSL + unified `masking.query` gate\n\nTwo related DSL consolidations land. The `q.scope()` half is purely additive; the `masking.query` half rejects three legacy per-capability flags at compile time (migration is mechanical — see below).\n\n**`q.scope(kind)` — single-declaration tenant scoping.** Replaces the three-place pattern (column declaration + firewall predicate + implicit ownership-guard) with one column. `q.scope('organization')` compiles to `text(...).notNull()` and tells the compiler:\n\n1. Auto-derive the firewall predicate (`{ field: 'organizationId', equals: 'ctx.activeOrgId' }`) so the explicit `firewall:` block can be omitted entirely.\n2. Add the column to `GUARDS_CONFIG.systemManaged` so client input is rejected at the guard layer.\n3. Auto-populate from `ctx` on create / upsert.\n\nThe systemManaged extension generalises beyond `q.scope()`: any firewall predicate whose `equals` references `ctx.*` adds its `field` to the systemManaged set. So a hand-rolled `firewall: [{ field: 'tenantId', equals: 'ctx.activeOrgId' }]` gets the same treatment.\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\nThe auto-derived firewall also includes the soft-delete predicate (`{ field: 'deletedAt', isNull: true }`) when audit-field injection is on (the default). See [`q.scope()` in the schema docs](/compiler/definitions/schema#qscope--tenant-scope-columns).\n\n**`masking[col].query.roles` — unified role gate for filter / sort / search.** The three legacy per-capability flags (`filterable`, `searchable`, `sortable`) are replaced by a single allowlist that says \"these roles can query the column.\"\n\n```typescript\nmasking: {\n email: {\n type: 'email',\n show: { roles: ['admin'] },\n query: { roles: ['admin'] }, // optional — defaults to show.roles\n },\n}\n```\n\nWhen omitted, `query` inherits from `show.roles` (\"if you can see it, you can query it\") which is the right shape for almost all PII. A 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. See [Masking query gate](/compiler/definitions/masking#query-gate-filter--sort--search).\n\n**Breaking:** Setting `masking[col].filterable / .searchable / .sortable` is rejected at compile time with a migration hint. Replace with `query.roles` (or just delete the flags — `query` defaults to `show.roles`).\n\n---\n\n## v0.9.0 — April 25, 2026\n\n### DSL v2: unified `read:` pipeline, transactional batches, ID-probe defense\n\nStep 8 of the DSL v2 refactor lands. The headline shift is that the read\nside of every resource now has its own block — `read:` — that owns the\ncollection-level `GET /` endpoint, single-record `GET /:id`, and named view\nprojections. The legacy `crud.list` and `crud.get` shapes are rejected at\ncompile time. See the new [Read pipeline](/compiler/definitions/read) page\nfor the full reference and migration table.\n\n**Breaking changes** (compile-time errors with migration hints):\n\n- `crud.list` → [`read.access`](/compiler/definitions/read) (plus `read.pageSize` / `read.maxPageSize`)\n- `crud.get` → `read.access` (single-record GET inherits automatically; use record-level conditions on `read.access` for differentiated single-record gates)\n- Top-level `views: {...}` → [`read.views: {...}`](/compiler/definitions/read#views-under-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 on `/:id`**: handlers now run a role-only\naccess check **before** the firewall query, so a caller without a matching\nrole gets 403 before the database is touched. This closes the 404-vs-403\nID-probe channel — an unauthorized caller can no longer distinguish \"row\nexists in another tenant\" from \"row doesn't exist.\" See\n[Access evaluation order](/compiler/definitions/access#evaluation-order).\n\n**Transactional batch operations**: batch endpoints now expose a\n`failFast` option (replacing the old `atomic` naming) and a\n`meta.transactional` response field. On tx-supporting providers\n(postgres, supabase, neon, libsql, better-sqlite3, bun-sqlite), `failFast: true`\nwraps the per-record loop in `db.transaction(...)` so any failure rolls\nback the entire batch. On Cloudflare D1 (no `db.transaction`), `failFast: true`\nstill stops on the first error but prior writes stay committed; inspect\n`meta.transactional` to know which guarantee you got. Embedding queue\nmessages and realtime broadcasts are emitted **after** the transaction\ncommits, so a rolled-back batch produces no orphan jobs. See\n[Batch Operations: Transactional semantics](/compiler/targets/hono-api/using-the-api/batch-operations#transactional-semantics).\n\n**`firewallErrorMode` lifted off the firewall block**: the field that\ncontrols 403-vs-404 on firewall misses now lives at the resource top level\n(sibling to `firewall:`), since the firewall config is now a predicate\narray and this is a presentation-layer choice. Existing `firewall.errorMode`\nvalues should be lifted to `firewallErrorMode` at the resource level.\n\n**Read-only resources**: an empty `crud: {}` block (or omitting `crud:`\nentirely) is valid for read-only resources. `read:` alone is enough to\nexpose `GET /` and `GET /:id`.\n\n**Strict-mode top-level keys**: the strict allow-list now includes `dev` so\n`defineConfig({ dev: { ... } })` is accepted at the top level.\n\n---\n\n## v0.8.7 — April 17, 2026\n\n### Security: Hono CVE cluster fix\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 (`^4.0.0` / `^4.5.0` / `^4.6.0` / `^4.7.11`) covered the vulnerable window. Recompile to pick up the fix in your generated project's `package.json`.\n\n### Cloudflare Email Sending is now in public beta\n\nQuickback already defaults to the Workers `send_email` binding for Cloudflare deploys, and Cloudflare Email Sending has now graduated to public beta — production-ready with zero-config, no API keys, no third-party accounts. No action needed; recompiling any existing project continues to wire the default Cloudflare transport. AWS SES remains a fully supported opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes or existing SES setups. See [Email Configuration](/compiler/config#email-configuration).\n\n### Minor/patch dep sweep\n\nAligned the whole dep surface — monorepo, compiler Docker image, and generator emissions into compiled projects — so new compiles and existing recompiles converge on the same versions:\n\n- `wrangler@^4.83.0`\n- `drizzle-orm@^0.45.2`, `drizzle-kit@^0.31.10`\n- `zod@^4.3.6`\n- `@cloudflare/workers-types@^4.20260417.1` (also deduped — was accidentally declared in both `dependencies` and `devDependencies` in some paths)\n- `@tanstack/react-query@^5.99.0` (Account app)\n\n---\n\n## v0.8.5 — April 15, 2026\n\n### Fix: Better Auth 1.5 and `@cloudflare/workers-types` Compatibility\n\nGenerated API code failed to typecheck after Better Auth bumped to 1.5 and `@cloudflare/workers-types` tightened `BufferSource` to `ArrayBufferView<ArrayBuffer>`. Four unrelated surfaces broke:\n\n- **`databaseHooks.member.update.after` was removed** in Better Auth 1.5. The compiler now emits the member role-change broadcast hook as `organizationHooks.afterUpdateMemberRole` inside the `organization()` plugin call, which is the current supported shape.\n- **`REALTIME_URL` and `ACCESS_TOKEN`** are always emitted as optional `CloudflareBindings` fields when the organization plugin is active, so the broadcast hook typechecks even when `realtimeMode` is `\"inline\"` (or realtime isn't configured at all).\n- **`auth.api.listOrganizations` / `getFullOrganization` / `session.session.activeOrganizationId`** — third-party Better Auth plugins narrow the inferred `auth.api` type and hide organization-plugin endpoints. The generated middleware and `/admin/v1/organizations` route now cast through `any` for these calls.\n- **`crypto.subtle.sign` / `verify`** no longer accept `Uint8Array<ArrayBufferLike>` directly. Generated `jwt.ts` casts encoded payloads to `BufferSource`.\n\nNo config changes required — recompile to pick up the fixes.\n\n### CMS Admin Gate Now 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 — the static assets, `/api/v1/schema`, and `/api/v1/custom_view` CRUD were reachable by any authenticated user. A non-admin with an API token or cookie could bypass the UI and read schema metadata or saved CMS views directly.\n\nThis release adds server-side enforcement at every CMS-facing surface:\n\n- **CMS SPA shell** — the Worker checks `ctx.userRole === \"admin\"` before serving `index.html`. Unauthenticated requests redirect to login; authenticated non-admins get `403 Admin access required`. Static bundles (JS/CSS) remain reachable so browser caches aren't invalidated.\n- **`/api/v1/schema`** — returns `403` to non-admins.\n- **`custom_view` CRUD** — now gated on the new `userRole: [\"admin\"]` primitive rather than org membership.\n- **In-SPA gate** — unchanged; defense in depth behind the server-side gates.\n\nYour resource CRUD endpoints are unaffected — they keep their per-resource `crud.access.roles`.\n\n### New `userRole` Access Primitive\n\nAdded `userRole?: string[]` to the declarative `Access` config, evaluated against `ctx.userRole` (the Better Auth admin-plugin `user.role` column). This is distinct from `roles`, which matches `ctx.roles` (org membership).\n\n```typescript\n// Old: in multi-tenant this meant org-admin, not platform-admin\naccess: { roles: ['admin'] }\n\n// New: explicitly require user.role === 'admin' regardless of org membership\naccess: { userRole: ['admin'] }\n\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### Fix: `ReferenceError: customAlphabet is not defined` in generated POST handlers\n\nProjects with `providers.database.config.generateId: \"short\"` (or `\"nanoid\"` / `\"cuid\"`) compiled routes that called the ID helper but never imported it. Every generated `src/features/**/*.routes.ts` had `customAlphabet('0123...', 6)()` in its POST body but no matching `import { customAlphabet } from 'nanoid';` at the top of the file. Every `POST /api/v1/<resource>` and batch-create returned `500` with `ReferenceError: customAlphabet is not defined` on the first write.\n\nThe compiler now emits the correct import alongside the ID expression for all three modes: `nanoid`, `customAlphabet`, and `createId` from `@paralleldrive/cuid2`.\n\nNo config changes required — recompile to pick up the fix.\n\n### Fix: Dangling `export const` in generated `actions.ts` breaks `tsc`\n\nWhen a feature authored actions as `export const xActions = defineActions(...)` (instead of `export default defineActions(...)`), the compiler's preamble extractor leaked the assignment's left-hand side into the generated `src/features/<feature>/actions.ts`. The output contained a dangling `export const xActions =` with no right-hand side, and `tsc --noEmit` failed with `TS1109: Expression expected`. Runtime happened to work because the unused placeholder was never evaluated, but typecheck was red.\n\nThe preamble extractor now anchors its boundary to the start of the top-level statement containing `defineActions(...)`, covering `export default`, `export const X =`, `const X =`, and bare call forms. Local Zod helper declarations above the call continue to be preserved.\n\n### Fix: Files worker `database_id` reverted to `\"local-files\"` on every compile\n\nProjects using the two-worker R2 architecture had their files worker's `wrangler.toml` (`apps/backend/cloudflare-workers/files/wrangler.toml`) rewritten with `database_id = \"local-files\"` on every `quickback compile`, even when `providers.database.config.filesDatabaseId` was set to a real D1 UUID. The main worker's binding was correct — only the files worker fell through. Remote deploys of the files worker bound to a non-existent D1, so file serving and access-control reads failed with a binding error.\n\nThe files-worker wrangler generator now reads `filesDatabaseId` (and `filesDatabaseName`) from `providers.database.config` as a fallback when they aren't set on `providers.fileStorage.config`, matching the precedence chain already used by the main worker. Local dev is unaffected — `wrangler dev --local` uses `.wrangler/state/` regardless of the configured ID.\n\nNo config changes required — recompile and redeploy the files worker.\n\n---\n\n## v0.8.6 — April 16, 2026\n\n### Fix: Audit columns silently dropped from tables with a same-line index callback\n\nTables authored with the composite-index shape Drizzle / prettier produces —\n\n```ts\nexport const episodeTags = sqliteTable(\"episode_tags\", {\n id: text(\"id\").primaryKey(),\n episodeId: text(\"episode_id\").notNull(),\n tagId: text(\"tag_id\").notNull(),\n}, (t) => [ // <-- \"}, (t) =>\" on one line\n uniqueIndex(\"episode_tag_unique\").on(t.episodeId, t.tagId),\n]);\n```\n\nnever received audit field injection. A regex in `injectAuditFields` required a literal `\\n` between the columns-object `},` and the `(t) =>` index callback, so same-line closers were silently skipped and the function returned the source unchanged. drizzle-kit then diffed the audit-less schema against the previous snapshot and emitted `ALTER TABLE ... DROP COLUMN created_at/modified_at/deleted_at/created_by/modified_by/deleted_by` for every affected table. Any project that applied those migrations had production CRUD return `500` because the generated firewall helper still referenced `deletedAt`.\n\nThe regex is now whitespace-flexible and the identifier class accepts any valid JS identifier (`t`, `table`, `_t`, `tbl2`). A defensive guard throws at compile time if all three terminator patterns fail on a recognizable Drizzle table — no more silent drops.\n\n**Recovery path:**\n\n- Most projects: recompile. drizzle-kit will detect the audit columns are missing from the DB snapshot and emit an `ADD COLUMN` migration to restore them. Apply it.\n- Projects that already hand-patched their schema and ran a manual `ADD COLUMN` migration (like the `podcast-app` workaround in commit `98d8758`): the next compile will regenerate a matching `ADD COLUMN` migration that will fail with \"duplicate column name\" against a DB that already has the columns. Mark the new migration as applied without running it (e.g. `INSERT INTO __drizzle_migrations` in the features DB) or hand-edit the generated SQL to a no-op, then continue normally.\n\n### Fix: `firewall.exception` generated `isNull(<table>.deletedAt)` against a missing column\n\nResources with `firewall: { exception: true }` always emitted `return isNull(<table>.deletedAt);` inside `buildFirewallConditions()`, regardless of whether the table actually had a `deletedAt` column. Projects that disabled audit injection globally (`compiler.features.auditFields: false`) or authored a schema without `deletedAt` ended up with Drizzle resolving `<table>.deletedAt` to `undefined` at query time — every `GET /api/v1/<resource>` returned `500`.\n\nThe three concerns are now fully independent:\n\n- **`firewall.exception: true`** — only disables tenant scoping (org/user/team `WHERE` clauses). It does not gate audit fields or soft-delete.\n- **Audit fields** — always injected unless globally opted out. Unchanged.\n- **Soft-delete filter** — emitted only when the schema actually has `deletedAt` *or* the user explicitly set `firewall.softDelete`.\n\nIn the default configuration (audit injection on), behavior is unchanged: exception resources still filter `deletedAt IS NULL`. Only the broken case changes — exception resources on a schema without `deletedAt` now return `undefined` (no firewall), matching the column reality.\n\nNo config changes required — recompile to pick up the fix.\n\n---\n\n## v0.8.4 — April 14, 2026\n\n### New `generateId: \"short\"` Strategy\n\nAdded a 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\", {\n generateId: \"short\",\n }),\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 in your project (same as the existing `\"nanoid\"` strategy).\n\n**When to use:** room codes, invite links, share URLs, ephemeral records — anywhere the ID appears in a URL or needs to be human-typeable.\n\n**When not to use:** high-volume tables. 62^6 ≈ 56.8B combinations means ~238K rows before a 50% collision probability (birthday bound). For large tables stick with `\"uuid\"`, `\"cuid\"`, or `\"prefixed\"`.\n\nSee [Providers - ID Generation Options](/compiler/config/providers#id-generation-options) for the full list of strategies.\n\n---\n\n## v0.8.3 — April 14, 2026\n\n### Fix: `wrangler.toml` Route Placement and Binding IDs\n\nTwo bugs in the generated `wrangler.toml` that blocked production deployment without manual edits:\n\n**Routes were nested under `[dev]`.** The `routes = [...]` array was emitted after the `[dev]` section header, so TOML parsed it as `dev.routes` and wrangler ignored the custom domain (warning: `Unexpected fields found in dev field: \"routes\"`). Routes now emit as a top-level key.\n\n**D1 and KV bindings used placeholder IDs.** Despite `databaseId`, `filesDatabaseId`, and `kvId` being set in the quickback config, the generated `wrangler.toml` wrote `\"local-features\"`, `\"local-files\"`, and `\"local\"` instead of the real UUIDs. The compiler now resolves IDs from multiple config sources:\n\n| Binding | Config sources checked (in order) |\n|---------|-----------------------------------|\n| `AUTH_DB` | `database.config.authDatabaseId` |\n| `DB` | `database.config.featuresDatabaseId`, `database.config.databaseId` |\n| `FILES_DB` | `fileStorage.config.filesDatabaseId`, `database.config.filesDatabaseId` |\n| `KV` | `database.config.kvNamespaceId`, `storage.config.namespaceId`, `auth.config.kvId` |\n\nSee [Providers - Database Options](/compiler/config/providers#database-options) for the full list of supported ID properties.\n\n### Fix: Account SPA Post-Login Redirect on Unified Domain\n\nWhen the Account SPA was served at `/account/` on the unified quickback domain (e.g. `secure.example.com/account/`), post-login redirects dropped the basepath and sent users to `/dashboard` instead of `/account/dashboard`. Sign-out redirects had the same issue.\n\nThe SPA now shares a basepath module across the router and all raw `window.location.href` assignments, so login, signup, email OTP, welcome, and sign-out flows all stay under the correct path prefix regardless of whether the SPA is on the unified domain or its own dedicated auth subdomain.\n\nNo config changes required — recompile to pick up the fix.\n\n---\n\n## v0.8.2 — April 11, 2026\n\n### Catch-All `VITE_QUICKBACK_URL` Environment Variable\n\nInstead of setting four separate URL env vars, you can now point at a single Quickback origin:\n\n```bash\n# One variable — done.\nVITE_QUICKBACK_URL=https://secure.example.com\n```\n\nWhen set, it's used as a fallback for the individual URLs:\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, not the Quickback server.\n\n**Non-breaking.** Individual vars still take precedence when set, so existing configurations work unchanged. The compiler now also emits `VITE_QUICKBACK_URL` into the generated SPA `.env` files, and library users can set `__QUICKBACK_URL__` on `globalThis` for the same effect.\n\nSee [Environment Variables](/stack/account-ui/environment-variables) for the full reference.\n\n---\n\n## v0.8.1 — April 9, 2026\n\n### Role Hierarchy with `+` Suffix\n\nYou can now define a role hierarchy in your config and use the `+` suffix in access rules to mean \"this role and above\":\n\n```typescript\n// quickback.config.ts\nauth: {\n roleHierarchy: ['member', 'admin', 'owner'],\n}\n\n// In resource definitions\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) for details.\n\n---\n\n## v0.8.0 — April 9, 2026\n\n### Breaking: VITE URL Environment Variables Renamed\n\nAll Quickback-generated URL environment variables are now 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\n**Non-URL variables are unchanged:** `VITE_ENABLE_*` feature flags, branding vars (`VITE_APP_NAME`, etc.), and `VITE_STRIPE_PUBLISHABLE_KEY` stay as-is.\n\n**Action required:**\n- **Compiled projects** — re-run `quickback compile`. The compiler generates the new names automatically.\n- **Standalone deploys** — update `.env`, `.env.production`, and `wrangler.toml` files manually.\n- **Library users** — the `__QUICKBACK_API_URL__` / `__QUICKBACK_APP_URL__` globalThis names are unchanged, but if you pipe Vite env vars into them, update the var names.\n\nSee [Environment Variables](/stack/account-ui/environment-variables) for the full reference.\n\n### CMS Access Control\n\nThe `cms.access` config option now enforces access at the CMS level, not just link visibility in Account UI.\n\n```typescript\ncms: { access: \"admin\" }\n```\n\nWhen set to `\"admin\"`, non-admin users (`user.role !== \"admin\"`) see an \"Access Denied\" screen with a sign-out button instead of the CMS. When set to `\"user\"` (the default), any authenticated user can access the CMS.\n\nSee [CMS Connecting](/stack/cms/connecting) and [Compiler Config](/compiler/config) for details.\n\n### SPA Sub-Route Fix\n\nFixed a bug where hard-refreshing or directly navigating to SPA sub-routes (e.g., `/account/profile`, `/cms/tables/users`) returned a blank white screen. The Worker now correctly serves `index.html` for all SPA paths, allowing the client-side router to handle routing.\n\n---\n\n## v0.5.11 — February 24, 2026\n\n### Email OTP & Auth Fixes\n\n- Fixed email-OTP magic links not working correctly\n- Removed deprecated `/internal/validate` endpoint — use standard Better Auth session validation instead\n- Auth is now required for all API routes when running locally (previously some routes were unprotected in dev)\n\n### Multiple Table Exports Fix\n\n- Fixed a compiler error when a single file exports multiple Drizzle tables alongside a `defineTable()` default export\n- The CLI now properly detects and reports this with a clear error message pointing to the fix\n\n### Headless Drizzle Rename Hints\n\n- Added `compiler.migrations.renames` configuration for CI/CD environments where Drizzle's interactive rename prompts would block compilation\n- Compile errors now include explicit rename key paths and fail fast on malformed rename config keys\n- See [Configuration](/compiler/config) for details\n\n### Security Contract Report Artifacts\n\n- Added generated security contract artifacts to compiler output:\n - `reports/security-contracts.report.json`\n - `reports/security-contracts.report.sig.json`\n- Added config-driven signing controls:\n - `compiler.securityContracts.report.signature.enabled`\n - `compiler.securityContracts.report.signature.required`\n - `compiler.securityContracts.report.signature.key` / `keyEnv` / `keyId`\n- Missing required signing keys now fail loudly with explicit remediation guidance\n- Added strict config validation for report/signature paths and signing options\n\n### Mandatory Unsafe Action Audit Trail\n\n- Added structured unsafe action config (`unsafe: { reason, adminOnly, crossTenant, targetScope }`)\n- Cross-tenant unsafe actions now require Better Auth authentication plus platform admin role (`ctx.userRole === \"admin\"`)\n- Added mandatory audit logging for unsafe cross-tenant actions (success, denial, and error paths)\n- Cloudflare output now includes optional `AUDIT_DB` wiring, `drizzle.audit.config.ts`, and `db:migrate:audit:*` scripts when unsafe actions are present\n- Added compile-time raw SQL guard for actions and handlers (`allowRawSql: true` required per action)\n\n---\n\n## v0.5.10 — February 19, 2026\n\n### Compiler Page Parsing & CLI Output\n\n- Improved compiler page parsing for `definePage()` definitions\n- Better CLI output formatting during compilation\n- Added `apiPath` to schema registry for CMS integration\n\n### Bug Fixes\n\n- Fixed hyphenated action names not being properly quoted in generated code (e.g., `mark-complete` now generates valid JavaScript)\n- API key authentication (`x-api-key` header) is now handled separately from session tokens (`Bearer` header)\n\n---\n\n## v0.5.9 — February 16, 2026\n\n### CMS Pages & CLI Page Support\n\n- Added `definePage()` support for CMS-managed pages\n- Auth middleware improvements for page routes\n- CLI now supports page definitions alongside table and action definitions\n\n---\n\n## v0.5.8 — February 14, 2026\n\n### CMS App\n\n- Introduced the Quickback CMS — a schema-driven admin panel that connects to your generated API\n- CMS namespace added to actions for admin-specific operations\n- Fixed `guard` → `access` naming inconsistency in CMS action definitions\n\n### Schema Registry & Firewall Improvements\n\n- Added schema registry generator — the compiler now outputs a JSON schema registry used by the CMS\n- Firewall error modes: choose between `reveal` (403 with details) and `hide` (opaque 404) for security-sensitive deployments\n\n### Bug Fixes\n\n- Fixed anonymous user email format generation\n- Organization selector improvements in Account UI\n- Config validation now catches more errors at compile time\n- Better CRUD error handling with structured error responses\n- Fixed masking to use representative star counts instead of fixed formatting\n\n---\n\n## v0.5.7 — February 12, 2026\n\n### Scoped Database for Actions\n\nActions now 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\nThe scoped DB uses duck-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\nThis means **every action is secure by default** — no manual `WHERE` clauses needed.\n\n```typescript\ndefineActions(todos, {\n complete: {\n type: \"record\",\n execute: async ({ db, ctx, record, input }) => {\n // db is scoped — only sees records in user's org, excludes soft-deleted\n const siblings = await db.select().from(todos);\n // ↑ automatically filtered to ctx.activeOrgId + deletedAt IS NULL\n },\n },\n});\n```\n\n#### Unsafe Mode\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:\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`.\n\n**Related docs:** [Actions](/compiler/definitions/actions), [Actions API](/compiler/targets/hono-api/using-the-api/actions-api)\n\n---\n\n### Cascading Soft Delete\n\nSoft-deleting a parent record now **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\n```\nDELETE /api/v1/projects/:id\n```\n\nGenerated behavior:\n```typescript\n// 1. Soft delete the parent\nawait db.update(projects)\n .set({ deletedAt: now, deletedBy: userId })\n .where(eq(projects.id, id));\n\n// 2. Auto-cascade to children (compiler-generated)\nawait db.update(projectMembers)\n .set({ deletedAt: now, deletedBy: userId })\n .where(eq(projectMembers.projectId, id));\n\nawait db.update(projectTasks)\n .set({ deletedAt: now, deletedBy: userId })\n .where(eq(projectTasks.projectId, id));\n```\n\nRules:\n- Only applies to **soft delete** (the default). Hard delete relies on database-level `ON DELETE CASCADE`.\n- Only cascades within the **same feature** — cross-feature references are not affected.\n- Child tables must have `deletedAt` / `deletedBy` columns (auto-added by the compiler's audit fields).\n\n**Related docs:** [Actions API — Cascading Soft Delete](/compiler/targets/hono-api/using-the-api/actions-api#cascading-soft-delete)\n\n---\n\n### Advanced Query Parameters\n\nNew query parameter capabilities for all list endpoints:\n\n- **Field selection** — `?fields=id,name,status` returns only the columns you need\n- **Multi-sort** — `?sort=status:asc,createdAt:desc` sorts by multiple fields\n- **Total count** — `?count=true` returns total matching records in response headers (`X-Total-Count`)\n- **Full-text search** — `?search=keyword` searches across all text columns\n\n```bash\n# Get only names and statuses, sorted by status then date, with total count\nGET /api/v1/todos?fields=id,name,status&sort=status:asc,createdAt:desc&count=true\n\n# Search across all text fields\nGET /api/v1/todos?search=urgent\n```\n\n**Related docs:** [Query Parameters](/compiler/targets/hono-api/using-the-api/query-params)\n\n---\n\n### Audit Field Improvements\n\n- `deletedAt` and `deletedBy` fields are now **always injected** by the compiler for tables with soft delete enabled — no need to define them in your schema\n- All audit fields (`createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`, `deletedAt`, `deletedBy`) are auto-managed\n\n---\n\n## v0.5.6 — February 8, 2026\n\n### Database Naming Conventions\n\n- Default table and column naming changed to **snake_case** with `usePlurals: false`\n- Table names derived from generated Better Auth schema for consistency\n- Removed legacy single-database mode — split databases (auth + features) is now the standard\n\n### Auth Variable Shadowing Fix\n\n- Fixed `member` variable in auth middleware that shadowed the Drizzle `member` table import\n- Renamed to `sessionMember` to avoid conflicts in generated routes\n\n---\n\n## v0.5.5 — February 5, 2026\n\n### Better Auth Plugins\n\n- Published `@quickback-dev/better-auth-upgrade-anonymous` v1.1.0 — post-passkey email collection flow\n- Published `@quickback-dev/better-auth-combo-auth` — combined email + password + OTP authentication\n- Published `@quickback-dev/better-auth-aws-ses` — AWS SES email provider for Better Auth\n\n### OpenAPI Spec Generation\n\n- Generated APIs now include a full OpenAPI specification at `/openapi.json`\n- Better Auth endpoints included in the spec\n- Runtime route: `GET /openapi.json`\n\n### Security Hardening\n\n- Global error handler prevents leaking internal error details\n- Security headers middleware (CSP, HSTS, X-Frame-Options, X-Content-Type-Options)\n- `BETTER_AUTH_SECRET` properly passed to generated config\n\n---\n\n## v0.5.4 — January 30, 2026\n\n### Account UI\n\n- Pre-built authentication UI deployed as Cloudflare Workers\n- Features: sessions, organizations, passkeys, passwordless, admin panel, API keys\n- Dual-mode: standalone (degit template) or embedded with Quickback projects\n\n### Webhook System\n\n- Inbound webhook endpoints with signature verification\n- Outbound webhooks via Cloudflare Queues with automatic retries\n- Configurable per-feature webhook events\n\n### Realtime & Vector Search\n\n- Durable Objects + WebSocket realtime subscriptions\n- Vector embeddings via Cloudflare Vectorize\n- 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, Bun standalone, B2B SaaS\n- **Cloud Compiler** — Remote compilation via `compiler.quickback.dev`\n- **CLI** — `quickback create`, `quickback compile`, `quickback init`\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,11 +51,11 @@ 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 features: { organizations: true },\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 — see [Single-Tenant 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## 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\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\"` | `\"user\"` | Controls who can access the CMS. When `\"admin\"`, only users with `user.role === \"admin\"` can enter — enforced at the Worker level (SPA shell, `/api/v1/schema`, and `custom_view` CRUD all return 403 to non-admins) and in the SPA. Also hides the CMS link in Account UI. See [CMS Connecting](/stack/cms/connecting) for the full enforcement model. |\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 included in the Account UI bundle. Disabled features are excluded at compile time — their routes are removed before the Vite build, keeping bundle sizes minimal.\n\n| Flag | Type | Default | Description |\n|------|------|---------|-------------|\n| `auth.password` | `boolean` | `true` | Email/password authentication |\n| `auth.emailOTP` | `boolean` | `false` | Email one-time password login |\n| `auth.passkey` | `boolean` | `false` | WebAuthn/FIDO2 passkey authentication |\n| `auth.signup` | `boolean` | `true` | Self-service account registration |\n| `auth.organizations` | `boolean` | `false` | Multi-tenant organization management (dashboard, invitations, roles) |\n| `auth.admin` | `boolean` | `false` | Admin panel for user management (requires Better Auth admin plugin) |\n| `auth.emailVerification` | `boolean` | `false` | Require email verification 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- [Single-Tenant Mode](/compiler/config/single-tenant) — Admin-only and public-facing apps without organizations\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 features: { organizations: true },\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 — see [Single-Tenant 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## 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\"` | `\"user\"` | Controls who can access the CMS. When `\"admin\"`, only users with `user.role === \"admin\"` can enter — enforced at the Worker level (SPA shell, `/api/v1/schema`, and `custom_view` CRUD all return 403 to non-admins) 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 `/admin/v1/sysadmin/organizations` endpoint, and the SPA's \"All organizations\" sentinel. The CMS HTML gate admits `userRole === \"sysadmin\"` alongside `\"admin\"` — sysadmin is a strict superset. 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 `\"admin\"` — admins keep org-scoped CMS access via the membership switcher; sysadmins get cross-tenant.\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 new `GET /admin/v1/sysadmin/organizations` endpoint selects directly from the auth-schema `organization` table — every row, every tenant. The existing `/admin/v1/organizations` (membership-bound, used by org admins) is unchanged.\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 `\"admin\"`. Org admins are not locked out — both roles can enter the CMS in `cms.access: \"admin\"` mode.\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 included in the Account UI bundle. Disabled features are excluded at compile time — their routes are removed before the Vite build, keeping bundle sizes minimal.\n\n| Flag | Type | Default | Description |\n|------|------|---------|-------------|\n| `auth.password` | `boolean` | `true` | Email/password authentication |\n| `auth.emailOTP` | `boolean` | `false` | Email one-time password login |\n| `auth.passkey` | `boolean` | `false` | WebAuthn/FIDO2 passkey authentication |\n| `auth.signup` | `boolean` | `true` | Self-service account registration |\n| `auth.organizations` | `boolean` | `false` | Multi-tenant organization management (dashboard, invitations, roles) |\n| `auth.admin` | `boolean` | `false` | Admin panel for user management (requires Better Auth admin plugin) |\n| `auth.emailVerification` | `boolean` | `false` | Require email verification 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- [Single-Tenant Mode](/compiler/config/single-tenant) — Admin-only and public-facing apps without organizations\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",
58
- "content": "The compiler generates a complete project structure based on your definitions and provider configuration. The output varies depending on your runtime (Cloudflare vs Bun) and enabled features.\n\n**Warning:** Never edit files in `src/` directly. They are overwritten on every compile. Make changes in your `quickback/` definitions instead.\n\n## Cloudflare Output\n\n```\nsrc/\n├── index.ts # Hono app entry point (Workers export)\n├── env.d.ts # Cloudflare bindings TypeScript types\n├── db/\n│ ├── index.ts # Database connection factory\n│ ├── auth-schema.ts # Auth table schemas (dual mode)\n│ └── features-schema.ts # Feature table schemas (dual mode)\n├── auth/\n│ └── index.ts # Better Auth instance & config\n├── features/\n│ └── {feature}/\n│ ├── schema.ts # Drizzle table definition\n│ ├── routes.ts # CRUD + action endpoints\n│ └── actions.ts # Action handlers (if defined)\n├── lib/\n│ ├── access.ts # Access control helpers\n│ ├── types.ts # Runtime type definitions\n│ ├── masks.ts # Field masking utilities\n│ ├── services.ts # Service layer\n│ ├── audit-wrapper.ts # Auto-inject audit fields\n│ └── security-audit.ts # Unsafe cross-tenant audit logger (when needed)\n└── middleware/\n ├── auth.ts # Auth context middleware\n ├── db.ts # Database instance middleware\n └── services.ts # Service injection middleware\n\nquickback/drizzle/\n├── auth/ # Auth migrations (dual mode)\n│ ├── meta/\n│ │ ├── _journal.json\n│ │ └── 0000_snapshot.json\n│ └── 0000_initial.sql\n├── features/ # Feature migrations (dual mode)\n│ ├── meta/\n│ │ ├── _journal.json\n│ │ └── 0000_snapshot.json\n│ └── 0000_initial.sql\n└── audit/ # Unsafe cross-tenant action audit migrations (when needed)\n ├── meta/\n └── 0000_initial.sql\n\n# Root config files\n├── package.json\n├── tsconfig.json\n├── wrangler.toml # Cloudflare Workers config\n├── drizzle.config.ts # Features DB drizzle config\n├── drizzle.auth.config.ts # Auth DB drizzle config (dual mode)\n└── drizzle.audit.config.ts # Audit DB drizzle config (when unsafe actions exist)\n```\n\n## Bun Output\n\n```\nsrc/\n├── index.ts # Hono app entry point (Bun server)\n├── db/\n│ ├── index.ts # SQLite connection (bun:sqlite)\n│ └── schema.ts # Combined schema (single DB)\n├── auth/\n│ └── index.ts # Better Auth instance\n├── features/\n│ └── {feature}/\n│ ├── schema.ts\n│ ├── routes.ts\n│ └── actions.ts\n├── lib/\n│ ├── access.ts\n│ ├── types.ts\n│ ├── masks.ts\n│ ├── services.ts\n│ └── audit-wrapper.ts\n└── middleware/\n ├── auth.ts\n ├── db.ts\n └── services.ts\n\nquickback/drizzle/ # Single migration directory\n├── meta/\n│ ├── _journal.json\n│ └── 0000_snapshot.json\n└── 0000_initial.sql\n\ndata/ # SQLite database files\n└── app.db\n\n├── package.json\n├── tsconfig.json\n└── drizzle.config.ts\n```\n\n## Key Differences by Runtime\n\n| Aspect | Cloudflare | Bun |\n|--------|-----------|-----|\n| Entry point | Workers `export default` | `Bun.serve()` with port |\n| Database | D1 bindings (dual mode) | SQLite file (single DB) |\n| Types | `env.d.ts` for bindings | No extra types needed |\n| Config | `wrangler.toml` | `.env` file |\n| Migrations | `quickback/drizzle/auth/` + `quickback/drizzle/features/` | `quickback/drizzle/` |\n| Drizzle configs | 2 configs (auth + features) | 1 config |\n\n## Optional Output Files\n\nThese files are generated only when the corresponding features are configured:\n\n### Embeddings\n\nWhen any feature has `embeddings` configured:\n\n```\nsrc/\n├── lib/\n│ └── embeddings.ts # Embedding helpers\n├── routes/\n│ └── embeddings.ts # POST /api/v1/embeddings endpoint\n└── queue-consumer.ts # Queue handler for async embedding jobs\n```\n\n### File Storage (R2)\n\nWhen `fileStorage` is configured:\n\n```\nsrc/\n└── routes/\n └── storage.ts # File upload/download endpoints\nquickback/drizzle/\n└── files/ # File metadata migrations\n ├── meta/\n └── 0000_*.sql\n```\n\n### Webhooks\n\nWhen webhooks are enabled:\n\n```\nsrc/\n└── lib/\n └── webhooks/\n ├── index.ts # Webhook module entry\n ├── sign.ts # Webhook payload signing\n ├── handlers.ts # Handler registry\n ├── emit.ts # Queue emission helpers\n ├── routes.ts # Inbound/outbound endpoints\n └── providers/\n ├── index.ts\n └── stripe.ts # Stripe webhook handler\nquickback/drizzle/\n└── webhooks/ # Webhook schema migrations\n ├── meta/\n └── 0000_*.sql\n```\n\n### Security Audit Database (Unsafe Actions)\n\nWhen any action enables unsafe cross-tenant mode (`unsafe.crossTenant: true`):\n\n```\nsrc/\n├── db/\n│ └── audit-schema.ts # audit_events table\n└── lib/\n └── security-audit.ts # mandatory audit writer\n\nquickback/drizzle/\n└── audit/\n ├── meta/\n └── 0000_*.sql\n\n# Root\n└── drizzle.audit.config.ts\n```\n\nCloudflare output also includes an `AUDIT_DB` D1 binding in `wrangler.toml` and migration scripts:\n\n- `db:migrate:audit:local`\n- `db:migrate:audit:remote`\n\n### Security Contract Report and Signature\n\nGenerated on every compile (unless disabled via `compiler.securityContracts.report.enabled: false`):\n\n```\nreports/\n├── security-contracts.report.json # Contract evaluation summary + violations\n└── security-contracts.report.sig.json # Signature / digest envelope for the report\n```\n\nThe signature file uses HMAC-SHA256 when a signing key is configured, otherwise it falls back to SHA-256 digest mode. \nSet `compiler.securityContracts.report.signature.required: true` to fail compilation when a signing key is missing.\n\n### Realtime\n\nWhen any feature has `realtime` configured:\n\n```\nsrc/\n├── lib/\n│ ├── realtime.ts # Broadcast helpers\n│ ├── Broadcaster.ts # Durable Object class (inline in main worker)\n│ └── ws-ticket.ts # WebSocket ticket auth utility\n└── routes/\n └── ws-ticket.ts # POST /realtime/v1/ws-ticket endpoint\n```\n\nThe Broadcaster DO class is exported from your main worker entry point and runs inline — no separate `cloudflare-workers/broadcast/` deployment needed.\n\n### Device Authorization\n\nWhen the `deviceAuthorization` plugin is enabled:\n\n```\nsrc/\n└── routes/\n └── cli-auth.ts # Device auth flow endpoints\n```\n\n## Database Schemas\n\n### Dual Database Mode (Cloudflare Default)\n\nThe compiler separates schemas into two files:\n\n**`src/db/auth-schema.ts`** — Re-exports Better Auth table schemas:\n- `users`, `sessions`, `accounts`\n- `organizations`, `members`, `invitations` (if organizations enabled)\n- Plugin-specific tables (`apiKeys`, etc.)\n\n**`src/db/features-schema.ts`** — Re-exports your feature schemas:\n- All tables defined with `defineTable()`\n- Audit field columns added automatically\n\n### Single Database Mode (Bun Default)\n\n**`src/db/schema.ts`** — Combined re-export of all schemas (auth + features).\n\n## Generated Routes\n\nFor each feature, the compiler generates a routes file at `src/features/{name}/routes.ts` containing:\n\n| Route | Generated When |\n|-------|----------------|\n| `GET /` | `crud.list` configured |\n| `GET /:id` | `crud.get` configured |\n| `POST /` | `crud.create` configured |\n| `PATCH /:id` | `crud.update` configured |\n| `DELETE /:id` | `crud.delete` configured |\n| `PUT /:id` | `crud.put` configured |\n| `POST /batch` | `crud.create` exists (auto-enabled) |\n| `PATCH /batch` | `crud.update` exists (auto-enabled) |\n| `DELETE /batch` | `crud.delete` exists (auto-enabled) |\n| `PUT /batch` | `crud.put` exists (auto-enabled) |\n| `GET /views/{name}` | `views` configured |\n| `POST /:id/{action}` | Record-based actions defined |\n| `POST /{action}` | Standalone actions defined |\n\nAll routes are mounted under `/api/v1/{feature}` in the main app.\n\n## Migrations\n\nThe compiler runs `drizzle-kit generate` during compilation to produce SQL migration files. On subsequent compiles, it uses `existingFiles` (your current migration state) to generate only incremental changes.\n\nThe CLI loads migration meta JSON from one location only — `<project>/quickback/drizzle/`:\n\n- `quickback/drizzle/auth/meta/`\n- `quickback/drizzle/features/meta/`\n- `quickback/drizzle/files/meta/`\n- `quickback/drizzle/webhooks/meta/`\n- `quickback/drizzle/audit/meta/`\n- `quickback/drizzle/meta/` (single-database mode)\n\nQuickback owns this state — nothing under a project-root `drizzle/` folder is ever read or written.\n\nMigration and report artifacts are written to the `quickback/` state directory:\n\n- `quickback/drizzle/...` for Drizzle migration SQL/meta artifacts\n- `quickback/reports/...` for security contract report artifacts\n\nFor non-interactive environments (cloud compile, CI), table/column renames must be declared with `compiler.migrations.renames` in `quickback.config.ts`. This avoids interactive rename prompts during migration generation.\n\nMigration files follow the Drizzle Kit naming convention:\n```\n0000_initial.sql\n0001_add_status_column.sql\n0002_create_orders_table.sql\n```\n\n## CMS and Account UI Assets\n\nWhen `cms` and/or `account` are enabled, the compiler builds the SPAs from source at compile time and includes the assets in the output.\n\nEach SPA is placed in its own subdirectory under `src/apps/`:\n\n```\nsrc/apps/ # Root assets directory\n├── cms/ # CMS SPA (served at /cms/ on unified domain)\n│ ├── index.html\n│ └── assets/\n│ ├── app.abc123.js # Content-hashed filenames from Vite\n│ └── app.xyz456.css\n└── account/ # Account SPA (served at /account/ on unified domain)\n ├── index.html\n └── assets/\n ├── app.def789.js\n └── app.ghi012.css\n```\n\nOn custom domains, each SPA is served at root (`/`) via hostname-based routing. On the unified domain, CMS is at `/cms/` and Account is at `/account/`.\n\n### Generated Wrangler Assets Config\n\nThe compiler always generates `run_worker_first = true` when SPAs are enabled — the Worker handles all SPA routing (per hostname and per path prefix):\n\n```toml\n[assets]\nbinding = \"ASSETS\"\ndirectory = \"src/apps\"\nnot_found_handling = \"none\"\nrun_worker_first = true\n```\n\nSee [Multi-Domain Architecture](/compiler/config/domains) for details on hostname routing.\n\n## See Also\n\n- [Providers](/compiler/config/providers) — Configure runtime, database, and auth providers\n- [Environment variables](/compiler/config/variables) — Required variables by runtime\n- [Multi-Domain Architecture](/compiler/config/domains) — Custom domains and hostname routing"
58
+ "content": "The compiler generates a complete project structure based on your definitions and provider configuration. The output varies depending on your runtime (Cloudflare vs Bun) and enabled features.\n\n**Warning:** Never edit files in `src/` directly. They are overwritten on every compile. Make changes in your `quickback/` definitions instead.\n\n## Cloudflare Output\n\n```\nsrc/\n├── index.ts # Hono app entry point (Workers export)\n├── env.d.ts # Cloudflare bindings TypeScript types\n├── db/\n│ ├── index.ts # Database connection factory\n│ ├── auth-schema.ts # Auth table schemas (dual mode)\n│ └── features-schema.ts # Feature table schemas (dual mode)\n├── auth/\n│ └── index.ts # Better Auth instance & config\n├── features/\n│ └── {feature}/\n│ ├── schema.ts # Drizzle table definition\n│ ├── routes.ts # CRUD + action endpoints\n│ └── actions.ts # Action handlers (if defined)\n├── lib/\n│ ├── access.ts # Access control helpers\n│ ├── types.ts # Runtime type definitions\n│ ├── masks.ts # Field masking utilities\n│ ├── services.ts # Service layer\n│ ├── audit-wrapper.ts # Auto-inject audit fields\n│ └── security-audit.ts # Unsafe cross-tenant audit logger (when needed)\n└── middleware/\n ├── auth.ts # Auth context middleware\n ├── db.ts # Database instance middleware\n └── services.ts # Service injection middleware\n\nquickback/drizzle/\n├── auth/ # Auth migrations (dual mode)\n│ ├── meta/\n│ │ ├── _journal.json\n│ │ └── 0000_snapshot.json\n│ └── 0000_initial.sql\n├── features/ # Feature migrations (dual mode)\n│ ├── meta/\n│ │ ├── _journal.json\n│ │ └── 0000_snapshot.json\n│ └── 0000_initial.sql\n└── audit/ # Unsafe cross-tenant action audit migrations (when needed)\n ├── meta/\n └── 0000_initial.sql\n\n# Root config files\n├── package.json\n├── tsconfig.json\n├── wrangler.toml # Cloudflare Workers config\n├── drizzle.config.ts # Features DB drizzle config\n├── drizzle.auth.config.ts # Auth DB drizzle config (dual mode)\n└── drizzle.audit.config.ts # Audit DB drizzle config (when unsafe actions exist)\n```\n\n## Bun Output\n\n```\nsrc/\n├── index.ts # Hono app entry point (Bun server)\n├── db/\n│ ├── index.ts # SQLite connection (bun:sqlite)\n│ └── schema.ts # Combined schema (single DB)\n├── auth/\n│ └── index.ts # Better Auth instance\n├── features/\n│ └── {feature}/\n│ ├── schema.ts\n│ ├── routes.ts\n│ └── actions.ts\n├── lib/\n│ ├── access.ts\n│ ├── types.ts\n│ ├── masks.ts\n│ ├── services.ts\n│ └── audit-wrapper.ts\n└── middleware/\n ├── auth.ts\n ├── db.ts\n └── services.ts\n\nquickback/drizzle/ # Single migration directory\n├── meta/\n│ ├── _journal.json\n│ └── 0000_snapshot.json\n└── 0000_initial.sql\n\ndata/ # SQLite database files\n└── app.db\n\n├── package.json\n├── tsconfig.json\n└── drizzle.config.ts\n```\n\n## Key Differences by Runtime\n\n| Aspect | Cloudflare | Bun |\n|--------|-----------|-----|\n| Entry point | Workers `export default` | `Bun.serve()` with port |\n| Database | D1 bindings (dual mode) | SQLite file (single DB) |\n| Types | `env.d.ts` for bindings | No extra types needed |\n| Config | `wrangler.toml` | `.env` file |\n| Migrations | `quickback/drizzle/auth/` + `quickback/drizzle/features/` | `quickback/drizzle/` |\n| Drizzle configs | 2 configs (auth + features) | 1 config |\n\n## Optional Output Files\n\nThese files are generated only when the corresponding features are configured:\n\n### Embeddings\n\nWhen any feature has `embeddings` configured:\n\n```\nsrc/\n├── lib/\n│ └── embeddings.ts # Embedding helpers\n├── routes/\n│ └── embeddings.ts # POST /api/v1/embeddings endpoint\n└── queue-consumer.ts # Queue handler for async embedding jobs\n```\n\n### File Storage (R2)\n\nWhen `fileStorage` is configured:\n\n```\nsrc/\n└── routes/\n └── storage.ts # File upload/download endpoints\nquickback/drizzle/\n└── files/ # File metadata migrations\n ├── meta/\n └── 0000_*.sql\n```\n\n### Webhooks\n\nWhen webhooks are enabled:\n\n```\nsrc/\n└── lib/\n └── webhooks/\n ├── index.ts # Webhook module entry\n ├── sign.ts # Webhook payload signing\n ├── handlers.ts # Handler registry\n ├── emit.ts # Queue emission helpers\n ├── routes.ts # Inbound/outbound endpoints\n └── providers/\n ├── index.ts\n └── stripe.ts # Stripe webhook handler\nquickback/drizzle/\n└── webhooks/ # Webhook schema migrations\n ├── meta/\n └── 0000_*.sql\n```\n\n### Security Audit Database (Unsafe Actions)\n\nWhen any action enables unsafe cross-tenant mode (`unsafe.crossTenant: true`):\n\n```\nsrc/\n├── db/\n│ └── audit-schema.ts # audit_events table\n└── lib/\n └── security-audit.ts # mandatory audit writer\n\nquickback/drizzle/\n└── audit/\n ├── meta/\n └── 0000_*.sql\n\n# Root\n└── drizzle.audit.config.ts\n```\n\nCloudflare output also includes an `AUDIT_DB` D1 binding in `wrangler.toml` and migration scripts:\n\n- `db:migrate:audit:local`\n- `db:migrate:audit:remote`\n\n### Security Contract Report and Signature\n\nGenerated on every compile (unless disabled via `compiler.securityContracts.report.enabled: false`):\n\n```\nreports/\n├── security-contracts.report.json # Contract evaluation summary + violations\n└── security-contracts.report.sig.json # Signature / digest envelope for the report\n```\n\nThe signature file uses HMAC-SHA256 when a signing key is configured, otherwise it falls back to SHA-256 digest mode. \nSet `compiler.securityContracts.report.signature.required: true` to fail compilation when a signing key is missing.\n\n### Realtime\n\nWhen any feature has `realtime` configured:\n\n```\nsrc/\n├── lib/\n│ ├── realtime.ts # Broadcast helpers\n│ ├── Broadcaster.ts # Durable Object class (inline in main worker)\n│ └── ws-ticket.ts # WebSocket ticket auth utility\n└── routes/\n └── ws-ticket.ts # POST /realtime/v1/ws-ticket endpoint\n```\n\nThe Broadcaster DO class is exported from your main worker entry point and runs inline — no separate `cloudflare-workers/broadcast/` deployment needed.\n\n### Device Authorization\n\nWhen the `deviceAuthorization` plugin is enabled:\n\n```\nsrc/\n└── routes/\n └── cli-auth.ts # Device auth flow endpoints\n```\n\n## Database Schemas\n\n### Dual Database Mode (Cloudflare Default)\n\nThe compiler separates schemas into two files:\n\n**`src/db/auth-schema.ts`** — Re-exports Better Auth table schemas:\n- `users`, `sessions`, `accounts`\n- `organizations`, `members`, `invitations` (if organizations enabled)\n- Plugin-specific tables (`apiKeys`, etc.)\n\n**`src/db/features-schema.ts`** — Re-exports your feature schemas:\n- All tables defined with `defineTable()`\n- Audit field columns added automatically\n\n### Single Database Mode (Bun Default)\n\n**`src/db/schema.ts`** — Combined re-export of all schemas (auth + features).\n\n## Generated Routes\n\nFor each feature, the compiler generates a routes file at `src/features/{name}/routes.ts` containing:\n\n| Route | Generated When |\n|-------|----------------|\n| `GET /` | `crud.list` configured |\n| `GET /:id` | `crud.get` configured |\n| `POST /` | `crud.create` configured |\n| `PATCH /:id` | `crud.update` configured |\n| `DELETE /:id` | `crud.delete` configured |\n| `PUT /:id` | `crud.put` configured |\n| `POST /batch` | `crud.create` exists (auto-enabled) |\n| `PATCH /batch` | `crud.update` exists (auto-enabled) |\n| `DELETE /batch` | `crud.delete` exists (auto-enabled) |\n| `PUT /batch` | `crud.put` exists (auto-enabled) |\n| `GET /views/{name}` | `views` configured |\n| `POST /:id/{action}` | Record-based actions defined |\n| `POST /{action}` | Standalone actions defined |\n\nAll routes are mounted under `/api/v1/{feature}` in the main app.\n\n## Migrations\n\nThe compiler runs `drizzle-kit generate` during compilation to produce SQL migration files. On subsequent compiles, it uses `existingFiles` (your current migration state) to generate only incremental changes.\n\nThe CLI loads migration meta JSON from one location only — `<project>/quickback/drizzle/`:\n\n- `quickback/drizzle/auth/meta/`\n- `quickback/drizzle/features/meta/`\n- `quickback/drizzle/files/meta/`\n- `quickback/drizzle/webhooks/meta/`\n- `quickback/drizzle/audit/meta/`\n- `quickback/drizzle/meta/` (single-database mode)\n\nQuickback owns this state — nothing under a project-root `drizzle/` folder is ever read or written.\n\nMigration and report artifacts are written to the `quickback/` state directory:\n\n- `quickback/drizzle/...` for Drizzle migration SQL/meta artifacts\n- `quickback/reports/...` for security contract report artifacts\n\nFor non-interactive environments (cloud compile, CI), table/column renames must be declared with `compiler.migrations.renames` in `quickback.config.ts`. This avoids interactive rename prompts during migration generation.\n\nMigration files follow the Drizzle Kit naming convention:\n```\n0000_initial.sql\n0001_add_status_column.sql\n0002_create_orders_table.sql\n```\n\n## CMS and Account UI Assets\n\nWhen `cms` and/or `account` are enabled, the compiler builds the SPAs from source at compile time and includes the assets in the output.\n\nEach SPA is placed in its own subdirectory under `src/apps/`:\n\n```\nsrc/apps/ # Root assets directory\n├── cms/ # CMS SPA (served at /cms/ on unified domain)\n│ ├── index.html\n│ └── assets/\n│ ├── app.abc123.js # Content-hashed filenames from Vite\n│ └── app.xyz456.css\n└── account/ # Account SPA (served at /account/ on unified domain)\n ├── index.html\n └── assets/\n ├── app.def789.js\n └── app.ghi012.css\n```\n\nOn custom domains, each SPA is served at root (`/`) via hostname-based routing. On the unified domain, CMS is at `/cms/` and Account is at `/account/`.\n\n### Static Assets (`quickback/public/`)\n\nAnything you drop under `quickback/public/` is copied verbatim into `src/apps/` on every compile. The compiler does not parse, template, or otherwise touch these files — they are bytes that ride past it into the Cloudflare ASSETS binding.\n\n```\nquickback/public/ # Source — checked into your repo\n├── favicon.ico\n├── robots.txt\n├── og/\n│ └── og-image.png\n└── pdfs/\n └── whitepaper.pdf\n```\n\nAfter compile:\n\n```\nsrc/apps/ # Destination — written by the CLI\n├── favicon.ico # Served at https://your-domain/favicon.ico\n├── robots.txt # Served at /robots.txt\n├── og/og-image.png # Served at /og/og-image.png\n├── pdfs/whitepaper.pdf\n├── cms/ # Compiler-emitted SPA (don't shadow)\n└── account/ # Compiler-emitted SPA (don't shadow)\n```\n\nNotes:\n\n- The folder is optional. If it doesn't exist, this step is a no-op.\n- Files removed from `quickback/public/` disappear from `src/apps/` on the next compile — `src/` is wiped and rewritten each run.\n- Hidden entries (`.DS_Store`, `.git/`, dotfiles) are skipped.\n- A file in `quickback/public/` that would overwrite a compiler-emitted path (e.g. `quickback/public/cms/index.html`) fails the compile with a clear error rather than silently shadowing the SPA shell.\n- Binaries (images, fonts, PDFs) are copied byte-for-byte — there is no string round-trip.\n\n### Generated Wrangler Assets Config\n\nThe compiler always generates `run_worker_first = true` when SPAs are enabled — the Worker handles all SPA routing (per hostname and per path prefix):\n\n```toml\n[assets]\nbinding = \"ASSETS\"\ndirectory = \"src/apps\"\nnot_found_handling = \"none\"\nrun_worker_first = true\n```\n\nSee [Multi-Domain Architecture](/compiler/config/domains) for details on hostname routing.\n\n## See Also\n\n- [Providers](/compiler/config/providers) — Configure runtime, database, and auth providers\n- [Environment variables](/compiler/config/variables) — Required variables by runtime\n- [Multi-Domain Architecture](/compiler/config/domains) — Custom domains and hostname routing"
59
59
  },
60
60
  "compiler/config/providers": {
61
61
  "title": "Providers",
@@ -75,7 +75,7 @@ export const DOCS = {
75
75
  },
76
76
  "compiler/definitions/access": {
77
77
  "title": "Access - Role & Condition-Based Access Control",
78
- "content": "Define who can perform CRUD operations and under what conditions.\n\n## Basic Usage\n\n```typescript\n// features/applications/applications.ts\n\nexport const applications = sqliteTable('applications', {\n id: text('id').primaryKey(),\n candidateId: text('candidate_id').notNull(),\n jobId: text('job_id').notNull(),\n stage: text('stage').notNull(),\n notes: text('notes'),\n organizationId: text('organization_id').notNull(),\n});\n\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: { createable: [\"candidateId\", \"jobId\", \"notes\"], updatable: [\"notes\"] },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n crud: {\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n },\n});\n```\n\n## Role Hierarchy\n\nIf your project uses a tiered role system (e.g., `member` < `admin` < `owner`), you can define a hierarchy in your config and use the `+` suffix to mean \"this role and above\":\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n name: \"my-app\",\n auth: {\n roleHierarchy: ['member', 'admin', 'owner'], // lowest → highest\n },\n // ...\n});\n```\n\nThen in your resource definitions:\n\n```typescript\nread: { access: { roles: [\"member+\"] } }, // member, admin, owner\ncrud: {\n create: { access: { roles: [\"admin+\"] } }, // admin, owner\n delete: { access: { roles: [\"owner\"] } }, // owner only (no +)\n}\n```\n\nThe `+` suffix expands at compile time — `\"member+\"` becomes `[\"member\", \"admin\", \"owner\"]` in the generated code. You can mix hierarchical and exact roles: `roles: [\"member+\", \"finance\"]` expands to `[\"member\", \"admin\", \"owner\", \"finance\"]`.\n\n- Roles without `+` are exact matches (no expansion)\n- Pseudo-roles (`PUBLIC`, `AUTHENTICATED`, `USER`, `ADMIN`) cannot use the `+` suffix — they're terminal markers\n- Using `+` with a role not in the hierarchy throws a compile error\n- Using `+` without configuring `auth.roleHierarchy` throws a compile error\n\n## Configuration Options\n\n```typescript\ninterface Access {\n // Org-membership roles (OR logic — user needs at least one)\n // Matched against ctx.roles. Use \"role+\" suffix for hierarchy expansion.\n roles?: string[];\n\n // User-table role (OR logic). Matched against ctx.userRole from the\n // user.role column — independent of org membership. See userRole below.\n userRole?: string[];\n\n // Record-level conditions\n record?: {\n [field: string]: FieldCondition;\n };\n\n // Combinators\n or?: Access[];\n and?: Access[];\n}\n```\n\n## `userRole` vs `roles`\n\n`roles` and `userRole` check **two different fields** and are often confused — get this wrong and you'll grant access too broadly.\n\n| Primitive | Checks | Source | Example values |\n|-----------|--------|--------|----------------|\n| `roles` | `ctx.roles` | Org membership (multi-tenant) or single-tenant mirror of `user.role` | `\"owner\"`, `\"admin\"`, `\"member\"` |\n| `userRole` | `ctx.userRole` | The `user.role` column (Better Auth admin plugin) | `\"user\"`, `\"admin\"` |\n\nIn multi-tenant mode, **`roles: [\"admin\"]` means \"org admin\" — not a platform-wide admin.** An org-admin of Acme Corp has no elevated rights across other orgs. If you want to let Better Auth system admins through regardless of org membership (e.g., for support/ops), use `userRole: [\"admin\"]`.\n\nIn single-tenant mode (`features.organizations: false`), `ctx.roles` mirrors `user.role`, so `roles: [\"admin\"]` and `userRole: [\"admin\"]` behave the same. Using `userRole` in single-tenant code is still preferred — it documents intent and keeps the gate correct if you later enable orgs.\n\n### When to use `userRole`\n\n```typescript\n// Platform admin can see SSNs on every customer record, regardless of org\nmasking: {\n ssn: { type: 'ssn', show: { userRole: ['admin'] } },\n}\n\n// Support staff (user.role === 'admin') OR the org owner can refund\naccess: {\n or: [\n { userRole: ['admin'] },\n { roles: ['owner'] },\n ],\n}\n\n// CMS-internal resource: only platform admins\nread: { access: { userRole: ['admin'] } },\ncrud: {\n create: { access: { userRole: ['admin'] } },\n update: { access: { userRole: ['admin'] } },\n delete: { access: { userRole: ['admin'] } },\n}\n```\n\nWhen `roles` and `userRole` both appear in a single `Access` node, they're combined with AND — the user must satisfy both. Use `or:` to express \"one or the other\".\n\n`userRole` doesn't expand with the `+` hierarchy suffix — user-table roles are flat (typically just `\"user\"` and `\"admin\"`). If you've added custom user-table roles via Better Auth, list them explicitly.\n\n### Pseudo-roles\n\nQuickback ships four UPPERCASE role markers that are **not backed by a Better Auth role column** — they're system-level shortcuts handled directly by the compiler. The casing carries the boundary: UPPERCASE = pseudo-role (no plugin context required), lowercase = real role from a plugin's table (e.g. `members.role` from the org plugin).\n\n| Role | Auth gate | Compile-time requirement | Runtime check |\n|------|-----------|-------------------------|---------------|\n| `PUBLIC` | bypassed | none — explicit opt-in for unauthenticated access | always passes (auth skipped) |\n| `AUTHENTICATED` | required | none | `ctx.authenticated === true` |\n| `USER` | required | resource firewall **must** scope by `userId` | `ctx.authenticated` AND (`ctx.userRole` is unset OR `ctx.userRole === \"user\"`) |\n| `ADMIN` | required | Better Auth admin plugin **must** be enabled | `ctx.authenticated && ctx.userRole === \"admin\"` |\n\nYou can mix pseudo-roles with real roles in the same list — they're OR'd together.\n\n#### `PUBLIC` — unauthenticated access\n\nUse `roles: [\"PUBLIC\"]` for public-facing endpoints like contact forms, public listings, or webhooks. Skips both the auth gate and the role check.\n\n```typescript\naccess: { roles: [\"PUBLIC\"] }\n```\n\n**Important:**\n- `PUBLIC` skips authentication and role checks — anyone can call the endpoint\n- **`PUBLIC` is the explicit, uppercase opt-in for unauthenticated access.** It works on every access node — reads, CRUD writes (`crud.create`/`update`/`delete`), views, and actions. The compiler trusts the marker; row-level safety comes from the firewall, masking, and (for token-gated endpoints like RSVP confirm, magic-link redemption, List-Unsubscribe-Post, webhook ingest) your handler's own validation. Anonymous CRUD endpoints typically pair `roles: [\"PUBLIC\"]` with `firewall: { exception: true }` on the resource so the row predicate doesn't reject every unauthenticated caller.\n- **Firewall still applies** — data is scoped by the firewall (organization, owner, team)\n- Every `PUBLIC` action invocation is **mandatory audit logged** to the security audit table (IP address, input, result, timing)\n- The wildcard `\"*\"` is **not supported** — using it throws a compile-time error\n- Tables with no isolation columns and any `PUBLIC` route do not require `firewall: [{ exception: true }]`\n\nFor org-scoped tables, `PUBLIC` routes still filter by organization. Since the user isn't authenticated, the organization ID must be passed as a query parameter:\n\n```\nGET /api/v1/listings?organizationId=org_abc123\n```\n\nThe firewall WHERE clause is always enforced. If no `organizationId` is provided, the API returns a `400` with code `ORG_REQUIRED`.\n\n```typescript\n// Public listing page — anyone can browse, but scoped to an org\nexport default defineTable(listings, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: { access: { roles: [\"PUBLIC\"] } }, // Public browsing + detail\n crud: {\n create: { access: { roles: [\"admin\", \"member\"] } }, // Auth required to create\n },\n});\n```\n\n#### `AUTHENTICATED` — any signed-in user\n\nUse `roles: [\"AUTHENTICATED\"]` for endpoints that any logged-in user can hit, regardless of role or org membership. No plugin context required.\n\n```typescript\n// Public events feed — any signed-in user can list/read; anonymous gets 401\nread: { access: { roles: [\"AUTHENTICATED\"] } }\n```\n\n#### `USER` — per-user records\n\nUse `roles: [\"USER\"]` for resources where each user only sees their own records. **Requires the firewall to scope by `userId`** — the role marker is the access half of the pair, the firewall is the row-filter half.\n\n```typescript\n// \"My todos\" — each caller sees only their own rows\nexport default defineTable(todos, {\n firewall: [{ field: 'userId', equals: 'ctx.userId' }],\n read: { access: { roles: [\"USER\"] } },\n crud: {\n create: { access: { roles: [\"USER\"] } },\n update: { access: { roles: [\"USER\"] } },\n delete: { access: { roles: [\"USER\"] } },\n },\n});\n```\n\nIf you forget the `userId` firewall predicate, the compiler throws:\n\n> `roles: [\"USER\"]` requires the resource to be scoped per-user. Add a `userId` column (auto-scoped) or an explicit owner predicate. If you want any signed-in user to read all records, use `roles: [\"AUTHENTICATED\"]` instead.\n\nWhen the Better Auth admin plugin is enabled, `USER` matches `user.role === \"user\"` specifically — admins are excluded and should use `[\"USER\", \"ADMIN\"]` if the same route should serve both.\n\n#### `ADMIN` — Better Auth admin-plugin admins\n\nUse `roles: [\"ADMIN\"]` for system-administrator endpoints. **Requires the Better Auth admin plugin** so `user.role` exists. Compiles to `ctx.userRole === \"admin\"`.\n\n```typescript\n// Platform-admin-only audit log\nread: { access: { roles: [\"ADMIN\"] } }\n```\n\nWithout the admin plugin you get a compile error pointing you to either enable the plugin or use lowercase `roles: [\"admin\"]` (the org-membership admin role).\n\n#### Mixing pseudo-roles with real roles\n\nPseudo-roles and lowercase real roles compose with OR:\n\n```typescript\n// Record owner OR a system admin can read\nread: { access: { roles: [\"USER\", \"ADMIN\"] } }\n\n// Org owner OR system admin\ndelete: { access: { roles: [\"owner\", \"ADMIN\"] } }\n```\n\n> Note: today, an `ADMIN` match still goes through the `userId` firewall scope on USER-scoped resources — admins see only records they own on those routes. Use `firewall: { exception: true }` on a separate admin-only route if you need cross-user visibility.\n\n#### Quick reference\n\n```typescript\n// Unauthenticated public\naccess: { roles: [\"PUBLIC\"] }\n\n// Any signed-in user, no scoping\naccess: { roles: [\"AUTHENTICATED\"] }\n\n// Per-user records (requires userId firewall scope)\naccess: { roles: [\"USER\"] }\n\n// System admin (requires admin plugin)\naccess: { roles: [\"ADMIN\"] }\n\n// Org-membership roles with hierarchy expansion\naccess: { roles: [\"member+\"] } // expands to [\"member\", \"admin\", \"owner\"]\naccess: { roles: [\"admin+\"] } // expands to [\"admin\", \"owner\"]\naccess: { roles: [\"admin\"] } // exact match (no expansion)\n```\n\n```typescript\n// Field conditions - value can be string | number | boolean\ntype FieldCondition =\n | { equals: value | '$ctx.userId' | '$ctx.activeOrgId' }\n | { notEquals: value }\n | { in: value[] }\n | { notIn: value[] }\n | { lessThan: number }\n | { greaterThan: number }\n | { lessThanOrEqual: number }\n | { greaterThanOrEqual: number };\n```\n\n## Relationship-based authorization\n\nBeyond Better Auth roles (org membership, user-table role) and pseudo-roles, Quickback supports **relationship-based authorization roles** — names that bind to a declared relationship between the caller and a resource. Use these when access should follow a domain-table membership (\"user is a confirmed guest of this event\") rather than an org/admin gate.\n\n### `authz.relationships` { #authz-relationships }\n\nDeclare relationships once in `quickback.config.ts`:\n\n```typescript\n// quickback.config.ts\n\nexport default defineConfig({\n // ...providers...\n authz: {\n relationships: {\n guestOf: {\n from: 'event_guests', // table name string\n subject: { column: 'userId', equals: 'ctx.userId' }, // caller side\n resource: { column: 'eventId' }, // resource side\n where: { status: 'confirmed' }, // optional filter\n },\n },\n roles: {\n guest: { via: 'guestOf' },\n // Composite: any guest OR an org owner/admin\n eventStaff: {\n or: [\n { via: 'guestOf' },\n { roles: ['admin', 'owner'] },\n ],\n },\n },\n },\n});\n```\n\n### Using relationship-roles in resources\n\nResource definitions reference declared roles by name in `roles: [...]` arrays exactly like BA roles or pseudo-roles. The compiler rewrites the access tree at build time so the runtime route does an inline relationship lookup against the declared table.\n\n**Today (v1) this works on:**\n\n| Surface | Status | Notes |\n|---|---|---|\n| `firewall:` `via:` predicate | ✓ Supported | Subquery composes as outermost AND |\n| `crud.*.access` `roles: ['guest']` | ✓ Supported | Inline async lookup per request |\n| `read.access` / `read.views.*.access` `roles: ['guest']` | ✓ Supported | Same inline path |\n| `masking.<field>.show` `roles: ['guest']` | ⚠ Refused at compile | v1 limitation — async/batched mask functions deferred |\n| `actions.<name>.access` `roles: ['guest']` | ⚠ Refused at compile | v1 limitation — explicit `relationshipBindings` deferred |\n\nFor the surfaces that are not yet supported, the compiler refuses at build time with a clear error pointing to a workaround. The runtime evaluator fails closed on relationship arms regardless, so silent grants are impossible.\n\n### Recommended pattern: gate at the firewall layer\n\nMost of the time, relationship-based row visibility is what you want, and putting it at the **firewall** layer is the cleanest expression. The firewall is row-filter; the access layer is route/role-filter; let each do its job:\n\n```typescript\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' }, // ← row visibility\n],\nread: {\n access: { roles: ['admin', 'member'] }, // ← who can hit the route\n views: {\n cms: { access: { roles: ['admin', 'member'] }, fields: [...] },\n guest: { access: { roles: ['member', 'admin'] }, fields: [...] },\n },\n},\n```\n\nA guest who's in your org as `member` can hit the endpoint and the firewall filters them down to events they're guests of. Cross-tenant access is impossible because the org filter is the outermost AND.\n\n### Cross-tenant \"my events\" dashboards are NOT this\n\nA common adjacent pattern — \"logged-in user wants `GET /my-events` returning events they're a guest of *across all tenants*\" — is **not** solved by relationship-roles. The tenant firewall is enforced at the outermost AND, so a guest of an event in another tenant remains correctly blocked.\n\nFor cross-tenant aggregation, use one of:\n\n- **User-scoped firewall**: `firewall: { owner: { column: 'userId' } }` — a flat per-user table.\n- **A standalone action that walks the relationship table itself** — see worked example below.\n\nDon't reach for relationship-roles first and then get confused when the tenant firewall blocks. The two patterns serve different problems.\n\n#### Worked example: `GET /my-events` standalone action\n\nThe cleanest expression of the cross-tenant attendee dashboard is a standalone action with a custom path that does its own join against the relationship table. The action is gated by `roles: ['AUTHENTICATED']` (any signed-in user can hit it; per-row scoping is the query itself), and the SQL filters by `ctx.userId` so each caller sees exactly the events they're a guest of:\n\n```ts\n// features/dashboard/actions/myEvents.ts\n\nexport default defineAction({\n description: \"List events the caller is a confirmed guest of, across all tenants.\",\n path: '/my-events',\n method: 'GET',\n input: z.object({}),\n // Any signed-in user. Row visibility comes from the query, not the role.\n access: { roles: ['AUTHENTICATED'] },\n async execute({ db, ctx }) {\n // 1. Find every event the caller has a confirmed guest row for.\n const guestRows = await db\n .select({ eventId: guests.eventId })\n .from(guests)\n .where(\n and(\n eq(guests.userId, ctx.userId!),\n eq(guests.status, 'confirmed'),\n // guests.organizationId is NOT filtered here — that's the whole\n // point of the cross-tenant lane. The relationship row's org is\n // ambient information that this action explicitly traverses.\n )\n );\n\n if (guestRows.length === 0) return { events: [] };\n\n // 2. Pull the matching events. NOTE: this query also bypasses\n // `events.organizationId` scope — by design — so explicitly filter\n // out soft-deleted rows yourself if your `events` table uses them.\n const eventIds = guestRows.map((r) => r.eventId);\n const rows = await db\n .select()\n .from(events)\n .where(inArray(events.id, eventIds));\n\n return { events: rows };\n },\n});\n```\n\nWhy this is a standalone action and not a CRUD route:\n\n- **Tenant firewall would block it.** The default `firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }]` on `events` is correct for every other read — only the cross-tenant dashboard wants to step outside it, and that's a deliberate, explicit step taken in handler code.\n- **The join is the access control.** A relationship-role at the firewall layer can't express \"filter by this user's relationships, ignoring the org context.\" The handler does that join directly.\n- **Audit-logged automatically.** Standalone actions are mandatorily audit-logged in the runtime — the cross-tenant traversal is recorded with `ctx.userId`, IP, and timing.\n\nTwo important guardrails when you write one of these:\n\n1. **Always filter by `ctx.userId` in the relationship lookup.** If you accept a `userId` from the request body and trust it, you've built an IDOR. The example above uses `ctx.userId!` directly so the only events returned are the caller's.\n2. **You take responsibility for soft-delete and other invariants the firewall would otherwise apply.** Add the `deletedAt` filter, status checks, and any other row-level predicates by hand. The action is OUTSIDE the firewall pipeline by design — the cost is that you can't lean on the auto-applied predicates.\n\nIf you find yourself writing more than one of these per project, that's usually a signal to revisit the schema (could a user-owned `userEvents` materialized view replace the join?) rather than a sign Quickback should ship a higher-level abstraction. Cross-tenant lanes are intentionally explicit.\n\n### Compile-time refusals (consolidated)\n\nThe validator and resolver reject:\n\n- Unknown key in `authz` block (typo guard — `realtionships` would otherwise silently produce a permanently-denied role).\n- Reserved role-name (auth-provider-derived). Names like `guest`, `speaker`, `attendee` are free; `admin`/`owner`/`member` are reserved when the BA org plugin is on.\n- Cycle in role composition (`a → b → a`).\n- Relationship `from` references unknown table.\n- Relationship-role used on a resource missing the `resource.column`.\n- Relationship table with `firewall: { exception: true }` (would let cross-tenant grants slip through).\n- `lowering: 'session'` (reserved for v2 — staleness/invalidation ergonomics not yet shipped).\n- `+` hierarchy suffix on a relationship-role name (terminal, like pseudo-roles).\n- Relationship-roles in `masking.show` / `actions.access` (deferred surfaces — see the table above).\n\n## Read & CRUD Configuration\n\nReads (`GET /` and `GET /:id`) live under `read:`; mutations live under `crud:`. See [Read](/compiler/definitions/read) for the full read pipeline reference.\n\n```typescript\nread: {\n // LIST + GET - GET /resource and GET /resource/:id\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n pageSize: 25, // Default page size\n maxPageSize: 100, // Client can't exceed this\n views: { // Per-view field projections\n summary: {\n fields: ['id', 'candidateId', 'jobId', 'stage'],\n access: { roles: [\"interviewer\"] },\n },\n },\n}\n\ncrud: {\n // CREATE - POST /resource\n create: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] },\n defaults: { // Default values for new records\n stage: 'applied',\n },\n },\n\n // UPDATE - PATCH /resource/:id\n update: {\n access: {\n or: [\n { roles: [\"hiring-manager\", \"recruiter\"] },\n { roles: [\"interviewer\"], record: { stage: { equals: \"interview\" } } }\n ]\n },\n },\n\n // DELETE - DELETE /resource/:id\n delete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"soft\", // 'soft' (default) or 'hard'\n },\n\n // PUT - PUT /resource/:id (only when generateId: false + guards: false)\n put: {\n access: { roles: [\"hiring-manager\", \"sync-service\"] },\n },\n}\n```\n\n## Evaluation Order\n\nGenerated `/:id` and batch handlers evaluate access in this fixed order:\n\n1. **Auth gate** — 401 if unauthenticated\n2. **Pre-record access** — role-only check (skips `access.record` predicates)\n3. **Firewall query** — `WHERE` clause filters by ownership\n4. **Post-record access** — full check including record-level predicates\n5. **Masking** — applied to the response\n\nStep 2 closes the 404-vs-403 ID-probe channel: an unauthorized caller without\na matching role gets 403 before the database is touched, so they can't tell\napart \"row exists out-of-scope\" from \"row doesn't exist.\" A caller with the\nright role but the wrong tenant gets 403 by default (firewall reveals via\nthe access layer); set\n[`firewallErrorMode: 'hide'`](/compiler/definitions/firewall) to return an\nopaque 404 instead.\n\nFunction-form access (`access: async (ctx, record) => ...`) is opaque to\nthe pre-record phase and always passes there; it's fully evaluated post-record.\n\n## List Filtering (Query Parameters)\n\nThe LIST endpoint automatically supports filtering via query params:\n\n```\nGET /jobs?status=open # Exact match\nGET /jobs?salaryMin.gt=50000 # Greater than\nGET /jobs?salaryMin.gte=50000 # Greater than or equal\nGET /jobs?salaryMax.lt=200000 # Less than\nGET /jobs?salaryMax.lte=200000 # Less than or equal\nGET /jobs?status.ne=closed # Not equal\nGET /jobs?title.like=Engineer # Pattern match (LIKE %value%)\nGET /jobs?status.in=open,draft # IN clause\n```\n\n| Operator | Query Param | SQL Equivalent |\n|----------|-------------|----------------|\n| Equals | `?field=value` | `WHERE field = value` |\n| Not equals | `?field.ne=value` | `WHERE field != value` |\n| Greater than | `?field.gt=value` | `WHERE field > value` |\n| Greater or equal | `?field.gte=value` | `WHERE field >= value` |\n| Less than | `?field.lt=value` | `WHERE field < value` |\n| Less or equal | `?field.lte=value` | `WHERE field <= value` |\n| Pattern match | `?field.like=value` | `WHERE field LIKE '%value%'` |\n| In list | `?field.in=a,b,c` | `WHERE field IN ('a','b','c')` |\n\n## Sorting & Pagination\n\n```\nGET /jobs?sort=createdAt&order=desc # Sort by field\nGET /jobs?limit=25&offset=50 # Pagination\n```\n\n- **Default limit**: 50\n- **Max limit**: 100 (or `maxPageSize` if configured)\n- **Default order**: `asc`\n\n## Delete Modes\n\n```typescript\ndelete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"soft\", // Sets deletedAt/deletedBy, record stays in DB\n}\n\ndelete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"hard\", // Permanent deletion from database\n}\n```\n\n## Context Variables\n\nUse `$ctx.` prefix to reference context values in conditions:\n\n```typescript\n// User can only view their own records\naccess: {\n record: { userId: { equals: \"$ctx.userId\" } }\n}\n\n// Nested path support for complex context objects\naccess: {\n record: { ownerId: { equals: \"$ctx.user.id\" } }\n}\n```\n\n### AppContext Reference\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `$ctx.userId` | `string` | Current authenticated user's ID |\n| `$ctx.activeOrgId` | `string` | User's active organization ID |\n| `$ctx.activeTeamId` | `string \\| null` | User's active team ID (if applicable) |\n| `$ctx.roles` | `string[]` | User's roles in current context |\n| `$ctx.isAnonymous` | `boolean` | Whether user is anonymous |\n| `$ctx.user` | `object` | Full user object from auth provider |\n| `$ctx.user.id` | `string` | User ID (nested path example) |\n| `$ctx.user.email` | `string` | User's email address |\n| `$ctx.{property}` | `any` | Any custom context property |\n\n## Function-Based Access\n\nFor complex access logic that can't be expressed declaratively, use a function:\n\n```typescript\ncrud: {\n update: {\n access: async (ctx, record) => {\n // Custom logic - return true to allow, false to deny\n if (ctx.roles.includes('admin')) return true;\n if (record.ownerId === ctx.userId) return true;\n\n // Check custom business logic\n const membership = await checkTeamMembership(ctx.userId, record.teamId);\n return membership.canEdit;\n }\n }\n}\n```\n\nFunction access receives:\n- `ctx`: The full AppContext object\n- `record`: The record being accessed (for get/update/delete operations)"
78
+ "content": "Define who can perform CRUD operations and under what conditions.\n\n## Basic Usage\n\n```typescript\n// features/applications/applications.ts\n\nexport const applications = sqliteTable('applications', {\n id: text('id').primaryKey(),\n candidateId: text('candidate_id').notNull(),\n jobId: text('job_id').notNull(),\n stage: text('stage').notNull(),\n notes: text('notes'),\n organizationId: text('organization_id').notNull(),\n});\n\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: { createable: [\"candidateId\", \"jobId\", \"notes\"], updatable: [\"notes\"] },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n crud: {\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n },\n});\n```\n\n## Role Hierarchy\n\nIf your project uses a tiered role system (e.g., `member` < `admin` < `owner`), you can define a hierarchy in your config and use the `+` suffix to mean \"this role and above\":\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n name: \"my-app\",\n auth: {\n roleHierarchy: ['member', 'admin', 'owner'], // lowest → highest\n },\n // ...\n});\n```\n\nThen in your resource definitions:\n\n```typescript\nread: { access: { roles: [\"member+\"] } }, // member, admin, owner\ncrud: {\n create: { access: { roles: [\"admin+\"] } }, // admin, owner\n delete: { access: { roles: [\"owner\"] } }, // owner only (no +)\n}\n```\n\nThe `+` suffix expands at compile time — `\"member+\"` becomes `[\"member\", \"admin\", \"owner\"]` in the generated code. You can mix hierarchical and exact roles: `roles: [\"member+\", \"finance\"]` expands to `[\"member\", \"admin\", \"owner\", \"finance\"]`.\n\n- Roles without `+` are exact matches (no expansion)\n- Pseudo-roles (`PUBLIC`, `AUTHENTICATED`, `USER`, `ADMIN`, `SYSADMIN`) cannot use the `+` suffix — they're terminal markers\n- Using `+` with a role not in the hierarchy throws a compile error\n- Using `+` without configuring `auth.roleHierarchy` throws a compile error\n\n## Configuration Options\n\n```typescript\ninterface Access {\n // Org-membership roles (OR logic — user needs at least one)\n // Matched against ctx.roles. Use \"role+\" suffix for hierarchy expansion.\n roles?: string[];\n\n // User-table role (OR logic). Matched against ctx.userRole from the\n // user.role column — independent of org membership. See userRole below.\n userRole?: string[];\n\n // Record-level conditions\n record?: {\n [field: string]: FieldCondition;\n };\n\n // Combinators\n or?: Access[];\n and?: Access[];\n}\n```\n\n## `userRole` vs `roles`\n\n`roles` and `userRole` check **two different fields** and are often confused — get this wrong and you'll grant access too broadly.\n\n| Primitive | Checks | Source | Example values |\n|-----------|--------|--------|----------------|\n| `roles` | `ctx.roles` | Org membership (multi-tenant) or single-tenant mirror of `user.role` | `\"owner\"`, `\"admin\"`, `\"member\"` |\n| `userRole` | `ctx.userRole` | The `user.role` column (Better Auth admin plugin) | `\"user\"`, `\"admin\"` |\n\nIn multi-tenant mode, **`roles: [\"admin\"]` means \"org admin\" — not a platform-wide admin.** An org-admin of Acme Corp has no elevated rights across other orgs. If you want to let Better Auth system admins through regardless of org membership (e.g., for support/ops), use `userRole: [\"admin\"]`.\n\nIn single-tenant mode (`features.organizations: false`), `ctx.roles` mirrors `user.role`, so `roles: [\"admin\"]` and `userRole: [\"admin\"]` behave the same. Using `userRole` in single-tenant code is still preferred — it documents intent and keeps the gate correct if you later enable orgs.\n\n### When to use `userRole`\n\n```typescript\n// Platform admin can see SSNs on every customer record, regardless of org\nmasking: {\n ssn: { type: 'ssn', show: { userRole: ['admin'] } },\n}\n\n// Support staff (user.role === 'admin') OR the org owner can refund\naccess: {\n or: [\n { userRole: ['admin'] },\n { roles: ['owner'] },\n ],\n}\n\n// CMS-internal resource: only platform admins\nread: { access: { userRole: ['admin'] } },\ncrud: {\n create: { access: { userRole: ['admin'] } },\n update: { access: { userRole: ['admin'] } },\n delete: { access: { userRole: ['admin'] } },\n}\n```\n\nWhen `roles` and `userRole` both appear in a single `Access` node, they're combined with AND — the user must satisfy both. Use `or:` to express \"one or the other\".\n\n`userRole` doesn't expand with the `+` hierarchy suffix — user-table roles are flat (typically just `\"user\"` and `\"admin\"`). If you've added custom user-table roles via Better Auth, list them explicitly.\n\n### Pseudo-roles\n\nQuickback ships five UPPERCASE role markers that are **not backed by a Better Auth role column** — they're system-level shortcuts handled directly by the compiler. The casing carries the boundary: UPPERCASE = pseudo-role (no plugin context required), lowercase = real role from a plugin's table (e.g. `members.role` from the org plugin).\n\n| Role | Auth gate | Compile-time requirement | Runtime check |\n|------|-----------|-------------------------|---------------|\n| `PUBLIC` | bypassed | none — explicit opt-in for unauthenticated access | always passes (auth skipped) |\n| `AUTHENTICATED` | required | none | `ctx.authenticated === true` |\n| `USER` | required | resource firewall **must** scope by `userId` | `ctx.authenticated` AND (`ctx.userRole` is unset OR `ctx.userRole === \"user\"`) |\n| `ADMIN` | required | Better Auth admin plugin **must** be enabled | `ctx.authenticated && ctx.userRole === \"admin\"` |\n| `SYSADMIN` | required | `cms: { sysadmin: true }` **must** be set on the project | `ctx.authenticated && ctx.userRole === \"sysadmin\"` |\n\nYou can mix pseudo-roles with real roles in the same list — they're OR'd together.\n\n#### `PUBLIC` — unauthenticated access\n\nUse `roles: [\"PUBLIC\"]` for public-facing endpoints like contact forms, public listings, or webhooks. Skips both the auth gate and the role check.\n\n```typescript\naccess: { roles: [\"PUBLIC\"] }\n```\n\n**Important:**\n- `PUBLIC` skips authentication and role checks — anyone can call the endpoint\n- **`PUBLIC` is the explicit, uppercase opt-in for unauthenticated access.** It works on every access node — reads, CRUD writes (`crud.create`/`update`/`delete`), views, and actions. The compiler trusts the marker; row-level safety comes from the firewall, masking, and (for token-gated endpoints like RSVP confirm, magic-link redemption, List-Unsubscribe-Post, webhook ingest) your handler's own validation. Anonymous CRUD endpoints typically pair `roles: [\"PUBLIC\"]` with `firewall: { exception: true }` on the resource so the row predicate doesn't reject every unauthenticated caller.\n- **Firewall still applies** — data is scoped by the firewall (organization, owner, team)\n- Every `PUBLIC` action invocation is **mandatory audit logged** to the security audit table (IP address, input, result, timing)\n- The wildcard `\"*\"` is **not supported** — using it throws a compile-time error\n- Tables with no isolation columns and any `PUBLIC` route do not require `firewall: [{ exception: true }]`\n\nFor org-scoped tables, `PUBLIC` routes still filter by organization. Since the user isn't authenticated, the organization ID must be passed as a query parameter:\n\n```\nGET /api/v1/listings?organizationId=org_abc123\n```\n\nThe firewall WHERE clause is always enforced. If no `organizationId` is provided, the API returns a `400` with code `ORG_REQUIRED`.\n\n```typescript\n// Public listing page — anyone can browse, but scoped to an org\nexport default defineTable(listings, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: { access: { roles: [\"PUBLIC\"] } }, // Public browsing + detail\n crud: {\n create: { access: { roles: [\"admin\", \"member\"] } }, // Auth required to create\n },\n});\n```\n\n#### `AUTHENTICATED` — any signed-in user\n\nUse `roles: [\"AUTHENTICATED\"]` for endpoints that any logged-in user can hit, regardless of role or org membership. No plugin context required.\n\n```typescript\n// Public events feed — any signed-in user can list/read; anonymous gets 401\nread: { access: { roles: [\"AUTHENTICATED\"] } }\n```\n\n#### `USER` — per-user records\n\nUse `roles: [\"USER\"]` for resources where each user only sees their own records. **Requires the firewall to scope by `userId`** — the role marker is the access half of the pair, the firewall is the row-filter half.\n\n```typescript\n// \"My todos\" — each caller sees only their own rows\nexport default defineTable(todos, {\n firewall: [{ field: 'userId', equals: 'ctx.userId' }],\n read: { access: { roles: [\"USER\"] } },\n crud: {\n create: { access: { roles: [\"USER\"] } },\n update: { access: { roles: [\"USER\"] } },\n delete: { access: { roles: [\"USER\"] } },\n },\n});\n```\n\nIf you forget the `userId` firewall predicate, the compiler throws:\n\n> `roles: [\"USER\"]` requires the resource to be scoped per-user. Add a `userId` column (auto-scoped) or an explicit owner predicate. If you want any signed-in user to read all records, use `roles: [\"AUTHENTICATED\"]` instead.\n\nWhen the Better Auth admin plugin is enabled, `USER` matches `user.role === \"user\"` specifically — admins are excluded and should use `[\"USER\", \"ADMIN\"]` if the same route should serve both.\n\n#### `ADMIN` — Better Auth admin-plugin admins\n\nUse `roles: [\"ADMIN\"]` for system-administrator endpoints. **Requires the Better Auth admin plugin** so `user.role` exists. Compiles to `ctx.userRole === \"admin\"`.\n\n```typescript\n// Platform-admin-only audit log\nread: { access: { roles: [\"ADMIN\"] } }\n```\n\nWithout the admin plugin you get a compile error pointing you to either enable the plugin or use lowercase `roles: [\"admin\"]` (the org-membership admin role).\n\n#### `SYSADMIN` — cross-tenant DB-admin tier\n\nUse `roles: [\"SYSADMIN\"]` for endpoints that should only be reachable by platform sysadmins — the cross-tenant DB-admin tier introduced in v0.15.0. Compiles to `ctx.userRole === \"sysadmin\"`. **Requires `cms: { sysadmin: true }` on the project config**; without that flag, using `SYSADMIN` fails the compile so the role can't sit as dead code.\n\n```typescript\n// Cross-tenant audit dashboard, sysadmin-only\nread: { access: { roles: [\"SYSADMIN\"] } }\n```\n\n`SYSADMIN` is a strict superset of `ADMIN` — at runtime, the universal-bypass shortcuts in `evaluateAccess` admit `userRole === 'sysadmin'` anywhere they admit `userRole === 'admin'`. The distinction matters for one thing only: **the firewall escape hatch**. When `cms.sysadmin: true`, every `buildFirewallConditions` emits an `if (ctx.userRole === 'sysadmin') return undefined;` (or just the soft-delete predicate when present) at the top — so sysadmins see every tenant's rows, not just their own org's. That escape hatch does NOT fire for `userRole === 'admin'`; admins still go through the firewall like everyone else.\n\nThis separation exists so Better Auth admin-plugin powers (user management, impersonation) and DB-admin powers (cross-tenant data inspection) stay decoupled. A user can have `user.role === 'admin'` without DB-level cross-tenant access; a user can have `user.role === 'sysadmin'` without org-membership context. See [CMS Configuration](/compiler/config#cms-configuration) for the `cms.sysadmin` flag, the cross-tenant `/admin/v1/sysadmin/organizations` endpoint, and the SPA's \"All organizations\" sentinel.\n\n#### Mixing pseudo-roles with real roles\n\nPseudo-roles and lowercase real roles compose with OR:\n\n```typescript\n// Record owner OR a system admin can read\nread: { access: { roles: [\"USER\", \"ADMIN\"] } }\n\n// Org owner OR system admin\ndelete: { access: { roles: [\"owner\", \"ADMIN\"] } }\n```\n\n> Note: today, an `ADMIN` match still goes through the `userId` firewall scope on USER-scoped resources — admins see only records they own on those routes. Use `firewall: { exception: true }` on a separate admin-only route if you need cross-user visibility.\n\n#### Quick reference\n\n```typescript\n// Unauthenticated public\naccess: { roles: [\"PUBLIC\"] }\n\n// Any signed-in user, no scoping\naccess: { roles: [\"AUTHENTICATED\"] }\n\n// Per-user records (requires userId firewall scope)\naccess: { roles: [\"USER\"] }\n\n// System admin (requires admin plugin)\naccess: { roles: [\"ADMIN\"] }\n\n// Org-membership roles with hierarchy expansion\naccess: { roles: [\"member+\"] } // expands to [\"member\", \"admin\", \"owner\"]\naccess: { roles: [\"admin+\"] } // expands to [\"admin\", \"owner\"]\naccess: { roles: [\"admin\"] } // exact match (no expansion)\n```\n\n```typescript\n// Field conditions - value can be string | number | boolean\ntype FieldCondition =\n | { equals: value | '$ctx.userId' | '$ctx.activeOrgId' }\n | { notEquals: value }\n | { in: value[] }\n | { notIn: value[] }\n | { lessThan: number }\n | { greaterThan: number }\n | { lessThanOrEqual: number }\n | { greaterThanOrEqual: number };\n```\n\n## Relationship-based authorization\n\nBeyond Better Auth roles (org membership, user-table role) and pseudo-roles, Quickback supports **relationship-based authorization roles** — names that bind to a declared relationship between the caller and a resource. Use these when access should follow a domain-table membership (\"user is a confirmed guest of this event\") rather than an org/admin gate.\n\n### `authz.relationships`\n\nDeclare relationships once in `quickback.config.ts`:\n\n```typescript\n// quickback.config.ts\n\nexport default defineConfig({\n // ...providers...\n authz: {\n relationships: {\n guestOf: {\n from: 'event_guests', // table name string\n subject: { column: 'userId', equals: 'ctx.userId' }, // caller side\n resource: { column: 'eventId' }, // resource side\n where: { status: 'confirmed' }, // optional filter\n },\n },\n roles: {\n guest: { via: 'guestOf' },\n // Composite: any guest OR an org owner/admin\n eventStaff: {\n or: [\n { via: 'guestOf' },\n { roles: ['admin', 'owner'] },\n ],\n },\n },\n },\n});\n```\n\n### Using relationship-roles in resources\n\nResource definitions reference declared roles by name in `roles: [...]` arrays exactly like BA roles or pseudo-roles. The compiler rewrites the access tree at build time so the runtime route does an inline relationship lookup against the declared table.\n\n**Today (v1) this works on:**\n\n| Surface | Status | Notes |\n|---|---|---|\n| `firewall:` `via:` predicate | ✓ Supported | Subquery composes as outermost AND |\n| `crud.*.access` `roles: ['guest']` | ✓ Supported | Inline async lookup per request |\n| `read.access` / `read.views.*.access` `roles: ['guest']` | ✓ Supported | Same inline path |\n| `masking.<field>.show` `roles: ['guest']` | ⚠ Refused at compile | v1 limitation — async/batched mask functions deferred |\n| `actions.<name>.access` `roles: ['guest']` | ⚠ Refused at compile | v1 limitation — explicit `relationshipBindings` deferred |\n\nFor the surfaces that are not yet supported, the compiler refuses at build time with a clear error pointing to a workaround. The runtime evaluator fails closed on relationship arms regardless, so silent grants are impossible.\n\n### Recommended pattern: gate at the firewall layer\n\nMost of the time, relationship-based row visibility is what you want, and putting it at the **firewall** layer is the cleanest expression. The firewall is row-filter; the access layer is route/role-filter; let each do its job:\n\n```typescript\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' }, // ← row visibility\n],\nread: {\n access: { roles: ['admin', 'member'] }, // ← who can hit the route\n views: {\n cms: { access: { roles: ['admin', 'member'] }, fields: [...] },\n guest: { access: { roles: ['member', 'admin'] }, fields: [...] },\n },\n},\n```\n\nA guest who's in your org as `member` can hit the endpoint and the firewall filters them down to events they're guests of. Cross-tenant access is impossible because the org filter is the outermost AND.\n\n### Cross-tenant \"my events\" dashboards are NOT this\n\nA common adjacent pattern — \"logged-in user wants `GET /my-events` returning events they're a guest of *across all tenants*\" — is **not** solved by relationship-roles. The tenant firewall is enforced at the outermost AND, so a guest of an event in another tenant remains correctly blocked.\n\nFor cross-tenant aggregation, use one of:\n\n- **User-scoped firewall**: `firewall: { owner: { column: 'userId' } }` — a flat per-user table.\n- **A standalone action that walks the relationship table itself** — see worked example below.\n\nDon't reach for relationship-roles first and then get confused when the tenant firewall blocks. The two patterns serve different problems.\n\n#### Worked example: `GET /my-events` standalone action\n\nThe cleanest expression of the cross-tenant attendee dashboard is a standalone action with a custom path that does its own join against the relationship table. The action is gated by `roles: ['AUTHENTICATED']` (any signed-in user can hit it; per-row scoping is the query itself), and the SQL filters by `ctx.userId` so each caller sees exactly the events they're a guest of:\n\n```ts\n// features/dashboard/actions/myEvents.ts\n\nexport default defineAction({\n description: \"List events the caller is a confirmed guest of, across all tenants.\",\n path: '/my-events',\n method: 'GET',\n input: z.object({}),\n // Any signed-in user. Row visibility comes from the query, not the role.\n access: { roles: ['AUTHENTICATED'] },\n async execute({ db, ctx }) {\n // 1. Find every event the caller has a confirmed guest row for.\n const guestRows = await db\n .select({ eventId: guests.eventId })\n .from(guests)\n .where(\n and(\n eq(guests.userId, ctx.userId!),\n eq(guests.status, 'confirmed'),\n // guests.organizationId is NOT filtered here — that's the whole\n // point of the cross-tenant lane. The relationship row's org is\n // ambient information that this action explicitly traverses.\n )\n );\n\n if (guestRows.length === 0) return { events: [] };\n\n // 2. Pull the matching events. NOTE: this query also bypasses\n // `events.organizationId` scope — by design — so explicitly filter\n // out soft-deleted rows yourself if your `events` table uses them.\n const eventIds = guestRows.map((r) => r.eventId);\n const rows = await db\n .select()\n .from(events)\n .where(inArray(events.id, eventIds));\n\n return { events: rows };\n },\n});\n```\n\nWhy this is a standalone action and not a CRUD route:\n\n- **Tenant firewall would block it.** The default `firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }]` on `events` is correct for every other read — only the cross-tenant dashboard wants to step outside it, and that's a deliberate, explicit step taken in handler code.\n- **The join is the access control.** A relationship-role at the firewall layer can't express \"filter by this user's relationships, ignoring the org context.\" The handler does that join directly.\n- **Audit-logged automatically.** Standalone actions are mandatorily audit-logged in the runtime — the cross-tenant traversal is recorded with `ctx.userId`, IP, and timing.\n\nTwo important guardrails when you write one of these:\n\n1. **Always filter by `ctx.userId` in the relationship lookup.** If you accept a `userId` from the request body and trust it, you've built an IDOR. The example above uses `ctx.userId!` directly so the only events returned are the caller's.\n2. **You take responsibility for soft-delete and other invariants the firewall would otherwise apply.** Add the `deletedAt` filter, status checks, and any other row-level predicates by hand. The action is OUTSIDE the firewall pipeline by design — the cost is that you can't lean on the auto-applied predicates.\n\nIf you find yourself writing more than one of these per project, that's usually a signal to revisit the schema (could a user-owned `userEvents` materialized view replace the join?) rather than a sign Quickback should ship a higher-level abstraction. Cross-tenant lanes are intentionally explicit.\n\n### Compile-time refusals (consolidated)\n\nThe validator and resolver reject:\n\n- Unknown key in `authz` block (typo guard — `realtionships` would otherwise silently produce a permanently-denied role).\n- Reserved role-name (auth-provider-derived). Names like `guest`, `speaker`, `attendee` are free; `admin`/`owner`/`member` are reserved when the BA org plugin is on.\n- Cycle in role composition (`a → b → a`).\n- Relationship `from` references unknown table.\n- Relationship-role used on a resource missing the `resource.column`.\n- Relationship table with `firewall: { exception: true }` (would let cross-tenant grants slip through).\n- `lowering: 'session'` (reserved for v2 — staleness/invalidation ergonomics not yet shipped).\n- `+` hierarchy suffix on a relationship-role name (terminal, like pseudo-roles).\n- Relationship-roles in `masking.show` / `actions.access` (deferred surfaces — see the table above).\n\n## Read & CRUD Configuration\n\nReads (`GET /` and `GET /:id`) live under `read:`; mutations live under `crud:`. See [Read](/compiler/definitions/read) for the full read pipeline reference.\n\n```typescript\nread: {\n // LIST + GET - GET /resource and GET /resource/:id\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n pageSize: 25, // Default page size\n maxPageSize: 100, // Client can't exceed this\n views: { // Per-view field projections\n summary: {\n fields: ['id', 'candidateId', 'jobId', 'stage'],\n access: { roles: [\"interviewer\"] },\n },\n },\n}\n\ncrud: {\n // CREATE - POST /resource\n create: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] },\n defaults: { // Default values for new records\n stage: 'applied',\n },\n },\n\n // UPDATE - PATCH /resource/:id\n update: {\n access: {\n or: [\n { roles: [\"hiring-manager\", \"recruiter\"] },\n { roles: [\"interviewer\"], record: { stage: { equals: \"interview\" } } }\n ]\n },\n },\n\n // DELETE - DELETE /resource/:id\n delete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"soft\", // 'soft' (default) or 'hard'\n },\n\n // PUT - PUT /resource/:id (only when generateId: false + guards: false)\n put: {\n access: { roles: [\"hiring-manager\", \"sync-service\"] },\n },\n}\n```\n\n## Evaluation Order\n\nGenerated `/:id` and batch handlers evaluate access in this fixed order:\n\n1. **Auth gate** — 401 if unauthenticated\n2. **Pre-record access** — role-only check (skips `access.record` predicates)\n3. **Firewall query** — `WHERE` clause filters by ownership\n4. **Post-record access** — full check including record-level predicates\n5. **Masking** — applied to the response\n\nStep 2 closes the 404-vs-403 ID-probe channel: an unauthorized caller without\na matching role gets 403 before the database is touched, so they can't tell\napart \"row exists out-of-scope\" from \"row doesn't exist.\" A caller with the\nright role but the wrong tenant gets 403 by default (firewall reveals via\nthe access layer); set\n[`firewallErrorMode: 'hide'`](/compiler/definitions/firewall) to return an\nopaque 404 instead.\n\nFunction-form access (`access: async (ctx, record) => ...`) is opaque to\nthe pre-record phase and always passes there; it's fully evaluated post-record.\n\n## List Filtering (Query Parameters)\n\nThe LIST endpoint automatically supports filtering via query params:\n\n```\nGET /jobs?status=open # Exact match\nGET /jobs?salaryMin.gt=50000 # Greater than\nGET /jobs?salaryMin.gte=50000 # Greater than or equal\nGET /jobs?salaryMax.lt=200000 # Less than\nGET /jobs?salaryMax.lte=200000 # Less than or equal\nGET /jobs?status.ne=closed # Not equal\nGET /jobs?title.like=Engineer # Pattern match (LIKE %value%)\nGET /jobs?status.in=open,draft # IN clause\n```\n\n| Operator | Query Param | SQL Equivalent |\n|----------|-------------|----------------|\n| Equals | `?field=value` | `WHERE field = value` |\n| Not equals | `?field.ne=value` | `WHERE field != value` |\n| Greater than | `?field.gt=value` | `WHERE field > value` |\n| Greater or equal | `?field.gte=value` | `WHERE field >= value` |\n| Less than | `?field.lt=value` | `WHERE field < value` |\n| Less or equal | `?field.lte=value` | `WHERE field <= value` |\n| Pattern match | `?field.like=value` | `WHERE field LIKE '%value%'` |\n| In list | `?field.in=a,b,c` | `WHERE field IN ('a','b','c')` |\n\n## Sorting & Pagination\n\n```\nGET /jobs?sort=createdAt&order=desc # Sort by field\nGET /jobs?limit=25&offset=50 # Pagination\n```\n\n- **Default limit**: 50\n- **Max limit**: 100 (or `maxPageSize` if configured)\n- **Default order**: `asc`\n\n## Delete Modes\n\n```typescript\ndelete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"soft\", // Sets deletedAt/deletedBy, record stays in DB\n}\n\ndelete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"hard\", // Permanent deletion from database\n}\n```\n\n## Context Variables\n\nUse `$ctx.` prefix to reference context values in conditions:\n\n```typescript\n// User can only view their own records\naccess: {\n record: { userId: { equals: \"$ctx.userId\" } }\n}\n\n// Nested path support for complex context objects\naccess: {\n record: { ownerId: { equals: \"$ctx.user.id\" } }\n}\n```\n\n### AppContext Reference\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `$ctx.userId` | `string` | Current authenticated user's ID |\n| `$ctx.activeOrgId` | `string` | User's active organization ID |\n| `$ctx.activeTeamId` | `string \\| null` | User's active team ID (if applicable) |\n| `$ctx.roles` | `string[]` | User's roles in current context |\n| `$ctx.isAnonymous` | `boolean` | Whether user is anonymous |\n| `$ctx.user` | `object` | Full user object from auth provider |\n| `$ctx.user.id` | `string` | User ID (nested path example) |\n| `$ctx.user.email` | `string` | User's email address |\n| `$ctx.{property}` | `any` | Any custom context property |\n\n## Function-Based Access\n\nFor complex access logic that can't be expressed declaratively, use a function:\n\n```typescript\ncrud: {\n update: {\n access: async (ctx, record) => {\n // Custom logic - return true to allow, false to deny\n if (ctx.roles.includes('admin')) return true;\n if (record.ownerId === ctx.userId) return true;\n\n // Check custom business logic\n const membership = await checkTeamMembership(ctx.userId, record.teamId);\n return membership.canEdit;\n }\n }\n}\n```\n\nFunction access receives:\n- `ctx`: The full AppContext object\n- `record`: The record being accessed (for get/update/delete operations)"
79
79
  },
80
80
  "compiler/definitions/actions": {
81
81
  "title": "Actions",
@@ -91,7 +91,7 @@ export const DOCS = {
91
91
  },
92
92
  "compiler/definitions/firewall": {
93
93
  "title": "Firewall - Data Isolation",
94
- "content": "The firewall generates WHERE clauses automatically to isolate data by user, organization, or team.\n\n## Basic Usage\n\nThe cleanest pattern is `q.scope()` — declare the tenant column once and the firewall is auto-derived:\n\n```typescript\n// features/candidates/candidates.ts\n\nexport default feature('candidates', {\n columns: {\n id: q.id(),\n name: q.text().required(),\n email: q.text().required(),\n organizationId: q.scope('organization'), // Auto-derives the firewall\n },\n // No firewall: block needed — auto-derived as\n // [{ field: 'organizationId', equals: 'ctx.activeOrgId' },\n // { field: 'deletedAt', isNull: true }]\n // ... guards, crud, read\n});\n```\n\nIf you need to declare the firewall explicitly, two forms are accepted — pick whichever reads better:\n\n**Named-scope** (compact, default for simple overrides):\n\n```typescript\nfirewall: { organization: { column: 'tenant_id' } }\nfirewall: { owner: { column: 'account_user_id' } }\nfirewall: { exception: true } // opt out of tenant scoping entirely\n```\n\n**Predicate array** (explicit, required for `in`-lists or custom non-scope predicates):\n\n```typescript\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n]\n```\n\nBoth shapes compile to the same canonical predicate array internally — the named-scope object is coerced at parse time. Pick by readability.\n\n## Auto-detected column synonyms\n\nWhen you omit the `firewall:` block entirely, the compiler scans the schema for one of these isolation columns and auto-derives the predicates:\n\n| Scope | Accepted column names |\n|---|---|\n| Organization | `organizationId`, `organisationId`, `orgId`, `organization`, `organisation`, `org` |\n| User | `userId` |\n| Team | `teamId` |\n\n`ownerId` is **not** auto-detected — it's reserved for business-logic ownership (who owns this record), not access control. A table that has only `ownerId` and no isolation column raises a targeted error explaining the distinction; either rename to `userId` if the column controls access, add an isolation column, or specify `firewall:` explicitly.\n\n## Predicate Shape\n\n```typescript\ntype FirewallPredicate =\n | { field: string; equals: string } // column = ctx.* (or literal)\n | { field: string; isNull: true } // column IS NULL\n | { field: string; in: string[] | string }// column IN (...)\n | { field: string; via: string } // column IN (relationship subquery)\n | { exception: true }; // opt out of tenant scoping\n\ntype FirewallConfig = ReadonlyArray<FirewallPredicate>;\n\n// Resource top-level (sibling to `firewall:`)\nfirewallErrorMode?: 'reveal' | 'hide';\n```\n\nPredicates are AND'd together. `firewallErrorMode` lives at the resource top level — it's a presentation-layer choice (403 vs 404), not a query-shape one.\n\n## Relationship-based scoping (`via:`)\n\nFor relationship authorization — \"this user can see rows X if they have a confirmed `event_guests` row pointing at X\" — declare the relationship under `authz.relationships` in `quickback.config.ts`, then reference it from `firewall:` with a `via:` predicate:\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests', // table name\n subject: { column: 'userId', equals: 'ctx.userId' }, // caller side\n resource: { column: 'eventId' }, // resource side\n where: { status: 'confirmed' }, // optional row filter\n },\n },\n}\n\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' },\n]\n```\n\nCompiles to:\n\n```sql\nWHERE sessions.organizationId = ?\n AND sessions.eventId IN (\n SELECT eventId FROM event_guests\n WHERE userId = ?\n AND status = 'confirmed'\n AND <event_guests' own firewall — tenant scope + soft-delete>\n )\n```\n\nKey properties:\n\n- **Firewall stays the outermost AND.** A guest of an event in another tenant is still blocked by your tenant predicate. Relationship-based scoping never bypasses tenant isolation.\n- **The relationship table's own firewall is AND'd into the subquery.** Soft-deleting a `event_guests` row revokes access immediately; cross-tenant relationship rows can't grant access.\n- **Anonymous callers fail closed.** `ctx.userId` is null-guarded; the subquery short-circuits to `WHERE 1 = 0` for unauthenticated requests.\n- **The relationship table must be tenant-scoped** (`firewall: { exception: true }` is rejected at compile time on relationship tables).\n\nSee [Access — relationships](/compiler/definitions/access#authz-relationships) for the full `authz.relationships` shape and role-binding patterns.\n\n## Context Sources\n\nWhen `equals` references the request context, use these standard sources:\n\n| Source | Description |\n|--------|-------------|\n| `ctx.userId` | Current authenticated user's ID |\n| `ctx.activeOrgId` | User's active organization ID |\n| `ctx.activeTeamId` | User's active team ID |\n\nThese values are populated by the auth middleware from the user's session. Any predicate where `equals` starts with `ctx.` is treated as server-derived: the column lands in `GUARDS_CONFIG.systemManaged` (clients cannot submit it) and is auto-populated on create / upsert from the context.\n\n## Auto-Derivation\n\nWhen the `firewall:` block is omitted, the compiler scans the schema for known scope columns and synthesises the predicate array:\n\n| Column found | Predicate emitted |\n|--------------|-------------------|\n| `organizationId` / `organisationId` / `orgId` / `organization` / `organisation` / `org` | `{ field: '...', equals: 'ctx.activeOrgId' }` |\n| `userId` | `{ field: 'userId', equals: 'ctx.userId' }` |\n| `teamId` | `{ field: 'teamId', equals: 'ctx.activeTeamId' }` |\n| `deletedAt` (always present via audit injection) | `{ field: 'deletedAt', isNull: true }` — appended automatically whenever the schema carries the column, regardless of which firewall shape you wrote |\n\n`q.scope(kind)` is the canonical way to declare the column — auto-derivation works the same way for plain `q.text().required()` or Drizzle `text(...).notNull()` columns named to match the convention.\n\n**Rules:**\n- Exactly one isolation column → auto-derived.\n- Zero columns AND no PUBLIC route → compile-time error (\"missing isolation column\").\n- Two or more (e.g. `organizationId` + `ownerId`) → compile-time error; declare `firewall:` explicitly.\n\n## What `{ exception: true }` Actually Does\n\n`{ exception: true }` disables **tenant scoping only** — the generated `buildFirewallConditions()` emits no tenant `WHERE` clauses. It does **not** affect:\n\n- **Audit field injection.** `createdAt`, `modifiedAt`, `createdBy`, `modifiedBy`, `deletedAt`, `deletedBy` are always added to every table unless you disable them globally with `compiler.features.auditFields: false`.\n- **Soft-delete filtering.** If the table has a `deletedAt` column (which it does by default, thanks to audit injection), the firewall still emits `isNull(<table>.deletedAt)` so soft-deleted records stay hidden. To opt out of soft-delete filtering on an exception resource, either set `compiler.features.auditFields: false` globally or hand-author a schema without `deletedAt`.\n\nSo `firewall: [{ exception: true }]` on the default configuration returns `isNull(<table>.deletedAt)` from `buildFirewallConditions()` — no tenant filter, soft-delete filter still applied.\n\n## Common Patterns\n\n```typescript\n// Public/system table - no tenant filtering (soft-delete still applied)\nfirewall: [{ exception: true }]\n\n// Organization-scoped (auto-derived when organizationId is present — block can be omitted)\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n]\n\n// User-owned personal data\nfirewall: [\n { field: 'ownerId', equals: 'ctx.userId' },\n { field: 'deletedAt', isNull: true },\n]\n\n// Multi-tenant + per-team scoping\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'teamId', equals: 'ctx.activeTeamId' },\n { field: 'deletedAt', isNull: true },\n]\n\n// Custom ctx field\nfirewall: [\n { field: 'workspaceId', equals: 'ctx.activeWorkspaceId' },\n]\n\n// Status-gated (literal value, not ctx-derived — does NOT add to systemManaged)\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'status', in: ['active', 'pending'] },\n]\n```\n\n## Error Responses\n\nWhen a record isn't found behind the firewall (wrong org, soft-deleted, or genuinely doesn't exist), the error response depends on `firewallErrorMode`:\n\n### Reveal Mode (Default)\n\nReturns **403** with a structured error:\n\n```json\n{\n \"error\": \"Record not found or not accessible\",\n \"layer\": \"firewall\",\n \"code\": \"FIREWALL_NOT_FOUND\",\n \"hint\": \"Check the record ID and your organization membership\"\n}\n```\n\nThis is developer-friendly and helps debug access issues during development.\n\n### Hide Mode\n\nReturns **404** with a generic error:\n\n```json\n{\n \"error\": \"Not found\",\n \"code\": \"NOT_FOUND\"\n}\n```\n\nUse `firewallErrorMode: 'hide'` for security-hardened deployments where you don't want attackers to distinguish between \"record exists but you can't access it\" and \"record doesn't exist\":\n\n```typescript\nexport default defineTable(records, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n firewallErrorMode: 'hide', // Opaque 404s prevent record enumeration\n});\n```\n\n### Foreign-Key Referential Checks\n\nGenerated `POST /` and `POST /batch` handlers validate every foreign-key column against the **target table's** firewall before inserting. If a record references a row that the caller can't see (wrong org, soft-deleted, or non-existent), the request fails with:\n\n```json\n{\n \"error\": \"Referenced jobs row not found\",\n \"code\": \"FK_NOT_FOUND\",\n \"layer\": \"validation\",\n \"field\": \"jobId\"\n}\n```\n\nThis closes a cross-tenant injection vector: even if an attacker knows a foreign tenant's row ID, they cannot attach a child record to it, and they cannot trigger a cross-tenant cascade delete. The check uses the target table's `buildXFirewallConditions(ctx)` helper, so it honors whatever firewall predicates the target declared (organization, owner, team, custom). FKs to tables with `{ exception: true }` get a plain existence check (still verifies the row exists, doesn't tenant-scope it).\n\nThe check runs after guards but before the insert, so it appears as `layer: \"validation\"` in error responses. Status code is `400`, not `404` — returning `404` would leak existence of out-of-scope rows.\n\n### Pre-Record ID-Probe Defense\n\nIndependent of `firewallErrorMode`, generated `/:id` handlers run a\n**role-only access check before** the firewall query (see\n[Access ordering](/compiler/definitions/access#evaluation-order)). A caller\nwithout the right role gets 403 before the database is touched, so they\ncan't distinguish \"row exists out-of-scope\" from \"row doesn't exist\" via\nresponse timing or status differences.\n\n`firewallErrorMode` controls what happens **after** the role check passes\nbut the firewall hides the row — i.e., when an authorized caller asks for\na record in another tenant. Use `'hide'` to make that case indistinguishable\nfrom a non-existent ID.\n\n## Rules\n\n- Every resource MUST have at least one tenant predicate OR `{ exception: true }` OR a PUBLIC route\n- `{ exception: true }` cannot be combined with tenant predicates in the same array\n\n## Why Can't You Mix `{ exception: true }` with Tenant Predicates?\n\nThey represent opposite intentions:\n- `{ exception: true }` = \"Don't generate tenant `WHERE` clauses, data is public/global\"\n- Tenant predicates = \"Generate tenant `WHERE` clauses to isolate data\"\n\nCombining them would be contradictory — you can't both isolate and not isolate. (Note: soft-delete filtering is independent of this decision, see above.)\n\n## Handling \"Some Public, Some Private\" Data\n\nIf you need records that are sometimes public and sometimes scoped, you have two options:\n\n### Option 1: Two Separate Tables\n\nSplit into two tables - one public, one scoped:\n\n```typescript\n// features/job-templates/template-library.ts - Public job templates\nexport default defineTable(templateLibrary, {\n firewall: [{ exception: true }],\n // ...\n});\n\n// features/job-templates/custom-templates.ts - Org's custom job templates\nexport default defineTable(customTemplates, {\n firewall: [{ field: 'ownerId', equals: 'ctx.userId' }],\n // ...\n});\n```\n\n### Option 2: Use Access Control Instead\n\nKeep tenant scope but make access permissive, then control visibility via `access`:\n\n```typescript\n// features/jobs/jobs.ts\nexport default defineTable(jobs, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: {\n // Anyone in the org can list — visibility differences are handled\n // via record-level access conditions on /:id\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n crud: {\n // Use record conditions to allow public jobs OR owned jobs on GET /:id\n // (single-record GET inherits read.access, with optional record-level overrides)\n },\n // ...\n});\n```\n\n### Which to Choose?\n\n| Scenario | Recommendation |\n|----------|----------------|\n| Truly global data (app config, public job templates) | `exception: true` in separate resource |\n| \"Public within org\" but still org-isolated | Ownership scope + permissive access rules |\n| Recruiter can toggle job postings public/private | Ownership scope + `visibility` field + access conditions |"
94
+ "content": "The firewall generates WHERE clauses automatically to isolate data by user, organization, or team.\n\n## Basic Usage\n\nThe cleanest pattern is `q.scope()` — declare the tenant column once and the firewall is auto-derived:\n\n```typescript\n// features/candidates/candidates.ts\n\nexport default feature('candidates', {\n columns: {\n id: q.id(),\n name: q.text().required(),\n email: q.text().required(),\n organizationId: q.scope('organization'), // Auto-derives the firewall\n },\n // No firewall: block needed — auto-derived as\n // [{ field: 'organizationId', equals: 'ctx.activeOrgId' },\n // { field: 'deletedAt', isNull: true }]\n // ... guards, crud, read\n});\n```\n\nIf you need to declare the firewall explicitly, two forms are accepted — pick whichever reads better:\n\n**Named-scope** (compact, default for simple overrides):\n\n```typescript\nfirewall: { organization: { column: 'tenant_id' } }\nfirewall: { owner: { column: 'account_user_id' } }\nfirewall: { exception: true } // opt out of tenant scoping entirely\n```\n\n**Predicate array** (explicit, required for `in`-lists or custom non-scope predicates):\n\n```typescript\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n]\n```\n\nBoth shapes compile to the same canonical predicate array internally — the named-scope object is coerced at parse time. Pick by readability.\n\n## Auto-detected column synonyms\n\nWhen you omit the `firewall:` block entirely, the compiler scans the schema for one of these isolation columns and auto-derives the predicates:\n\n| Scope | Accepted column names |\n|---|---|\n| Organization | `organizationId`, `organisationId`, `orgId`, `organization`, `organisation`, `org` |\n| User | `userId` |\n| Team | `teamId` |\n\n`ownerId` is **not** auto-detected — it's reserved for business-logic ownership (who owns this record), not access control. A table that has only `ownerId` and no isolation column raises a targeted error explaining the distinction; either rename to `userId` if the column controls access, add an isolation column, or specify `firewall:` explicitly.\n\n## Predicate Shape\n\n```typescript\ntype FirewallPredicate =\n | { field: string; equals: string } // column = ctx.* (or literal)\n | { field: string; isNull: true } // column IS NULL\n | { field: string; in: string[] | string }// column IN (...)\n | { field: string; via: string } // column IN (relationship subquery)\n | { exception: true }; // opt out of tenant scoping\n\ntype FirewallConfig = ReadonlyArray<FirewallPredicate>;\n\n// Resource top-level (sibling to `firewall:`)\nfirewallErrorMode?: 'reveal' | 'hide';\n```\n\nPredicates are AND'd together. `firewallErrorMode` lives at the resource top level — it's a presentation-layer choice (403 vs 404), not a query-shape one.\n\n## Relationship-based scoping (`via:`)\n\nFor relationship authorization — \"this user can see rows X if they have a confirmed `event_guests` row pointing at X\" — declare the relationship under `authz.relationships` in `quickback.config.ts`, then reference it from `firewall:` with a `via:` predicate:\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests', // table name\n subject: { column: 'userId', equals: 'ctx.userId' }, // caller side\n resource: { column: 'eventId' }, // resource side\n where: { status: 'confirmed' }, // optional row filter\n },\n },\n}\n\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' },\n]\n```\n\nCompiles to:\n\n```sql\nWHERE sessions.organizationId = ?\n AND sessions.eventId IN (\n SELECT eventId FROM event_guests\n WHERE userId = ?\n AND status = 'confirmed'\n AND <event_guests' own firewall — tenant scope + soft-delete>\n )\n```\n\nKey properties:\n\n- **Firewall stays the outermost AND.** A guest of an event in another tenant is still blocked by your tenant predicate. Relationship-based scoping never bypasses tenant isolation.\n- **The relationship table's own firewall is AND'd into the subquery.** Soft-deleting a `event_guests` row revokes access immediately; cross-tenant relationship rows can't grant access.\n- **Anonymous callers fail closed.** `ctx.userId` is null-guarded; the subquery short-circuits to `WHERE 1 = 0` for unauthenticated requests.\n- **The relationship table must be tenant-scoped** (`firewall: { exception: true }` is rejected at compile time on relationship tables).\n\nSee [Access — relationships](/compiler/definitions/access#authz-relationships) for the full `authz.relationships` shape and role-binding patterns.\n\n## Context Sources\n\nWhen `equals` references the request context, use these standard sources:\n\n| Source | Description |\n|--------|-------------|\n| `ctx.userId` | Current authenticated user's ID |\n| `ctx.activeOrgId` | User's active organization ID |\n| `ctx.activeTeamId` | User's active team ID |\n\nThese values are populated by the auth middleware from the user's session. Any predicate where `equals` starts with `ctx.` is treated as server-derived: the column lands in `GUARDS_CONFIG.systemManaged` (clients cannot submit it) and is auto-populated on create / upsert from the context.\n\n## Auto-Derivation\n\nWhen the `firewall:` block is omitted, the compiler scans the schema for known scope columns and synthesises the predicate array:\n\n| Column found | Predicate emitted |\n|--------------|-------------------|\n| `organizationId` / `organisationId` / `orgId` / `organization` / `organisation` / `org` | `{ field: '...', equals: 'ctx.activeOrgId' }` |\n| `userId` | `{ field: 'userId', equals: 'ctx.userId' }` |\n| `teamId` | `{ field: 'teamId', equals: 'ctx.activeTeamId' }` |\n| `deletedAt` (always present via audit injection) | `{ field: 'deletedAt', isNull: true }` — appended automatically whenever the schema carries the column, regardless of which firewall shape you wrote |\n\n`q.scope(kind)` is the canonical way to declare the column — auto-derivation works the same way for plain `q.text().required()` or Drizzle `text(...).notNull()` columns named to match the convention.\n\n**Rules:**\n- Exactly one isolation column → auto-derived.\n- Zero columns AND no PUBLIC route → compile-time error (\"missing isolation column\").\n- Two or more (e.g. `organizationId` + `ownerId`) → compile-time error; declare `firewall:` explicitly.\n\n## What `{ exception: true }` Actually Does\n\n`{ exception: true }` disables **tenant scoping only** — the generated `buildFirewallConditions()` emits no tenant `WHERE` clauses. It does **not** affect:\n\n- **Audit field injection.** `createdAt`, `modifiedAt`, `createdBy`, `modifiedBy`, `deletedAt`, `deletedBy` are always added to every table unless you disable them globally with `compiler.features.auditFields: false`.\n- **Soft-delete filtering.** If the table has a `deletedAt` column (which it does by default, thanks to audit injection), the firewall still emits `isNull(<table>.deletedAt)` so soft-deleted records stay hidden. To opt out of soft-delete filtering on an exception resource, either set `compiler.features.auditFields: false` globally or hand-author a schema without `deletedAt`.\n\nSo `firewall: [{ exception: true }]` on the default configuration returns `isNull(<table>.deletedAt)` from `buildFirewallConditions()` — no tenant filter, soft-delete filter still applied.\n\n## Sysadmin Escape Hatch\n\nWhen `cms: { sysadmin: true }` is set on the project (introduced in v0.15.0), every `buildFirewallConditions()` emits a runtime branch that drops tenant scopes for `ctx.userRole === 'sysadmin'` callers while keeping the soft-delete predicate:\n\n```typescript\n// Generated for an org-scoped table when cms.sysadmin: true\nexport function buildFirewallConditions(ctx: AppContext): SQL | undefined {\n if (ctx.userRole === 'sysadmin') {\n return isNull(invoices.deletedAt); // tenant predicate dropped, soft-delete kept\n }\n return and(\n eq(invoices.organizationId, ctx.activeOrgId!),\n isNull(invoices.deletedAt),\n );\n}\n```\n\nThe escape branch is **only** emitted when:\n\n- `cms.sysadmin: true` is set on the project config\n- The table has at least one tenant-scope predicate (org / owner / team / `via:` relationship). Tables with no tenant scopes already return what a sysadmin would see, so the runtime check would be dead code.\n- The firewall does not declare `{ exception: true }` (no tenant scopes to drop).\n\n**Sysadmin is distinct from admin.** `userRole === 'admin'` callers still go through the firewall normally — only `userRole === 'sysadmin'` triggers the bypass. Admins keep their existing universal-bypass at the *access* layer (cross-org reads on per-record routes via `?organizationId=`), but the firewall's row predicate remains in force. Sysadmin is opt-in, configured per-project, and intended for the cross-tenant CMS DB-admin tier — see [CMS Configuration](/compiler/config#cms-configuration).\n\nIf your project doesn't set `cms.sysadmin: true`, the escape branch is never emitted and the role value is functionally inert.\n\n## Common Patterns\n\n```typescript\n// Public/system table - no tenant filtering (soft-delete still applied)\nfirewall: [{ exception: true }]\n\n// Organization-scoped (auto-derived when organizationId is present — block can be omitted)\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n]\n\n// User-owned personal data\nfirewall: [\n { field: 'ownerId', equals: 'ctx.userId' },\n { field: 'deletedAt', isNull: true },\n]\n\n// Multi-tenant + per-team scoping\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'teamId', equals: 'ctx.activeTeamId' },\n { field: 'deletedAt', isNull: true },\n]\n\n// Custom ctx field\nfirewall: [\n { field: 'workspaceId', equals: 'ctx.activeWorkspaceId' },\n]\n\n// Status-gated (literal value, not ctx-derived — does NOT add to systemManaged)\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'status', in: ['active', 'pending'] },\n]\n```\n\n## Error Responses\n\nWhen a record isn't found behind the firewall (wrong org, soft-deleted, or genuinely doesn't exist), the error response depends on `firewallErrorMode`:\n\n### Reveal Mode (Default)\n\nReturns **403** with a structured error:\n\n```json\n{\n \"error\": \"Record not found or not accessible\",\n \"layer\": \"firewall\",\n \"code\": \"FIREWALL_NOT_FOUND\",\n \"hint\": \"Check the record ID and your organization membership\"\n}\n```\n\nThis is developer-friendly and helps debug access issues during development.\n\n### Hide Mode\n\nReturns **404** with a generic error:\n\n```json\n{\n \"error\": \"Not found\",\n \"code\": \"NOT_FOUND\"\n}\n```\n\nUse `firewallErrorMode: 'hide'` for security-hardened deployments where you don't want attackers to distinguish between \"record exists but you can't access it\" and \"record doesn't exist\":\n\n```typescript\nexport default defineTable(records, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n firewallErrorMode: 'hide', // Opaque 404s prevent record enumeration\n});\n```\n\n### Foreign-Key Referential Checks\n\nGenerated `POST /` and `POST /batch` handlers validate every foreign-key column against the **target table's** firewall before inserting. If a record references a row that the caller can't see (wrong org, soft-deleted, or non-existent), the request fails with:\n\n```json\n{\n \"error\": \"Referenced jobs row not found\",\n \"code\": \"FK_NOT_FOUND\",\n \"layer\": \"validation\",\n \"field\": \"jobId\"\n}\n```\n\nThis closes a cross-tenant injection vector: even if an attacker knows a foreign tenant's row ID, they cannot attach a child record to it, and they cannot trigger a cross-tenant cascade delete. The check uses the target table's `buildXFirewallConditions(ctx)` helper, so it honors whatever firewall predicates the target declared (organization, owner, team, custom). FKs to tables with `{ exception: true }` get a plain existence check (still verifies the row exists, doesn't tenant-scope it).\n\nThe check runs after guards but before the insert, so it appears as `layer: \"validation\"` in error responses. Status code is `400`, not `404` — returning `404` would leak existence of out-of-scope rows.\n\n### Pre-Record ID-Probe Defense\n\nIndependent of `firewallErrorMode`, generated `/:id` handlers run a\n**role-only access check before** the firewall query (see\n[Access ordering](/compiler/definitions/access#evaluation-order)). A caller\nwithout the right role gets 403 before the database is touched, so they\ncan't distinguish \"row exists out-of-scope\" from \"row doesn't exist\" via\nresponse timing or status differences.\n\n`firewallErrorMode` controls what happens **after** the role check passes\nbut the firewall hides the row — i.e., when an authorized caller asks for\na record in another tenant. Use `'hide'` to make that case indistinguishable\nfrom a non-existent ID.\n\n## Rules\n\n- Every resource MUST have at least one tenant predicate OR `{ exception: true }` OR a PUBLIC route\n- `{ exception: true }` cannot be combined with tenant predicates in the same array\n\n## Why Can't You Mix `{ exception: true }` with Tenant Predicates?\n\nThey represent opposite intentions:\n- `{ exception: true }` = \"Don't generate tenant `WHERE` clauses, data is public/global\"\n- Tenant predicates = \"Generate tenant `WHERE` clauses to isolate data\"\n\nCombining them would be contradictory — you can't both isolate and not isolate. (Note: soft-delete filtering is independent of this decision, see above.)\n\n## Handling \"Some Public, Some Private\" Data\n\nIf you need records that are sometimes public and sometimes scoped, you have two options:\n\n### Option 1: Two Separate Tables\n\nSplit into two tables - one public, one scoped:\n\n```typescript\n// features/job-templates/template-library.ts - Public job templates\nexport default defineTable(templateLibrary, {\n firewall: [{ exception: true }],\n // ...\n});\n\n// features/job-templates/custom-templates.ts - Org's custom job templates\nexport default defineTable(customTemplates, {\n firewall: [{ field: 'ownerId', equals: 'ctx.userId' }],\n // ...\n});\n```\n\n### Option 2: Use Access Control Instead\n\nKeep tenant scope but make access permissive, then control visibility via `access`:\n\n```typescript\n// features/jobs/jobs.ts\nexport default defineTable(jobs, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: {\n // Anyone in the org can list — visibility differences are handled\n // via record-level access conditions on /:id\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n crud: {\n // Use record conditions to allow public jobs OR owned jobs on GET /:id\n // (single-record GET inherits read.access, with optional record-level overrides)\n },\n // ...\n});\n```\n\n### Which to Choose?\n\n| Scenario | Recommendation |\n|----------|----------------|\n| Truly global data (app config, public job templates) | `exception: true` in separate resource |\n| \"Public within org\" but still org-isolated | Ownership scope + permissive access rules |\n| Recruiter can toggle job postings public/private | Ownership scope + `visibility` field + access conditions |"
95
95
  },
96
96
  "compiler/definitions/guards": {
97
97
  "title": "Guards - Field Modification Rules",
@@ -203,7 +203,7 @@ export const DOCS = {
203
203
  },
204
204
  "compiler/targets/hono-api/using-the-api/errors": {
205
205
  "title": "Errors",
206
- "content": "The generated API returns structured error responses with consistent fields across all security layers.\n\n## Status Codes\n\n| Code | Meaning | When |\n|------|---------|------|\n| `200` | OK | Successful GET, PATCH, DELETE |\n| `201` | Created | Successful POST |\n| `207` | Multi-Status | Batch operation with mixed results |\n| `400` | Bad Request | Guard violation, validation error, invalid input |\n| `401` | Unauthorized | Missing or expired authentication |\n| `403` | Forbidden | Access denied (wrong role, condition failed) or firewall blocked it |\n| `404` | Not Found | Record doesn't exist (or firewall blocked with `errorMode: 'hide'`) |\n| `429` | Too Many Requests | Rate limit exceeded |\n\n## Error Response Format\n\nAll errors use a flat structure with contextual fields:\n\n```json\n{\n \"error\": \"Insufficient permissions\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ROLE_REQUIRED\",\n \"details\": {\n \"required\": [\"hiring-manager\"],\n \"current\": [\"interviewer\"]\n },\n \"hint\": \"Contact an administrator to grant necessary permissions\"\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `error` | string | Human-readable error message |\n| `layer` | string | Security layer that rejected the request |\n| `code` | string | Machine-readable error code |\n| `details` | object | Layer-specific context (optional) |\n| `hint` | string | Actionable guidance for resolution (optional) |\n\n## Errors by Security Layer\n\n### Authentication (401)\n\nMissing or invalid authentication tokens.\n\n```json\n{\n \"error\": \"Authentication required\",\n \"layer\": \"authentication\",\n \"code\": \"AUTH_MISSING\",\n \"hint\": \"Include Authorization header with Bearer token\"\n}\n```\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `AUTH_MISSING` | No Authorization header provided |\n| `AUTH_INVALID_TOKEN` | Token is malformed or invalid |\n| `AUTH_EXPIRED` | Token has expired |\n| `AUTH_RATE_LIMITED` | Too many auth attempts |\n\n### Firewall (403)\n\nRecords outside the user's firewall scope return **403 Forbidden** by default with a structured error:\n\n```json\n{\n \"error\": \"Record not found or not accessible\",\n \"layer\": \"firewall\",\n \"code\": \"FIREWALL_NOT_FOUND\",\n \"hint\": \"Check the record ID and your organization membership\"\n}\n```\n\nFirewall filtering is transparent — the query is scoped by `WHERE organizationId = ?` so inaccessible records simply don't appear in results.\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `FIREWALL_NOT_FOUND` | Record not found behind firewall (wrong org, soft-deleted, or doesn't exist) |\n| `FIREWALL_ORG_ISOLATION` | Record belongs to a different organization |\n| `FIREWALL_USER_ISOLATION` | Record belongs to another user |\n| `FIREWALL_SOFT_DELETED` | Record has been soft deleted |\n\nFor security-hardened deployments, set `errorMode: 'hide'` in your firewall config to return opaque **404 Not Found** responses instead. This prevents attackers from distinguishing between \"record exists but you can't access it\" and \"record doesn't exist\".\n\n### Access (403)\n\nAccess violations return **403 Forbidden** when the user's role doesn't match the required roles for the operation.\n\n```json\n{\n \"error\": \"Insufficient permissions\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ROLE_REQUIRED\",\n \"details\": {\n \"required\": [\"hiring-manager\"],\n \"current\": [\"interviewer\"]\n },\n \"hint\": \"Contact an administrator to grant necessary permissions\"\n}\n```\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `ACCESS_ROLE_REQUIRED` | User doesn't have the required role |\n| `ACCESS_CONDITION_FAILED` | Record-level access condition not met |\n| `ACCESS_OWNERSHIP_REQUIRED` | User must own the record |\n| `ACCESS_NO_ORG` | No active organization set |\n\n### Guards (400)\n\nGuard violations return **400 Bad Request** when the request body contains fields that aren't allowed.\n\n```json\n{\n \"error\": \"Field cannot be set during creation\",\n \"layer\": \"guards\",\n \"code\": \"GUARD_FIELD_NOT_CREATEABLE\",\n \"details\": {\n \"fields\": [\"stage\"]\n },\n \"hint\": \"These fields are set automatically or must be omitted\"\n}\n```\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `GUARD_FIELD_NOT_CREATEABLE` | Field not in `createable` list |\n| `GUARD_FIELD_NOT_UPDATABLE` | Field not in `updatable` list |\n| `GUARD_FIELD_PROTECTED` | Field is action-only (protected) |\n| `GUARD_FIELD_IMMUTABLE` | Field cannot be modified after creation |\n| `GUARD_SYSTEM_MANAGED` | System field (createdAt, modifiedAt, etc.) |\n\n### Masking\n\nMasking doesn't produce errors — it silently transforms field values in the response.\n\n### Database\n\nSurfaced when a SQL write fails *post-validation* — most often a `NOT NULL` or `UNIQUE` constraint hit at the storage layer (e.g. an FK target was deleted concurrently, or a unique column collided with another tenant's row). All four codes share the same `layer: \"database\"` so consumers can switch on the layer alone and treat the rest as one bucket.\n\n```json\n{\n \"error\": \"Duplicate value\",\n \"layer\": \"database\",\n \"code\": \"DB_UNIQUE_VIOLATION\",\n \"details\": { \"column\": \"email\" },\n \"hint\": \"A record with this \\\"email\\\" already exists\"\n}\n```\n\n**Error codes:**\n\n| Code | Status | Description |\n|------|--------|-------------|\n| `DB_NOT_NULL_VIOLATION` | 400 | Required column was null at write time |\n| `DB_UNIQUE_VIOLATION` | 409 | Unique constraint hit |\n| `DB_INSERT_FAILED` | 500 | INSERT failed for an unrecognized reason |\n| `DB_UPDATE_FAILED` | 500 | UPDATE failed for an unrecognized reason |\n\nThe `details.column` field is only present when the driver's error message identified the offending column (SQLite/D1 do; some PG variants don't).\n\n## Batch Errors\n\nBatch operations can return:\n- **201** — All records succeeded\n- **207** — Partial success (some records failed)\n- **400** — Atomic mode and at least one record failed (all rolled back)\n\n### Partial Success (207)\n\n```json\n{\n \"success\": [{ \"id\": \"app_1\", \"candidateId\": \"cand_101\", \"stage\": \"applied\" }],\n \"errors\": [\n {\n \"index\": 1,\n \"record\": { \"candidateId\": \"cand_102\", \"jobId\": \"job_201\", \"stage\": \"interview\" },\n \"error\": {\n \"error\": \"Field cannot be set during creation\",\n \"layer\": \"guards\",\n \"code\": \"GUARD_FIELD_NOT_CREATEABLE\",\n \"details\": { \"fields\": [\"stage\"] },\n \"hint\": \"These fields are set automatically or must be omitted\"\n }\n }\n ],\n \"meta\": { \"total\": 2, \"succeeded\": 1, \"failed\": 1, \"atomic\": false }\n}\n```\n\n### Atomic Failure (400)\n\n```json\n{\n \"error\": \"Batch operation failed in atomic mode\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_ATOMIC_FAILED\",\n \"details\": {\n \"failedAt\": 2,\n \"reason\": { \"error\": \"Not found\", \"code\": \"NOT_FOUND\" }\n },\n \"hint\": \"Transaction rolled back. Fix the error and retry the entire batch.\"\n}\n```\n\n**Batch error codes:**\n\n| Code | Description |\n|------|-------------|\n| `BATCH_SIZE_EXCEEDED` | Too many records in a single request |\n| `BATCH_ATOMIC_FAILED` | Atomic batch failed, all changes rolled back |\n| `BATCH_MISSING_IDS` | Batch update/delete missing required IDs |"
206
+ "content": "The generated API returns structured error responses with consistent fields across all security layers.\n\n## Status Codes\n\n| Code | Meaning | When |\n|------|---------|------|\n| `200` | OK | Successful GET, PATCH, DELETE |\n| `201` | Created | Successful POST |\n| `207` | Multi-Status | Batch operation with mixed results |\n| `400` | Bad Request | Guard violation, validation error, invalid input |\n| `401` | Unauthorized | Missing or expired authentication |\n| `403` | Forbidden | Access denied (wrong role, condition failed) or firewall blocked it |\n| `404` | Not Found | Record doesn't exist (or firewall blocked with `errorMode: 'hide'`) |\n| `429` | Too Many Requests | Rate limit exceeded |\n\n## Error Response Format\n\nAll errors use a flat structure with contextual fields. Every structured error response also carries a `request` block with the HTTP method, URL, request ID, and a redacted+truncated copy of the request body — enough to triage or hand the response to an LLM agent without grepping logs:\n\n```json\n{\n \"error\": \"Insufficient permissions\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ROLE_REQUIRED\",\n \"details\": {\n \"required\": [\"hiring-manager\"],\n \"current\": [\"interviewer\"]\n },\n \"hint\": \"Contact an administrator to grant necessary permissions\",\n \"request\": {\n \"method\": \"POST\",\n \"url\": \"/api/v1/candidates/cnd_01H.../advance\",\n \"body\": \"{\\\"stage\\\":\\\"offer\\\"}\",\n \"requestId\": \"0c4f2c9e-...\"\n }\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `error` | string | Human-readable error message |\n| `layer` | string | Security layer that rejected the request |\n| `code` | string | Machine-readable error code |\n| `details` | object | Layer-specific context (optional) |\n| `hint` | string | Actionable guidance for resolution (optional) |\n| `request` | object | Method, URL, redacted body, and request ID. Auto-attached by the runtime so the error body is self-contained — bodies are capped at 4 KB and well-known sensitive keys (`password`, `token`, `secret`, `apiKey`, `otp`, `code`, `authorization`, …) are replaced with `\"[REDACTED]\"` |\n\n## Errors by Security Layer\n\n### Authentication (401)\n\nMissing or invalid authentication tokens.\n\n```json\n{\n \"error\": \"Authentication required\",\n \"layer\": \"authentication\",\n \"code\": \"AUTH_MISSING\",\n \"hint\": \"Include Authorization header with Bearer token\"\n}\n```\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `AUTH_MISSING` | No Authorization header provided |\n| `AUTH_INVALID_TOKEN` | Token is malformed or invalid |\n| `AUTH_EXPIRED` | Token has expired |\n| `AUTH_RATE_LIMITED` | Too many auth attempts |\n\n### Firewall (403)\n\nRecords outside the user's firewall scope return **403 Forbidden** by default with a structured error:\n\n```json\n{\n \"error\": \"Record not found or not accessible\",\n \"layer\": \"firewall\",\n \"code\": \"FIREWALL_NOT_FOUND\",\n \"hint\": \"Check the record ID and your organization membership\"\n}\n```\n\nFirewall filtering is transparent — the query is scoped by `WHERE organizationId = ?` so inaccessible records simply don't appear in results.\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `FIREWALL_NOT_FOUND` | Record not found behind firewall (wrong org, soft-deleted, or doesn't exist) |\n| `FIREWALL_ORG_ISOLATION` | Record belongs to a different organization |\n| `FIREWALL_USER_ISOLATION` | Record belongs to another user |\n| `FIREWALL_SOFT_DELETED` | Record has been soft deleted |\n\nFor security-hardened deployments, set `errorMode: 'hide'` in your firewall config to return opaque **404 Not Found** responses instead. This prevents attackers from distinguishing between \"record exists but you can't access it\" and \"record doesn't exist\".\n\n### Access (403)\n\nAccess violations return **403 Forbidden** when the user's role doesn't match the required roles for the operation.\n\n```json\n{\n \"error\": \"Insufficient permissions\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ROLE_REQUIRED\",\n \"details\": {\n \"required\": [\"hiring-manager\"],\n \"current\": [\"interviewer\"]\n },\n \"hint\": \"Contact an administrator to grant necessary permissions\"\n}\n```\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `ACCESS_ROLE_REQUIRED` | User doesn't have the required role |\n| `ACCESS_CONDITION_FAILED` | Record-level access condition not met |\n| `ACCESS_OWNERSHIP_REQUIRED` | User must own the record |\n| `ACCESS_NO_ORG` | No active organization set |\n\n### Guards (400)\n\nGuard violations return **400 Bad Request** when the request body contains fields that aren't allowed.\n\n```json\n{\n \"error\": \"Field cannot be set during creation\",\n \"layer\": \"guards\",\n \"code\": \"GUARD_FIELD_NOT_CREATEABLE\",\n \"details\": {\n \"fields\": [\"stage\"]\n },\n \"hint\": \"These fields are set automatically or must be omitted\"\n}\n```\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `GUARD_FIELD_NOT_CREATEABLE` | Field not in `createable` list |\n| `GUARD_FIELD_NOT_UPDATABLE` | Field not in `updatable` list |\n| `GUARD_FIELD_PROTECTED` | Field is action-only (protected) |\n| `GUARD_FIELD_IMMUTABLE` | Field cannot be modified after creation |\n| `GUARD_SYSTEM_MANAGED` | System field (createdAt, modifiedAt, etc.) |\n\n### Masking\n\nMasking doesn't produce errors — it silently transforms field values in the response.\n\n### Database\n\nSurfaced when a SQL write fails *post-validation* — most often a `NOT NULL` or `UNIQUE` constraint hit at the storage layer (e.g. an FK target was deleted concurrently, or a unique column collided with another tenant's row). All four codes share the same `layer: \"database\"` so consumers can switch on the layer alone and treat the rest as one bucket.\n\n```json\n{\n \"error\": \"Duplicate value\",\n \"layer\": \"database\",\n \"code\": \"DB_UNIQUE_VIOLATION\",\n \"details\": { \"column\": \"email\" },\n \"hint\": \"A record with this \\\"email\\\" already exists\"\n}\n```\n\n**Error codes:**\n\n| Code | Status | Description |\n|------|--------|-------------|\n| `DB_NOT_NULL_VIOLATION` | 400 | Required column was null at write time |\n| `DB_UNIQUE_VIOLATION` | 409 | Unique constraint hit |\n| `DB_INSERT_FAILED` | 500 | INSERT failed for an unrecognized reason |\n| `DB_UPDATE_FAILED` | 500 | UPDATE failed for an unrecognized reason |\n\nThe `details.column` field is only present when the driver's error message identified the offending column (SQLite/D1 do; some PG variants don't).\n\n## Batch Errors\n\nBatch operations can return:\n- **201** — All records succeeded\n- **207** — Partial success (some records failed)\n- **400** — Atomic mode and at least one record failed (all rolled back)\n\n### Partial Success (207)\n\n```json\n{\n \"success\": [{ \"id\": \"app_1\", \"candidateId\": \"cand_101\", \"stage\": \"applied\" }],\n \"errors\": [\n {\n \"index\": 1,\n \"record\": { \"candidateId\": \"cand_102\", \"jobId\": \"job_201\", \"stage\": \"interview\" },\n \"error\": {\n \"error\": \"Field cannot be set during creation\",\n \"layer\": \"guards\",\n \"code\": \"GUARD_FIELD_NOT_CREATEABLE\",\n \"details\": { \"fields\": [\"stage\"] },\n \"hint\": \"These fields are set automatically or must be omitted\"\n }\n }\n ],\n \"meta\": { \"total\": 2, \"succeeded\": 1, \"failed\": 1, \"atomic\": false }\n}\n```\n\n### Atomic Failure (400)\n\n```json\n{\n \"error\": \"Batch operation failed in atomic mode\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_ATOMIC_FAILED\",\n \"details\": {\n \"failedAt\": 2,\n \"reason\": { \"error\": \"Not found\", \"code\": \"NOT_FOUND\" }\n },\n \"hint\": \"Transaction rolled back. Fix the error and retry the entire batch.\"\n}\n```\n\n**Batch error codes:**\n\n| Code | Description |\n|------|-------------|\n| `BATCH_SIZE_EXCEEDED` | Too many records in a single request |\n| `BATCH_ATOMIC_FAILED` | Atomic batch failed, all changes rolled back |\n| `BATCH_MISSING_IDS` | Batch update/delete missing required IDs |\n\n## Action Failures (500)\n\nWhen an action's `execute()` body throws something that isn't a known\ntransition / state / FK / constraint failure (e.g. a `TypeError`, a\nfetch timeout, a third-party API error), the route returns\n`ACTION_EXECUTION_FAILED`. The body forwards as much of the underlying\nerror as is safe to expose: error class name, message, cause-chain\nmessage, and the top three stack frames with absolute paths sanitized\nto basename + line number.\n\n```json\n{\n \"error\": \"Cannot read properties of undefined (reading 'getXmlFragment')\",\n \"layer\": \"action\",\n \"code\": \"ACTION_EXECUTION_FAILED\",\n \"details\": {\n \"name\": \"TypeError\",\n \"frames\": [\n \"at updateContent (notebooks.ts:142:31)\",\n \"at execute (actions.ts:88:7)\"\n ]\n },\n \"hint\": \"The action handler threw an unhandled error. Check server logs for the underlying cause.\",\n \"request\": {\n \"method\": \"POST\",\n \"url\": \"/api/v1/notebooks/nb_123/updateContent\",\n \"body\": \"{\\\"content\\\":\\\"...\\\"}\",\n \"requestId\": \"0c4f2c9e-...\"\n }\n}\n```\n\n## Internal Errors (500)\n\nUncaught throws that escape every route handler land in the global\n`onError` and return `INTERNAL_ERROR`. The body carries the same\nunderlying-error context as `ACTION_EXECUTION_FAILED`: `name`, `cause`,\nsanitized `frames`, and the request block.\n\n```json\n{\n \"error\": \"Connection terminated unexpectedly\",\n \"layer\": \"database\",\n \"code\": \"INTERNAL_ERROR\",\n \"details\": {\n \"name\": \"Error\",\n \"cause\": \"ECONNRESET\",\n \"frames\": [\"at query (db.ts:54:12)\"]\n },\n \"hint\": \"Uncaught error during request handling. Look up the requestId in server logs for the full stack trace, or set EXPOSE_ERROR_STACK=1 to include it inline.\",\n \"requestId\": \"0c4f2c9e-...\",\n \"request\": {\n \"method\": \"GET\",\n \"url\": \"/api/v1/jobs\",\n \"requestId\": \"0c4f2c9e-...\"\n }\n}\n```\n\n### Exposing the full stack\n\nBy default the response body only carries the top three sanitized\nframes — full stack traces stay server-side so the worker bundle's\non-disk layout doesn't leak to API clients. To include the full stack\nin the response (useful in dev / staging), set `EXPOSE_ERROR_STACK=1`\non the worker (`wrangler.toml` `[vars]`, or `wrangler secret put`):\n\n```toml\n[vars]\nEXPOSE_ERROR_STACK = \"1\"\n```\n\nWhen set, both the global 500 and `ACTION_EXECUTION_FAILED` bodies\ngain a `details.stack` field with the unsanitized stack trace."
207
207
  },
208
208
  "compiler/targets/hono-api/using-the-api": {
209
209
  "title": "Using the API",
@@ -333,6 +333,10 @@ export const DOCS = {
333
333
  "title": "JWT Optimization",
334
334
  "content": "Quickback automatically optimizes authenticated API requests using JWT tokens. After the first request (which uses session cookies), subsequent requests skip the database entirely by sending a signed JWT that encodes the full auth context.\n\n## How It Works\n\n### Request Flow\n\n```\nFirst request (no JWT cached):\n Browser → Cookie auth → 2 DB queries → Response + set-auth-token header\n Browser caches JWT in localStorage\n\nSubsequent requests (JWT cached):\n Browser → Bearer JWT → Signature check only → Response (0 DB queries)\n```\n\n### What's in the JWT\n\nThe JWT encodes everything needed for auth middleware:\n\n| Claim | Description |\n|-------|-------------|\n| `sub` | User ID |\n| `orgId` | Active organization ID |\n| `role` | Organization membership role (`owner`, `admin`, `member`) |\n| `userRole` | Global user role (when admin panel is enabled) |\n| `email` | User email |\n| `name` | User display name |\n| `iat` | Issued-at timestamp |\n| `exp` | Expiry (15 minutes from issue) |\n\n### Signing\n\nJWTs are signed with HMAC-SHA256 using your `BETTER_AUTH_SECRET`. No additional configuration is needed — this uses the same secret you already set for Better Auth.\n\n---\n\n## Server-Side Validation\n\n**Every authenticated API request is validated server-side before it reaches your handler.** There is no \"trust the client\" shortcut — the middleware runs full signature verification on each request.\n\nValidation steps (in generated `src/middleware/auth.ts`):\n\n1. Extract the `Authorization: Bearer <token>` header\n2. Call `verifyJwt(token, BETTER_AUTH_SECRET)` from `src/lib/jwt.ts`\n3. Decode header + payload, recompute the HMAC-SHA256 signature, and compare via `crypto.subtle.verify()` (constant-time — no timing-attack surface)\n4. Check `exp` against the current time\n5. On success: hydrate `AppContext` from claims (`sub`, `orgId`, `role`, `userRole`, `email`, `name`) — no DB query\n6. On failure (bad signature, expired, malformed): **silently fall back** to Better Auth's session cookie auth; if that succeeds, mint a fresh JWT and return it in the `set-auth-token` response header\n\nThe Files worker (R2 uploads) performs the same verification using the shared secret — no network round-trip to the auth API for file operations.\n\n---\n\n## Token Lifecycle\n\n### Automatic Minting\n\nWhen a request arrives without a JWT (or with an expired one), the auth middleware:\n\n1. Authenticates via session cookie (existing Better Auth flow)\n2. Signs a JWT with the full auth context\n3. Returns it in the `set-auth-token` response header\n\nThe Quickback API client (`quickback-client.ts`) automatically captures this header and stores the JWT in `localStorage`.\n\n### Re-minting on Org Switch\n\nWhen a user switches organizations, the JWT must be re-minted because `orgId` and `role` change. The auth UI handles this automatically:\n\n```typescript\n// This happens automatically in the org switcher\nawait authClient.organization.setActive({ organizationSlug: slug });\n\n// Fetch fresh JWT with new org context\nconst res = await fetch('/api/v1/token', {\n method: 'POST',\n credentials: 'include',\n});\nconst { token } = await res.json();\nlocalStorage.setItem('bearer_token', token);\n```\n\n### Invalidation on Role Changes\n\nWhen an admin changes a user's role or removes them from an organization, the server broadcasts an `auth:token-invalidated` event via WebSocket. The client automatically clears the cached JWT, forcing the next request to fall back to session auth and mint a fresh token.\n\n```\nAdmin changes user role\n → databaseHooks fires on member update\n → Broadcasts auth:token-invalidated via realtime\n → Client clears localStorage JWT\n → Next request uses session cookie → gets fresh JWT\n```\n\n### Expiry\n\nJWTs expire after 15 minutes. This is a safety net — in practice, JWTs are re-minted well before expiry through the `set-auth-token` response header on session-fallback requests.\n\nWhen a JWT expires or is invalid:\n1. The middleware silently falls back to session cookie auth\n2. A fresh JWT is minted and returned in the response header\n3. The client stores the new JWT for subsequent requests\n\n---\n\n## Token Endpoint\n\n`POST /api/v1/token` mints a fresh JWT from the current session. This endpoint goes through normal auth middleware, so the user must have a valid session cookie.\n\n**Request:**\n```bash\ncurl -X POST https://your-api.example.com/api/v1/token \\\n -H \"Content-Type: application/json\" \\\n --cookie \"better-auth.session_token=...\"\n```\n\n**Response:**\n```json\n{\n \"token\": \"eyJhbGciOiJIUzI1NiJ9...\"\n}\n```\n\nUse this endpoint after operations that change auth context (like switching organizations) to get a JWT that reflects the new state.\n\n---\n\n## Client Integration\n\n### Quickback API Client\n\nThe `quickback-client.ts` API client handles JWT auth automatically:\n\n- **Sends** the cached JWT as `Authorization: Bearer <token>` on every request\n- **Captures** refreshed JWTs from `set-auth-token` response headers\n- **Clears** the JWT on `401` responses (falls back to session cookie)\n\nNo additional client configuration is needed.\n\n### Custom API Calls\n\nIf you make direct `fetch()` calls to your API (outside the Quickback client), include the JWT:\n\n```typescript\nconst jwt = localStorage.getItem('bearer_token');\n\nconst res = await fetch('https://your-api.example.com/api/v1/things', {\n headers: {\n 'Authorization': `Bearer ${jwt}`,\n 'Content-Type': 'application/json',\n },\n credentials: 'include', // Fallback to session cookie if no JWT\n});\n\n// Capture refreshed token\nconst newToken = res.headers.get('set-auth-token');\nif (newToken) {\n localStorage.setItem('bearer_token', newToken);\n}\n```\n\n### Sign Out\n\nClear the JWT on sign-out to prevent stale tokens:\n\n```typescript\nlocalStorage.removeItem('bearer_token');\nawait authClient.signOut();\n```\n\n---\n\n## Security\n\n### Threat Model\n\n| Threat | Mitigation |\n|--------|------------|\n| Token theft (XSS) | 15-minute expiry limits exposure window. `httpOnly` cookies protect the session. |\n| Token replay | Short expiry + `set-auth-token` rotation on session fallback |\n| Stale permissions | WebSocket `auth:token-invalidated` broadcast on role changes |\n| Token forgery | HMAC-SHA256 signature verified with `BETTER_AUTH_SECRET` |\n| Timing attacks | `crypto.subtle.verify()` provides constant-time comparison |\n\n### Key Points\n\n- JWTs are a **performance optimization**, not a replacement for session auth\n- Session cookies remain the source of truth — JWTs are derived from them\n- If a JWT is lost, stolen, or cleared, the system gracefully falls back to cookie auth\n- No additional secrets or configuration needed — uses your existing `BETTER_AUTH_SECRET`\n- The JWT contains no sensitive data beyond what's already in the auth context\n\n---\n\n## Files Worker\n\nThe files worker (for Cloudflare R2 file uploads) also supports JWT authentication. When a request includes a JWT `Authorization` header, the worker verifies it directly instead of calling back to the auth API — eliminating a network round-trip for file operations.\n\n---\n\n## Relation to Better Auth's JWT Plugin\n\nQuickback's JWT fast-path (documented above) is a **custom HMAC-SHA256 implementation**, separate from Better Auth's [`jwt` plugin](https://www.better-auth.com/docs/plugins/jwt). The distinction matters if you're comparing options.\n\n### What Quickback ships by default\n\n- Custom HMAC-SHA256 JWTs minted by the compiled API at `POST /api/v1/token`\n- Payload includes `sub`, `orgId`, `role`, `userRole`, `email`, `name` — everything the middleware needs to reconstruct `AppContext` with zero DB queries\n- Signed with `BETTER_AUTH_SECRET`\n- Used by the generated auth middleware as a fast-path ahead of `getSession()`\n\n### What Better Auth's JWT plugin gives you (opt-in)\n\nEnable it with `plugins: [\"jwt\"]` in your auth config:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: [\"jwt\"],\n}),\n```\n\nYou get:\n- JWKS endpoint at `/auth/v1/jwks` for asymmetric public-key verification by external services\n- BA's own `/auth/v1/token` endpoint (asymmetric-signed, EdDSA by default)\n- Standard OIDC-style claims via BA's `definePayload` hook\n\n### Why Quickback doesn't use BA's plugin internally\n\nBetter Auth's `definePayload` hook only receives `{ user }`. It cannot embed the active organization context (`orgId`, org-member `role`) that Quickback's Firewall and Access layers need. Without that context in the JWT, the middleware would have to do a DB lookup per request — defeating the whole point of the fast-path.\n\n### When to enable BA's JWT plugin anyway\n\nTurn it on if **external services** need to verify tokens without sharing `BETTER_AUTH_SECRET` — e.g. a third-party worker that wants to confirm a user's identity via JWKS. The BA-issued tokens won't have Quickback's org context, so they're useful for identity assertions, not for hitting the Quickback API directly.\n\nEnabling BA's plugin does **not** change how the compiled API authenticates requests — the middleware keeps using the custom HMAC JWT regardless.\n\n---\n\n## Related\n\n- [Auth Overview](/stack/auth) — Setup and configuration\n- [Auth Security](/stack/auth/security) — Cookie security, rate limiting, CORS\n- [API Keys](/stack/auth/api-keys) — Programmatic API access"
335
335
  },
336
+ "stack/auth/plugins/agent-auth": {
337
+ "title": "Agent Auth Plugin",
338
+ "content": "`@better-auth/agent-auth` is the official server implementation of the [Agent Auth Protocol](https://agentauthprotocol.com). When you enable it, your Quickback worker becomes an Agent Auth provider: AI agents can register, request scoped capability grants from a real user, get approved through device-authorization or CIBA, and then call your API with short-lived signed JWTs.\n\n## What gets enabled\n\nAdding `agentAuth` to your auth config force-enables two more plugins:\n\n| Plugin | Why |\n|--------|-----|\n| `bearer` | Lets clients send Better Auth session tokens via `Authorization: Bearer …` instead of cookies. The agent surface is bearer-only. |\n| `oauthProvider` | OAuth 2.1 + OIDC provider so MCP clients can register, get tokens, and call your API as a real user. Replaces the deprecated `mcp` plugin. |\n\nThere's no useful Agent Auth deployment without these — the compiler auto-adds them so you don't trip over a confusing runtime error.\n\nThe full Bearer matrix on the agent surface (everything reached through `/mcp` and the agent-auth REST projection):\n\n| Bearer flavor | Resolved by | Identity |\n|---------------|-------------|----------|\n| BA session token | `bearer` plugin | The signed-in user |\n| OAuth access token | `oauthProvider` plugin | The user who consented at OAuth time |\n| Agent JWT | `@better-auth/agent-auth` | The agent (acting on behalf of its bound user) |\n\nCookie auth is **not** forwarded into `/mcp` — bearer is the only channel, and CSRF surface is zero.\n\n## Configuration\n\n```ts\n\nexport default defineConfig({\n name: \"acme-api\",\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: {\n agentAuth: {\n providerName: \"Acme\",\n providerDescription: \"Acme APIs for AI agents.\",\n modes: [\"delegated\", \"autonomous\"],\n defaultHostCapabilities: [\"GET\", \"HEAD\"],\n },\n },\n }),\n },\n});\n```\n\nThe plain-flag form is also valid — use it when you don't need to override any defaults:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: [\"agentAuth\"],\n})\n```\n\n### Options\n\n| Option | Type | Default | Notes |\n|--------|------|---------|-------|\n| `providerName` | `string` | `env.APP_NAME` | Shown in the discovery doc and in the approval UI. |\n| `providerDescription` | `string` | `\"Agent-callable API powered by Quickback.\"` | Free-form description in `/.well-known/agent-configuration`. |\n| `modes` | `(\"delegated\" \\| \"autonomous\")[]` | `[\"delegated\", \"autonomous\"]` | Supported agent modes. |\n| `defaultHostCapabilities` | `string[]` \\| `true` | `[\"GET\", \"HEAD\"]` | Capabilities auto-granted to a newly registered host. |\n\nMost of the underlying plugin's surface (capability list, `onExecute`, custom approval-method resolver, `onEvent` audit hook) isn't projected through the compiler in v1 — see \"Limitations\".\n\n## Routes\n\nWhen the plugin is enabled the compiler emits:\n\n- `GET /.well-known/agent-configuration` — discovery document with issuer, endpoints, supported modes, default location.\n- All of the plugin's own endpoints, mounted by Better Auth under `/auth/v1/agent/*`.\n\nThe Account SPA gets a new route at `/agents/approve` for device-code approval. The plugin's `deviceAuthorizationPage` is automatically pinned at `${ACCOUNT_URL}/agents/approve`.\n\n## Approval flow\n\n1. The agent calls `/auth/v1/agent/register` to create itself, then requests a capability grant.\n2. The user enters the device code at `${ACCOUNT_URL}/agents/approve` (or follows the deep-link the agent showed them).\n3. The Account SPA fetches the pending request, shows the agent name + provider name + the capabilities being requested, with a \"Step-up\" badge on any capability whose `approvalStrength` is `\"webauthn\"`.\n4. User clicks **Authorize** (or **Deny**). Approval grants the capabilities; denial leaves the request pending.\n5. The agent polls or receives the token via the configured method, then calls capabilities with `Authorization: Bearer <agent-jwt>`.\n\nYou revoke an agent at any time from your account settings (or directly via the BA admin API).\n\n## Schema\n\nThe plugin adds tables for `agent`, `host`, `grant`, and `approval`. They're created automatically by `auth migrate` / `auth generate` — no manual Drizzle work needed.\n\n## OpenAPI capability projection (default on)\n\nWhen `agentAuth` is enabled, the compiler emits `src/lib/openapi-spec.ts` (the project's full OpenAPI spec inlined as a const) and wires `createFromOpenAPI(openapiSpec, { ... })` into the `agentAuth(...)` call. Every operation with an `operationId` becomes a capability. No manual capability list required.\n\n**How requests flow:**\n\n1. Agent calls `POST /capability/execute` with its agent JWT.\n2. The plugin verifies JWT + grant + constraints, then runs `onExecute`.\n3. `onExecute` (the plugin's built-in proxy) makes a self-fetch to the worker's own URL (`env.BETTER_AUTH_URL`).\n4. `resolveHeaders` mints a Better Auth JWT with `sub: agentSession.user.id` so the inner request looks like an authenticated user call.\n5. The worker's JWT fast-path picks it up, populates `ctx`, and the full firewall + access + masking pipeline runs.\n\n**Default approval strength:** GET → `\"session\"`, POST/PUT/PATCH/DELETE → `\"webauthn\"`. Override with the `approvalStrength` option.\n\n**To opt out** and wire capabilities by hand:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: {\n agentAuth: { fromOpenAPI: false },\n },\n})\n```\n\nWhen `fromOpenAPI: false`, the emitted call has `capabilities: []` and no proxy — you write the capability list + `onExecute` in your own `lib/auth.ts` overrides.\n\n## Limitations (v1)\n\n- **WebAuthn step-up isn't wired in the approval UI yet.** Capabilities tagged `approvalStrength: \"webauthn\"` show a Step-up badge but the actual escalation call isn't made — the upstream API for that escalation is still settling. Until it lands, those capabilities will fail server-side regardless of approval.\n- **No CLI helpers for listing / revoking agents.** Use the BA admin API directly.\n- **Self-fetch on Cloudflare Workers** adds one subrequest per capability call (~50ms). For typical agent traffic this is fine; for very high-frequency agents consider pinning a custom `onExecute` that uses `app.request()` for in-process routing.\n- **`@better-auth/agent-auth` 0.4.5 ships ESM-only exports** without a `require` condition. The compiler image patches the package's `package.json` at install time so the Better Auth CLI's `auth generate` step (jiti / CJS) can resolve it. Remove the patch in the Dockerfile when upstream ships proper exports.\n\n## Why bearer-only?\n\nThe MCP and agent surfaces are server-to-server by nature. Cookies on those surfaces add CSRF surface for no benefit (no browser callers), and `x-api-key` was the legacy `apiKey`-plugin path that fragments the auth model. Bearer is the one true channel here. If your project still wants API-key auth, configure the `apiKey` plugin to accept its key via `Authorization: Bearer` so everything stays one channel."
339
+ },
336
340
  "stack/auth/plugins/aws-ses": {
337
341
  "title": "AWS SES Plugin",
338
342
  "content": "`@quickback-dev/better-auth-aws-ses` is a Better Auth plugin that sends transactional emails via AWS SES. It handles AWS Signature V4 signing, HTML/text email templates, and rate limiting — designed to work in Cloudflare Workers (no Node.js `aws-sdk` dependency).\n\n> **Cloudflare Email is the default.** As of the Cloudflare Email Sending public beta, the zero-config `send_email` binding is Quickback's default transport for Cloudflare deploys — no API keys, no SES setup. See [Email Configuration](/compiler/config#email-configuration). Use AWS SES when you need it (non-Cloudflare runtimes, existing SES infra, or specific deliverability/compliance requirements).\n\n## Installation\n\n```bash\nnpm install @quickback-dev/better-auth-aws-ses\n```\n\nThis plugin is wired up only when you explicitly opt in via `email.provider: 'aws-ses'` in your Quickback config. Without that, `email.provider` defaults to `'cloudflare'` and the Cloudflare Email helper is used instead.\n\n## Email Types\n\nThe plugin handles 8 email types:\n\n| Endpoint | When Sent |\n|----------|-----------|\n| `/ses/send-verification` | Signup email verification |\n| `/ses/send-password-reset` | Password reset request |\n| `/ses/send-magic-link` | Passwordless sign-in link |\n| `/ses/send-otp` | One-time password code |\n| `/ses/send-welcome` | Post-signup welcome email |\n| `/ses/send-organization-invitation` | Team/org invite with role |\n| Combo auth | Magic link + OTP in a single email |\n| Delete account | Account deletion confirmation |\n\n### Combo Auth Mode\n\nWhen `useComboAuthEmail: true` is set, the plugin sends a single email that includes both a magic link button and an OTP code. Users can choose either method to authenticate.\n\n## AWS Signature V4\n\nThe plugin signs requests to SES using AWS Signature V4 with the Web Crypto API (`crypto.subtle`), making it compatible with Cloudflare Workers without any AWS SDK dependency.\n\n## Templates\n\nEach email type has both HTML and plain text templates. Templates include:\n\n- Responsive HTML layout with MSO (Microsoft Outlook) support\n- Security warning banners for sensitive operations\n- Fallback plain text versions for all email clients\n- XSS prevention via HTML escaping and URL sanitization\n\n## Configuration\n\n### Server Plugin\n\n```typescript\n\nconst auth = betterAuth({\n plugins: [\n awsSESPlugin({\n region: env.AWS_SES_REGION,\n accessKeyId: env.AWS_ACCESS_KEY_ID,\n secretAccessKey: env.AWS_SECRET_ACCESS_KEY,\n fromEmail: env.EMAIL_FROM,\n fromName: env.EMAIL_FROM_NAME || \"My App\",\n replyTo: env.EMAIL_REPLY_TO,\n appName: env.APP_NAME || \"My App\",\n appUrl: env.APP_URL,\n useComboAuthEmail: true, // Optional: combine magic link + OTP\n }),\n ],\n});\n```\n\n### Client Plugin\n\n```typescript\n\nconst authClient = createAuthClient({\n plugins: [awsSESClientPlugin()],\n});\n```\n\n## Required Environment Variables\n\n| Variable | Description |\n|----------|-------------|\n| `AWS_ACCESS_KEY_ID` | AWS access key (use Wrangler secrets) |\n| `AWS_SECRET_ACCESS_KEY` | AWS secret key (use Wrangler secrets) |\n| `AWS_SES_REGION` | SES region (e.g., `us-east-2`) |\n| `EMAIL_FROM` | Sender email address (must be SES-verified) |\n\n## Optional Variables\n\n| Variable | Description |\n|----------|-------------|\n| `EMAIL_FROM_NAME` | Sender display name |\n| `EMAIL_REPLY_TO` | Reply-to address (defaults to `EMAIL_FROM`) |\n| `APP_NAME` | Application name shown in email templates |\n| `APP_URL` | Application URL for links in emails |\n| `BETTER_AUTH_URL` | Auth API URL (for verification/reset links) |\n\n## Rate Limiting\n\nThe plugin includes basic in-memory rate limiting per recipient:\n\n- Configurable hourly and daily limits\n- Per-recipient tracking\n- For production, consider using an external store (Redis, KV)\n\n```typescript\nawsSESPlugin({\n // ...\n rateLimit: {\n maxEmailsPerHour: 10,\n maxEmailsPerDay: 50,\n },\n})\n```\n\n## Error Handling\n\n- Email failures return `false` (don't throw) — signup/login flows continue even if email delivery fails\n- Invalid or placeholder AWS credentials are detected at startup\n- Detailed console logging for debugging delivery issues\n\n## See Also\n\n- [Combo Auth Plugin](/stack/auth/plugins/combo-auth) — Combined magic link + OTP authentication\n- [Auth Configuration](/compiler/config/providers) — Configuring auth plugins"
@@ -431,7 +435,7 @@ export const DOCS = {
431
435
  },
432
436
  "stack/realtime/partyserver-rooms": {
433
437
  "title": "PartyServer Rooms",
434
- "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 // 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- **Multi-resource form** — same gate but with a regex parser dispatching to per-kind firewall lookups. Unknown kinds 400 at the gate.\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.\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."
438
+ "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 // 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- **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 }`).\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.\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."
435
439
  },
436
440
  "stack/realtime/using-realtime": {
437
441
  "title": "Using Realtime",
@@ -566,6 +570,7 @@ export const TOPIC_LIST = [
566
570
  "stack/auth/device-auth",
567
571
  "stack/auth",
568
572
  "stack/auth/jwt-optimization",
573
+ "stack/auth/plugins/agent-auth",
569
574
  "stack/auth/plugins/aws-ses",
570
575
  "stack/auth/plugins/combo-auth",
571
576
  "stack/auth/plugins",