@quickback-dev/cli 0.47.0 → 0.47.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 (30) hide show
  1. package/dist/commands/compile.d.ts +1 -1
  2. package/dist/commands/compile.js +1 -1
  3. package/dist/docs/content.js +10 -10
  4. package/dist/docs/content.js.map +1 -1
  5. package/dist/index.js +1 -1
  6. package/dist/lib/file-loader.d.ts +1 -1
  7. package/dist/lib/file-loader.d.ts.map +1 -1
  8. package/dist/lib/file-loader.js +16 -3
  9. package/dist/lib/file-loader.js.map +1 -1
  10. package/dist/skill/docs/changelog.md +328 -0
  11. package/dist/skill/docs/compiler/definitions/access.md +17 -0
  12. package/dist/skill/docs/compiler/definitions/actions.md +9 -4
  13. package/dist/skill/docs/compiler/targets/hono-api/database/neon.md +27 -8
  14. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/openapi.md +2 -1
  15. package/dist/skill/docs/stack/account-ui/features/organizations.md +1 -1
  16. package/dist/skill/docs/stack/cms/pages.md +1 -1
  17. package/dist/skill/docs/stack/realtime/durable-objects.md +9 -0
  18. package/dist/skill/docs/stack/realtime/live-views.md +4 -0
  19. package/dist/skill/docs/stack/realtime/using-realtime.md +2 -2
  20. package/package.json +1 -1
  21. package/src/skill/docs/changelog.md +328 -0
  22. package/src/skill/docs/compiler/definitions/access.md +17 -0
  23. package/src/skill/docs/compiler/definitions/actions.md +9 -4
  24. package/src/skill/docs/compiler/targets/hono-api/database/neon.md +27 -8
  25. package/src/skill/docs/compiler/targets/hono-api/using-the-api/openapi.md +2 -1
  26. package/src/skill/docs/stack/account-ui/features/organizations.md +1 -1
  27. package/src/skill/docs/stack/cms/pages.md +1 -1
  28. package/src/skill/docs/stack/realtime/durable-objects.md +9 -0
  29. package/src/skill/docs/stack/realtime/live-views.md +4 -0
  30. package/src/skill/docs/stack/realtime/using-realtime.md +2 -2
@@ -3,7 +3,7 @@
3
3
  export const DOCS = {
4
4
  "changelog": {
5
5
  "title": "Changelog",
6
- "content": "## v0.47.0 — June 11, 2026\n\n### Breaking: zero-false-positive analyzer checks are now compile errors\n\nThe authz/authn analyzer (v0.37) shipped warn-only. After a release cycle of\ndata, the checks whose every trip is a definite misconfiguration — never a\nlegitimate config — are **promoted to compile errors**. Warnings nobody is\nforced to read are documentation; the pillar guarantees are now enforced.\n\n**Breaking** — a config that previously compiled with one of these warnings\nnow fails the compile:\n\n- `AUTHZ_EMPTY_PERMISSION` — a permission that is structurally unsatisfiable\n (`allOf(a, not(a))`: a fact AND its exact negation at the same AND-level).\n- `AUTHZ_CAPABILITY_CEILING` — a resource's firewall grants a\n `scope:<kind>:<role>` role access beyond its capability profile (or the\n role has no profile at all). This is the M0.2 pillar guarantee — it was\n authored as an error all along and is now enforced.\n- `AUTHN_ROUTE_COVERAGE`, `AUTHN_SURFACE_INVARIANT`,\n `AUTHN_SECRET_CONSISTENCY`, `AUTHN_CREDENTIAL_DELIVERY`,\n `AUTHN_CLAIM_PROVENANCE` — the structural-authn set (route auth coverage,\n bearer-only `/mcp`/agent surfaces + INTERNAL unreachability, mint↔verify\n key/issuer/audience pairing, anchored credential delivery, verifier-only\n identity claims). These still run against empty route/credential metadata\n on a real compile (no-ops until the generators emit it), but the severity\n contract is locked in now — they fail the build the moment they can fire.\n\nThe heuristic/advisory checks are unchanged: `AUTHZ_SHADOWED_ARM`,\n`AUTHZ_UNREACHABLE_ROLE`, `AUTHZ_UNREACHABLE_VIEW`, and\n`AUTHZ_NOT_OVER_RESOURCE` stay warnings; `AUTHZ_PUSHDOWN_COST` stays an info\nreport. `QUICKBACK_AUTHZ_STRICT=true` still promotes those warnings too.\n\n**The override escape hatch** — every promoted finding can be explicitly\naccepted, per finding, with a required reason:\n\n```ts\nauthz: {\n analyzer: {\n allow: [\n {\n check: 'AUTHZ_CAPABILITY_CEILING',\n target: 'sessions/scope:event:organizer', // from the rendered finding\n reason: 'organizer grant profile lands with the v2 rollout (TICKET-123)',\n },\n ],\n },\n}\n```\n\nAn override downgrades that exact `(check, target)` finding back to a warning\nthat cites the reason — even under strict mode (it's an explicit, reasoned\nacceptance). Every rendered error prints its exact override recipe. Guard\nrails: `check` must be one of the promoted ids (unknown or keep-warn ids are\nrejected at config validation), `reason` is required, and an `allow` entry\nthat matches no current finding is itself a compile error — no dead\noverrides accumulating after the underlying issue is fixed.\n\nAnalyzer-internal defects are still fail-open: a bug in the analyzer itself\ndowngrades to a single warning and the compile continues. Only real findings\nfail builds.\n\n## v0.46.0 — June 11, 2026\n\n### Breaking: \"no organization context\" responses unified on HTTP 403\n\nGenerated APIs used to answer the same semantic condition — *the caller has no\nactive organization context* — with two different statuses: `400 ORG_REQUIRED`\nfrom the collection list guard and the create/PUT/batch org validation, but\n`403 ACCESS_NO_ORG` from standalone actions and `403\nACCESS_TENANT_SCOPE_REQUIRED` from unsafe org-scoped actions. Clients and SDKs\nhad to special-case the split.\n\n**Breaking** — recompile + redeploy required; every \"no org context\" denial is\nnow **403**:\n\n- `GET /api/v1/<resource>` (and views) without an active org or\n `?organizationId=` → `403 ORG_REQUIRED` (was 400).\n- `POST /`, `PUT /:id`, `POST /batch`, `PUT /batch` without an active org →\n `403 ORG_REQUIRED` (was 400).\n- Standalone actions (`403 ACCESS_NO_ORG`) and unsafe org-scoped actions\n (`403 ACCESS_TENANT_SCOPE_REQUIRED`) were already 403 and are unchanged.\n\nError **codes are unchanged** — `ORG_REQUIRED`, `ACCESS_NO_ORG`, and\n`ACCESS_TENANT_SCOPE_REQUIRED` keep their identities, so clients that\ndiscriminate on `code` need no changes. Only clients that branch on the raw\n`400` status for these responses must update to `403`.\n\n### Breaking: root-mounted actions lose their nested alias URLs\n\nA standalone action whose declared `path:` lives outside its feature prefix\n(e.g. `path: \"/reports/orders\"` in the `orders` feature) mounts at the root:\n`/api/v1/reports/orders`. That root URL is the one the OpenAPI spec, the MCP\nsurface, and the operations manifest have always advertised — but the\ngenerated per-feature routes file *also* carried an undocumented, fully-gated\ncopy at the nested `/api/v1/<feature><path>` URL (e.g.\n`/api/v1/orders/reports/orders`).\n\n**Breaking** — the nested alias is no longer emitted. One URL per operation:\na root-mounted action exists only at its advertised `/api/v1<path>` mount.\nAnything calling the unadvertised nested URL gets a 404 after recompile +\nredeploy; switch to the documented root URL. Actions declared *under* the\nfeature prefix are untouched, and a feature whose standalone actions are all\nroot-mounted no longer emits an (empty) feature actions routes file.\n\n## v0.45.0 — June 9, 2026\n\n### `auth.jwt.revocationCheck: 'kv'` — sub-TTL JWT revocation\n\nThe JWT fast-path trusts signed claims for their full lifetime — that's what\nmakes it a fast-path. Until now the only revocation bounds were the TTL\n(plain claims) and the carry-forward cap (scope claims, v0.44.0). The\nlong-promised `'kv'` mode is now real on the **Cloudflare runtime**:\n\n```ts\nauth: { jwt: { revocationCheck: 'kv' } }\n```\n\n- **Per-principal revocation timestamps, not per-token denylists.** A\n revocation event writes \"everything for this principal minted before now is\n dead\" to the project's **existing `KV` binding** (keys prefixed `qbrev:`) —\n nothing extra to provision. Entries self-expire after the maximum token\n lifetime, so the store never accumulates.\n- **The bearer fast-path checks before trusting.** A verified token whose\n `iat` (or `sct`, for the relationship-scope claim) predates the stored\n timestamp is rejected and falls through to session auth, which re-checks\n membership and re-mints — an active legitimate session recovers\n transparently. Costs 2+ edge-cached KV reads per bearer verify; the\n explicit trade the opt-in buys.\n- **Written automatically where revocation actually happens:** org-member\n removal and role change (Better Auth `organizationHooks`), and\n UPDATE/DELETE of scope-conferring relationship rows — through the same\n audit-wrapper write chokepoint Live Views uses, plus the single DELETE\n route (which has the row in hand but no `.returning()`). Revoke-on-touch:\n a false positive just forces a cheap re-prove.\n- **User bans flip automatically.** The Better Auth admin plugin's ban lands\n as a user-row update, so a generated `databaseHooks.user.update.after` hook\n stamps the user-level revocation the moment `banned` flips — every\n outstanding JWT dies on its next use, and the cookie/session path already\n rejects banned sessions, completing the lockout. When outbound webhooks are\n configured, the same hook emits a `user.banned` event so subscribed\n endpoints are notified.\n- **App-code helpers** for everything else: `src/lib/jwt-revocation.ts`\n exports `revokeUserTokens` / `revokeMemberTokens` / `revokeScopeTokens`\n (e.g. call `revokeUserTokens` from a custom revoke-all flow).\n- **Fails open.** A KV outage degrades revocation to the TTL /\n carry-forward-cap bound — it never locks every bearer out.\n\nBun/Node + `'kv'` fails at compile time with a clear message (the store rides\nthe Cloudflare KV binding; those runtimes own immediate-revoke via the\ncookie/session path). Default remains `'none'`; without the flag the emitted\nmiddleware is byte-identical to v0.44.0.\n\n## v0.44.0 — June 9, 2026\n\n### Scope carry-forward is now bounded (revocation fix)\n\nThe auth middleware's rolling refresh re-signs a verified `scope` claim on\nevery authed call without re-probing the relationship — that's what lets a\nscoped session ride past the short JWT TTL with zero per-request DB cost. But\nunbounded, it defeated the revocation model the docs promised: a removed\nguest/staff who kept polling got a fresh TTL on every request, so \"removal\ntakes effect within one TTL\" only held for *idle* clients, and the refresh\nalso bypassed the ≤180s scope-token ceiling (it re-signed with the raw\n`auth.jwt.expiresIn`).\n\nScope tokens now carry a proof timestamp (`sct`), stamped exclusively by the\nproven mint sites (`POST /scope/v1/enter` and the namespace resolver, via the\nshared mint helper). The rolling refresh:\n\n- **refuses once the claim's proof is older than the carry-forward cap\n (15 minutes)** — past it, the token expires within one TTL and the client\n re-proves via `enter` or any minting namespace route, which won't re-mint a\n revoked role. Worst-case post-revocation window for an active client:\n **cap + one TTL** from the last real proof, instead of unbounded.\n- **carries `sct` forward verbatim** — the refresh can never restart the\n window without an actual relationship probe. Claims without `sct`\n (pre-0.44 tokens) fail closed and simply stop refreshing.\n- **signs through the same ≤180s ceiling as the mint sites** — an\n `auth.jwt.expiresIn` above the ceiling no longer leaks into scope-bearing\n tokens via the refresh path.\n\nNo client changes needed: tokens renew exactly as before inside the window,\nand re-entering is the existing flow. For tables where even the capped window\nis too wide, gate with a `via` arm (live relationship subquery per request)\ninstead of a bare `ctx.scope.<kind>` arm; immediate revocation\n(`auth.jwt.revocationCheck: 'kv'`) remains on the roadmap.\n\n## v0.43.0 — June 4, 2026\n\n### Better Auth 1.6\n\nGenerated projects are now pinned to Better Auth **1.6**. The `agents.mcp.requireAuth` work in 0.42.0 surfaced a long-standing version drift: the compiler emitted `better-auth: ^1.5.0`, but `@better-auth/oauth-provider` resolves a tree that requires `@better-auth/core ^1.6.14` and imports `@better-auth/core/utils/host` + `/redirect-uri` — subpaths that only exist in 1.6.x. The result was a `wrangler deploy` that failed at bundle time with `Could not resolve …` and never uploaded.\n\nThis release aligns the **entire** Better Auth dependency set to a coherent 1.6.9 floor so npm resolves one consistent tree:\n\n- `better-auth`, `@better-auth/drizzle-adapter`, `@better-auth/api-key`, `@better-auth/passkey`, `@better-auth/oauth-provider` → `^1.6.9` (generated projects, the baked Docker deps, and the bundled CMS/Account SPAs).\n- Added an explicit `kysely ^0.28.16` pin: Better Auth 1.6's migrator imports `DEFAULT_MIGRATION_TABLE` / `DEFAULT_MIGRATION_LOCK_TABLE` from kysely but doesn't *declare* kysely, so the Worker bundle needs it pinned directly.\n\nNo code migration was required — Quickback already uses `@better-auth/oauth-provider` (not the now-deprecated OIDC Provider plugin), and emits no `freshAge`/SAML usage affected by 1.6's behavioral changes. Verified end to end: a `requireAuth` project and a normal project both `npm install` a clean 1.6.14 tree and bundle with `wrangler deploy --dry-run` with zero resolution errors.\n\n### Larger migration histories no longer hit the upload ceiling\n\nLong-lived projects accumulate one full-schema drizzle snapshot per migration, and the whole cumulative meta payload (snapshots + journals + `.sql`, across both the auth and features dirs) is re-sent on **every** compile — even a no-schema-change one. Projects with deep migration histories were hitting the compiler's `existingFiles` size limit and failing to compile, with no schema drift and nothing to fix on their end.\n\nThe server-side ceilings are raised so this is no longer the binding constraint:\n\n- `existingFiles` payload: **4 MiB → 16 MiB**\n- total request body: **8 MiB → 32 MiB** (kept above the per-category limits so it doesn't trip first)\n\nThis is enforced entirely on the compiler, so no CLI upgrade is needed — the new headroom applies as soon as `compiler.quickback.dev` is on this release.\n\n### Custom response headers (`security.headers`)\n\nThe generated Worker emitted a fixed set of security headers (CSP, HSTS,\n`X-Content-Type-Options`, …) with no supported way to add your own — teams that\nwanted, say, an `X-Server-Version` build stamp on every response had to\npost-patch the generated middleware after each compile.\n\nNew `security.headers` sets arbitrary response headers natively. Values are\nstatic strings or templates interpolating per-deploy Worker env vars via the\n`{{env.VAR_NAME}}` token:\n\n```ts\nsecurity: {\n headers: {\n // Both vars must be set, or the header is omitted entirely.\n 'X-Server-Version': '{{env.SERVER_VERSION}}+{{env.SERVER_BUILD}}',\n 'X-Powered-By': 'Quickback',\n },\n}\n```\n\n- **Omit-if-unset** — a header that references env vars is emitted only when\n *every* referenced var is set (non-empty) at runtime. A Worker that forgot to\n inject the var emits no header, never `X-Server-Version: undefined`. Static\n headers are always emitted.\n- The value is read from `c.env` per request, so it picks up whatever Worker\n var is injected at deploy time — nothing is baked at compile time.\n- **Managed headers are rejected** — names owned by a dedicated `security` field\n (CSP, HSTS, `X-Frame-Options`, `Referrer-Policy`, …) error at compile so the\n two emitters can't race. Malformed `{{env…}}` tokens error too, rather than\n leaking literal braces into the wire header.\n\nSurvives a clean `quickback compile` with no post-processing. See\n[Security Headers → Custom response headers](/compiler/config/security#custom-response-headers).\n\n## v0.42.0 — June 4, 2026\n\n### Interactive OAuth for the generated MCP server\n\nMCP connectors (Claude, Cursor, …) could only connect to a generated `/mcp`\nendpoint **anonymously** — they never launched a sign-in flow, so auth-gated\ntools stayed invisible. The OAuth machinery was already present (Better Auth's\n`oauth-provider` ships `/oauth2/authorize`, `/token`, `/register` + PKCE under\n`/auth/v1`); the compiler just never let a connector discover or trigger it.\n\nNew `agents.mcp.requireAuth` makes the MCP surface authenticated-only:\n\n```ts\nagents: { mcp: { requireAuth: true } },\n```\n\nWhen enabled, the compiler:\n\n- **Challenges unauthenticated `/mcp`** with `401` + `WWW-Authenticate: Bearer\n resource_metadata=\"…\"` ([RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) §5.1) — the signal connectors use to start OAuth.\n- **Force-enables `oauthProvider` + `bearer`**, so `/oauth2/authorize`, `/token`,\n and `/register` ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591) dynamic client registration) exist with PKCE.\n- **Delegates `/.well-known/oauth-authorization-server`** to Better Auth's real\n metadata instead of a hand-rolled stub that advertised a non-existent\n authorization endpoint.\n- Adds the `<origin>/mcp` resource to `validAudiences`\n ([RFC 8707](https://datatracker.ietf.org/doc/html/rfc8707)) so the connector's access token isn't rejected.\n\nLogin and consent are served by your Account SPA, so users authenticate with\nwhatever methods you already enabled. Default is unchanged (anonymous public\ntools); set `requireAuth: true` for servers meant for authenticated users.\n\n## v0.40.2 — June 3, 2026\n\n### Passwordless plugins can no longer bypass the signup gate\n\nBetter Auth's `emailOtp` and `magicLink` plugins auto-create an account when a\ncode/link is verified for an unknown email — and that path is independent of\n`emailAndPassword.disableSignUp`. As a result, `account.auth.signup: false`\nclosed `POST /auth/v1/sign-up/email` but left OTP / magic-link verification as an\nopen back-door for account creation.\n\nThe compiler now emits each plugin's own `disableSignUp` flag, and new\nper-plugin options expose it directly:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: {\n emailOtp: { disableSignUp: true }, // OTP sign-in only; unknown emails rejected\n magicLink: { disableSignUp: true }, // same for magic links\n },\n}),\n```\n\nBoth default to following the global gate: setting `account.auth.signup: false`\n(→ `emailAndPassword.disableSignUp: true`) now also gates the OTP and magic-link\npaths automatically. Set `{ disableSignUp: false }` on a plugin explicitly to\nkeep its sign-up open while password sign-up stays closed.\n\n## v0.40.1 — June 2, 2026\n\n- The generated `wrangler.toml` and `Env` type now emit the `ASSETS` binding\n type for projects that mount SPAs (CMS / Account), so handler code that\n references `c.env.ASSETS` typechecks.\n- Compiler Docker builds preserve their layer cache across rebuilds, cutting\n local recompile time.\n\n## v0.40.0 — June 2, 2026\n\nR2 file storage is now **presign-only by default**. Adding\n`defineFileStorage(\"cloudflare-r2\")` emits just the `ctx.storage` signer — no\nFILES_DB database, no `/storage/v1/*` endpoints, no files worker. You sign\npresigned URLs against a bucket and store references in your own table. The\nturnkey managed subsystem is still available, now behind `managed: true`.\n\nThis decouples the lightweight primitive from the heavyweight subsystem so you\ncan add uploads without standing up a metadata database you don't use.\n\n### Presign-only by default; managed is opt-in\n\n```ts\n// Presign-only (default) — ctx.storage against a bucket, nothing else\ndefineFileStorage(\"cloudflare-r2\", { bucketName: \"my-app-media\" })\n\n// Managed subsystem — FILES_DB + /storage/v1/* + files worker\ndefineFileStorage(\"cloudflare-r2\", { managed: true })\n```\n\n- New projects can omit `bucketName` — it defaults to `<project>-media`, so\n setup is one `wrangler r2 bucket create` plus the R2 API-token secrets.\n- Existing projects set `bucketName` to a bucket they already have. Presign-only\n emits **no** R2 bucket binding and **no** FILES_DB binding — nothing to\n provision, nothing to migrate.\n\n### Per-call bucket + custom secret names\n\n```ts\n// Sign against a different bucket than the configured default\nawait storage.signPutUrl(key, { bucket: \"my-app-public\", contentType });\n```\n\nIf your project already stores R2 credentials under different env-var names,\nmap them so the signer reads yours:\n\n```ts\ndefineFileStorage(\"cloudflare-r2\", {\n bucketName: \"my-app-media\",\n presign: { accountIdEnv: \"CF_ACCOUNT_ID\", accessKeyIdEnv: \"S3_KEY\", secretAccessKeyEnv: \"S3_SECRET\" },\n})\n```\n\n### Fixes\n\n- `maxFileSize` now accepts a human string (`\"100mb\"`, `\"5gb\"`) as well as a\n number of bytes — previously a string emitted invalid TypeScript.\n- Presign-only no longer emits a stray `FILES_DB` `[[d1_databases]]` block (with\n an invalid `database_id = \"local-files\"`) into `wrangler.toml`, which would\n have made `wrangler deploy` reject the worker.\n\n## v0.39.1 — June 2, 2026\n\nDeduplicate colliding OpenAPI `operationId`s. The auto-generated list id\n`list\n</Button>\n```\n\n`ResponsiveModal` survived the migration unchanged — it composes the higher-level Dialog + Drawer wrappers (preserved public API), not the underlying primitives.\n\n#### Caller-side API changes worth noting\n\nBase-ui ships some real behavioural changes the Radix variants didn't:\n\n- `<Select onValueChange>` now receives `(value: string | null, eventDetails) => void` (was `(value: string) => void`). Existing `Dispatch<SetStateAction<string>>` setters reject `null` — wrap callbacks defensively: `onValueChange={(v) => v != null && setX(v)}`.\n- `<DropdownMenuContent forceMount>` removed (base-ui has no `forceMount`). Use base-ui's `keepMounted` on the Popup/Positioner if you need to preserve unmounted state.\n- Component sub-names shifted (`Dialog.Content` → `Dialog.Popup`, `Dialog.Overlay` → `Dialog.Backdrop`). Data attributes are now `data-open` / `data-closed` (no more `data-state=\"open\"`).\n\n#### Adding a new primitive after this release\n\n```bash\ncd packages/ui\npnpm dlx shadcn@latest add <component> --overwrite --yes\n# Sweep generated `@/` imports to relative paths — the SPAs' vite-tsconfig-paths\n# plugin doesn't see packages/ui's @/* mapping at bundle time:\nsed -i.bak \\\n -e 's|\"@/lib/utils\"|\"../lib/utils\"|g' \\\n -e 's|\"@/components/|\"./|g' \\\n -e 's|\"@/hooks/|\"../hooks/|g' \\\n components/<component>.tsx && rm components/<component>.tsx.bak\n```\n\nIf the new primitive pulls in fresh deps, mirror them into `apps/compiler/deps-spa-{cms,account}-package.json` per the SPA build pipeline or Docker SPA builds will fail.\n\n---\n\n## v0.18.1 — May 18, 2026\n\n### Account SPA — teams, active-team picker, permission-aware UI\n\nThe Account SPA's organization surface is now feature-parity with Better Auth's `organization` plugin for the basic team workflow, and replaces the long-standing hardcoded `role === 'owner' || 'admin'` checks with `checkRolePermission` so projects that ship custom roles get a UI that respects them.\n\n#### Teams (opt-in)\n\nWhen the BA config enables teams — `organization({ teams: { enabled: true } })` — the compiler emits `VITE_ENABLE_ORG_TEAMS=true` and the Account SPA exposes a Teams tab on each organization:\n\n- **Teams index** (`/$slug/teams`) — splits into \"Your teams\" (from `listUserTeams`) and \"Other teams\" so non-admins land on what's relevant. Create / rename / delete from the list, gated on `team:create` / `team:update` / `team:delete`.\n- **Team detail** (`/$slug/teams/$teamId`) — member roster with add / remove, joining `listTeamMembers` against the org's full member list for display.\n- **Active-team picker** in the org header — calls `setActiveTeam` and exposes the choice via `OrganizationContext.activeTeamId` so downstream routes (and the BA `session.activeTeamId` server-side) stay in sync.\n- **Team-aware invites** — `InviteMemberDialog` shows an optional team picker when teams are on and forwards `teamId` to `inviteMember`, so accepting the invite drops the new member straight into the right team.\n\nTeams are loaded once by the `$slug` layout (`listTeams` + `listUserTeams`) and exposed via `OrganizationContext.teams` / `userTeamIds` / `refreshTeams`, so individual team routes don't re-fetch the list.\n\n#### Permission-aware UI via `checkRolePermission`\n\n`OrganizationContext.isOwnerOrAdmin` is gone. Routes now read `can(resource, action)` from context, which delegates to `authClient.organization.checkRolePermission` — synchronous, no roundtrip, and aware of any custom roles registered via the BA `ac` option. Multi-role users (BA stores multiple roles comma-separated) are handled by checking each role; the action is allowed if any role grants it.\n\nMigrated sites:\n\n- `$slug.tsx` tab gates → `can('invitation', 'create')`, `can('organization', 'update')`\n- `members.tsx` action menu → `can('member', 'update' | 'delete')`; the owner-hierarchy guard (non-owners can't touch owner-role members) is preserved as a client-side mirror of BA's server enforcement\n- `invitations.tsx` → `can('invitation', 'create' | 'cancel')` gates the Invite button, resend, and cancel separately\n- `settings.tsx` → `can('organization', 'update')` for the form, `can('organization', 'delete')` for the danger zone (was owner-only)\n- `teams.tsx` / `teams.$teamId.tsx` → `can('team', 'create' | 'update' | 'delete')`\n\nProjects on the default three-role hierarchy see no behaviour change; projects that defined `admin`/`member` overrides via BA's access-control API now get a UI that matches what the server will actually authorize.\n\n#### Editable slug + metadata on organization settings\n\nThe `$slug/settings.tsx` form now edits two more `organization.update` fields:\n\n- **URL slug** — full debounced `checkSlug` flow (mirroring the create-org form); on rename, the SPA navigates to `/${newSlug}/settings` and the layout re-fetches with the new slug.\n- **Metadata** — single `Record<string, any> | null` JSON textarea, parsed on submit with inline error messaging. Empty clears the field.\n\nSlug rename is non-breaking for the SPA itself, but every external link / bookmark that references the old slug becomes a 404 — the form warns about this before saving.\n\n#### Auth client wiring\n\nWhen `VITE_ENABLE_ORG_TEAMS=true`, the SPA's `organizationClient(...)` is instantiated with `teams: { enabled: true }` so the team APIs are typed end-to-end. When the flag is off, team methods aren't surfaced — and the Teams tab is hidden — keeping the bundle and UI honest about what the server actually supports.\n\n---\n\n## v0.18.0 — May 17, 2026\n\n### `config.apps` — mount user-authored SPAs on dedicated hostnames\n\nThe compiler now generates per-hostname Worker middleware for arbitrary user SPAs alongside the built-in CMS and Account UIs. Previously the only way to host a product app next to a Quickback API was a second Worker; `config.apps` brings the full stack — API, account, and product UI — onto one deployment with same-origin auth.\n\n```ts\napps: {\n www: {\n domain: \"www.example.com\",\n aliasDomains: [\"example.com\"], // apex serves the same SPA\n },\n}\n```\n\nEach entry binds one or more hostnames to a directory under `src/apps/<name>/` and inherits the Account-domain pass-through behavior — `/api/`, `/auth/`, `/admin/`, `/storage/`, and `/health` route to Hono so the SPA fetches its API without CORS. The compiler:\n\n- emits a `custom_domain = true` route in `wrangler.toml` for the primary hostname and every alias\n- adds each hostname to Better Auth's `TRUSTED_ORIGINS` (when `trustedOrigins` is left unset)\n- widens the CSP `connect-src` to cover the SPA-baked origins\n- folds the new hostnames into shared-parent detection for `crossSubDomainCookies`\n\nDrop the prebuilt SPA bundle at `quickback/apps/<name>/` — the existing source-apps passthrough copies it byte-for-byte into `src/apps/<name>/`. The compiler doesn't build the SPA; it only emits routing for whatever's already there. The names `cms`, `account`, and `public` are reserved; hostname collisions with `cms.domain` / `account.domain` / `account.adminDomain` or between two `apps[*]` entries fail at compile time.\n\nWhen `cms` and `account` are both configured, the multi-domain catchall now explicitly skips app hostnames — an API miss on an app host returns the standard 404 JSON via `app.notFound` instead of stray-serving a sibling SPA's HTML shell.\n\n### Cross-subdomain cookie inference handles apex aliases\n\nThe shared-parent detection that drives `advanced.crossSubDomainCookies` previously reduced any hostname by stripping the leftmost label — `'example.com'` collapsed to `'com'`, which broke equality against sibling subdomains. Apex hostnames (exactly two dot-segments) are now treated as already being the parent, so apex aliases (`example.com` listed alongside `www.example.com`) coexist cleanly with `auth.example.com` / `cms.example.com` and the compiler still emits `crossSubDomainCookies: { enabled: true, domain: '.example.com' }`.\n\n---\n\n## v0.17.2 — May 15, 2026\n\n### `customPlugins` escape hatch on `defineAuth(\"better-auth\", …)`\n\nThe Better Auth provider now accepts `customPlugins` alongside the named-plugin registry — a path to ship third-party plugins (`@better-auth-kit/audit`, …), unregistered built-ins, or one-off project-local plugins without forking the compiler.\n\nEach entry is an explicit import descriptor:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: { passkey: true, organization: true },\n customPlugins: [\n // (1) Project-local plugin file at quickback/plugins/long-session.ts\n { from: \"./plugins/long-session\", export: \"longSessionPlugin\" },\n // (2) Third-party npm package\n {\n from: \"@better-auth-kit/audit\",\n export: \"auditPlugin\",\n args: { events: [\"sign-in\"] },\n dependencies: { \"@better-auth-kit/audit\": \"^1.0.0\" },\n },\n ],\n}),\n```\n\n`from` is either a relative path under `./plugins/` (the CLI auto-uploads matching files from `quickback/plugins/`; the compiler copies them into `src/plugins/<name>.ts` and rewrites the emitted import) or a bare npm specifier (emitted verbatim; declare `dependencies` so the package lands in the generated `package.json`). Omit `args` to emit the symbol uncalled (plugin instance); provide `args` to emit a JSON-serialized factory call.\n\nThe descriptor is validated with Zod — typos in `from`/`export`, paths that escape `./plugins/`, and references to files the CLI didn't ship all fail at compile time with a targeted message.\n\n---\n\n## v0.17.1 — May 14, 2026\n\n### `quickback start` — interactive onboarding\n\n```bash\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n```\n\n`start` walks new users through template selection, scaffolds the project on disk, and only prompts for an account when it's ready to compile. Cancelling at the login prompt leaves the scaffold intact — sign in and run `quickback compile` whenever you're ready.\n\nThe same deferred-auth flow applies to `quickback create`. Scaffolding and (optional) Cloudflare D1 setup run before authentication, so you can preview the project on disk before committing to an account.\n\n### Named views on the free tier\n\nThe `todos` template now ships a `dashboard` named view, exposing a projected response at `GET /api/v1/todos/views/dashboard`. Named views support per-view access rules and per-view field selection while inheriting the table's firewall and masking — the canonical way to ship list-view payloads that are cheaper to fetch and easier to cache than a full collection read.\n\n### `quickback init` removed\n\nFolded into `start` and `create`. The legacy command name prints a deprecation notice pointing at its replacements.\n\n### Minor\n\n- `quickback whoami` reads the stored tier from your credentials.\n- Pro upsell copy in `quickback login` is shown only when the server returns an explicit free-tier subscription.\n- Bare scaffolds (`cloudflare`, `empty`) report accurately when there are no features to generate migrations for.\n\n---\n\n## v0.16.10 — May 14, 2026\n\n### D1-specific safety pass on generated migrations\n\nThe `cloudflare-d1` provider now runs a post-generation pass over every Drizzle migration directory (auth, features, webhooks, audit) before the compile finishes. Better Auth cleanup for retired managed tables is stripped from raw `DROP TABLE` statements. Drop-only cleanup migrations are reordered child-first when foreign-key dependencies require it. Every generated D1 migration directory is replayed against SQLite during compile, so a D1-breaking migration fails at compile time rather than at `wrangler d1 migrations apply`.\n\n---\n\n## v0.16.9 — May 13, 2026\n\n### Resource-scoped realtime tickets\n\n`providers.database.config.realtime` accepts an object form for projects whose WebSocket subscribers aren't org members:\n\n```ts\nrealtime: {\n wsTicket: {\n role: \"attendee\",\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n}\n```\n\nThe generated `/broadcast/v1/ws-ticket` route authenticates the caller, evaluates the declared relationship role against the request, and mints a short-lived WebSocket ticket scoped to the resolved resource. `realtime: true` continues to enable the org-scoped broadcaster.\n\n### Unified broadcast targeting\n\nThe realtime helper and Broadcaster now route by `scopeKey || organizationId || userId`. String targets remain shorthand for `organizationId`; explicit targets can scope a broadcast to a resource or a single user:\n\n```ts\nawait realtime.broadcast(\"event-page-updated\", payload, { scopeKey: \"events:evt_123\" });\nawait realtime.broadcast(\"dm\", payload, { userId: recipientId });\n```\n\nWebSocket tickets are Quickback-minted (signed with `BETTER_AUTH_SECRET`), not Better Auth tokens — Better Auth remains the front-door auth check; Quickback signs the upgrade ticket after authorization succeeds.\n\n---\n\n## v0.16.8 — May 13, 2026\n\n### One auth transport per request\n\nGenerated middleware treats `Cookie`, `Authorization: Bearer`, and `x-api-key` as distinct auth methods and rejects mixed requests with `400 AUTH_METHOD_CONFLICT`. Query-string API keys (`?api_key=` / `?key=`) are no longer accepted. Machine-to-machine auth is explicit; precedence rules between transports are gone.\n\n### Cookie-backed CSRF gate\n\nGenerated apps now block cross-site `POST` / `PUT` / `PATCH` / `DELETE` requests from cookie-relying callers. The middleware skips explicit `Authorization` clients, requires a trusted `Origin` or `Referer`, and blocks `Sec-Fetch-Site: cross-site`. This matters most for cross-subdomain session setups where `SameSite=None` is intentional.\n\n### First-class Wrangler observability\n\n`providers.runtime.config.observability` now supports nested `logs` / `traces` blocks for `headSamplingRate`, `destinations`, `persist`, and `logs.invocationLogs`, emitting matching `[observability]`, `[observability.logs]`, and `[observability.traces]` TOML.\n\n---\n\n## v0.16.7 — May 12, 2026\n\n### Bearer wins over cookie\n\nA request carrying both `Authorization` and a session `Cookie` resolves entirely from the bearer; the cookie is dropped before `getSession()` runs. All three Bearer flavors (API key, JWT, session-token) now behave consistently — no more silent cookie precedence on session-token bearers.\n\n### Bearer plugin defaults to `requireSignature: true`\n\nBetter Auth's `bearer` plugin defaults to unsigned tokens; Quickback now emits `bearer({ requireSignature: true })`. Tokens emitted in the CORS-exposed `set-auth-token` header are server-signed with `BETTER_AUTH_SECRET` and verified on every request. Projects that genuinely need unsigned bearers can override via `providers.auth.config.plugins.bearer`.\n\nSee [Authentication Security → Bearer Tokens and Cookie Precedence](/stack/auth/security#bearer-tokens-and-cookie-precedence).\n\n---\n\n## v0.16.5 — May 12, 2026\n\n### Flat write DSL\n\nResource write operations are now declared at the table level alongside `read`, replacing the nested `crud` block:\n\n```ts\ndefineTable(customers, {\n read: { ... },\n create: { access: { roles: [\"admin\"] } },\n update: { access: { roles: [\"admin\"] } },\n delete: { access: { roles: [\"admin\"] }, mode: \"soft\" },\n upsert: { access: { roles: [\"admin\"] } },\n guards: { ... },\n});\n```\n\n`crud` and top-level `put` still compile as deprecated compatibility aliases. Mixed usage on the same resource is rejected. `schema-registry.json` emits both shapes during the transition.\n\n### CMS placement for multi-table feature actions\n\nStandalone actions on multi-table features have an explicit placement model:\n\n- `cms.placement: \"feature\"` shows the action on every table toolbar in the feature\n- `cms.placement: \"tables\"` with `cms.tables` scopes it to specific tables\n- `cms.hidden: true` keeps it API-only\n\nFeature-root standalone actions are emitted under a new `featureActions` bucket in `schema-registry.json`. Ambiguous multi-table standalone actions without placement compile with a warning.\n\n### `openapi.types` accepts a string array\n\nOne compile can write the generated types file to multiple locations, keeping colocated SPA clients in sync:\n\n```ts\nopenapi: { types: ['api-types.gen.ts', 'apps/web/src/lib/api-types.gen.ts'] }\n```\n\n### Stable artifact ordering\n\nGenerated route files and `schema-registry.json` are emitted in a stable order across runs. Identical logical input produces identical artifacts.\n\n---\n\n## v0.16.4 — May 12, 2026\n\n### Drizzle snapshot integrity\n\nDrizzle metadata files (`<n>_snapshot.json`) are no longer stamped with a Quickback warning key. The warning is now journal-only. Projects whose snapshots were corrupted by an earlier release self-heal on the next compile — the stripped header is removed during staging and the rewritten snapshot is clean.\n\n### `account.auth.*` drives the server, not just the SPA\n\nThe Account UI's auth flags (`signup`, `password`, `passkey`, `emailOTP`, `emailVerification`) now configure the Better Auth server alongside the SPA bundle. A normalizer maps them into the server config:\n\n- `signup → emailAndPassword.disableSignUp` (inverted)\n- `password → emailAndPassword.enabled`\n- `emailVerification → emailAndPassword.requireEmailVerification`\n- `passkey` / `emailOTP` → plugin additions\n\nThe SPA's `VITE_ENABLE_*` flags are derived from the same canonicalized server config, so the bundle and the server cannot drift. Two new flags ride along: `VITE_ENABLE_API_KEYS` and `VITE_ENABLE_MAGIC_LINK`.\n\n**Breaking** for projects that implicitly relied on the SPA-only behaviour: `account.auth.signup: false` now actually disables `POST /auth/v1/sign-up/email` on the server. Set `providers.auth.config.emailAndPassword.disableSignUp: false` explicitly to keep server signup open while hiding the SPA screen.\n\n---\n\n## v0.16.3 — May 9, 2026\n\n### Standalone action mount order\n\nFeature-level standalone action routers now register before sibling CRUD routers when both mount at the exact same prefix. A literal path like `GET /api/v1/records/today-bundle` resolves to the standalone handler instead of falling through to `GET /:id` and treating `\"today-bundle\"` as a record ID.\n\n---\n\n## v0.16.1 — May 9, 2026\n\n### Cloudflare ASSETS canonicalization\n\nWorker SPA fallbacks now request `/<dir>/` instead of `/<dir>/index.html`. Cloudflare's static-assets binding rewrites `/index.html` requests as 307 redirects to the trailing-slash path under the default `html_handling=auto-trailing-slash`, which previously caused redirect loops in SPA fallback handlers. Affects CMS, Account, admin, and the multi-domain catchall.\n\n### `account.customLogin`\n\nSet `account: { customLogin: true }` to drop a project-branded sign-in page in front of the bundled SPA. Place the page at `quickback/public/account/login/index.html` (as a directory) and the existing public passthrough serves it. The route registers before the `/account/*` SPA catch-all so the static handler wins; everything else under `/account/` continues to route through the bundled SPA.\n\n### Project-level realtime defaults\n\n`providers.database.config.realtime: true` now treats every resource as realtime-enabled by default. Per-resource `realtime: { enabled: false }` still wins.\n\n### Compile-time validators\n\nTwo new compile-time errors over silent runtime failures:\n\n- `AUTHENTICATED` + org-scoped firewall is rejected. The combination silently returned empty lists to sign-in-only callers who lacked an active org; the validator names three valid resolutions (drop the org scope, use `USER`, or split the route).\n- `createRealtime` imports without `realtime: true` enabled in the config are rejected at compile.\n\n### Drizzle metadata hardening\n\nDrizzle journal files carry a \"do not edit\" header. The compiler warns when the journal entry count exceeds the snapshot file count (typically the trace of a hand-deleted snapshot).\n\n### Minor\n\n- `SYSADMIN` is now recognised by the standalone-action org gate's pseudo-role matcher.\n- Apex `/` and `/account/login` get fallback redirects to `auth.loginUrl` when neither bundled SPA is enabled.\n- Record-based action URLs are kebab-case to match the OpenAPI spec (e.g. `/api/v1/widgets/:id/send-invite`).\n\n---\n\n## v0.16.0 — May 9, 2026\n\n### Agent Auth Protocol\n\nQuickback ships a server implementation of the [Agent Auth Protocol](https://agentauthprotocol.com) via `@better-auth/agent-auth`. Enable with `auth.plugins.agentAuth: true` and the compiler emits the full agent-auth surface: discovery at `/.well-known/agent-configuration`, capability projection from the project's OpenAPI spec, a device-authorization approval page in the Account SPA at `/agents/approve`, and the four agent-auth tables added to the auth schema automatically.\n\n**OpenAPI capability projection runs by default.** Every operation with an `operationId` becomes an agent capability. Default `approvalStrength` map: `GET → \"session\"`, `POST/PUT/PATCH/DELETE → \"webauthn\"`. The proxy `onExecute` makes a self-fetch with a Better Auth JWT minted for the agent session, so the inner request hits the existing JWT fast-path and runs the full firewall + access + masking pipeline. Opt out of OpenAPI projection with `agentAuth: { fromOpenAPI: false }` and wire `capabilities` + `onExecute` by hand.\n\n### Bearer-only on `/mcp` and the agent-auth surface\n\n`/mcp` forwards only `Authorization: Bearer …` into the inner request. Cookie and `x-api-key` forwarding are removed. Three Bearer flavors land on the same header — Better Auth session token (via the `bearer` plugin), OAuth access token (via OAuth Provider), and agent JWT (via `@better-auth/agent-auth`).\n\n### Auth DSL gains first-class plugin entries\n\n`bearer`, `oauthProvider`, and `agentAuth` are now typed entries in both the array-form union and the `BetterAuthPlugins` interface, with their own options shapes (`OAuthProviderOptions`, `AgentAuthOptions`). Existing `as any` casts can come out.\n\nAuto-enable rule: turning on `agentAuth` force-adds `bearer` + `oauthProvider`. No useful agent-auth deployment ships without those two.\n\n### `queue-consumer.ts` gating\n\nThe queue consumer is emitted when any of the following are true: embeddings are configured, queue handlers exist under `services/queues/*`, or `additionalQueues` is declared. Previously the third case left projects with a wrangler binding pointing at a missing handler.\n\n---\n\n## v0.15.0 — May 7, 2026\n\n### Sysadmin tier for the CMS\n\nA new opt-in `cms: { sysadmin: true }` flag turns the CMS into a cross-tenant DB-admin tool gated by `user.role === 'sysadmin'`. Distinct from the Better Auth `'admin'` plugin role, so user-management powers and DB-admin powers stay decoupled. Off by default.\n\nWhen enabled, the compiler emits a `SYSADMIN` pseudo-role (a fifth marker alongside `PUBLIC` / `AUTHENTICATED` / `USER` / `ADMIN`), a firewall escape hatch that drops tenant scopes for sysadmins while preserving soft-delete, a true cross-tenant `/admin/v1/sysadmin/organizations` endpoint, and a relaxed cross-tenant guard for list routes.\n\nThe CMS SPA gains a two-mode design: org admins keep the existing membership-based switcher, sysadmins get an \"All organizations\" selector that pins tenants via `?organizationId=` on every API call.\n\n### Durable Object `[[migrations]]` order is preserved\n\nCloudflare's migration list is append-only. The compiler now reads your existing `wrangler.toml` (when present) and emits auto-generated DO `[[migrations]]` blocks in two phases: deployed entries first (preserving order), net-new entries appended last. Reordering DOs in the config array no longer reshuffles deployed migrations.\n\n### `quickback/public/` — static-asset passthrough\n\nAnything dropped under `quickback/public/` is copied verbatim into `src/apps/` on every compile and served by the wrangler `[assets]` binding. Use for favicons, `robots.txt`, OG images, `.well-known/` files, marketing PDFs — anything that needs to ride past the compiler as bytes.\n\n- Optional. Missing folder is a no-op.\n- Stale-cleaned. Files removed from `quickback/public/` disappear on the next compile.\n- Hidden entries (`.DS_Store`, dotfiles) are skipped.\n- Collisions with compiler-emitted manifest paths fail the compile loudly.\n\n### Minor\n\n- Standalone-action wrapper skips the org gate when the access tree references any pseudo-role.\n- Queue handler emit no longer drops the `queue` export when there are no embeddings.\n\n---\n\n## v0.14.7 — May 7, 2026\n\n### Codegen fixes for projects with non-`id` primary keys and DO-only features\n\nFour surgical fixes to the generated output:\n\n- Duplicate table imports in relationship-role routes are deduplicated.\n- `db` references in single-record and bulk action handlers now resolve correctly during pre-fetch.\n- PartyServer auth gates pass the in-scope `db` handle into firewall calls.\n- Durable-object-only features keep their `lib/` files in the output.\n\n### `emailOtp` + AWS SES is OTP-only\n\n`auth.emailOtp` with the AWS SES email provider no longer auto-wires the magic-link companion. Mail-client URL prefetching can burn the one-time code before the human sees it; the Account SPA's `/email-otp` route is the single canonical entry point. Projects that explicitly want the magic-link arm can wire `sendVerificationOTP` directly.\n\n---\n\n## v0.14.6 — May 7, 2026\n\n### MCP transport correctness\n\nFour fixes to the MCP-over-HTTP path:\n\n- `tools/call` URLs are no longer double-prefixed for action tools.\n- Auth middleware accepts API keys via `Authorization: Bearer` in addition to `x-api-key` and query parameters — the channel MCP clients use exclusively.\n- `auth.roleHierarchy` is expanded for runtime role checks across api-key, JWT, and session auth paths. A higher role inherits the privileges of every lower role.\n- Team-scoped firewall predicates degrade gracefully when no team is active (org scoping continues to apply; team scoping is optional).\n\n---\n\n## v0.14.5 — May 7, 2026\n\n### MCP environment threading\n\nThe generated MCP server's `tools/call` dispatch threads `env` and `executionCtx` into the inner request, so action tools that touch Cloudflare bindings (D1, KV, R2, Queues) no longer crash with `undefined` env access.\n\n---\n\n## v0.14.4 — May 7, 2026\n\n### `via:` firewall predicates pull required imports\n\nThe relationship-role generator emits `inArray` and `sql` imports when the firewall has any `via:` predicate, and `buildFirewallConditions` accepts `(ctx, db)` so the relationship subquery has a Drizzle client to evaluate against. Every CRUD and action call site passes `db` through automatically.\n\n---\n\n## v0.14.3 — May 7, 2026\n\n### Relationship-role table re-exports\n\nGenerated `<table>.resource.ts` files now re-export their Drizzle table binding. Cross-feature relationship subqueries that import the binding from the resource file (rather than the schema) resolve correctly.\n\n---\n\n## v0.14.2 — May 7, 2026\n\n### Historical DO `[[migrations]]` are preserved\n\nA new `bindings.durableObjectMigrations` config slot carries forward `deleted_classes`, `renamed_classes`, and `transferred_classes` lifecycle entries across recompiles. Cloudflare's migration list is append-only; entries declared here are emitted first in `wrangler.toml`, then auto-generated current-class entries follow:\n\n```ts\nbindings: {\n durableObjects: [{ name: 'NOTEPAD', className: 'Notepad', from: 'lib/Notepad' }],\n durableObjectMigrations: [\n { tag: 'qb-do-deleted-legacy-notes-2026-05-05', deletedClasses: ['LegacyNotes'] },\n ],\n}\n```\n\nAll four lifecycle shapes are supported. User-declared entries can override auto-emit by reusing the same tag.\n\n---\n\n## v0.14.1 — May 7, 2026\n\n### Bulk action variants in `openapi.json`\n\nRecord-based actions with `bulkVariant: true` are now emitted as sibling operations in the OpenAPI spec, with the documented `{ ids, input, failFast? }` request shape, 200/207/400 responses, and a separate `<Resource><Action>Bulk` `operationId` so typed-client codegen distinguishes single from bulk.\n\n### Cross-tenant \"my events\" patterns\n\nThe access docs now include a worked example for the cross-tenant aggregation pattern (e.g. `GET /my-events` returning resources across all tenants a caller is invited to). See [Access → Cross-tenant dashboards](/compiler/definitions/access#cross-tenant-my-events-dashboards-are-not-this).\n\n---\n\n## v0.14.0 — May 7, 2026\n\n### Relationship-based authorization\n\nRoles can now be bound to a domain-table membership (\"user is a confirmed guest of this event\") rather than an org membership or a pseudo-role. Declare the relationship once and reference it from `firewall:` or `access.roles:`:\n\n```ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n },\n },\n roles: {\n guest: { via: 'guestOf' },\n eventStaff: { or: [{ via: 'guestOf' }, { roles: ['admin', 'owner'] }] },\n },\n}\n\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' },\n],\nread: { access: { roles: ['admin', 'member', 'guest'] } },\ncreate: { access: { roles: ['admin', 'guest'] } },\nupdate: { access: { roles: ['admin'] } },\n```\n\nThe compiler emits an inline Drizzle subquery against the relationship table and AND-composes it as the outermost firewall clause. The relationship table's own firewall (tenant scope, soft-delete) is honored inside the subquery; cross-tenant grants are impossible because the resource's tenant filter sits outermost.\n\nSupported surfaces: row-level scoping via `firewall: [{ field, via }]`, role gates on writes and reads, view access. Masking and action access reject relationship-roles at compile time with pointers to the working pattern (gate the row at the firewall layer, gate the role at the access layer).\n\nCross-tenant aggregation dashboards aren't solved by relationship-roles — the tenant firewall remains the outermost AND. For that pattern, use a user-scoped firewall or function-form access on a dedicated route.\n\nSee [Firewall → Relationship-based scoping](/compiler/definitions/firewall#relationship-based-scoping-via) and [Access → Relationship-based authorization](/compiler/definitions/access#relationship-based-authorization).\n\n### Bulk variants on record-based actions\n\n`defineAction({ bulkVariant: true })` emits `POST /:resource/batch/{action}` alongside the per-record route. The bulk handler loops the same access + transition + execute pipeline over a `{ ids, input, failFast? }` body:\n\n```ts\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n bulkVariant: true,\n transition: { field: \"status\", via: \"nextStatus\", fromTo: { /* ... */ } },\n async execute({ db, record, input, whereTransition }) {\n // exact same body — runs once per id\n },\n});\n```\n\nPer-record outcomes return as 207 Multi-Status. `failFast: true` aborts on the first failure and wraps the loop in `db.transaction()` on tx-supporting providers; D1 fails fast without rollback. Max 100 IDs per request. Rejected on standalone actions and `unsafe` actions.\n\n### Aggregations on read views\n\nRead views can declare pre-computed metrics that surface alongside the row payload:\n\n```ts\nread: {\n views: {\n pipeline: {\n fields: [\"id\", \"jobId\", \"candidateId\", \"status\", \"appliedAt\"],\n aggregations: {\n totalApplications: { fn: \"count\" },\n byStatus: { fn: \"groupBy\", field: \"status\" },\n },\n },\n },\n}\n```\n\nAggregations run over the same firewalled, filtered set as the row query; pagination is intentionally ignored. Supported functions: `sum`, `avg`, `min`, `max`, `count`, `count_distinct`, `groupBy`. See [Views → Aggregations](/compiler/definitions/views#aggregations).\n\n---\n\n## v0.13.5 — May 6, 2026\n\n### Object-form `auth.plugins` config is honored\n\nThe documented `plugins: { oauthProvider: {...} }`, `plugins: { organization: { teams: { enabled: true } } }` shapes now flow through the compiler unchanged. Per-plugin options reach the generated `auth.ts` as written.\n\n### `roles: [\"PUBLIC\"]` allowed on writes and actions\n\n`PUBLIC` is the explicit, uppercase opt-in for unauthenticated access on every access node — reads, writes, views, and actions. The runtime trusts the marker; row-level safety comes from firewall, masking, and the action's own validation. `PUBLIC` actions continue to receive mandatory audit logging.\n\nCommon pattern: pair `roles: [\"PUBLIC\"]` with `firewall: { exception: true }` on the resource so the row predicate doesn't reject every unauthenticated caller.\n\n---\n\n## v0.12.0 — May 5, 2026\n\n### Per-room authorization for PartyServer\n\n`bindings.durableObjects[].access` declares a path-scoped gate that runs the declared resource's firewall and `read.access` pipeline before the WebSocket upgrade:\n\n```ts\ndurableObjects: [\n // Single-resource: roomId IS the chat row id.\n { name: 'Chat', className: 'Chat', from: 'lib/Chat',\n access: { resource: 'chats' } },\n\n // Multi-resource: regex dispatches kind → resource.\n { name: 'Notepad', className: 'Notepad', from: 'lib/Notepad',\n access: {\n roomId: { pattern: '^(day-note|interaction|record):([A-Za-z0-9_-]+)$', kindGroup: 1, idGroup: 2 },\n resources: {\n 'day-note': { resource: 'day-notes' },\n 'interaction': { resource: 'interactions' },\n 'record': { resource: 'records' },\n },\n } },\n\n // Anonymous lobbies / public pads: explicit opt-out.\n { name: 'PublicLobby', className: 'PublicLobby', from: 'lib/PublicLobby',\n access: 'public' },\n]\n```\n\nThe gate 401s unauthenticated callers, 403s when the firewall hides the row, 404s when the row is missing. Resource references are validated against feature names at compile time. See [PartyServer Rooms → Per-room authorization](/stack/realtime/partyserver-rooms#per-room-authorization-via-access-v012).\n\n---\n\n## v0.11.1 — May 5, 2026\n\n### PartyServer auto-mount is secure by default\n\nThe `/realtime/*` auto-mount now wraps `partyserverMiddleware` in an auth check. Unauthenticated upgrades return 401; the four auth mechanisms (session cookie, JWT bearer, `x-api-key` header, query parameter) all unlock connections. Per-room access remains the `Server` class's responsibility in `onConnect`.\n\n---\n\n## v0.11.0 — May 5, 2026\n\n### OAuth Provider (MCP-ready)\n\nQuickback can act as a standards-compliant OAuth 2.1 + OIDC authorization server via [`@better-auth/oauth-provider`](https://better-auth.com/docs/plugins/oauth-provider). Enable with `plugins: [\"oauthProvider\"]`. The compiler auto-includes Better Auth's `jwt` plugin and the Account SPA gains a `/consent` page for the standard authorization-code flow.\n\nThis replaces Better Auth's deprecated `mcp` plugin and gives every MCP client (Cursor, Claude Desktop, claude.ai connectors, custom tooling) RFC 7591 dynamic client registration plus the discovery documents they need to bootstrap. See [Auth Plugins → OAuth Provider](/stack/auth/plugins#oauth-provider-mcp-ready).\n\n### API keys via query parameter\n\nThe auth middleware now accepts API keys as `?api_key=…` or `?key=…` query parameters. The `x-api-key` header takes precedence when both are sent. Prefer the header whenever the client supports it — query parameters land in access logs and `Referer` headers.\n\n### PartyServer rooms + realtime URL split\n\nThe realtime URL space is reorganized so names match what each primitive does:\n\n- **`/realtime/v1/*` → `/broadcast/v1/*`** — the org-wide Broadcaster moves to its semantically accurate prefix.\n- **`/realtime/<binding>/<room-id>`** — new mount for [PartyServer](/stack/realtime/partyserver-rooms) rooms. Per-room Durable Objects with presence and lifecycle hooks. Auto-mounted whenever a project declares any in-worker DO.\n\n**Breaking** — recompile + redeploy required:\n\n- `REALTIME_URL` env var renamed to `BROADCAST_URL`.\n- SPA helpers `getRealtimeWsUrl()` / `getRealtimeTicketUrl()` renamed to `getBroadcastWsUrl()` / `getBroadcastTicketUrl()`.\n- `appConfig.routes.api.realtime` renamed to `appConfig.routes.api.broadcast`.\n\n`partyserver`, `partysocket`, and `hono-party` are pre-installed in the compiler image; collab projects compile without an extra `npm install` step.\n\n---\n\n## v0.10.20 — May 4, 2026\n\n### In-worker Durable Objects\n\n`bindings.durableObjects[].from` flips a DO binding into in-worker mode and emits the export, the `[[migrations]]` block, and the `CloudflareBindings` type all together:\n\n```ts\ndurableObjects: [{\n name: \"ITEM_STREAM\",\n className: \"ItemStream\",\n from: \"features/loops/lib/ItemStream\",\n}]\n```\n\nDO class files live under `quickback/lib/` or `quickback/features/<feature>/lib/` — both copy verbatim into the generated `src/` tree on every compile. `from` and `scriptName` are mutually exclusive; cross-worker DOs (`scriptName` set) skip the re-export and migration block.\n\n`migrationTag` (default `qb-do-${className}`) is stable across regenerations and must never be removed or renamed once deployed. `useSqlite` defaults to `true`. See [Bindings → Durable Objects](/compiler/config/bindings#durableobjects).\n\n---\n\n## v0.10.18 — May 2, 2026\n\n### `experimentalRemote` — share deployed D1 with `wrangler dev`\n\nPer-binding `experimental_remote = true` lets `wrangler dev` read/write deployed D1 for selected bindings:\n\n```ts\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n splitDatabases: true,\n experimentalRemote: { auth: true, features: false },\n }),\n}\n```\n\nUseful for \"share prod auth in dev, keep feature writes sandboxed.\" Off by default.\n\n### Google OAuth + signup ToS\n\nThe Account SPA wires Google OAuth end-to-end when configured under `auth.config.socialProviders.google.enabled`. The signup flow gains a Terms-of-Service checkbox gate (configurable via the Account SPA branding).\n\n### CLI compile auth gate\n\n`quickback compile` now requires authentication for cloud-compiler runs. Device-flow `?redirect=` parameters are standardized across the login + signup pages so a user clicking \"Create one\" no longer loses their return URL.\n\n---\n\n## v0.10.15–v0.10.17 — May 2, 2026\n\n### CSP auto-config\n\nWhen `security.csp` is set, the compiler widens directives additively based on the project's enabled features:\n\n| Trigger | Auto-added | Directive |\n|---|---|---|\n| `cms: true` OR `account: true` | `'unsafe-inline'`, `https://fonts.googleapis.com` | `styleSrc` |\n| `cms: true` OR `account: true` | `https://fonts.gstatic.com` | `fontSrc` |\n| `csp` set (always) | `@trustedOrigins` | `connectSrc` |\n| Bundled SPA enabled | SPA-baked API origin (`config.domain`, `quickback.{baseDomain}`, `cms.domain`, `account.domain`) | `connectSrc` |\n\nAnything you already wrote stays — auto-config never removes or overrides. Each applied addition is logged to stderr. Opt out with `security: { cspAutoConfig: false }`.\n\nMost projects can write the minimal:\n\n```ts\nsecurity: {\n csp: {\n defaultSrc: ['@self'],\n scriptSrc: ['@self'],\n objectSrc: ['@none'],\n upgradeInsecureRequests: true,\n },\n}\n```\n\n…and the compiler fills in font hosts, trusted origins, and SPA-baked URLs.\n\nWhen a target directive is missing, auto-config scaffolds it from `default-src` baseline rather than widening `default-src` itself — CSP3 fall-back semantics would otherwise leak the addition to every directive that falls back to `default-src`.\n\n---\n\n## v0.10.14 — May 1, 2026\n\n### `auth.jwt` config\n\nThe bearer-token JWT used by the auth fast-path is configurable. Tune `expiresIn` to bound the post-revocation replay window without affecting browser SPAs (which auto-refresh on every authed call):\n\n```ts\nauth: {\n jwt: {\n expiresIn: 30,\n issuer: 'my-api',\n audience: 'partner-svc',\n secretEnv: 'CUSTOM_JWT_SECRET',\n },\n}\n```\n\n### Admin MCP endpoints filtered\n\nBetter Auth admin endpoints (`/admin/list-users`, `/admin/ban-user`, etc.) now carry `x-access: { userRole: ['admin'] }` in the generated OpenAPI spec. The MCP `tools/list` access-filter drops them for non-admin callers.\n\n### Declarative `security` config\n\nEvery security response header (`Content-Security-Policy`, COOP, COEP, CORP, HSTS, `X-Frame-Options`, `Referrer-Policy`, `Permissions-Policy`) is configurable from `quickback.config.ts`. `@`-prefixed sentinels (`@self`, `@none`, `@unsafe-inline`, `@trustedOrigins`, etc.) replace awkward `\"'self'\"` quoting.\n\nThe compiler lints the resolved config for known footguns: `@unsafe-inline` in `script-src`, wildcard sources, missing `default-src`, HSTS preload-list misconfiguration.\n\n### HSTS skipped on localhost\n\nGenerated middleware skips `Strict-Transport-Security` when the request hostname is `localhost`, `127.0.0.1`, or `*.localhost`. Without this gate, `wrangler dev` would pin a developer's browser to HTTPS across every project on that machine.\n\n---\n\n## v0.10.13 — May 1, 2026\n\n### Clickjacking defence on every Worker\n\nEvery Worker emits `Content-Security-Policy: frame-ancestors 'self' <TRUSTED_ORIGINS…>` and `X-Frame-Options: SAMEORIGIN` on every response. The CSP allowlist is sourced from the same `TRUSTED_ORIGINS` constant that gates CORS.\n\n---\n\n## v0.10.11 — May 1, 2026\n\n### MCP `tools/list` is access-filtered\n\nEach MCP tool now carries sanitised access metadata. `tools/list` filters against the caller's `ctx`: unauthenticated callers see only `PUBLIC` tools, authenticated callers see only role-gated tools they pass.\n\n- Wildcard CORS removed from the MCP endpoint.\n- Unauthenticated `GET /mcp` no longer enumerates tool names.\n- Internal flavor text is removed; `annotations.destructiveHint` and `_unsafe` remain — those are the spec-correct signals for clients.\n\n`tools/call` continues to re-enter the Hono app and run every middleware (auth, firewall, access, guards, masking), so hiding a tool from list never weakens the underlying gate.\n\n---\n\n## v0.10.10 — April 29, 2026\n\n### Reserved keys in `access.record` are rejected\n\n`access.record` is a flat field map evaluated as implicit AND between entries — keys must be column names. The compiler now rejects reserved keys (`and`, `or`, `roles`, `userRole`) inside `record` with migration guidance pointing at the working pattern (top-level siblings with their own `record:` blocks).\n\n---\n\n## v0.10.8 — April 29, 2026\n\n### Audit logging on Postgres targets\n\n`audit_events` previously only existed on `cloudflare-d1`. The audit table now lives in a dedicated `audit` schema (`drizzle.pgSchema('audit')`) on Postgres targets. The `hasSecurityAudit` gate accepts D1 or any PG dialect; `auditDatabaseId` remains a D1-only requirement.\n\n### `auditDatabaseId` is a compile-time requirement\n\nProjects with unsafe or `PUBLIC` actions that previously produced a placeholder `database_id = \"local-audit\"` in production now fail at compile time with the exact `wrangler d1 create <project>-audit` command and the config key where the returned ID goes.\n\n### Action input → OpenAPI / MCP\n\n`defineAction({ input: z.object({...}) })` schemas flow into the OpenAPI `requestBody` and the MCP tool's `inputSchema.properties`. Simple `z.object` shapes are extracted at compile time; discriminated unions, refinements, recursive schemas, and bare-identifier references run through Zod's native `z.toJSONSchema()` for full-fidelity output.\n\n### OpenAPI fidelity\n\n- Response schemas emit `required[]` for every non-nullable column.\n- `text(_, { enum: [...] })` columns emit as closed `{ type: \"string\", enum: [...] }`.\n- `id` claims `format: \"uuid\"` only when the project's `generateId` actually produces UUIDs. cuid2 / prefixed / nanoid / serial generators emit plain `{ type: \"string\" }`.\n\n### Minor\n\n- Auto-mask predicate verifies the resolved owner column exists before emitting an `or: 'owner'` clause; falls back to roles-only with a warning otherwise.\n- Generated CRUD errors emit canonical `QuickbackErrorCode` enum values (`DB_NOT_NULL_VIOLATION`, `DB_UNIQUE_VIOLATION`, etc.) so generated SDKs can exhaustively switch on `code`. See [API errors](/compiler/targets/hono-api/using-the-api/errors#database).\n\n---\n\n## DSL: one file per action, multi-table per feature\n\n### One file per action\n\nAction authoring is one file per action under `<feature>/actions/<name>.ts`. The filename is the action name and the URL segment:\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: { applied: [\"screening\"], screening: [\"interview\"], interview: [\"offer\"] },\n },\n async execute({ db, record, input, auditFields, whereTransition }) { /* … */ },\n});\n```\n\n`defineAction` is imported from a generated per-feature helper at `<feature>/.quickback/define-action.ts` — `record`, `input`, and audit fields are typed without manual annotations.\n\n**Discovery rules:**\n- `actions/<name>.ts` binds to the feature's primary table.\n- `actions/<table>/<name>.ts` binds to the sibling table file.\n- Setting `path:` makes the action standalone (custom URL, no record fetch).\n- Tableless features require every action to be standalone.\n\n**Retired** (rejected at load time with migration guidance): `actions.ts` (bundled multi-action file), `_feature.ts`, `handlers/` directory + `handler:` string ref, `defineActions(table, {…})`, colocated `defineActions` inside table files, `standalone: true` flag, `*-actions.ts` / `*.actions.ts` filename patterns.\n\nSee [Actions docs](/compiler/definitions/actions).\n\n### Multi-table actions per feature\n\nOne feature directory can own actions on multiple tables. Three discovery modes:\n\n- **Colocated** (canonical) — `<table>.ts` containing both `defineTable` and `defineActions(<table>, …)`. One file per entity.\n- **`actions.ts`** — single primary-table actions file at feature root.\n- **`actions/<table>.ts`** — per-table action files for strict schema/behavior separation.\n\nPlus a universal `_feature.ts` slot for non-table-bound feature-level actions and shared Zod schemas.\n\nAction names are unique per `(bindTable, name)` pair. Sibling-bound `actions/episodes/publish.ts` and `actions/shows/publish.ts` mount at `/episodes/:id/publish` and `/shows/:id/publish` and compile cleanly.\n\n---\n\n## Firewall: named-scope shape\n\nThe named-scope firewall shape is a co-equal user-facing input alongside the predicate array:\n\n```typescript\nfirewall: { organization: { column: 'tenant_id' } } // named-scope (compact)\nfirewall: { owner: { column: 'account_user_id' } }\nfirewall: { exception: true }\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n] // predicate array (explicit)\n```\n\nPick the form that reads better — named-scope for the common one-line case, predicate array when you need custom `in`-lists or non-scope predicates.\n\n**Auto-detection synonyms.** When `firewall:` is omitted, the compiler scans the schema for an isolation column. The org-scope list accepts `organizationId`, `organisationId`, `orgId`, `organization`, `organisation`, `org` (American + British). User-scope accepts `userId`.\n\n**`ownerId` is a targeted error signal.** When a table carries `ownerId` but no isolation column and no explicit `firewall:`, the compiler raises a specific error — `ownerId` is business-logic ownership, not access control. Use `userId` for access control, declare an explicit `firewall:`, or add a separate isolation column.\n\n---\n\n## v0.10.0 — April 26, 2026\n\n### `q.scope()` — single-declaration tenant scoping\n\n`q.scope(kind)` replaces the three-place pattern (column declaration + firewall predicate + ownership-guard) with one column:\n\n```typescript\ncolumns: {\n organizationId: q.scope('organization'), // → ctx.activeOrgId\n ownerId: q.scope('owner'), // → ctx.userId\n teamId: q.scope('team'), // → ctx.activeTeamId\n}\n```\n\n`q.scope()` columns auto-derive the firewall predicate, register with the guards layer as `systemManaged` (client input rejected), and auto-populate from `ctx` on create / upsert. The systemManaged extension generalises beyond `q.scope()`: any firewall predicate whose `equals` references `ctx.*` registers its `field` automatically.\n\nSee [`q.scope()`](/compiler/definitions/schema#qscope--tenant-scope-columns).\n\n### `masking[col].query.roles` — unified filter / sort / search gate\n\nThe three legacy per-capability flags (`filterable`, `searchable`, `sortable`) are replaced by a single `query.roles` allowlist:\n\n```typescript\nmasking: {\n email: {\n type: 'email',\n show: { roles: ['admin'] },\n query: { roles: ['admin'] }, // defaults to show.roles when omitted\n },\n}\n```\n\nA view's own `query.{filterable,searchable,sortable}` allowlist is the opt-in for higher-privileged roles; the existing intersection validator gates it at compile time.\n\n**Breaking:** `masking[col].filterable / .searchable / .sortable` is rejected at compile time with a migration hint. Replace with `query.roles` (or delete the flags — `query` defaults to `show.roles`).\n\n---\n\n## v0.9.0 — April 25, 2026\n\n### Unified `read:` pipeline\n\nThe read side of every resource has its own block — `read:` — that owns the collection-level `GET /` endpoint, single-record `GET /:id`, and named view projections.\n\n**Breaking changes** (compile-time errors with migration hints):\n\n- `crud.list` → `read.access` (plus `read.pageSize` / `read.maxPageSize`)\n- `crud.get` → `read.access` (single-record GET inherits automatically)\n- Top-level `views: {...}` → `read.views: {...}`\n- `crud.list.fields` / `crud.get.fields` → declare a named view under `read.views` and call `/views/{name}`\n\n### Pre-record access ordering\n\nHandlers on `/:id` run a role-only access check before the firewall query. A caller without a matching role gets 403 before the database is touched. This closes the 404-vs-403 ID-probe channel — an unauthorized caller can no longer distinguish \"row exists in another tenant\" from \"row doesn't exist.\" See [Access evaluation order](/compiler/definitions/access#evaluation-order).\n\n### Transactional batch operations\n\nBatch endpoints expose `failFast` and a `meta.transactional` response field. On tx-supporting providers (postgres, supabase, neon, libsql, better-sqlite3, bun-sqlite), `failFast: true` wraps the per-record loop in `db.transaction(...)` so any failure rolls back the entire batch. On Cloudflare D1 (no `db.transaction`), `failFast: true` stops on the first error but prior writes stay committed.\n\nEmbedding queue messages and realtime broadcasts emit after the transaction commits — rolled-back batches produce no orphan jobs.\n\nSee [Batch Operations → Transactional semantics](/compiler/targets/hono-api/using-the-api/batch-operations#transactional-semantics).\n\n---\n\n## v0.8.7 — April 17, 2026\n\n### Hono CVE bump\n\nHono is bumped to `^4.12.14` across the monorepo, the compiler Docker image's pre-installed deps, and every generator path that emits Hono into compiled projects. Older ranges covered the vulnerable window. Recompile to pick up the fix in your generated project's `package.json`.\n\n### Cloudflare Email Sending in public beta\n\nQuickback defaults to the Workers `send_email` binding for Cloudflare deploys. Cloudflare Email Sending has graduated to public beta — production-ready with zero-config. AWS SES remains a fully supported opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes. See [Email Configuration](/compiler/config#email-configuration).\n\n### Dependency sweep\n\n`wrangler@^4.83.0`, `drizzle-orm@^0.45.2`, `drizzle-kit@^0.31.10`, `zod@^4.3.6`, `@cloudflare/workers-types@^4.20260417.1`.\n\n---\n\n## v0.8.5 — April 15, 2026\n\n### `userRole` access primitive\n\nA new `userRole?: string[]` field in the declarative `Access` config evaluates against `ctx.userRole` (the Better Auth admin-plugin `user.role` column). Distinct from `roles`, which matches `ctx.roles` (org membership).\n\n```typescript\n// Org owner OR platform admin\naccess: { or: [{ roles: ['owner'] }, { userRole: ['admin'] }] }\n\n// Platform admins see SSNs across every org\nmasking: { ssn: { type: 'ssn', show: { userRole: ['admin'] } } }\n```\n\n`userRole` works everywhere `Access` is accepted — CRUD, actions, views, masking, and inside `or` / `and` combinators. See [Access → userRole vs roles](/compiler/definitions/access#userrole-vs-roles).\n\n### CMS admin gate enforced server-side\n\n`cms: { access: \"admin\" }` previously only hid the CMS link in Account UI and rendered an \"Access Denied\" screen inside the SPA. Server-side enforcement now applies at every CMS-facing surface: the SPA shell, `/api/v1/schema`, and `custom_view` CRUD.\n\n### Better Auth 1.5 + `@cloudflare/workers-types` compatibility\n\nGenerated API code typechecks against the new versions. The org-member role-change broadcast hook is emitted via `organizationHooks.afterUpdateMemberRole` (the supported shape after the 1.5 deprecation of `databaseHooks.member.update.after`). `REALTIME_URL` and `ACCESS_TOKEN` are always emitted as optional bindings when the organization plugin is active.\n\n---\n\n## v0.8.4 — April 14, 2026\n\n### `generateId: \"short\"` strategy\n\nA compact ID option for tables where short, shareable codes matter more than collision resistance at scale:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", { generateId: \"short\" }),\n}\n```\n\nGenerates 6-character alphanumeric IDs (e.g. `a3F9xK`) using nanoid's `customAlphabet` with the full 62-char alphabet (`0-9A-Za-z`). Requires the `nanoid` package.\n\n**When to use:** room codes, invite links, share URLs, ephemeral records.\n\n**When not to use:** high-volume tables. 62^6 ≈ 56.8B combinations means ~238K rows before a 50% collision probability. For large tables stick with `\"uuid\"`, `\"cuid\"`, or `\"prefixed\"`. See [Providers → ID Generation Options](/compiler/config/providers#id-generation-options).\n\n---\n\n## v0.8.2 — April 11, 2026\n\n### Catch-all `VITE_QUICKBACK_URL`\n\nA single Quickback origin can be set in place of four separate URL env vars:\n\n```bash\nVITE_QUICKBACK_URL=https://secure.example.com\n```\n\n| Individual var (explicit) | Fallback when unset |\n|---|---|\n| `VITE_QUICKBACK_API_URL` | `${VITE_QUICKBACK_URL}` |\n| `VITE_QUICKBACK_ACCOUNT_URL` | `${VITE_QUICKBACK_URL}/account` |\n| `VITE_QUICKBACK_CMS_URL` | `${VITE_QUICKBACK_URL}/cms` |\n\n`VITE_QUICKBACK_APP_URL` stays independent — it points at the tenant's own frontend. Non-breaking; individual vars take precedence when set. Library users can set `__QUICKBACK_URL__` on `globalThis`. See [Environment Variables](/stack/account-ui/environment-variables).\n\n---\n\n## v0.8.1 — April 9, 2026\n\n### Role hierarchy with `+` suffix\n\nDefine a hierarchy and use `+` to mean \"this role and above\":\n\n```typescript\nauth: { roleHierarchy: ['member', 'admin', 'owner'] }\n\ncrud: {\n list: { access: { roles: [\"member+\"] } }, // member, admin, owner\n create: { access: { roles: [\"admin+\"] } }, // admin, owner\n delete: { access: { roles: [\"owner\"] } }, // owner only\n}\n```\n\nRoles are expanded at compile time. No `+` = exact match. See [Access → Role Hierarchy](/compiler/definitions/access#role-hierarchy).\n\n---\n\n## v0.8.0 — April 9, 2026\n\n### Breaking: VITE URL environment variables namespaced\n\nAll Quickback-generated URL environment variables are namespaced under `VITE_QUICKBACK_*` to avoid collisions with other Vite projects.\n\n| Old | New |\n|-----|-----|\n| `VITE_API_URL` | `VITE_QUICKBACK_API_URL` |\n| `VITE_ACCOUNT_URL` | `VITE_QUICKBACK_ACCOUNT_URL` |\n| `VITE_APP_URL` | `VITE_QUICKBACK_APP_URL` |\n| `VITE_CMS_URL` | `VITE_QUICKBACK_CMS_URL` |\n\nNon-URL variables are unchanged (`VITE_ENABLE_*`, branding vars, `VITE_STRIPE_PUBLISHABLE_KEY`).\n\n**Action required:**\n- Compiled projects: re-run `quickback compile`.\n- Standalone deploys: update `.env`, `.env.production`, and `wrangler.toml` files manually.\n- Library users: `__QUICKBACK_API_URL__` / `__QUICKBACK_APP_URL__` globals are unchanged.\n\n### CMS access control\n\n`cms.access: \"admin\"` enforces access at the CMS level, not just link visibility. Non-admin users (`user.role !== \"admin\"`) see an \"Access Denied\" screen with a sign-out button.\n\n---\n\n## v0.5.11 — February 24, 2026\n\n### Mandatory unsafe action audit trail\n\nStructured `unsafe` config (`unsafe: { reason, adminOnly, crossTenant, targetScope }`). Cross-tenant unsafe actions require Better Auth authentication plus platform admin role (`ctx.userRole === \"admin\"`). Mandatory audit logging on success, denial, and error paths. Cloudflare output includes `AUDIT_DB` wiring, `drizzle.audit.config.ts`, and `db:migrate:audit:*` scripts when unsafe actions are present.\n\nCompile-time raw SQL guard for actions and handlers (`allowRawSql: true` required per action).\n\n### Security contract report artifacts\n\nGenerated security contract artifacts: `reports/security-contracts.report.json`, `reports/security-contracts.report.sig.json`. Config-driven signing controls (`compiler.securityContracts.report.signature.*`). Missing required signing keys fail loudly with explicit remediation.\n\n### Headless Drizzle rename hints\n\n`compiler.migrations.renames` configuration for CI/CD environments where Drizzle's interactive rename prompts block compilation. See [Configuration](/compiler/config).\n\n### Minor\n\n- Email OTP magic links work correctly.\n- Auth is required for all API routes when running locally.\n- Single-file multi-table exports alongside `defineTable()` produce a clear error.\n\n---\n\n## v0.5.8 — February 14, 2026\n\n### Quickback CMS\n\nA schema-driven admin panel that connects to your generated API. The compiler now outputs a JSON schema registry consumed by the CMS at runtime. Firewall error modes (`reveal` for 403 with details, `hide` for opaque 404) are configurable per resource for security-sensitive deployments.\n\n---\n\n## v0.5.7 — February 12, 2026\n\n### Scoped database for actions\n\nActions receive a security-scoped database instead of a raw Drizzle instance. The compiler generates a proxy wrapper that automatically enforces org isolation, owner filtering, and soft-delete visibility — the same protections that CRUD routes have always had.\n\nDuck-typed column detection at runtime:\n\n| Column Detected | SELECT / UPDATE / DELETE | INSERT |\n|---|---|---|\n| `organizationId` | Adds `WHERE organizationId = ?` | Auto-injects `organizationId` from context |\n| `ownerId` | Adds `WHERE ownerId = ?` | Auto-injects `ownerId` from context |\n| `deletedAt` | Adds `WHERE deletedAt IS NULL` | — |\n\nEvery action is secure by default — no manual `WHERE` clauses needed.\n\nActions that intentionally need to bypass security (admin reports, cross-org queries, migrations) can declare `unsafe: true` to receive a raw, unscoped database handle via `rawDb`:\n\n```typescript\ndefineActions(analytics, {\n globalReport: {\n unsafe: true,\n execute: async ({ db, rawDb, ctx, input }) => {\n // db → still scoped (safety net)\n // rawDb → bypasses all security filters\n const allOrgs = await rawDb.select().from(organizations);\n },\n },\n});\n```\n\nWithout `unsafe: true`, `rawDb` is `undefined`. See [Actions](/compiler/definitions/actions).\n\n### Cascading soft delete\n\nSoft-deleting a parent record automatically cascades to child and junction tables within the same feature. The compiler detects foreign key references at build time and generates cascade `UPDATE` statements.\n\nRules:\n- Applies to soft delete only. Hard delete relies on database-level `ON DELETE CASCADE`.\n- Cascades within the same feature only — cross-feature references are not affected.\n- Child tables must have `deletedAt` / `deletedBy` columns (auto-added by the compiler).\n\nSee [Actions API → Cascading Soft Delete](/compiler/targets/hono-api/using-the-api/actions-api#cascading-soft-delete).\n\n### Advanced query parameters\n\nNew capabilities for all list endpoints:\n\n- **Field selection** — `?fields=id,name,status`\n- **Multi-sort** — `?sort=status:asc,createdAt:desc`\n- **Total count** — `?count=true` returns total matching records in `X-Total-Count`\n- **Full-text search** — `?search=keyword` searches across all text columns\n\nSee [Query Parameters](/compiler/targets/hono-api/using-the-api/query-params).\n\n---\n\n## v0.5.5 — February 5, 2026\n\n### OpenAPI spec generation\n\nGenerated APIs include a full OpenAPI specification at `/openapi.json`. Better Auth endpoints are included in the spec.\n\n### Better Auth plugins\n\nPublished `@quickback-dev/better-auth-upgrade-anonymous` (post-passkey email collection flow), `@quickback-dev/better-auth-combo-auth` (combined email + password + OTP), and `@quickback-dev/better-auth-aws-ses` (AWS SES email provider).\n\n### Security headers\n\nGlobal error handler prevents leaking internal error details. Security headers middleware (CSP, HSTS, X-Frame-Options, X-Content-Type-Options). `BETTER_AUTH_SECRET` properly passed to generated config.\n\n---\n\n## v0.5.4 — January 30, 2026\n\n### Account UI\n\nPre-built authentication UI deployed as Cloudflare Workers. Sessions, organizations, passkeys, passwordless, admin panel, API keys. Dual-mode: standalone (degit template) or embedded with Quickback projects.\n\n### Webhook system\n\nInbound webhook endpoints with signature verification. Outbound webhooks via Cloudflare Queues with automatic retries. Configurable per-feature webhook events.\n\n### Realtime & vector search\n\nDurable Objects + WebSocket realtime subscriptions. Vector embeddings via Cloudflare Vectorize. KV and R2 storage integrations.\n\n---\n\n## v0.5.0 — January 2026\n\n### Initial release\n\n- **Quickback Compiler** — TypeScript-first backend compiler.\n- **Four security pillars** — Firewall, Access, Guards, Masking.\n- **`defineTable()`** — schema + security configuration in a single file.\n- **Templates** — Cloudflare Workers, B2B SaaS.\n- **Cloud compiler** — remote compilation via `compiler.quickback.dev`.\n- **CLI** — `quickback create`, `quickback compile`.\n- **Better Auth integration** — organizations, roles, sessions.\n- **Drizzle ORM** — schema-first with automatic migrations.\n- **Cloudflare D1** — split database support (auth + features)."
6
+ "content": "## v0.47.0 — June 11, 2026\n\n### Breaking: zero-false-positive analyzer checks are now compile errors\n\nThe authz/authn analyzer (v0.37) shipped warn-only. After a release cycle of\ndata, the checks whose every trip is a definite misconfiguration — never a\nlegitimate config — are **promoted to compile errors**. Warnings nobody is\nforced to read are documentation; the pillar guarantees are now enforced.\n\n**Breaking** — a config that previously compiled with one of these warnings\nnow fails the compile:\n\n- `AUTHZ_EMPTY_PERMISSION` — a permission that is structurally unsatisfiable\n (`allOf(a, not(a))`: a fact AND its exact negation at the same AND-level).\n- `AUTHZ_CAPABILITY_CEILING` — a resource's firewall grants a\n `scope:<kind>:<role>` role access beyond its capability profile (or the\n role has no profile at all). This is the M0.2 pillar guarantee — it was\n authored as an error all along and is now enforced.\n- `AUTHN_ROUTE_COVERAGE`, `AUTHN_SURFACE_INVARIANT`,\n `AUTHN_SECRET_CONSISTENCY`, `AUTHN_CREDENTIAL_DELIVERY`,\n `AUTHN_CLAIM_PROVENANCE` — the structural-authn set (route auth coverage,\n bearer-only `/mcp`/agent surfaces + INTERNAL unreachability, mint↔verify\n key/issuer/audience pairing, anchored credential delivery, verifier-only\n identity claims). These still run against empty route/credential metadata\n on a real compile (no-ops until the generators emit it), but the severity\n contract is locked in now — they fail the build the moment they can fire.\n\nThe heuristic/advisory checks are unchanged: `AUTHZ_SHADOWED_ARM`,\n`AUTHZ_UNREACHABLE_ROLE`, `AUTHZ_UNREACHABLE_VIEW`, and\n`AUTHZ_NOT_OVER_RESOURCE` stay warnings; `AUTHZ_PUSHDOWN_COST` stays an info\nreport. `QUICKBACK_AUTHZ_STRICT=true` still promotes those warnings too.\n\n**The override escape hatch** — every promoted finding can be explicitly\naccepted, per finding, with a required reason:\n\n```ts\nauthz: {\n analyzer: {\n allow: [\n {\n check: 'AUTHZ_CAPABILITY_CEILING',\n target: 'sessions/scope:event:organizer', // from the rendered finding\n reason: 'organizer grant profile lands with the v2 rollout (TICKET-123)',\n },\n ],\n },\n}\n```\n\nAn override downgrades that exact `(check, target)` finding back to a warning\nthat cites the reason — even under strict mode (it's an explicit, reasoned\nacceptance). Every rendered error prints its exact override recipe. Guard\nrails: `check` must be one of the promoted ids (unknown or keep-warn ids are\nrejected at config validation), `reason` is required, and an `allow` entry\nthat matches no current finding is itself a compile error — no dead\noverrides accumulating after the underlying issue is fixed.\n\nAnalyzer-internal defects are still fail-open: a bug in the analyzer itself\ndowngrades to a single warning and the compile continues. Only real findings\nfail builds.\n\n### CLI: live views now compile through the CLI\n\n`defineView` files under `quickback/services/views/` were never loaded by\nthe CLI — the compile payload simply omitted them, so\n[live views](/stack/realtime/live-views) (v0.35) only worked when driving\nthe compiler API directly. The CLI now discovers and ships them like every\nother service definition, and the compile summary counts them\n(`Loaded services: … 1 live view(s)`). If you declared views and wondered\nwhy no surface ever went live: upgrade the CLI and recompile.\n\n### CLI: deterministic compile output across machines\n\nFeature and service discovery used raw `readdir` order, which differs\nbetween macOS and Linux — route registration order, schema re-exports,\nOpenAPI paths, and the Neon RLS document's content hash could all churn when\nthe same project was recompiled on a different machine. All discovery sites\nnow sort by codepoint, so the same input compiles to the same bytes\neverywhere. Expect a one-time diff on the first recompile if your previous\noutput was generated in a different filesystem order.\n\n### Fixes\n\n- Read-only resources (no `crud` block) generated routes importing a\n `CRUD_ACCESS` symbol their resource file never exported — a tsc/bundle\n break. The export is now unconditional.\n- The `blog` starter template gated writes on the removed `ADMIN`\n pseudo-role, which hard-fails current compiles; it now uses the\n org-membership `admin` role.\n- `reports/operations.manifest.json` and `reports/conformance.manifest.json`\n now also cover the realtime (`/broadcast/v1`), storage (`/storage/v1`),\n and FGA (`/fga/v1`) surfaces.\n- The dead free/pro tier plumbing is gone: no Tier row in\n `quickback whoami`, no upsell copy at login. Compiling complete projects\n requires login, exactly as before — there was never a paid gate behind it.\n- The CLI is published to npm via trusted publishing (GitHub OIDC) — signed\n provenance, no long-lived npm token in the pipeline.\n\n## v0.46.0 — June 11, 2026\n\n### Breaking: \"no organization context\" responses unified on HTTP 403\n\nGenerated APIs used to answer the same semantic condition — *the caller has no\nactive organization context* — with two different statuses: `400 ORG_REQUIRED`\nfrom the collection list guard and the create/PUT/batch org validation, but\n`403 ACCESS_NO_ORG` from standalone actions and `403\nACCESS_TENANT_SCOPE_REQUIRED` from unsafe org-scoped actions. Clients and SDKs\nhad to special-case the split.\n\n**Breaking** — recompile + redeploy required; every \"no org context\" denial is\nnow **403**:\n\n- `GET /api/v1/<resource>` (and views) without an active org or\n `?organizationId=` → `403 ORG_REQUIRED` (was 400).\n- `POST /`, `PUT /:id`, `POST /batch`, `PUT /batch` without an active org →\n `403 ORG_REQUIRED` (was 400).\n- Standalone actions (`403 ACCESS_NO_ORG`) and unsafe org-scoped actions\n (`403 ACCESS_TENANT_SCOPE_REQUIRED`) were already 403 and are unchanged.\n\nError **codes are unchanged** — `ORG_REQUIRED`, `ACCESS_NO_ORG`, and\n`ACCESS_TENANT_SCOPE_REQUIRED` keep their identities, so clients that\ndiscriminate on `code` need no changes. Only clients that branch on the raw\n`400` status for these responses must update to `403`.\n\n### Breaking: root-mounted actions lose their nested alias URLs\n\nA standalone action whose declared `path:` lives outside its feature prefix\n(e.g. `path: \"/reports/orders\"` in the `orders` feature) mounts at the root:\n`/api/v1/reports/orders`. That root URL is the one the OpenAPI spec, the MCP\nsurface, and the operations manifest have always advertised — but the\ngenerated per-feature routes file *also* carried an undocumented, fully-gated\ncopy at the nested `/api/v1/<feature><path>` URL (e.g.\n`/api/v1/orders/reports/orders`).\n\n**Breaking** — the nested alias is no longer emitted. One URL per operation:\na root-mounted action exists only at its advertised `/api/v1<path>` mount.\nAnything calling the unadvertised nested URL gets a 404 after recompile +\nredeploy; switch to the documented root URL. Actions declared *under* the\nfeature prefix are untouched, and a feature whose standalone actions are all\nroot-mounted no longer emits an (empty) feature actions routes file.\n\n### Behavior change: `PUBLIC` inside `or:` arms admits anonymous callers\n\n[Access](/compiler/definitions/access) has always documented `PUBLIC` as\nworking on every access node, but the emitted auth gate only honored it in a\nflat `roles: [...]` list. A tree like\n\n```ts\naccess: {\n or: [\n { roles: [\"PUBLIC\"] },\n { roles: [\"admin\"] },\n ],\n}\n```\n\nstill answered anonymous callers with `401`. The auth gate is now tree-aware\nand matches the documented semantics: a `PUBLIC` `or:` arm admits anonymous\ncallers past the authentication gate (an `and:` group admits them only when\n*every* arm does), and the access / org / firewall layers still evaluate the\nfull tree. One shared predicate now drives the emitted gates, the OpenAPI\n`security` blocks, and view routes (which gate per view on the\nview-effective access).\n\n**Worth a loud note:** if you have a nested `PUBLIC` arm that was silently\n401-ing, that endpoint becomes anonymously reachable after recompile —\nexactly what the config declares, but verify it's what you meant. `PUBLIC`\naudit logging applies to the newly-admitted routes as usual.\n\n### Realtime broadcasts now enforce `requiredRoles` and masking\n\nA table's declared realtime gates weren't being applied to the generated\nCRUD broadcasts: `realtime: { requiredRoles: [...] }` and column masking were\nhonored on the HTTP surface but not on the WebSocket fanout. The docs\npromised per-role, masked realtime delivery; the generated broadcasts now\nmatch it. **Recompile and redeploy** any project using realtime on\nrole-gated or masked tables.\n\nGenerated `realtime.insert / update / delete` calls now carry:\n\n- **`targetRoles`** — the table's `realtime.requiredRoles` (post role-\n hierarchy `+` expansion), enforced per subscriber at fanout.\n- **`maskingConfig`** — serialized from the same effective masking\n (declared + auto-detected sensitive columns) the HTTP mask functions are\n generated from. What HTTP masks is what the WebSocket wire masks.\n\nLive-view `view_changes` deltas honor the same table-level `requiredRoles`\nat fanout, so a role-gated table can't leak through a\n[live view](/stack/realtime/live-views) subscription either.\n\nNotes:\n\n- Recompile suffices — no config change needed.\n- If you worked around this with hand-written `realtime.*` calls passing\n `targetRoles` / `maskingConfig`, those workaround broadcasts can be\n removed.\n- `type: 'custom'` mask functions can't ride the wire — the Broadcaster\n fails closed and broadcasts `[REDACTED]` for those columns.\n- Tables without `requiredRoles` or masking are byte-identical: the open\n broadcast default is unchanged.\n\n### Batch operations inherit the base operation's access\n\nWhen a batch operation was declared without its own `access`, it didn't pick\nup the base operation's role requirement:\n\n```ts\ncrud: {\n update: { access: { roles: [\"admin\"] } },\n batchUpdate: { maxBatchSize: 25 }, // ← no access of its own\n}\n```\n\nA batch config declared without `access` now inherits the base operation's\naccess at compile time — fail closed, so runtime, the OpenAPI spec, and the\ngenerated code all agree. Explicit batch `access` still wins (including\nper-side on upserts); a base op without access still yields an\nauthenticated-only batch op. The flat `update: { batch: true }` shape and\nauto-promoted batch ops were never affected. **Recompile and redeploy** if\nyou use the explicit-batch shape without per-batch access.\n\n### Record actions, PUT upserts, and legacy firewall arms fail closed\n\nThree fail-closed hardening fixes, found and verified against the new\nconformance catalog (route × principal expectations derived from the\ncompiler's own IR — see the\n[conformance manifest](/compiler/targets/hono-api/using-the-api/openapi#operations-manifest)).\nAll apply on recompile + redeploy; no config change needed:\n\n- **Record actions evaluate the role gate before fetching the record**, so\n the denial response no longer varies with record state — a uniform\n `403 ACCESS_ROLE_REQUIRED`. (Bulk actions already had this order; unsafe\n actions write their audit row on the pre-record denial.)\n- **PUT upsert treats an out-of-scope id as a firewall miss** (`403` reveal /\n `404` hide, per your firewall error mode; a standard 207 miss entry on\n `PUT /batch`) instead of routing it into the create path. Genuinely new\n ids keep the create path.\n- **Legacy (array-form) firewall arms deny cleanly when a bound context\n claim is absent at runtime** (e.g. no active org), rather than surfacing a\n database error — the same deny-when-absent behavior the explicit `all:` /\n `any:` group forms already had.\n\n### Root-mounted standalone actions use the standard gate stack\n\nStandalone actions mounted outside their feature prefix\n(`path: \"/reports/orders\"`) were emitted through a separate code path that\ndid not apply the full access / audit / scoped-database treatment that\nin-feature standalone actions receive. They now render through the same\ngenerator, so the same access checks, security-audit writes, and\ntenant-scoped database wrapping apply everywhere. If you use root-mounted\nstandalone actions, recompile and redeploy. (Unifying the two code paths is\nalso what surfaced the two breaking changes above.)\n\n### Namespace routing fixes\n\n- An action whose declared `path` exactly equals its namespace prefix is now\n claimed by the namespace like any nested action (Hono's `/x/*` mount\n already matched the bare `/x`) — it's served through the namespace's gate\n instead of carrying a second inline copy of the resolver.\n- A namespace with zero claimed standalone actions (e.g. record-based-only)\n no longer mounts its middleware at all — a dead gate can no longer\n intercept requests under its prefix.\n\n### Custom org roles work with Better Auth member management\n\nCustom roles referenced in access trees (e.g. `roles: [\"support\"]`) are now\nauto-registered with the Better Auth organization plugin. They were already\nenforceable on routes but unprovisionable through Better Auth —\n`invite-member` / `update-member-role` rejected them with\n`400 ROLE_NOT_FOUND`, so there was no supported way to actually give a\nmember the role. Auto-registered roles carry member-equivalent permissions\n(this is about assignability; your access trees remain the authorization\nmodel). If you pass your own `roles` / `ac` to the organization plugin\noptions, those win and auto-registration is skipped. Built-in, pseudo, and\n`scope:` roles are excluded; projects with no custom roles emit\nbyte-identical output.\n\n### snake_case tables: dropped record actions and broken helpers fixed\n\nTwo fixes for tables declared with snake_case names (`event_notes`):\n\n- The generated `.quickback/define-action.ts` helpers imported the camelCase\n identifier while the generated alias file exports the verbatim declared\n name (`export { event_notes }`) — a TS2724 compile failure for any\n snake_case table with action files. The helpers now import the real export\n aliased to the camelCase local.\n- Record actions on a snake-declared table living in a kebab-named feature\n file (`event-notes/actions/pin.ts`) were not emitted — missing from both\n the generated routes and OpenAPI. They now emit and document consistently.\n\nIf you have snake_case tables with record actions, recompiling **adds routes\nthat previously didn't exist** — review the new surface.\n\n### First-class MCP OAuth config: `auth.oauth`\n\nThe OAuth 2.1 surface behind `agents.mcp.requireAuth` (v0.42.0) gains a\nfirst-class config block — env-resolvable issuer / login / consent URLs,\nscopes, RFC 8707 audiences, and a dynamic-client-registration toggle:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n oauth: {\n enabled: true,\n issuerUrl: { env: \"OAUTH_ISSUER_URL\", fallback: \"http://localhost:8787/auth/v1\" },\n loginPage: { env: \"OAUTH_LOGIN_URL\", fallback: \"http://localhost:8787/account/login\" },\n consentPage: { env: \"OAUTH_CONSENT_URL\", fallback: \"http://localhost:8787/account/consent\" },\n scopes: [\"openid\", \"profile\", \"email\", \"offline_access\"],\n audiences: [{ env: \"OAUTH_MCP_AUDIENCE\", fallback: \"http://localhost:8787/mcp\" }],\n allowDynamicClientRegistration: true,\n },\n}),\n```\n\nSetting it auto-enables the `oauthProvider`, `jwt`, and `bearer` plugins,\nemits the RFC 8414 / RFC 9728 discovery documents, and accepts the\nprovider's JWKS-signed access tokens in the standard auth middleware. A new\nproject hook, `quickback/hooks/resolve-oauth-context.ts`, lets you derive\ntenant fields (`activeOrgId` / `activeTeamId` / roles) from the validated\nOAuth identity. On Neon, the auth schema is now owned by the Better Auth CLI\nend to end (the compiler no longer emits its placeholder `src/auth/schema.ts`\nor `src/lib/neon.ts`). See\n[OAuth Provider (MCP-ready)](/stack/auth/plugins#oauth-provider-mcp-ready)\nand [Auth Hooks](/stack/account-ui/hooks#oauth-context-resolver).\n\n### Neon RLS covers force-enabled plugin tables\n\nOn Neon, row-level-security policies are generated for the Better Auth\ntables. The list of tables receiving policies was derived from your declared\nauth config and didn't account for plugins the compiler force-enables\nautomatically — so some auth-owned tables could be created without RLS\npolicies. The list now derives from the fully resolved plugin set, so every\ngenerated auth table receives appropriate policies (self-scoped where there\nis a clear owner, service-role-only otherwise — fail closed). The RLS\nmigration is content-addressed, so the update arrives as a new journaled\nentry on the next recompile + `db:migrate`. **Neon projects should recompile\nand run `db:migrate`.**\n\n### New compile reports: operations + conformance manifests\n\nEvery compile now writes two machine-readable reports next to\n`openapi.json`:\n\n- **`reports/operations.manifest.json`** — a stable, sorted index of every\n operation: `{ operationId, method, path, auth, feature, kind }`, covering\n the resource, action, view, auth, realtime, storage, and FGA surfaces. An\n extend-only public contract — the recommended integration point for\n scripting against the generated surface.\n- **`reports/conformance.manifest.json`** — for each route × principal\n class, the expected outcome (allow / 401 / 403 / cross-tenant miss …),\n derived from the same IR the emitters consume. This is the artifact the\n conformance fixes above were found and verified against.\n\nThe OpenAPI generator itself now reads the same IR as the route emitters, so\nthe spec follows the emitted surface by construction — including four\naccuracy fixes: `PUT /{id}` is documented only when actually enabled, the\nbatch surface documents the emitter's auto-promotion + access inheritance,\nand views document their effective (view-level, falling back to read-level)\naccess. See\n[Operations manifest](/compiler/targets/hono-api/using-the-api/openapi#operations-manifest).\n\n## v0.45.0 — June 9, 2026\n\n### `auth.jwt.revocationCheck: 'kv'` — sub-TTL JWT revocation\n\nThe JWT fast-path trusts signed claims for their full lifetime — that's what\nmakes it a fast-path. Until now the only revocation bounds were the TTL\n(plain claims) and the carry-forward cap (scope claims, v0.44.0). The\nlong-promised `'kv'` mode is now real on the **Cloudflare runtime**:\n\n```ts\nauth: { jwt: { revocationCheck: 'kv' } }\n```\n\n- **Per-principal revocation timestamps, not per-token denylists.** A\n revocation event writes \"everything for this principal minted before now is\n dead\" to the project's **existing `KV` binding** (keys prefixed `qbrev:`) —\n nothing extra to provision. Entries self-expire after the maximum token\n lifetime, so the store never accumulates.\n- **The bearer fast-path checks before trusting.** A verified token whose\n `iat` (or `sct`, for the relationship-scope claim) predates the stored\n timestamp is rejected and falls through to session auth, which re-checks\n membership and re-mints — an active legitimate session recovers\n transparently. Costs 2+ edge-cached KV reads per bearer verify; the\n explicit trade the opt-in buys.\n- **Written automatically where revocation actually happens:** org-member\n removal and role change (Better Auth `organizationHooks`), and\n UPDATE/DELETE of scope-conferring relationship rows — through the same\n audit-wrapper write chokepoint Live Views uses, plus the single DELETE\n route (which has the row in hand but no `.returning()`). Revoke-on-touch:\n a false positive just forces a cheap re-prove.\n- **User bans flip automatically.** The Better Auth admin plugin's ban lands\n as a user-row update, so a generated `databaseHooks.user.update.after` hook\n stamps the user-level revocation the moment `banned` flips — every\n outstanding JWT dies on its next use, and the cookie/session path already\n rejects banned sessions, completing the lockout. When outbound webhooks are\n configured, the same hook emits a `user.banned` event so subscribed\n endpoints are notified.\n- **App-code helpers** for everything else: `src/lib/jwt-revocation.ts`\n exports `revokeUserTokens` / `revokeMemberTokens` / `revokeScopeTokens`\n (e.g. call `revokeUserTokens` from a custom revoke-all flow).\n- **Fails open.** A KV outage degrades revocation to the TTL /\n carry-forward-cap bound — it never locks every bearer out.\n\nBun/Node + `'kv'` fails at compile time with a clear message (the store rides\nthe Cloudflare KV binding; those runtimes own immediate-revoke via the\ncookie/session path). Default remains `'none'`; without the flag the emitted\nmiddleware is byte-identical to v0.44.0.\n\n### Neon: `npm run db:migrate` now applies the RLS layer\n\nThe RLS SQL (helper functions, policies, triggers) used to be emitted as\norphaned `drizzle/migrations/0099–0102` files that no tool ever applied —\n`db:migrate` ran the schema migrations and silently skipped the security\nlayer. The RLS document now rides the journaled drizzle set in\n`quickback/drizzle/` as a content-addressed migration\n(`<idx>_quickback_rls_<hash>`), so one `npm run db:migrate` applies schema\n**and** security, in dependency order. The migration is idempotent\n(`DROP POLICY IF EXISTS` + re-create), so it converges over databases where\nthe old files were applied by hand; an unchanged security config appends\nnothing (the journal stays byte-stable across recompiles), and a changed one\nappends a new content-addressed entry — append-only, like every other\nmigration. Existing Neon projects: recompile + `db:migrate`, nothing breaks.\n\n### Neon: `user_sessions` is real, and the SQL layer speaks TEXT ids\n\n`get_active_org_id()` — the helper every org-scoped RLS policy reads — was\nquerying a `public.user_sessions` table that **no migration created**, and\nthe helper layer was typed `uuid` against Better Auth's TEXT ids\n(`org_abc123`), which would throw on first contact. Now:\n\n- `user_sessions` is compiler-owned migration state\n (`src/db/rls-support.schema.ts`), created by the normal journaled flow\n with a FK to the users table — outside `src/auth/schema.ts`, which the\n Better Auth CLI rewrites.\n- Generated Better Auth session hooks mirror the session's active\n organization (and team, in teams mode) into it on create/update.\n Switching to \"no org\" nulls it through — SQL-side access revokes, fail\n closed.\n- The RLS helper layer (`get_active_org_id`, `get_active_team_id`,\n `is_owner`, the audit helpers) is TEXT-typed to match Better Auth ids.\n- Policies for Better Auth's own tables use the plural physical names the\n BA CLI actually generates on Neon, and BA tables no longer get Quickback\n audit triggers for columns they don't have.\n\n### Hard deletes wire into the audit pipeline correctly\n\nTwo codegen bugs around `delete: { mode: 'hard' }`:\n\n- Firewall auto-detection emitted an `isNull(deletedAt)` predicate for\n tables with no soft-delete column — every read on a hard-delete table\n referenced a column that doesn't exist.\n- Hard-delete routes import the `logHardDelete` audit helper, but the helper\n file was only emitted when the project also had unsafe or `PUBLIC` actions\n — a project with hard deletes and neither failed at deploy time. Hard\n deletes are now a first-class trigger of the security-audit pipeline\n (helper file, `AUDIT_DB` binding, env types, audit migration); on D1 that\n means [`auditDatabaseId`](/compiler/config/providers) is required, and the\n compile error says so.\n\n### Generated output is now typechecked — with the first crop of fixes\n\nEvery compiler change now compiles a matrix of fixture projects and runs\n`tsc` + `wrangler deploy --dry-run` against the **generated output** — the\nclass of bug where the compiler emits syntactically valid TypeScript that\nfails downstream. The first runs caught real ones, all fixed here:\n\n- **Neon:** `src/db/org.schema.ts` re-exported tables that don't exist after\n the Better Auth CLI's plural rewrite; a missing `AuthDatabase` type\n export; transaction callbacks typed bare `(tx)` failing `noImplicitAny`;\n the auth middleware's member-table fallback hardcoded the singular name.\n- **Embeddings:** the queue consumer's `Ai.run` result and the optional\n `EMBEDDINGS_QUEUE` binding both failed strict checks — the route now\n returns a structured `503` when the producer binding is missing instead\n of crashing.\n- **snake_case relationship tables:** relationship/arrow emitters imported\n the camelCase identifier where the generated file exports the verbatim\n table name (`export { event_guests }`) — TS2724 for any snake_case\n relationship table. Imports now alias the real export\n (`event_guests as eventGuests`).\n\n## v0.44.0 — June 9, 2026\n\n### Scope carry-forward is now bounded (revocation fix)\n\nThe auth middleware's rolling refresh re-signs a verified `scope` claim on\nevery authed call without re-probing the relationship — that's what lets a\nscoped session ride past the short JWT TTL with zero per-request DB cost. But\nunbounded, it defeated the revocation model the docs promised: a removed\nguest/staff who kept polling got a fresh TTL on every request, so \"removal\ntakes effect within one TTL\" only held for *idle* clients, and the refresh\nalso bypassed the ≤180s scope-token ceiling (it re-signed with the raw\n`auth.jwt.expiresIn`).\n\nScope tokens now carry a proof timestamp (`sct`), stamped exclusively by the\nproven mint sites (`POST /scope/v1/enter` and the namespace resolver, via the\nshared mint helper). The rolling refresh:\n\n- **refuses once the claim's proof is older than the carry-forward cap\n (15 minutes)** — past it, the token expires within one TTL and the client\n re-proves via `enter` or any minting namespace route, which won't re-mint a\n revoked role. Worst-case post-revocation window for an active client:\n **cap + one TTL** from the last real proof, instead of unbounded.\n- **carries `sct` forward verbatim** — the refresh can never restart the\n window without an actual relationship probe. Claims without `sct`\n (pre-0.44 tokens) fail closed and simply stop refreshing.\n- **signs through the same ≤180s ceiling as the mint sites** — an\n `auth.jwt.expiresIn` above the ceiling no longer leaks into scope-bearing\n tokens via the refresh path.\n\nNo client changes needed: tokens renew exactly as before inside the window,\nand re-entering is the existing flow. For tables where even the capped window\nis too wide, gate with a `via` arm (live relationship subquery per request)\ninstead of a bare `ctx.scope.<kind>` arm; immediate revocation\n(`auth.jwt.revocationCheck: 'kv'`) remains on the roadmap.\n\n## v0.43.0 — June 4, 2026\n\n### Better Auth 1.6\n\nGenerated projects are now pinned to Better Auth **1.6**. The `agents.mcp.requireAuth` work in 0.42.0 surfaced a long-standing version drift: the compiler emitted `better-auth: ^1.5.0`, but `@better-auth/oauth-provider` resolves a tree that requires `@better-auth/core ^1.6.14` and imports `@better-auth/core/utils/host` + `/redirect-uri` — subpaths that only exist in 1.6.x. The result was a `wrangler deploy` that failed at bundle time with `Could not resolve …` and never uploaded.\n\nThis release aligns the **entire** Better Auth dependency set to a coherent 1.6.9 floor so npm resolves one consistent tree:\n\n- `better-auth`, `@better-auth/drizzle-adapter`, `@better-auth/api-key`, `@better-auth/passkey`, `@better-auth/oauth-provider` → `^1.6.9` (generated projects, the baked Docker deps, and the bundled CMS/Account SPAs).\n- Added an explicit `kysely ^0.28.16` pin: Better Auth 1.6's migrator imports `DEFAULT_MIGRATION_TABLE` / `DEFAULT_MIGRATION_LOCK_TABLE` from kysely but doesn't *declare* kysely, so the Worker bundle needs it pinned directly.\n\nNo code migration was required — Quickback already uses `@better-auth/oauth-provider` (not the now-deprecated OIDC Provider plugin), and emits no `freshAge`/SAML usage affected by 1.6's behavioral changes. Verified end to end: a `requireAuth` project and a normal project both `npm install` a clean 1.6.14 tree and bundle with `wrangler deploy --dry-run` with zero resolution errors.\n\n### Larger migration histories no longer hit the upload ceiling\n\nLong-lived projects accumulate one full-schema drizzle snapshot per migration, and the whole cumulative meta payload (snapshots + journals + `.sql`, across both the auth and features dirs) is re-sent on **every** compile — even a no-schema-change one. Projects with deep migration histories were hitting the compiler's `existingFiles` size limit and failing to compile, with no schema drift and nothing to fix on their end.\n\nThe server-side ceilings are raised so this is no longer the binding constraint:\n\n- `existingFiles` payload: **4 MiB → 16 MiB**\n- total request body: **8 MiB → 32 MiB** (kept above the per-category limits so it doesn't trip first)\n\nThis is enforced entirely on the compiler, so no CLI upgrade is needed — the new headroom applies as soon as `compiler.quickback.dev` is on this release.\n\n### Custom response headers (`security.headers`)\n\nThe generated Worker emitted a fixed set of security headers (CSP, HSTS,\n`X-Content-Type-Options`, …) with no supported way to add your own — teams that\nwanted, say, an `X-Server-Version` build stamp on every response had to\npost-patch the generated middleware after each compile.\n\nNew `security.headers` sets arbitrary response headers natively. Values are\nstatic strings or templates interpolating per-deploy Worker env vars via the\n`{{env.VAR_NAME}}` token:\n\n```ts\nsecurity: {\n headers: {\n // Both vars must be set, or the header is omitted entirely.\n 'X-Server-Version': '{{env.SERVER_VERSION}}+{{env.SERVER_BUILD}}',\n 'X-Powered-By': 'Quickback',\n },\n}\n```\n\n- **Omit-if-unset** — a header that references env vars is emitted only when\n *every* referenced var is set (non-empty) at runtime. A Worker that forgot to\n inject the var emits no header, never `X-Server-Version: undefined`. Static\n headers are always emitted.\n- The value is read from `c.env` per request, so it picks up whatever Worker\n var is injected at deploy time — nothing is baked at compile time.\n- **Managed headers are rejected** — names owned by a dedicated `security` field\n (CSP, HSTS, `X-Frame-Options`, `Referrer-Policy`, …) error at compile so the\n two emitters can't race. Malformed `{{env…}}` tokens error too, rather than\n leaking literal braces into the wire header.\n\nSurvives a clean `quickback compile` with no post-processing. See\n[Security Headers → Custom response headers](/compiler/config/security#custom-response-headers).\n\n## v0.42.0 — June 4, 2026\n\n### Interactive OAuth for the generated MCP server\n\nMCP connectors (Claude, Cursor, …) could only connect to a generated `/mcp`\nendpoint **anonymously** — they never launched a sign-in flow, so auth-gated\ntools stayed invisible. The OAuth machinery was already present (Better Auth's\n`oauth-provider` ships `/oauth2/authorize`, `/token`, `/register` + PKCE under\n`/auth/v1`); the compiler just never let a connector discover or trigger it.\n\nNew `agents.mcp.requireAuth` makes the MCP surface authenticated-only:\n\n```ts\nagents: { mcp: { requireAuth: true } },\n```\n\nWhen enabled, the compiler:\n\n- **Challenges unauthenticated `/mcp`** with `401` + `WWW-Authenticate: Bearer\n resource_metadata=\"…\"` ([RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) §5.1) — the signal connectors use to start OAuth.\n- **Force-enables `oauthProvider` + `bearer`**, so `/oauth2/authorize`, `/token`,\n and `/register` ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591) dynamic client registration) exist with PKCE.\n- **Delegates `/.well-known/oauth-authorization-server`** to Better Auth's real\n metadata instead of a hand-rolled stub that advertised a non-existent\n authorization endpoint.\n- Adds the `<origin>/mcp` resource to `validAudiences`\n ([RFC 8707](https://datatracker.ietf.org/doc/html/rfc8707)) so the connector's access token isn't rejected.\n\nLogin and consent are served by your Account SPA, so users authenticate with\nwhatever methods you already enabled. Default is unchanged (anonymous public\ntools); set `requireAuth: true` for servers meant for authenticated users.\n\n## v0.40.2 — June 3, 2026\n\n### Passwordless plugins can no longer bypass the signup gate\n\nBetter Auth's `emailOtp` and `magicLink` plugins auto-create an account when a\ncode/link is verified for an unknown email — and that path is independent of\n`emailAndPassword.disableSignUp`. As a result, `account.auth.signup: false`\nclosed `POST /auth/v1/sign-up/email` but left OTP / magic-link verification as an\nopen back-door for account creation.\n\nThe compiler now emits each plugin's own `disableSignUp` flag, and new\nper-plugin options expose it directly:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: {\n emailOtp: { disableSignUp: true }, // OTP sign-in only; unknown emails rejected\n magicLink: { disableSignUp: true }, // same for magic links\n },\n}),\n```\n\nBoth default to following the global gate: setting `account.auth.signup: false`\n(→ `emailAndPassword.disableSignUp: true`) now also gates the OTP and magic-link\npaths automatically. Set `{ disableSignUp: false }` on a plugin explicitly to\nkeep its sign-up open while password sign-up stays closed.\n\n## v0.40.1 — June 2, 2026\n\n- The generated `wrangler.toml` and `Env` type now emit the `ASSETS` binding\n type for projects that mount SPAs (CMS / Account), so handler code that\n references `c.env.ASSETS` typechecks.\n- Compiler Docker builds preserve their layer cache across rebuilds, cutting\n local recompile time.\n\n## v0.40.0 — June 2, 2026\n\nR2 file storage is now **presign-only by default**. Adding\n`defineFileStorage(\"cloudflare-r2\")` emits just the `ctx.storage` signer — no\nFILES_DB database, no `/storage/v1/*` endpoints, no files worker. You sign\npresigned URLs against a bucket and store references in your own table. The\nturnkey managed subsystem is still available, now behind `managed: true`.\n\nThis decouples the lightweight primitive from the heavyweight subsystem so you\ncan add uploads without standing up a metadata database you don't use.\n\n### Presign-only by default; managed is opt-in\n\n```ts\n// Presign-only (default) — ctx.storage against a bucket, nothing else\ndefineFileStorage(\"cloudflare-r2\", { bucketName: \"my-app-media\" })\n\n// Managed subsystem — FILES_DB + /storage/v1/* + files worker\ndefineFileStorage(\"cloudflare-r2\", { managed: true })\n```\n\n- New projects can omit `bucketName` — it defaults to `<project>-media`, so\n setup is one `wrangler r2 bucket create` plus the R2 API-token secrets.\n- Existing projects set `bucketName` to a bucket they already have. Presign-only\n emits **no** R2 bucket binding and **no** FILES_DB binding — nothing to\n provision, nothing to migrate.\n\n### Per-call bucket + custom secret names\n\n```ts\n// Sign against a different bucket than the configured default\nawait storage.signPutUrl(key, { bucket: \"my-app-public\", contentType });\n```\n\nIf your project already stores R2 credentials under different env-var names,\nmap them so the signer reads yours:\n\n```ts\ndefineFileStorage(\"cloudflare-r2\", {\n bucketName: \"my-app-media\",\n presign: { accountIdEnv: \"CF_ACCOUNT_ID\", accessKeyIdEnv: \"S3_KEY\", secretAccessKeyEnv: \"S3_SECRET\" },\n})\n```\n\n### Fixes\n\n- `maxFileSize` now accepts a human string (`\"100mb\"`, `\"5gb\"`) as well as a\n number of bytes — previously a string emitted invalid TypeScript.\n- Presign-only no longer emits a stray `FILES_DB` `[[d1_databases]]` block (with\n an invalid `database_id = \"local-files\"`) into `wrangler.toml`, which would\n have made `wrangler deploy` reject the worker.\n\n## v0.39.1 — June 2, 2026\n\nDeduplicate colliding OpenAPI `operationId`s. The auto-generated list id\n`list\n</Button>\n```\n\n`ResponsiveModal` survived the migration unchanged — it composes the higher-level Dialog + Drawer wrappers (preserved public API), not the underlying primitives.\n\n#### Caller-side API changes worth noting\n\nBase-ui ships some real behavioural changes the Radix variants didn't:\n\n- `<Select onValueChange>` now receives `(value: string | null, eventDetails) => void` (was `(value: string) => void`). Existing `Dispatch<SetStateAction<string>>` setters reject `null` — wrap callbacks defensively: `onValueChange={(v) => v != null && setX(v)}`.\n- `<DropdownMenuContent forceMount>` removed (base-ui has no `forceMount`). Use base-ui's `keepMounted` on the Popup/Positioner if you need to preserve unmounted state.\n- Component sub-names shifted (`Dialog.Content` → `Dialog.Popup`, `Dialog.Overlay` → `Dialog.Backdrop`). Data attributes are now `data-open` / `data-closed` (no more `data-state=\"open\"`).\n\n#### Adding a new primitive after this release\n\n```bash\ncd packages/ui\npnpm dlx shadcn@latest add <component> --overwrite --yes\n# Sweep generated `@/` imports to relative paths — the SPAs' vite-tsconfig-paths\n# plugin doesn't see packages/ui's @/* mapping at bundle time:\nsed -i.bak \\\n -e 's|\"@/lib/utils\"|\"../lib/utils\"|g' \\\n -e 's|\"@/components/|\"./|g' \\\n -e 's|\"@/hooks/|\"../hooks/|g' \\\n components/<component>.tsx && rm components/<component>.tsx.bak\n```\n\nIf the new primitive pulls in fresh deps, mirror them into `apps/compiler/deps-spa-{cms,account}-package.json` per the SPA build pipeline or Docker SPA builds will fail.\n\n---\n\n## v0.18.1 — May 18, 2026\n\n### Account SPA — teams, active-team picker, permission-aware UI\n\nThe Account SPA's organization surface is now feature-parity with Better Auth's `organization` plugin for the basic team workflow, and replaces the long-standing hardcoded `role === 'owner' || 'admin'` checks with `checkRolePermission` so projects that ship custom roles get a UI that respects them.\n\n#### Teams (opt-in)\n\nWhen the BA config enables teams — `organization({ teams: { enabled: true } })` — the compiler emits `VITE_ENABLE_ORG_TEAMS=true` and the Account SPA exposes a Teams tab on each organization:\n\n- **Teams index** (`/$slug/teams`) — splits into \"Your teams\" (from `listUserTeams`) and \"Other teams\" so non-admins land on what's relevant. Create / rename / delete from the list, gated on `team:create` / `team:update` / `team:delete`.\n- **Team detail** (`/$slug/teams/$teamId`) — member roster with add / remove, joining `listTeamMembers` against the org's full member list for display.\n- **Active-team picker** in the org header — calls `setActiveTeam` and exposes the choice via `OrganizationContext.activeTeamId` so downstream routes (and the BA `session.activeTeamId` server-side) stay in sync.\n- **Team-aware invites** — `InviteMemberDialog` shows an optional team picker when teams are on and forwards `teamId` to `inviteMember`, so accepting the invite drops the new member straight into the right team.\n\nTeams are loaded once by the `$slug` layout (`listTeams` + `listUserTeams`) and exposed via `OrganizationContext.teams` / `userTeamIds` / `refreshTeams`, so individual team routes don't re-fetch the list.\n\n#### Permission-aware UI via `checkRolePermission`\n\n`OrganizationContext.isOwnerOrAdmin` is gone. Routes now read `can(resource, action)` from context, which delegates to `authClient.organization.checkRolePermission` — synchronous, no roundtrip, and aware of any custom roles registered via the BA `ac` option. Multi-role users (BA stores multiple roles comma-separated) are handled by checking each role; the action is allowed if any role grants it.\n\nMigrated sites:\n\n- `$slug.tsx` tab gates → `can('invitation', 'create')`, `can('organization', 'update')`\n- `members.tsx` action menu → `can('member', 'update' | 'delete')`; the owner-hierarchy guard (non-owners can't touch owner-role members) is preserved as a client-side mirror of BA's server enforcement\n- `invitations.tsx` → `can('invitation', 'create' | 'cancel')` gates the Invite button, resend, and cancel separately\n- `settings.tsx` → `can('organization', 'update')` for the form, `can('organization', 'delete')` for the danger zone (was owner-only)\n- `teams.tsx` / `teams.$teamId.tsx` → `can('team', 'create' | 'update' | 'delete')`\n\nProjects on the default three-role hierarchy see no behaviour change; projects that defined `admin`/`member` overrides via BA's access-control API now get a UI that matches what the server will actually authorize.\n\n#### Editable slug + metadata on organization settings\n\nThe `$slug/settings.tsx` form now edits two more `organization.update` fields:\n\n- **URL slug** — full debounced `checkSlug` flow (mirroring the create-org form); on rename, the SPA navigates to `/${newSlug}/settings` and the layout re-fetches with the new slug.\n- **Metadata** — single `Record<string, any> | null` JSON textarea, parsed on submit with inline error messaging. Empty clears the field.\n\nSlug rename is non-breaking for the SPA itself, but every external link / bookmark that references the old slug becomes a 404 — the form warns about this before saving.\n\n#### Auth client wiring\n\nWhen `VITE_ENABLE_ORG_TEAMS=true`, the SPA's `organizationClient(...)` is instantiated with `teams: { enabled: true }` so the team APIs are typed end-to-end. When the flag is off, team methods aren't surfaced — and the Teams tab is hidden — keeping the bundle and UI honest about what the server actually supports.\n\n---\n\n## v0.18.0 — May 17, 2026\n\n### `config.apps` — mount user-authored SPAs on dedicated hostnames\n\nThe compiler now generates per-hostname Worker middleware for arbitrary user SPAs alongside the built-in CMS and Account UIs. Previously the only way to host a product app next to a Quickback API was a second Worker; `config.apps` brings the full stack — API, account, and product UI — onto one deployment with same-origin auth.\n\n```ts\napps: {\n www: {\n domain: \"www.example.com\",\n aliasDomains: [\"example.com\"], // apex serves the same SPA\n },\n}\n```\n\nEach entry binds one or more hostnames to a directory under `src/apps/<name>/` and inherits the Account-domain pass-through behavior — `/api/`, `/auth/`, `/admin/`, `/storage/`, and `/health` route to Hono so the SPA fetches its API without CORS. The compiler:\n\n- emits a `custom_domain = true` route in `wrangler.toml` for the primary hostname and every alias\n- adds each hostname to Better Auth's `TRUSTED_ORIGINS` (when `trustedOrigins` is left unset)\n- widens the CSP `connect-src` to cover the SPA-baked origins\n- folds the new hostnames into shared-parent detection for `crossSubDomainCookies`\n\nDrop the prebuilt SPA bundle at `quickback/apps/<name>/` — the existing source-apps passthrough copies it byte-for-byte into `src/apps/<name>/`. The compiler doesn't build the SPA; it only emits routing for whatever's already there. The names `cms`, `account`, and `public` are reserved; hostname collisions with `cms.domain` / `account.domain` / `account.adminDomain` or between two `apps[*]` entries fail at compile time.\n\nWhen `cms` and `account` are both configured, the multi-domain catchall now explicitly skips app hostnames — an API miss on an app host returns the standard 404 JSON via `app.notFound` instead of stray-serving a sibling SPA's HTML shell.\n\n### Cross-subdomain cookie inference handles apex aliases\n\nThe shared-parent detection that drives `advanced.crossSubDomainCookies` previously reduced any hostname by stripping the leftmost label — `'example.com'` collapsed to `'com'`, which broke equality against sibling subdomains. Apex hostnames (exactly two dot-segments) are now treated as already being the parent, so apex aliases (`example.com` listed alongside `www.example.com`) coexist cleanly with `auth.example.com` / `cms.example.com` and the compiler still emits `crossSubDomainCookies: { enabled: true, domain: '.example.com' }`.\n\n---\n\n## v0.17.2 — May 15, 2026\n\n### `customPlugins` escape hatch on `defineAuth(\"better-auth\", …)`\n\nThe Better Auth provider now accepts `customPlugins` alongside the named-plugin registry — a path to ship third-party plugins (`@better-auth-kit/audit`, …), unregistered built-ins, or one-off project-local plugins without forking the compiler.\n\nEach entry is an explicit import descriptor:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: { passkey: true, organization: true },\n customPlugins: [\n // (1) Project-local plugin file at quickback/plugins/long-session.ts\n { from: \"./plugins/long-session\", export: \"longSessionPlugin\" },\n // (2) Third-party npm package\n {\n from: \"@better-auth-kit/audit\",\n export: \"auditPlugin\",\n args: { events: [\"sign-in\"] },\n dependencies: { \"@better-auth-kit/audit\": \"^1.0.0\" },\n },\n ],\n}),\n```\n\n`from` is either a relative path under `./plugins/` (the CLI auto-uploads matching files from `quickback/plugins/`; the compiler copies them into `src/plugins/<name>.ts` and rewrites the emitted import) or a bare npm specifier (emitted verbatim; declare `dependencies` so the package lands in the generated `package.json`). Omit `args` to emit the symbol uncalled (plugin instance); provide `args` to emit a JSON-serialized factory call.\n\nThe descriptor is validated with Zod — typos in `from`/`export`, paths that escape `./plugins/`, and references to files the CLI didn't ship all fail at compile time with a targeted message.\n\n---\n\n## v0.17.1 — May 14, 2026\n\n### `quickback start` — interactive onboarding\n\n```bash\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n```\n\n`start` walks new users through template selection, scaffolds the project on disk, and only prompts for an account when it's ready to compile. Cancelling at the login prompt leaves the scaffold intact — sign in and run `quickback compile` whenever you're ready.\n\nThe same deferred-auth flow applies to `quickback create`. Scaffolding and (optional) Cloudflare D1 setup run before authentication, so you can preview the project on disk before committing to an account.\n\n### Named views on the free tier\n\nThe `todos` template now ships a `dashboard` named view, exposing a projected response at `GET /api/v1/todos/views/dashboard`. Named views support per-view access rules and per-view field selection while inheriting the table's firewall and masking — the canonical way to ship list-view payloads that are cheaper to fetch and easier to cache than a full collection read.\n\n### `quickback init` removed\n\nFolded into `start` and `create`. The legacy command name prints a deprecation notice pointing at its replacements.\n\n### Minor\n\n- `quickback whoami` reads the stored tier from your credentials.\n- Pro upsell copy in `quickback login` is shown only when the server returns an explicit free-tier subscription.\n- Bare scaffolds (`cloudflare`, `empty`) report accurately when there are no features to generate migrations for.\n\n---\n\n## v0.16.10 — May 14, 2026\n\n### D1-specific safety pass on generated migrations\n\nThe `cloudflare-d1` provider now runs a post-generation pass over every Drizzle migration directory (auth, features, webhooks, audit) before the compile finishes. Better Auth cleanup for retired managed tables is stripped from raw `DROP TABLE` statements. Drop-only cleanup migrations are reordered child-first when foreign-key dependencies require it. Every generated D1 migration directory is replayed against SQLite during compile, so a D1-breaking migration fails at compile time rather than at `wrangler d1 migrations apply`.\n\n---\n\n## v0.16.9 — May 13, 2026\n\n### Resource-scoped realtime tickets\n\n`providers.database.config.realtime` accepts an object form for projects whose WebSocket subscribers aren't org members:\n\n```ts\nrealtime: {\n wsTicket: {\n role: \"attendee\",\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n}\n```\n\nThe generated `/broadcast/v1/ws-ticket` route authenticates the caller, evaluates the declared relationship role against the request, and mints a short-lived WebSocket ticket scoped to the resolved resource. `realtime: true` continues to enable the org-scoped broadcaster.\n\n### Unified broadcast targeting\n\nThe realtime helper and Broadcaster now route by `scopeKey || organizationId || userId`. String targets remain shorthand for `organizationId`; explicit targets can scope a broadcast to a resource or a single user:\n\n```ts\nawait realtime.broadcast(\"event-page-updated\", payload, { scopeKey: \"events:evt_123\" });\nawait realtime.broadcast(\"dm\", payload, { userId: recipientId });\n```\n\nWebSocket tickets are Quickback-minted (signed with `BETTER_AUTH_SECRET`), not Better Auth tokens — Better Auth remains the front-door auth check; Quickback signs the upgrade ticket after authorization succeeds.\n\n---\n\n## v0.16.8 — May 13, 2026\n\n### One auth transport per request\n\nGenerated middleware treats `Cookie`, `Authorization: Bearer`, and `x-api-key` as distinct auth methods and rejects mixed requests with `400 AUTH_METHOD_CONFLICT`. Query-string API keys (`?api_key=` / `?key=`) are no longer accepted. Machine-to-machine auth is explicit; precedence rules between transports are gone.\n\n### Cookie-backed CSRF gate\n\nGenerated apps now block cross-site `POST` / `PUT` / `PATCH` / `DELETE` requests from cookie-relying callers. The middleware skips explicit `Authorization` clients, requires a trusted `Origin` or `Referer`, and blocks `Sec-Fetch-Site: cross-site`. This matters most for cross-subdomain session setups where `SameSite=None` is intentional.\n\n### First-class Wrangler observability\n\n`providers.runtime.config.observability` now supports nested `logs` / `traces` blocks for `headSamplingRate`, `destinations`, `persist`, and `logs.invocationLogs`, emitting matching `[observability]`, `[observability.logs]`, and `[observability.traces]` TOML.\n\n---\n\n## v0.16.7 — May 12, 2026\n\n### Bearer wins over cookie\n\nA request carrying both `Authorization` and a session `Cookie` resolves entirely from the bearer; the cookie is dropped before `getSession()` runs. All three Bearer flavors (API key, JWT, session-token) now behave consistently — no more silent cookie precedence on session-token bearers.\n\n### Bearer plugin defaults to `requireSignature: true`\n\nBetter Auth's `bearer` plugin defaults to unsigned tokens; Quickback now emits `bearer({ requireSignature: true })`. Tokens emitted in the CORS-exposed `set-auth-token` header are server-signed with `BETTER_AUTH_SECRET` and verified on every request. Projects that genuinely need unsigned bearers can override via `providers.auth.config.plugins.bearer`.\n\nSee [Authentication Security → Bearer Tokens and Cookie Precedence](/stack/auth/security#bearer-tokens-and-cookie-precedence).\n\n---\n\n## v0.16.5 — May 12, 2026\n\n### Flat write DSL\n\nResource write operations are now declared at the table level alongside `read`, replacing the nested `crud` block:\n\n```ts\ndefineTable(customers, {\n read: { ... },\n create: { access: { roles: [\"admin\"] } },\n update: { access: { roles: [\"admin\"] } },\n delete: { access: { roles: [\"admin\"] }, mode: \"soft\" },\n upsert: { access: { roles: [\"admin\"] } },\n guards: { ... },\n});\n```\n\n`crud` and top-level `put` still compile as deprecated compatibility aliases. Mixed usage on the same resource is rejected. `schema-registry.json` emits both shapes during the transition.\n\n### CMS placement for multi-table feature actions\n\nStandalone actions on multi-table features have an explicit placement model:\n\n- `cms.placement: \"feature\"` shows the action on every table toolbar in the feature\n- `cms.placement: \"tables\"` with `cms.tables` scopes it to specific tables\n- `cms.hidden: true` keeps it API-only\n\nFeature-root standalone actions are emitted under a new `featureActions` bucket in `schema-registry.json`. Ambiguous multi-table standalone actions without placement compile with a warning.\n\n### `openapi.types` accepts a string array\n\nOne compile can write the generated types file to multiple locations, keeping colocated SPA clients in sync:\n\n```ts\nopenapi: { types: ['api-types.gen.ts', 'apps/web/src/lib/api-types.gen.ts'] }\n```\n\n### Stable artifact ordering\n\nGenerated route files and `schema-registry.json` are emitted in a stable order across runs. Identical logical input produces identical artifacts.\n\n---\n\n## v0.16.4 — May 12, 2026\n\n### Drizzle snapshot integrity\n\nDrizzle metadata files (`<n>_snapshot.json`) are no longer stamped with a Quickback warning key. The warning is now journal-only. Projects whose snapshots were corrupted by an earlier release self-heal on the next compile — the stripped header is removed during staging and the rewritten snapshot is clean.\n\n### `account.auth.*` drives the server, not just the SPA\n\nThe Account UI's auth flags (`signup`, `password`, `passkey`, `emailOTP`, `emailVerification`) now configure the Better Auth server alongside the SPA bundle. A normalizer maps them into the server config:\n\n- `signup → emailAndPassword.disableSignUp` (inverted)\n- `password → emailAndPassword.enabled`\n- `emailVerification → emailAndPassword.requireEmailVerification`\n- `passkey` / `emailOTP` → plugin additions\n\nThe SPA's `VITE_ENABLE_*` flags are derived from the same canonicalized server config, so the bundle and the server cannot drift. Two new flags ride along: `VITE_ENABLE_API_KEYS` and `VITE_ENABLE_MAGIC_LINK`.\n\n**Breaking** for projects that implicitly relied on the SPA-only behaviour: `account.auth.signup: false` now actually disables `POST /auth/v1/sign-up/email` on the server. Set `providers.auth.config.emailAndPassword.disableSignUp: false` explicitly to keep server signup open while hiding the SPA screen.\n\n---\n\n## v0.16.3 — May 9, 2026\n\n### Standalone action mount order\n\nFeature-level standalone action routers now register before sibling CRUD routers when both mount at the exact same prefix. A literal path like `GET /api/v1/records/today-bundle` resolves to the standalone handler instead of falling through to `GET /:id` and treating `\"today-bundle\"` as a record ID.\n\n---\n\n## v0.16.1 — May 9, 2026\n\n### Cloudflare ASSETS canonicalization\n\nWorker SPA fallbacks now request `/<dir>/` instead of `/<dir>/index.html`. Cloudflare's static-assets binding rewrites `/index.html` requests as 307 redirects to the trailing-slash path under the default `html_handling=auto-trailing-slash`, which previously caused redirect loops in SPA fallback handlers. Affects CMS, Account, admin, and the multi-domain catchall.\n\n### `account.customLogin`\n\nSet `account: { customLogin: true }` to drop a project-branded sign-in page in front of the bundled SPA. Place the page at `quickback/public/account/login/index.html` (as a directory) and the existing public passthrough serves it. The route registers before the `/account/*` SPA catch-all so the static handler wins; everything else under `/account/` continues to route through the bundled SPA.\n\n### Project-level realtime defaults\n\n`providers.database.config.realtime: true` now treats every resource as realtime-enabled by default. Per-resource `realtime: { enabled: false }` still wins.\n\n### Compile-time validators\n\nTwo new compile-time errors over silent runtime failures:\n\n- `AUTHENTICATED` + org-scoped firewall is rejected. The combination silently returned empty lists to sign-in-only callers who lacked an active org; the validator names three valid resolutions (drop the org scope, use `USER`, or split the route).\n- `createRealtime` imports without `realtime: true` enabled in the config are rejected at compile.\n\n### Drizzle metadata hardening\n\nDrizzle journal files carry a \"do not edit\" header. The compiler warns when the journal entry count exceeds the snapshot file count (typically the trace of a hand-deleted snapshot).\n\n### Minor\n\n- `SYSADMIN` is now recognised by the standalone-action org gate's pseudo-role matcher.\n- Apex `/` and `/account/login` get fallback redirects to `auth.loginUrl` when neither bundled SPA is enabled.\n- Record-based action URLs are kebab-case to match the OpenAPI spec (e.g. `/api/v1/widgets/:id/send-invite`).\n\n---\n\n## v0.16.0 — May 9, 2026\n\n### Agent Auth Protocol\n\nQuickback ships a server implementation of the [Agent Auth Protocol](https://agentauthprotocol.com) via `@better-auth/agent-auth`. Enable with `auth.plugins.agentAuth: true` and the compiler emits the full agent-auth surface: discovery at `/.well-known/agent-configuration`, capability projection from the project's OpenAPI spec, a device-authorization approval page in the Account SPA at `/agents/approve`, and the four agent-auth tables added to the auth schema automatically.\n\n**OpenAPI capability projection runs by default.** Every operation with an `operationId` becomes an agent capability. Default `approvalStrength` map: `GET → \"session\"`, `POST/PUT/PATCH/DELETE → \"webauthn\"`. The proxy `onExecute` makes a self-fetch with a Better Auth JWT minted for the agent session, so the inner request hits the existing JWT fast-path and runs the full firewall + access + masking pipeline. Opt out of OpenAPI projection with `agentAuth: { fromOpenAPI: false }` and wire `capabilities` + `onExecute` by hand.\n\n### Bearer-only on `/mcp` and the agent-auth surface\n\n`/mcp` forwards only `Authorization: Bearer …` into the inner request. Cookie and `x-api-key` forwarding are removed. Three Bearer flavors land on the same header — Better Auth session token (via the `bearer` plugin), OAuth access token (via OAuth Provider), and agent JWT (via `@better-auth/agent-auth`).\n\n### Auth DSL gains first-class plugin entries\n\n`bearer`, `oauthProvider`, and `agentAuth` are now typed entries in both the array-form union and the `BetterAuthPlugins` interface, with their own options shapes (`OAuthProviderOptions`, `AgentAuthOptions`). Existing `as any` casts can come out.\n\nAuto-enable rule: turning on `agentAuth` force-adds `bearer` + `oauthProvider`. No useful agent-auth deployment ships without those two.\n\n### `queue-consumer.ts` gating\n\nThe queue consumer is emitted when any of the following are true: embeddings are configured, queue handlers exist under `services/queues/*`, or `additionalQueues` is declared. Previously the third case left projects with a wrangler binding pointing at a missing handler.\n\n---\n\n## v0.15.0 — May 7, 2026\n\n### Sysadmin tier for the CMS\n\nA new opt-in `cms: { sysadmin: true }` flag turns the CMS into a cross-tenant DB-admin tool gated by `user.role === 'sysadmin'`. Distinct from the Better Auth `'admin'` plugin role, so user-management powers and DB-admin powers stay decoupled. Off by default.\n\nWhen enabled, the compiler emits a `SYSADMIN` pseudo-role (a fifth marker alongside `PUBLIC` / `AUTHENTICATED` / `USER` / `ADMIN`), a firewall escape hatch that drops tenant scopes for sysadmins while preserving soft-delete, a true cross-tenant `/admin/v1/sysadmin/organizations` endpoint, and a relaxed cross-tenant guard for list routes.\n\nThe CMS SPA gains a two-mode design: org admins keep the existing membership-based switcher, sysadmins get an \"All organizations\" selector that pins tenants via `?organizationId=` on every API call.\n\n### Durable Object `[[migrations]]` order is preserved\n\nCloudflare's migration list is append-only. The compiler now reads your existing `wrangler.toml` (when present) and emits auto-generated DO `[[migrations]]` blocks in two phases: deployed entries first (preserving order), net-new entries appended last. Reordering DOs in the config array no longer reshuffles deployed migrations.\n\n### `quickback/public/` — static-asset passthrough\n\nAnything dropped under `quickback/public/` is copied verbatim into `src/apps/` on every compile and served by the wrangler `[assets]` binding. Use for favicons, `robots.txt`, OG images, `.well-known/` files, marketing PDFs — anything that needs to ride past the compiler as bytes.\n\n- Optional. Missing folder is a no-op.\n- Stale-cleaned. Files removed from `quickback/public/` disappear on the next compile.\n- Hidden entries (`.DS_Store`, dotfiles) are skipped.\n- Collisions with compiler-emitted manifest paths fail the compile loudly.\n\n### Minor\n\n- Standalone-action wrapper skips the org gate when the access tree references any pseudo-role.\n- Queue handler emit no longer drops the `queue` export when there are no embeddings.\n\n---\n\n## v0.14.7 — May 7, 2026\n\n### Codegen fixes for projects with non-`id` primary keys and DO-only features\n\nFour surgical fixes to the generated output:\n\n- Duplicate table imports in relationship-role routes are deduplicated.\n- `db` references in single-record and bulk action handlers now resolve correctly during pre-fetch.\n- PartyServer auth gates pass the in-scope `db` handle into firewall calls.\n- Durable-object-only features keep their `lib/` files in the output.\n\n### `emailOtp` + AWS SES is OTP-only\n\n`auth.emailOtp` with the AWS SES email provider no longer auto-wires the magic-link companion. Mail-client URL prefetching can burn the one-time code before the human sees it; the Account SPA's `/email-otp` route is the single canonical entry point. Projects that explicitly want the magic-link arm can wire `sendVerificationOTP` directly.\n\n---\n\n## v0.14.6 — May 7, 2026\n\n### MCP transport correctness\n\nFour fixes to the MCP-over-HTTP path:\n\n- `tools/call` URLs are no longer double-prefixed for action tools.\n- Auth middleware accepts API keys via `Authorization: Bearer` in addition to `x-api-key` and query parameters — the channel MCP clients use exclusively.\n- `auth.roleHierarchy` is expanded for runtime role checks across api-key, JWT, and session auth paths. A higher role inherits the privileges of every lower role.\n- Team-scoped firewall predicates degrade gracefully when no team is active (org scoping continues to apply; team scoping is optional).\n\n---\n\n## v0.14.5 — May 7, 2026\n\n### MCP environment threading\n\nThe generated MCP server's `tools/call` dispatch threads `env` and `executionCtx` into the inner request, so action tools that touch Cloudflare bindings (D1, KV, R2, Queues) no longer crash with `undefined` env access.\n\n---\n\n## v0.14.4 — May 7, 2026\n\n### `via:` firewall predicates pull required imports\n\nThe relationship-role generator emits `inArray` and `sql` imports when the firewall has any `via:` predicate, and `buildFirewallConditions` accepts `(ctx, db)` so the relationship subquery has a Drizzle client to evaluate against. Every CRUD and action call site passes `db` through automatically.\n\n---\n\n## v0.14.3 — May 7, 2026\n\n### Relationship-role table re-exports\n\nGenerated `<table>.resource.ts` files now re-export their Drizzle table binding. Cross-feature relationship subqueries that import the binding from the resource file (rather than the schema) resolve correctly.\n\n---\n\n## v0.14.2 — May 7, 2026\n\n### Historical DO `[[migrations]]` are preserved\n\nA new `bindings.durableObjectMigrations` config slot carries forward `deleted_classes`, `renamed_classes`, and `transferred_classes` lifecycle entries across recompiles. Cloudflare's migration list is append-only; entries declared here are emitted first in `wrangler.toml`, then auto-generated current-class entries follow:\n\n```ts\nbindings: {\n durableObjects: [{ name: 'NOTEPAD', className: 'Notepad', from: 'lib/Notepad' }],\n durableObjectMigrations: [\n { tag: 'qb-do-deleted-legacy-notes-2026-05-05', deletedClasses: ['LegacyNotes'] },\n ],\n}\n```\n\nAll four lifecycle shapes are supported. User-declared entries can override auto-emit by reusing the same tag.\n\n---\n\n## v0.14.1 — May 7, 2026\n\n### Bulk action variants in `openapi.json`\n\nRecord-based actions with `bulkVariant: true` are now emitted as sibling operations in the OpenAPI spec, with the documented `{ ids, input, failFast? }` request shape, 200/207/400 responses, and a separate `<Resource><Action>Bulk` `operationId` so typed-client codegen distinguishes single from bulk.\n\n### Cross-tenant \"my events\" patterns\n\nThe access docs now include a worked example for the cross-tenant aggregation pattern (e.g. `GET /my-events` returning resources across all tenants a caller is invited to). See [Access → Cross-tenant dashboards](/compiler/definitions/access#cross-tenant-my-events-dashboards-are-not-this).\n\n---\n\n## v0.14.0 — May 7, 2026\n\n### Relationship-based authorization\n\nRoles can now be bound to a domain-table membership (\"user is a confirmed guest of this event\") rather than an org membership or a pseudo-role. Declare the relationship once and reference it from `firewall:` or `access.roles:`:\n\n```ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n },\n },\n roles: {\n guest: { via: 'guestOf' },\n eventStaff: { or: [{ via: 'guestOf' }, { roles: ['admin', 'owner'] }] },\n },\n}\n\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' },\n],\nread: { access: { roles: ['admin', 'member', 'guest'] } },\ncreate: { access: { roles: ['admin', 'guest'] } },\nupdate: { access: { roles: ['admin'] } },\n```\n\nThe compiler emits an inline Drizzle subquery against the relationship table and AND-composes it as the outermost firewall clause. The relationship table's own firewall (tenant scope, soft-delete) is honored inside the subquery; cross-tenant grants are impossible because the resource's tenant filter sits outermost.\n\nSupported surfaces: row-level scoping via `firewall: [{ field, via }]`, role gates on writes and reads, view access. Masking and action access reject relationship-roles at compile time with pointers to the working pattern (gate the row at the firewall layer, gate the role at the access layer).\n\nCross-tenant aggregation dashboards aren't solved by relationship-roles — the tenant firewall remains the outermost AND. For that pattern, use a user-scoped firewall or function-form access on a dedicated route.\n\nSee [Firewall → Relationship-based scoping](/compiler/definitions/firewall#relationship-based-scoping-via) and [Access → Relationship-based authorization](/compiler/definitions/access#relationship-based-authorization).\n\n### Bulk variants on record-based actions\n\n`defineAction({ bulkVariant: true })` emits `POST /:resource/batch/{action}` alongside the per-record route. The bulk handler loops the same access + transition + execute pipeline over a `{ ids, input, failFast? }` body:\n\n```ts\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n bulkVariant: true,\n transition: { field: \"status\", via: \"nextStatus\", fromTo: { /* ... */ } },\n async execute({ db, record, input, whereTransition }) {\n // exact same body — runs once per id\n },\n});\n```\n\nPer-record outcomes return as 207 Multi-Status. `failFast: true` aborts on the first failure and wraps the loop in `db.transaction()` on tx-supporting providers; D1 fails fast without rollback. Max 100 IDs per request. Rejected on standalone actions and `unsafe` actions.\n\n### Aggregations on read views\n\nRead views can declare pre-computed metrics that surface alongside the row payload:\n\n```ts\nread: {\n views: {\n pipeline: {\n fields: [\"id\", \"jobId\", \"candidateId\", \"status\", \"appliedAt\"],\n aggregations: {\n totalApplications: { fn: \"count\" },\n byStatus: { fn: \"groupBy\", field: \"status\" },\n },\n },\n },\n}\n```\n\nAggregations run over the same firewalled, filtered set as the row query; pagination is intentionally ignored. Supported functions: `sum`, `avg`, `min`, `max`, `count`, `count_distinct`, `groupBy`. See [Views → Aggregations](/compiler/definitions/views#aggregations).\n\n---\n\n## v0.13.5 — May 6, 2026\n\n### Object-form `auth.plugins` config is honored\n\nThe documented `plugins: { oauthProvider: {...} }`, `plugins: { organization: { teams: { enabled: true } } }` shapes now flow through the compiler unchanged. Per-plugin options reach the generated `auth.ts` as written.\n\n### `roles: [\"PUBLIC\"]` allowed on writes and actions\n\n`PUBLIC` is the explicit, uppercase opt-in for unauthenticated access on every access node — reads, writes, views, and actions. The runtime trusts the marker; row-level safety comes from firewall, masking, and the action's own validation. `PUBLIC` actions continue to receive mandatory audit logging.\n\nCommon pattern: pair `roles: [\"PUBLIC\"]` with `firewall: { exception: true }` on the resource so the row predicate doesn't reject every unauthenticated caller.\n\n---\n\n## v0.12.0 — May 5, 2026\n\n### Per-room authorization for PartyServer\n\n`bindings.durableObjects[].access` declares a path-scoped gate that runs the declared resource's firewall and `read.access` pipeline before the WebSocket upgrade:\n\n```ts\ndurableObjects: [\n // Single-resource: roomId IS the chat row id.\n { name: 'Chat', className: 'Chat', from: 'lib/Chat',\n access: { resource: 'chats' } },\n\n // Multi-resource: regex dispatches kind → resource.\n { name: 'Notepad', className: 'Notepad', from: 'lib/Notepad',\n access: {\n roomId: { pattern: '^(day-note|interaction|record):([A-Za-z0-9_-]+)$', kindGroup: 1, idGroup: 2 },\n resources: {\n 'day-note': { resource: 'day-notes' },\n 'interaction': { resource: 'interactions' },\n 'record': { resource: 'records' },\n },\n } },\n\n // Anonymous lobbies / public pads: explicit opt-out.\n { name: 'PublicLobby', className: 'PublicLobby', from: 'lib/PublicLobby',\n access: 'public' },\n]\n```\n\nThe gate 401s unauthenticated callers, 403s when the firewall hides the row, 404s when the row is missing. Resource references are validated against feature names at compile time. See [PartyServer Rooms → Per-room authorization](/stack/realtime/partyserver-rooms#per-room-authorization-via-access-v012).\n\n---\n\n## v0.11.1 — May 5, 2026\n\n### PartyServer auto-mount is secure by default\n\nThe `/realtime/*` auto-mount now wraps `partyserverMiddleware` in an auth check. Unauthenticated upgrades return 401; the four auth mechanisms (session cookie, JWT bearer, `x-api-key` header, query parameter) all unlock connections. Per-room access remains the `Server` class's responsibility in `onConnect`.\n\n---\n\n## v0.11.0 — May 5, 2026\n\n### OAuth Provider (MCP-ready)\n\nQuickback can act as a standards-compliant OAuth 2.1 + OIDC authorization server via [`@better-auth/oauth-provider`](https://better-auth.com/docs/plugins/oauth-provider). Enable with `plugins: [\"oauthProvider\"]`. The compiler auto-includes Better Auth's `jwt` plugin and the Account SPA gains a `/consent` page for the standard authorization-code flow.\n\nThis replaces Better Auth's deprecated `mcp` plugin and gives every MCP client (Cursor, Claude Desktop, claude.ai connectors, custom tooling) RFC 7591 dynamic client registration plus the discovery documents they need to bootstrap. See [Auth Plugins → OAuth Provider](/stack/auth/plugins#oauth-provider-mcp-ready).\n\n### API keys via query parameter\n\nThe auth middleware now accepts API keys as `?api_key=…` or `?key=…` query parameters. The `x-api-key` header takes precedence when both are sent. Prefer the header whenever the client supports it — query parameters land in access logs and `Referer` headers.\n\n### PartyServer rooms + realtime URL split\n\nThe realtime URL space is reorganized so names match what each primitive does:\n\n- **`/realtime/v1/*` → `/broadcast/v1/*`** — the org-wide Broadcaster moves to its semantically accurate prefix.\n- **`/realtime/<binding>/<room-id>`** — new mount for [PartyServer](/stack/realtime/partyserver-rooms) rooms. Per-room Durable Objects with presence and lifecycle hooks. Auto-mounted whenever a project declares any in-worker DO.\n\n**Breaking** — recompile + redeploy required:\n\n- `REALTIME_URL` env var renamed to `BROADCAST_URL`.\n- SPA helpers `getRealtimeWsUrl()` / `getRealtimeTicketUrl()` renamed to `getBroadcastWsUrl()` / `getBroadcastTicketUrl()`.\n- `appConfig.routes.api.realtime` renamed to `appConfig.routes.api.broadcast`.\n\n`partyserver`, `partysocket`, and `hono-party` are pre-installed in the compiler image; collab projects compile without an extra `npm install` step.\n\n---\n\n## v0.10.20 — May 4, 2026\n\n### In-worker Durable Objects\n\n`bindings.durableObjects[].from` flips a DO binding into in-worker mode and emits the export, the `[[migrations]]` block, and the `CloudflareBindings` type all together:\n\n```ts\ndurableObjects: [{\n name: \"ITEM_STREAM\",\n className: \"ItemStream\",\n from: \"features/loops/lib/ItemStream\",\n}]\n```\n\nDO class files live under `quickback/lib/` or `quickback/features/<feature>/lib/` — both copy verbatim into the generated `src/` tree on every compile. `from` and `scriptName` are mutually exclusive; cross-worker DOs (`scriptName` set) skip the re-export and migration block.\n\n`migrationTag` (default `qb-do-${className}`) is stable across regenerations and must never be removed or renamed once deployed. `useSqlite` defaults to `true`. See [Bindings → Durable Objects](/compiler/config/bindings#durableobjects).\n\n---\n\n## v0.10.18 — May 2, 2026\n\n### `experimentalRemote` — share deployed D1 with `wrangler dev`\n\nPer-binding `experimental_remote = true` lets `wrangler dev` read/write deployed D1 for selected bindings:\n\n```ts\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n splitDatabases: true,\n experimentalRemote: { auth: true, features: false },\n }),\n}\n```\n\nUseful for \"share prod auth in dev, keep feature writes sandboxed.\" Off by default.\n\n### Google OAuth + signup ToS\n\nThe Account SPA wires Google OAuth end-to-end when configured under `auth.config.socialProviders.google.enabled`. The signup flow gains a Terms-of-Service checkbox gate (configurable via the Account SPA branding).\n\n### CLI compile auth gate\n\n`quickback compile` now requires authentication for cloud-compiler runs. Device-flow `?redirect=` parameters are standardized across the login + signup pages so a user clicking \"Create one\" no longer loses their return URL.\n\n---\n\n## v0.10.15–v0.10.17 — May 2, 2026\n\n### CSP auto-config\n\nWhen `security.csp` is set, the compiler widens directives additively based on the project's enabled features:\n\n| Trigger | Auto-added | Directive |\n|---|---|---|\n| `cms: true` OR `account: true` | `'unsafe-inline'`, `https://fonts.googleapis.com` | `styleSrc` |\n| `cms: true` OR `account: true` | `https://fonts.gstatic.com` | `fontSrc` |\n| `csp` set (always) | `@trustedOrigins` | `connectSrc` |\n| Bundled SPA enabled | SPA-baked API origin (`config.domain`, `quickback.{baseDomain}`, `cms.domain`, `account.domain`) | `connectSrc` |\n\nAnything you already wrote stays — auto-config never removes or overrides. Each applied addition is logged to stderr. Opt out with `security: { cspAutoConfig: false }`.\n\nMost projects can write the minimal:\n\n```ts\nsecurity: {\n csp: {\n defaultSrc: ['@self'],\n scriptSrc: ['@self'],\n objectSrc: ['@none'],\n upgradeInsecureRequests: true,\n },\n}\n```\n\n…and the compiler fills in font hosts, trusted origins, and SPA-baked URLs.\n\nWhen a target directive is missing, auto-config scaffolds it from `default-src` baseline rather than widening `default-src` itself — CSP3 fall-back semantics would otherwise leak the addition to every directive that falls back to `default-src`.\n\n---\n\n## v0.10.14 — May 1, 2026\n\n### `auth.jwt` config\n\nThe bearer-token JWT used by the auth fast-path is configurable. Tune `expiresIn` to bound the post-revocation replay window without affecting browser SPAs (which auto-refresh on every authed call):\n\n```ts\nauth: {\n jwt: {\n expiresIn: 30,\n issuer: 'my-api',\n audience: 'partner-svc',\n secretEnv: 'CUSTOM_JWT_SECRET',\n },\n}\n```\n\n### Admin MCP endpoints filtered\n\nBetter Auth admin endpoints (`/admin/list-users`, `/admin/ban-user`, etc.) now carry `x-access: { userRole: ['admin'] }` in the generated OpenAPI spec. The MCP `tools/list` access-filter drops them for non-admin callers.\n\n### Declarative `security` config\n\nEvery security response header (`Content-Security-Policy`, COOP, COEP, CORP, HSTS, `X-Frame-Options`, `Referrer-Policy`, `Permissions-Policy`) is configurable from `quickback.config.ts`. `@`-prefixed sentinels (`@self`, `@none`, `@unsafe-inline`, `@trustedOrigins`, etc.) replace awkward `\"'self'\"` quoting.\n\nThe compiler lints the resolved config for known footguns: `@unsafe-inline` in `script-src`, wildcard sources, missing `default-src`, HSTS preload-list misconfiguration.\n\n### HSTS skipped on localhost\n\nGenerated middleware skips `Strict-Transport-Security` when the request hostname is `localhost`, `127.0.0.1`, or `*.localhost`. Without this gate, `wrangler dev` would pin a developer's browser to HTTPS across every project on that machine.\n\n---\n\n## v0.10.13 — May 1, 2026\n\n### Clickjacking defence on every Worker\n\nEvery Worker emits `Content-Security-Policy: frame-ancestors 'self' <TRUSTED_ORIGINS…>` and `X-Frame-Options: SAMEORIGIN` on every response. The CSP allowlist is sourced from the same `TRUSTED_ORIGINS` constant that gates CORS.\n\n---\n\n## v0.10.11 — May 1, 2026\n\n### MCP `tools/list` is access-filtered\n\nEach MCP tool now carries sanitised access metadata. `tools/list` filters against the caller's `ctx`: unauthenticated callers see only `PUBLIC` tools, authenticated callers see only role-gated tools they pass.\n\n- Wildcard CORS removed from the MCP endpoint.\n- Unauthenticated `GET /mcp` no longer enumerates tool names.\n- Internal flavor text is removed; `annotations.destructiveHint` and `_unsafe` remain — those are the spec-correct signals for clients.\n\n`tools/call` continues to re-enter the Hono app and run every middleware (auth, firewall, access, guards, masking), so hiding a tool from list never weakens the underlying gate.\n\n---\n\n## v0.10.10 — April 29, 2026\n\n### Reserved keys in `access.record` are rejected\n\n`access.record` is a flat field map evaluated as implicit AND between entries — keys must be column names. The compiler now rejects reserved keys (`and`, `or`, `roles`, `userRole`) inside `record` with migration guidance pointing at the working pattern (top-level siblings with their own `record:` blocks).\n\n---\n\n## v0.10.8 — April 29, 2026\n\n### Audit logging on Postgres targets\n\n`audit_events` previously only existed on `cloudflare-d1`. The audit table now lives in a dedicated `audit` schema (`drizzle.pgSchema('audit')`) on Postgres targets. The `hasSecurityAudit` gate accepts D1 or any PG dialect; `auditDatabaseId` remains a D1-only requirement.\n\n### `auditDatabaseId` is a compile-time requirement\n\nProjects with unsafe or `PUBLIC` actions that previously produced a placeholder `database_id = \"local-audit\"` in production now fail at compile time with the exact `wrangler d1 create <project>-audit` command and the config key where the returned ID goes.\n\n### Action input → OpenAPI / MCP\n\n`defineAction({ input: z.object({...}) })` schemas flow into the OpenAPI `requestBody` and the MCP tool's `inputSchema.properties`. Simple `z.object` shapes are extracted at compile time; discriminated unions, refinements, recursive schemas, and bare-identifier references run through Zod's native `z.toJSONSchema()` for full-fidelity output.\n\n### OpenAPI fidelity\n\n- Response schemas emit `required[]` for every non-nullable column.\n- `text(_, { enum: [...] })` columns emit as closed `{ type: \"string\", enum: [...] }`.\n- `id` claims `format: \"uuid\"` only when the project's `generateId` actually produces UUIDs. cuid2 / prefixed / nanoid / serial generators emit plain `{ type: \"string\" }`.\n\n### Minor\n\n- Auto-mask predicate verifies the resolved owner column exists before emitting an `or: 'owner'` clause; falls back to roles-only with a warning otherwise.\n- Generated CRUD errors emit canonical `QuickbackErrorCode` enum values (`DB_NOT_NULL_VIOLATION`, `DB_UNIQUE_VIOLATION`, etc.) so generated SDKs can exhaustively switch on `code`. See [API errors](/compiler/targets/hono-api/using-the-api/errors#database).\n\n---\n\n## DSL: one file per action, multi-table per feature\n\n### One file per action\n\nAction authoring is one file per action under `<feature>/actions/<name>.ts`. The filename is the action name and the URL segment:\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: { applied: [\"screening\"], screening: [\"interview\"], interview: [\"offer\"] },\n },\n async execute({ db, record, input, auditFields, whereTransition }) { /* … */ },\n});\n```\n\n`defineAction` is imported from a generated per-feature helper at `<feature>/.quickback/define-action.ts` — `record`, `input`, and audit fields are typed without manual annotations.\n\n**Discovery rules:**\n- `actions/<name>.ts` binds to the feature's primary table.\n- `actions/<table>/<name>.ts` binds to the sibling table file.\n- Setting `path:` makes the action standalone (custom URL, no record fetch).\n- Tableless features require every action to be standalone.\n\n**Retired** (rejected at load time with migration guidance): `actions.ts` (bundled multi-action file), `_feature.ts`, `handlers/` directory + `handler:` string ref, `defineActions(table, {…})`, colocated `defineActions` inside table files, `standalone: true` flag, `*-actions.ts` / `*.actions.ts` filename patterns.\n\nSee [Actions docs](/compiler/definitions/actions).\n\n### Multi-table actions per feature\n\nOne feature directory can own actions on multiple tables. Three discovery modes:\n\n- **Colocated** (canonical) — `<table>.ts` containing both `defineTable` and `defineActions(<table>, …)`. One file per entity.\n- **`actions.ts`** — single primary-table actions file at feature root.\n- **`actions/<table>.ts`** — per-table action files for strict schema/behavior separation.\n\nPlus a universal `_feature.ts` slot for non-table-bound feature-level actions and shared Zod schemas.\n\nAction names are unique per `(bindTable, name)` pair. Sibling-bound `actions/episodes/publish.ts` and `actions/shows/publish.ts` mount at `/episodes/:id/publish` and `/shows/:id/publish` and compile cleanly.\n\n---\n\n## Firewall: named-scope shape\n\nThe named-scope firewall shape is a co-equal user-facing input alongside the predicate array:\n\n```typescript\nfirewall: { organization: { column: 'tenant_id' } } // named-scope (compact)\nfirewall: { owner: { column: 'account_user_id' } }\nfirewall: { exception: true }\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n] // predicate array (explicit)\n```\n\nPick the form that reads better — named-scope for the common one-line case, predicate array when you need custom `in`-lists or non-scope predicates.\n\n**Auto-detection synonyms.** When `firewall:` is omitted, the compiler scans the schema for an isolation column. The org-scope list accepts `organizationId`, `organisationId`, `orgId`, `organization`, `organisation`, `org` (American + British). User-scope accepts `userId`.\n\n**`ownerId` is a targeted error signal.** When a table carries `ownerId` but no isolation column and no explicit `firewall:`, the compiler raises a specific error — `ownerId` is business-logic ownership, not access control. Use `userId` for access control, declare an explicit `firewall:`, or add a separate isolation column.\n\n---\n\n## v0.10.0 — April 26, 2026\n\n### `q.scope()` — single-declaration tenant scoping\n\n`q.scope(kind)` replaces the three-place pattern (column declaration + firewall predicate + ownership-guard) with one column:\n\n```typescript\ncolumns: {\n organizationId: q.scope('organization'), // → ctx.activeOrgId\n ownerId: q.scope('owner'), // → ctx.userId\n teamId: q.scope('team'), // → ctx.activeTeamId\n}\n```\n\n`q.scope()` columns auto-derive the firewall predicate, register with the guards layer as `systemManaged` (client input rejected), and auto-populate from `ctx` on create / upsert. The systemManaged extension generalises beyond `q.scope()`: any firewall predicate whose `equals` references `ctx.*` registers its `field` automatically.\n\nSee [`q.scope()`](/compiler/definitions/schema#qscope--tenant-scope-columns).\n\n### `masking[col].query.roles` — unified filter / sort / search gate\n\nThe three legacy per-capability flags (`filterable`, `searchable`, `sortable`) are replaced by a single `query.roles` allowlist:\n\n```typescript\nmasking: {\n email: {\n type: 'email',\n show: { roles: ['admin'] },\n query: { roles: ['admin'] }, // defaults to show.roles when omitted\n },\n}\n```\n\nA view's own `query.{filterable,searchable,sortable}` allowlist is the opt-in for higher-privileged roles; the existing intersection validator gates it at compile time.\n\n**Breaking:** `masking[col].filterable / .searchable / .sortable` is rejected at compile time with a migration hint. Replace with `query.roles` (or delete the flags — `query` defaults to `show.roles`).\n\n---\n\n## v0.9.0 — April 25, 2026\n\n### Unified `read:` pipeline\n\nThe read side of every resource has its own block — `read:` — that owns the collection-level `GET /` endpoint, single-record `GET /:id`, and named view projections.\n\n**Breaking changes** (compile-time errors with migration hints):\n\n- `crud.list` → `read.access` (plus `read.pageSize` / `read.maxPageSize`)\n- `crud.get` → `read.access` (single-record GET inherits automatically)\n- Top-level `views: {...}` → `read.views: {...}`\n- `crud.list.fields` / `crud.get.fields` → declare a named view under `read.views` and call `/views/{name}`\n\n### Pre-record access ordering\n\nHandlers on `/:id` run a role-only access check before the firewall query. A caller without a matching role gets 403 before the database is touched. This closes the 404-vs-403 ID-probe channel — an unauthorized caller can no longer distinguish \"row exists in another tenant\" from \"row doesn't exist.\" See [Access evaluation order](/compiler/definitions/access#evaluation-order).\n\n### Transactional batch operations\n\nBatch endpoints expose `failFast` and a `meta.transactional` response field. On tx-supporting providers (postgres, supabase, neon, libsql, better-sqlite3, bun-sqlite), `failFast: true` wraps the per-record loop in `db.transaction(...)` so any failure rolls back the entire batch. On Cloudflare D1 (no `db.transaction`), `failFast: true` stops on the first error but prior writes stay committed.\n\nEmbedding queue messages and realtime broadcasts emit after the transaction commits — rolled-back batches produce no orphan jobs.\n\nSee [Batch Operations → Transactional semantics](/compiler/targets/hono-api/using-the-api/batch-operations#transactional-semantics).\n\n---\n\n## v0.8.7 — April 17, 2026\n\n### Hono CVE bump\n\nHono is bumped to `^4.12.14` across the monorepo, the compiler Docker image's pre-installed deps, and every generator path that emits Hono into compiled projects. Older ranges covered the vulnerable window. Recompile to pick up the fix in your generated project's `package.json`.\n\n### Cloudflare Email Sending in public beta\n\nQuickback defaults to the Workers `send_email` binding for Cloudflare deploys. Cloudflare Email Sending has graduated to public beta — production-ready with zero-config. AWS SES remains a fully supported opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes. See [Email Configuration](/compiler/config#email-configuration).\n\n### Dependency sweep\n\n`wrangler@^4.83.0`, `drizzle-orm@^0.45.2`, `drizzle-kit@^0.31.10`, `zod@^4.3.6`, `@cloudflare/workers-types@^4.20260417.1`.\n\n---\n\n## v0.8.5 — April 15, 2026\n\n### `userRole` access primitive\n\nA new `userRole?: string[]` field in the declarative `Access` config evaluates against `ctx.userRole` (the Better Auth admin-plugin `user.role` column). Distinct from `roles`, which matches `ctx.roles` (org membership).\n\n```typescript\n// Org owner OR platform admin\naccess: { or: [{ roles: ['owner'] }, { userRole: ['admin'] }] }\n\n// Platform admins see SSNs across every org\nmasking: { ssn: { type: 'ssn', show: { userRole: ['admin'] } } }\n```\n\n`userRole` works everywhere `Access` is accepted — CRUD, actions, views, masking, and inside `or` / `and` combinators. See [Access → userRole vs roles](/compiler/definitions/access#userrole-vs-roles).\n\n### CMS admin gate enforced server-side\n\n`cms: { access: \"admin\" }` previously only hid the CMS link in Account UI and rendered an \"Access Denied\" screen inside the SPA. Server-side enforcement now applies at every CMS-facing surface: the SPA shell, `/api/v1/schema`, and `custom_view` CRUD.\n\n### Better Auth 1.5 + `@cloudflare/workers-types` compatibility\n\nGenerated API code typechecks against the new versions. The org-member role-change broadcast hook is emitted via `organizationHooks.afterUpdateMemberRole` (the supported shape after the 1.5 deprecation of `databaseHooks.member.update.after`). `REALTIME_URL` and `ACCESS_TOKEN` are always emitted as optional bindings when the organization plugin is active.\n\n---\n\n## v0.8.4 — April 14, 2026\n\n### `generateId: \"short\"` strategy\n\nA compact ID option for tables where short, shareable codes matter more than collision resistance at scale:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", { generateId: \"short\" }),\n}\n```\n\nGenerates 6-character alphanumeric IDs (e.g. `a3F9xK`) using nanoid's `customAlphabet` with the full 62-char alphabet (`0-9A-Za-z`). Requires the `nanoid` package.\n\n**When to use:** room codes, invite links, share URLs, ephemeral records.\n\n**When not to use:** high-volume tables. 62^6 ≈ 56.8B combinations means ~238K rows before a 50% collision probability. For large tables stick with `\"uuid\"`, `\"cuid\"`, or `\"prefixed\"`. See [Providers → ID Generation Options](/compiler/config/providers#id-generation-options).\n\n---\n\n## v0.8.2 — April 11, 2026\n\n### Catch-all `VITE_QUICKBACK_URL`\n\nA single Quickback origin can be set in place of four separate URL env vars:\n\n```bash\nVITE_QUICKBACK_URL=https://secure.example.com\n```\n\n| Individual var (explicit) | Fallback when unset |\n|---|---|\n| `VITE_QUICKBACK_API_URL` | `${VITE_QUICKBACK_URL}` |\n| `VITE_QUICKBACK_ACCOUNT_URL` | `${VITE_QUICKBACK_URL}/account` |\n| `VITE_QUICKBACK_CMS_URL` | `${VITE_QUICKBACK_URL}/cms` |\n\n`VITE_QUICKBACK_APP_URL` stays independent — it points at the tenant's own frontend. Non-breaking; individual vars take precedence when set. Library users can set `__QUICKBACK_URL__` on `globalThis`. See [Environment Variables](/stack/account-ui/environment-variables).\n\n---\n\n## v0.8.1 — April 9, 2026\n\n### Role hierarchy with `+` suffix\n\nDefine a hierarchy and use `+` to mean \"this role and above\":\n\n```typescript\nauth: { roleHierarchy: ['member', 'admin', 'owner'] }\n\ncrud: {\n list: { access: { roles: [\"member+\"] } }, // member, admin, owner\n create: { access: { roles: [\"admin+\"] } }, // admin, owner\n delete: { access: { roles: [\"owner\"] } }, // owner only\n}\n```\n\nRoles are expanded at compile time. No `+` = exact match. See [Access → Role Hierarchy](/compiler/definitions/access#role-hierarchy).\n\n---\n\n## v0.8.0 — April 9, 2026\n\n### Breaking: VITE URL environment variables namespaced\n\nAll Quickback-generated URL environment variables are namespaced under `VITE_QUICKBACK_*` to avoid collisions with other Vite projects.\n\n| Old | New |\n|-----|-----|\n| `VITE_API_URL` | `VITE_QUICKBACK_API_URL` |\n| `VITE_ACCOUNT_URL` | `VITE_QUICKBACK_ACCOUNT_URL` |\n| `VITE_APP_URL` | `VITE_QUICKBACK_APP_URL` |\n| `VITE_CMS_URL` | `VITE_QUICKBACK_CMS_URL` |\n\nNon-URL variables are unchanged (`VITE_ENABLE_*`, branding vars, `VITE_STRIPE_PUBLISHABLE_KEY`).\n\n**Action required:**\n- Compiled projects: re-run `quickback compile`.\n- Standalone deploys: update `.env`, `.env.production`, and `wrangler.toml` files manually.\n- Library users: `__QUICKBACK_API_URL__` / `__QUICKBACK_APP_URL__` globals are unchanged.\n\n### CMS access control\n\n`cms.access: \"admin\"` enforces access at the CMS level, not just link visibility. Non-admin users (`user.role !== \"admin\"`) see an \"Access Denied\" screen with a sign-out button.\n\n---\n\n## v0.5.11 — February 24, 2026\n\n### Mandatory unsafe action audit trail\n\nStructured `unsafe` config (`unsafe: { reason, adminOnly, crossTenant, targetScope }`). Cross-tenant unsafe actions require Better Auth authentication plus platform admin role (`ctx.userRole === \"admin\"`). Mandatory audit logging on success, denial, and error paths. Cloudflare output includes `AUDIT_DB` wiring, `drizzle.audit.config.ts`, and `db:migrate:audit:*` scripts when unsafe actions are present.\n\nCompile-time raw SQL guard for actions and handlers (`allowRawSql: true` required per action).\n\n### Security contract report artifacts\n\nGenerated security contract artifacts: `reports/security-contracts.report.json`, `reports/security-contracts.report.sig.json`. Config-driven signing controls (`compiler.securityContracts.report.signature.*`). Missing required signing keys fail loudly with explicit remediation.\n\n### Headless Drizzle rename hints\n\n`compiler.migrations.renames` configuration for CI/CD environments where Drizzle's interactive rename prompts block compilation. See [Configuration](/compiler/config).\n\n### Minor\n\n- Email OTP magic links work correctly.\n- Auth is required for all API routes when running locally.\n- Single-file multi-table exports alongside `defineTable()` produce a clear error.\n\n---\n\n## v0.5.8 — February 14, 2026\n\n### Quickback CMS\n\nA schema-driven admin panel that connects to your generated API. The compiler now outputs a JSON schema registry consumed by the CMS at runtime. Firewall error modes (`reveal` for 403 with details, `hide` for opaque 404) are configurable per resource for security-sensitive deployments.\n\n---\n\n## v0.5.7 — February 12, 2026\n\n### Scoped database for actions\n\nActions receive a security-scoped database instead of a raw Drizzle instance. The compiler generates a proxy wrapper that automatically enforces org isolation, owner filtering, and soft-delete visibility — the same protections that CRUD routes have always had.\n\nDuck-typed column detection at runtime:\n\n| Column Detected | SELECT / UPDATE / DELETE | INSERT |\n|---|---|---|\n| `organizationId` | Adds `WHERE organizationId = ?` | Auto-injects `organizationId` from context |\n| `ownerId` | Adds `WHERE ownerId = ?` | Auto-injects `ownerId` from context |\n| `deletedAt` | Adds `WHERE deletedAt IS NULL` | — |\n\nEvery action is secure by default — no manual `WHERE` clauses needed.\n\nActions that intentionally need to bypass security (admin reports, cross-org queries, migrations) can declare `unsafe: true` to receive a raw, unscoped database handle via `rawDb`:\n\n```typescript\ndefineActions(analytics, {\n globalReport: {\n unsafe: true,\n execute: async ({ db, rawDb, ctx, input }) => {\n // db → still scoped (safety net)\n // rawDb → bypasses all security filters\n const allOrgs = await rawDb.select().from(organizations);\n },\n },\n});\n```\n\nWithout `unsafe: true`, `rawDb` is `undefined`. See [Actions](/compiler/definitions/actions).\n\n### Cascading soft delete\n\nSoft-deleting a parent record automatically cascades to child and junction tables within the same feature. The compiler detects foreign key references at build time and generates cascade `UPDATE` statements.\n\nRules:\n- Applies to soft delete only. Hard delete relies on database-level `ON DELETE CASCADE`.\n- Cascades within the same feature only — cross-feature references are not affected.\n- Child tables must have `deletedAt` / `deletedBy` columns (auto-added by the compiler).\n\nSee [Actions API → Cascading Soft Delete](/compiler/targets/hono-api/using-the-api/actions-api#cascading-soft-delete).\n\n### Advanced query parameters\n\nNew capabilities for all list endpoints:\n\n- **Field selection** — `?fields=id,name,status`\n- **Multi-sort** — `?sort=status:asc,createdAt:desc`\n- **Total count** — `?count=true` returns total matching records in `X-Total-Count`\n- **Full-text search** — `?search=keyword` searches across all text columns\n\nSee [Query Parameters](/compiler/targets/hono-api/using-the-api/query-params).\n\n---\n\n## v0.5.5 — February 5, 2026\n\n### OpenAPI spec generation\n\nGenerated APIs include a full OpenAPI specification at `/openapi.json`. Better Auth endpoints are included in the spec.\n\n### Better Auth plugins\n\nPublished `@quickback-dev/better-auth-upgrade-anonymous` (post-passkey email collection flow), `@quickback-dev/better-auth-combo-auth` (combined email + password + OTP), and `@quickback-dev/better-auth-aws-ses` (AWS SES email provider).\n\n### Security headers\n\nGlobal error handler prevents leaking internal error details. Security headers middleware (CSP, HSTS, X-Frame-Options, X-Content-Type-Options). `BETTER_AUTH_SECRET` properly passed to generated config.\n\n---\n\n## v0.5.4 — January 30, 2026\n\n### Account UI\n\nPre-built authentication UI deployed as Cloudflare Workers. Sessions, organizations, passkeys, passwordless, admin panel, API keys. Dual-mode: standalone (degit template) or embedded with Quickback projects.\n\n### Webhook system\n\nInbound webhook endpoints with signature verification. Outbound webhooks via Cloudflare Queues with automatic retries. Configurable per-feature webhook events.\n\n### Realtime & vector search\n\nDurable Objects + WebSocket realtime subscriptions. Vector embeddings via Cloudflare Vectorize. KV and R2 storage integrations.\n\n---\n\n## v0.5.0 — January 2026\n\n### Initial release\n\n- **Quickback Compiler** — TypeScript-first backend compiler.\n- **Four security pillars** — Firewall, Access, Guards, Masking.\n- **`defineTable()`** — schema + security configuration in a single file.\n- **Templates** — Cloudflare Workers, B2B SaaS.\n- **Cloud compiler** — remote compilation via `compiler.quickback.dev`.\n- **CLI** — `quickback create`, `quickback compile`.\n- **Better Auth integration** — organizations, roles, sessions.\n- **Drizzle ORM** — schema-first with automatic migrations.\n- **Cloudflare D1** — split database support (auth + features)."
7
7
  },
8
8
  "compiler/claude-code-skill": {
9
9
  "title": "AI Developer Tools",
@@ -75,11 +75,11 @@ 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 read and write operations and under what conditions.\n\n## Basic Usage\n\n```typescript\n// features/applications/applications.ts\n\nexport const applications = sqliteTable('applications', {\n id: text('id').primaryKey(),\n candidateId: text('candidate_id').notNull(),\n jobId: text('job_id').notNull(),\n stage: text('stage').notNull(),\n notes: text('notes'),\n organizationId: text('organization_id').notNull(),\n});\n\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: { createable: [\"candidateId\", \"jobId\", \"notes\"], updatable: [\"notes\"] },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n});\n```\n\n## Role Hierarchy\n\nIf your project uses a tiered role system (e.g., `member` < `admin` < `owner`), you can define a hierarchy in your config and use the `+` suffix to mean \"this role and above\":\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n name: \"my-app\",\n auth: {\n roleHierarchy: ['member', 'admin', 'owner'], // lowest → highest\n },\n // ...\n});\n```\n\nThen in your resource definitions:\n\n```typescript\nread: { access: { roles: [\"member+\"] } }, // member, admin, owner\ncreate: { access: { roles: [\"admin+\"] } }, // admin, owner\ndelete: { access: { roles: [\"owner\"] } }, // owner only (no +)\n```\n\nThe `+` suffix expands at compile time — `\"member+\"` becomes `[\"member\", \"admin\", \"owner\"]` in the generated code. You can mix hierarchical and exact roles: `roles: [\"member+\", \"finance\"]` expands to `[\"member\", \"admin\", \"owner\", \"finance\"]`.\n\n- Roles without `+` are exact matches (no expansion)\n- Pseudo-roles / reserved markers (`PUBLIC`, `AUTHENTICATED`, `USER`, `ADMIN`, `SYSADMIN`) cannot use the `+` suffix — they're terminal markers\n- Using `+` with a role not in the hierarchy throws a compile error\n- Using `+` without configuring `auth.roleHierarchy` throws a compile error\n\n## Configuration Options\n\n```typescript\ninterface Access {\n // Org-membership roles (OR logic — user needs at least one)\n // Matched against ctx.roles. Use \"role+\" suffix for hierarchy expansion.\n roles?: string[];\n\n // User-table role (OR logic). Matched against ctx.userRole from the\n // user.role column — independent of org membership. See userRole below.\n userRole?: string[];\n\n // Record-level conditions\n record?: {\n [field: string]: FieldCondition;\n };\n\n // Combinators\n or?: Access[];\n and?: Access[];\n}\n```\n\n## `userRole` vs `roles`\n\n`roles` and `userRole` check **two different fields** and are often confused — get this wrong and you'll grant access too broadly.\n\n| Primitive | Checks | Source | Example values |\n|-----------|--------|--------|----------------|\n| `roles` | `ctx.roles` | Org membership roles | `\"owner\"`, `\"admin\"`, `\"member\"` |\n| `userRole` | `ctx.userRole` | The `user.role` column (Better Auth / platform control-plane roles) | `\"user\"`, `\"appmanager\"`, `\"sysadmin\"` |\n\nIn multi-tenant mode, **`roles: [\"admin\"]` means \"org admin\" — not a platform-wide role.** An org-admin of Acme Corp has no elevated rights across other orgs. If you want platform control-plane operators through regardless of org membership (CMS, Better Auth admin surfaces, support tooling), use `userRole: [\"appmanager\"]`. If you need true cross-tenant data-plane access, use `roles: [\"SYSADMIN\"]` (with `cms: { sysadmin: true }`).\n\nPinned organization mode does not change this split. `roles` still come from organization membership in the pinned org, while `userRole` still comes from Better Auth's `user.role` column.\n\n### When to use `userRole`\n\n```typescript\n// Platform control-plane users can see SSNs on every customer record, regardless of org\nmasking: {\n ssn: { type: 'ssn', show: { userRole: ['appmanager'] } },\n}\n\n// Platform ops (user.role === 'appmanager') OR the org owner can refund\naccess: {\n or: [\n { userRole: ['appmanager'] },\n { roles: ['owner'] },\n ],\n}\n\n// CMS-internal resource: only platform control-plane users\nread: { access: { userRole: ['appmanager'] } },\ncreate: { access: { userRole: ['appmanager'] } },\nupdate: { access: { userRole: ['appmanager'] } },\ndelete: { access: { userRole: ['appmanager'] } },\n```\n\nWhen `roles` and `userRole` both appear in a single `Access` node, they're combined with AND — the user must satisfy both. Use `or:` to express \"one or the other\".\n\n`userRole` doesn't expand with the `+` hierarchy suffix — user-table roles are flat (typically just `\"user\"`, `\"appmanager\"`, and `\"sysadmin\"`). If you've added custom user-table roles via Better Auth, list them explicitly.\n\n### Pseudo-roles\n\nQuickback ships five reserved UPPERCASE markers. Four are real pseudo-roles handled directly by the compiler; `ADMIN` is retained only as a reserved legacy marker so the compiler can fail loudly with migration guidance. The casing carries the boundary: UPPERCASE = compiler-owned marker, lowercase = real role from a plugin's table (e.g. `members.role` from the org plugin).\n\n| Role | Auth gate | Compile-time requirement | Runtime check |\n|------|-----------|-------------------------|---------------|\n| `PUBLIC` | bypassed | none — explicit opt-in for unauthenticated access | always passes (auth skipped) |\n| `AUTHENTICATED` | required | none | `ctx.authenticated === true` |\n| `USER` | required | resource firewall **must** scope by `userId` | `ctx.authenticated` AND (`ctx.userRole` is unset OR `ctx.userRole === \"user\"`) |\n| `ADMIN` | required | reserved legacy marker — compiler rejects it | `false` |\n| `SYSADMIN` | required | `cms: { sysadmin: true }` **must** be set on the project | `ctx.authenticated && ctx.userRole === \"sysadmin\"` |\n\nYou can mix pseudo-roles with real roles in the same list — they're OR'd together.\n\n#### `PUBLIC` — unauthenticated access\n\nUse `roles: [\"PUBLIC\"]` for public-facing endpoints like contact forms, public listings, or webhooks. Skips both the auth gate and the role check.\n\n```typescript\naccess: { roles: [\"PUBLIC\"] }\n```\n\n**Important:**\n- `PUBLIC` skips authentication and role checks — anyone can call the endpoint\n- **`PUBLIC` is the explicit, uppercase opt-in for unauthenticated access.** It works on every access node — reads, top-level writes (`create`/`update`/`delete`/`upsert`), views, and actions. The compiler trusts the marker; row-level safety comes from the firewall, masking, and (for token-gated endpoints like RSVP confirm, magic-link redemption, List-Unsubscribe-Post, webhook ingest) your handler's own validation. Anonymous write endpoints typically pair `roles: [\"PUBLIC\"]` with `firewall: { exception: true }` on the resource so the row predicate doesn't reject every unauthenticated caller.\n- **Firewall still applies** — data is scoped by the firewall (organization, owner, team)\n- Every `PUBLIC` action invocation is **mandatory audit logged** to the security audit table (IP address, input, result, timing)\n- The wildcard `\"*\"` is **not supported** — using it throws a compile-time error\n- Tables with no isolation columns and any `PUBLIC` route do not require `firewall: [{ exception: true }]`\n\nFor org-scoped tables, `PUBLIC` routes still filter by organization. Since the user isn't authenticated, the organization ID must be passed as a query parameter:\n\n```\nGET /api/v1/listings?organizationId=org_abc123\n```\n\nThe firewall WHERE clause is always enforced. If no `organizationId` is provided, the API returns a `403` with code `ORG_REQUIRED`.\n\n```typescript\n// Public listing page — anyone can browse, but scoped to an org\nexport default defineTable(listings, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: { access: { roles: [\"PUBLIC\"] } }, // Public browsing + detail\n create: { access: { roles: [\"admin\", \"member\"] } }, // Auth required to create\n});\n```\n\n#### `AUTHENTICATED` — any signed-in user\n\nUse `roles: [\"AUTHENTICATED\"]` for endpoints that any logged-in user can hit, regardless of role or org membership. No plugin context required.\n\n```typescript\n// Public events feed — any signed-in user can list/read; anonymous gets 401\nread: { access: { roles: [\"AUTHENTICATED\"] } }\n```\n\n#### `USER` — per-user records\n\nUse `roles: [\"USER\"]` for resources where each user only sees their own records. **Requires the firewall to scope by `userId`** — the role marker is the access half of the pair, the firewall is the row-filter half.\n\n```typescript\n// \"My todos\" — each caller sees only their own rows\nexport default defineTable(todos, {\n firewall: [{ field: 'userId', equals: 'ctx.userId' }],\n read: { access: { roles: [\"USER\"] } },\n create: { access: { roles: [\"USER\"] } },\n update: { access: { roles: [\"USER\"] } },\n delete: { access: { roles: [\"USER\"] } },\n});\n```\n\nIf you forget the `userId` firewall predicate, the compiler throws:\n\n> `roles: [\"USER\"]` requires the resource to be scoped per-user. Add a `userId` column (auto-scoped) or an explicit owner predicate. If you want any signed-in user to read all records, use `roles: [\"AUTHENTICATED\"]` instead.\n\nWhen the Better Auth admin plugin is enabled, `USER` matches `user.role === \"user\"` specifically — appmanagers and sysadmins are excluded. If the same route should serve both, express it explicitly with `or: [{ roles: [\"USER\"] }, { userRole: [\"appmanager\"] }]`.\n\n#### `ADMIN` — legacy reserved marker (compile-time error)\n\n`roles: [\"ADMIN\"]` is no longer supported. The compiler fails hard on any use of `ADMIN` so platform and tenant roles can't be confused.\n\n```typescript\n// Platform control-plane audit log\nread: { access: { userRole: [\"appmanager\"] } }\n```\n\nUse one of these instead:\n\n- `userRole: [\"appmanager\"]` for platform control-plane access\n- `roles: [\"admin\"]` for org-membership admin access\n- `roles: [\"SYSADMIN\"]` for true cross-tenant access\n\n#### `SYSADMIN` — cross-tenant DB-admin tier\n\nUse `roles: [\"SYSADMIN\"]` for endpoints that should only be reachable by platform sysadmins — the cross-tenant DB-admin tier introduced in v0.15.0. Compiles to `ctx.userRole === \"sysadmin\"`. **Requires `cms: { sysadmin: true }` on the project config**; without that flag, using `SYSADMIN` fails the compile so the role can't sit as dead code.\n\n```typescript\n// Cross-tenant audit dashboard, sysadmin-only\nread: { access: { roles: [\"SYSADMIN\"] } }\n```\n\n`SYSADMIN` is distinct from `userRole: [\"appmanager\"]`. Appmanager is the platform control-plane tier (CMS shell, Better Auth admin surfaces, support tooling); sysadmin is the cross-tenant data-plane tier. The one place sysadmin gets implicit extra powers is **the firewall escape hatch**: when `cms.sysadmin: true`, every `buildFirewallConditions` emits an `if (ctx.userRole === 'sysadmin') return undefined;` (or just the soft-delete predicate when present) at the top — so sysadmins see every tenant's rows, not just their own org's. That escape hatch does NOT fire for `userRole === 'appmanager'`; appmanagers still go through the firewall like everyone else.\n\nThis separation exists so Better Auth admin-plugin powers (user management, impersonation, org creation) and DB-admin powers (cross-tenant data inspection) stay decoupled. A user can have `user.role === 'appmanager'` without DB-level cross-tenant access; a user can have `user.role === 'sysadmin'` without org-membership context. See [CMS Configuration](/compiler/config#cms-configuration) for the `cms.sysadmin` flag, the cross-tenant `/auth/v1/admin/list-organizations` endpoint, and the SPA's \"All organizations\" sentinel.\n\n#### Mixing pseudo-roles with real roles\n\nPseudo-roles and lowercase real roles compose with OR:\n\n```typescript\n// Record owner OR a platform control-plane user can read\nread: { access: { or: [{ roles: [\"USER\"] }, { userRole: [\"appmanager\"] }] } }\n\n// Org owner OR sysadmin\ndelete: { access: { or: [{ roles: [\"owner\"] }, { roles: [\"SYSADMIN\"] }] } }\n```\n\n> Note: `userRole: [\"appmanager\"]` never bypasses a `userId` firewall scope. If you need cross-user visibility, expose a separate route with `firewall: { exception: true }` or a `SYSADMIN`-gated cross-tenant surface.\n\n#### Quick reference\n\n```typescript\n// Unauthenticated public\naccess: { roles: [\"PUBLIC\"] }\n\n// Any signed-in user, no scoping\naccess: { roles: [\"AUTHENTICATED\"] }\n\n// Per-user records (requires userId firewall scope)\naccess: { roles: [\"USER\"] }\n\n// Platform control-plane\naccess: { userRole: [\"appmanager\"] }\n\n// Cross-tenant DB-admin tier\naccess: { roles: [\"SYSADMIN\"] }\n\n// Org-membership roles with hierarchy expansion\naccess: { roles: [\"member+\"] } // expands to [\"member\", \"admin\", \"owner\"]\naccess: { roles: [\"admin+\"] } // expands to [\"admin\", \"owner\"]\naccess: { roles: [\"admin\"] } // exact match (no expansion)\n```\n\n```typescript\n// Field conditions - value can be string | number | boolean\ntype FieldCondition =\n | { equals: value | '$ctx.userId' | '$ctx.activeOrgId' }\n | { notEquals: value }\n | { in: value[] }\n | { notIn: value[] }\n | { lessThan: number }\n | { greaterThan: number }\n | { lessThanOrEqual: number }\n | { greaterThanOrEqual: number };\n```\n\n## Relationship-based authorization\n\nBeyond Better Auth roles (org membership, user-table role) and pseudo-roles, Quickback supports **relationship-based authorization roles** — names that bind to a declared relationship between the caller and a resource. Use these when access should follow a domain-table membership (\"user is a confirmed guest of this event\") rather than an org/admin gate.\n\n### `authz.relationships`\n\nDeclare relationships once in `quickback.config.ts`:\n\n```typescript\n// quickback.config.ts\n\nexport default defineConfig({\n // ...providers...\n authz: {\n relationships: {\n guestOf: {\n from: 'event_guests', // table name string\n subject: { column: 'userId', equals: 'ctx.userId' }, // caller side\n resource: { column: 'eventId' }, // resource side\n where: { status: 'confirmed' }, // optional filter\n },\n },\n roles: {\n guest: { via: 'guestOf' },\n // Composite: any guest OR an org owner/admin\n eventStaff: {\n or: [\n { via: 'guestOf' },\n { roles: ['admin', 'owner'] },\n ],\n },\n },\n },\n});\n```\n\n### Using relationship-roles in resources\n\nResource definitions reference declared roles by name in `roles: [...]` arrays exactly like BA roles or pseudo-roles. The compiler rewrites the access tree at build time so the runtime route does an inline relationship lookup against the declared table.\n\n**Today (v1) this works on:**\n\n| Surface | Status | Notes |\n|---|---|---|\n| `firewall:` `via:` predicate | ✓ Supported | Subquery composes as outermost AND |\n| `crud.*.access` `roles: ['guest']` | ✓ Supported | Inline async lookup per request |\n| `read.access` / `read.views.*.access` `roles: ['guest']` | ✓ Supported | Same inline path |\n| `masking.<field>.show` `roles: ['guest']` | ⚠ Refused at compile | v1 limitation — async/batched mask functions deferred |\n| **Standalone** `actions.<name>.access` `roles: ['guest']` | ✓ Supported (v0.19+) | Inline gate; surface must expose `resource.column` as path param or input field |\n| **Record-based** `actions.<name>.access` `roles: ['guest']` | ⚠ Fail-closed at runtime | Runtime helper denies; inline emission is a planned follow-up. Use `firewall: { exception: true }` or move the check into `execute()` until then |\n\nFor the surfaces that are not yet supported, the compiler refuses at build time with a clear error pointing to a workaround. The runtime evaluator fails closed on relationship arms regardless, so silent grants are impossible.\n\n### Standalone actions: surface keys and `loads` / `exposeAs` (v0.19+)\n\nWhen a standalone action's `access.roles` references a relationship-role, the compiler emits a runtime gate between input validation and `execute()`. The gate reads the relationship's `resource.column` value from the action surface — either a path parameter (`:eventId`) or an input field (`input.eventId`). If neither is present, the compiler:\n\n- **v0.19** — emits a `[quickback:authz]` warning and skips resolver emission. The action's own hand-rolled gate (if any) keeps the route working at runtime.\n- **v0.20** — hard compile error. Set `firewall: { exception: true }` to opt out (cross-tenant/admin routes only).\n\nPair the relationship with `loads` + `exposeAs` to hydrate the loaded resource onto `ctx`:\n\n```typescript\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events', // ← v0.19+: load matching event row\n exposeAs: 'event', // ← onto ctx.event for the action body\n },\n },\n roles: {\n attendee: { via: 'attendeeOf' },\n },\n}\n```\n\nThe resolver (v0.20):\n\n1. **Cheap in-memory role check** first — `ctx.roles?.includes('admin')` and friends. If the caller has a qualifying role, this short-circuits and no DB queries fire for the access gate.\n2. **Firewall-gated relationship match** if the role check failed — `SELECT { organizationId, teamId } FROM guests WHERE userId=ctx.userId AND eventId=input.eventId AND status='confirmed'` with the `guests` table's full firewall AND-applied. If neither role nor relationship qualifies → 403.\n3. **Tenant stamping from the matched row** — for any tenant column the `from` table carries (`organizationId`, `teamId`), the resolver stamps `ctx.activeOrgId ??= matchedRow.organizationId` (and similar for team). This is **in-memory mutation of the request-scoped ctx only** — no JWT remint, no session-record write, no persistent grant.\n4. **Firewall-gated load of the loaded resource** — `SELECT * FROM events WHERE id = :eventId AND buildEventsFirewallConditions(ctx, db)`. The events firewall is applied as normal; it succeeds for attendees because tenant was just stamped from the relationship row.\n5. Assigns the loaded row to `ctx.event` for the action body.\n\n**No firewall bypass anywhere.** Both queries run with their respective tables' full firewalls. The relationship row's existence is the proof that the caller is authorized; its tenant columns are the source of the stamped claim.\n\n### Conditional tenant preconditions (v0.20+)\n\nStandalone actions in features with org/team-scoped tables previously emitted unconditional preconditions:\n\n```ts\nif (!ctx.activeOrgId) return c.json(AccessErrors.noOrg(), 403);\nif (!ctx.activeTeamId) return c.json(AccessErrors.noTeam(), 403);\n```\n\nThese ran **before** the relationship resolver, which 403'd attendees whose sessions don't carry an active tenant claim (the canonical event-attendee shape).\n\nv0.20 makes these preconditions **conditional on relationship supply**. If the access tree contains a relationship arm whose `from` table carries the matching tenant column, the precondition is skipped — the resolver runs first and stamps the value. Pseudo-role short-circuits (PUBLIC / AUTHENTICATED / USER / SYSADMIN) and `firewall: { exception: true }` still bypass the preconditions as before. `ADMIN` is now rejected at compile time.\n\nTypical event-attendee setup (`guests` table carries `organizationId`): the org precondition is dropped on every action whose access references `attendee` or `eventStaff`. Org admins still get `ctx.activeOrgId` from their session as today; attendees get it from the relationship row, mid-request. Both paths converge on a valid tenant claim before `execute()` runs.\n\n### Requirement on the relationship's `from` table\n\nFor the v0.20 tenant-stamping to work, the relationship's `from` table must carry tenant columns:\n\n- For org stamping: an `organizationId` column (or whatever spelling the project's auth-provider defaults pick).\n- For team stamping: a `teamId` column.\n\nWhen the `from` table has **neither**, the compiler emits a `[quickback:authz]` warning at compile time:\n\n```\nRelationship \"X\" at authz.relationships.X has no organization or team columns\non its `from` table (\"guests\"). Action \"Y\" will compile, but downstream\nscoped-db queries inside execute() may 403 because ctx.activeOrgId /\nactiveTeamId cannot be stamped from the match row. Either add the tenant\ncolumn to \"guests\", or set firewall: { exception: true } on the action.\n```\n\nThe relationship match still works (existence check), but no tenant gets stamped — so the conventional precondition still fires and the action still 403s for callers without a session-resident tenant claim. Add the tenant column (or denormalize it onto the relationship table during writes) to enable the stamping path.\n\nThe body can then trust `ctx.event` and drop the hand-rolled `SELECT … FROM guests WHERE …` boilerplate:\n\n```ts\n// features/chat/actions/getInbox.ts\nexport default defineAction({\n path: '/chat/get-inbox',\n input: z.object({ eventId: z.number().int().positive() }),\n access: { roles: ['admin', 'member', 'attendee'] }, // attendee is a relationship-role\n execute: async ({ db, ctx, input }) => {\n // No hand-rolled attendance check needed — the resolver already ran.\n // ctx.event is the loaded events row. Typed as `any` here because the\n // hand-rolled `roles: ['attendee']` action gates per-action, not per-\n // namespace — see \"Narrow ctx.<exposeAs> typing\" below for the typed\n // import flip available when the same hydration runs through a\n // namespace mount.\n const event = ctx.event as typeof events.$inferSelect;\n // … domain logic only.\n },\n});\n```\n\n`loads` and `exposeAs` are co-required (set both or neither). `exposeAs` must be a valid JS identifier and must not collide with built-in `ctx` fields (`userId`, `activeOrgId`, `activeTeamId`, `db`, etc.).\n\n### Action firewall escape hatch (v0.19+)\n\n`defineAction({ firewall: { exception: true } })` opts the action out of the inherited session-key preconditions (`ctx.activeOrgId` / `ctx.activeTeamId` requirements) AND the relationship resolver. The handler receives `unsafeDb` for raw Drizzle access. Use for cross-tenant or admin routes whose surface intentionally doesn't name a session/relationship key:\n\n```ts\ndefineAction({\n path: '/admin/cross-tenant-report',\n firewall: { exception: true },\n unsafe: { reason: 'cross-tenant audit', adminOnly: true, targetScope: 'all' },\n access: { roles: ['ADMIN'] },\n execute: async ({ unsafeDb, ctx }) => { /* cross-org query */ },\n});\n```\n\n`firewall: { exception: true }` is the declarative twin of `unsafe: true` — they're conceptually distinct: `firewall.exception` opts out of the gate-emission pillars; `unsafe` signals audit/cross-tenant intent (and still applies for logging). Most cross-tenant actions set both.\n\n### Recommended pattern: gate at the firewall layer\n\nMost of the time, relationship-based row visibility is what you want, and putting it at the **firewall** layer is the cleanest expression. The firewall is row-filter; the access layer is route/role-filter; let each do its job:\n\n```typescript\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' }, // ← row visibility\n],\nread: {\n access: { roles: ['admin', 'member'] }, // ← who can hit the route\n views: {\n cms: { access: { roles: ['admin', 'member'] }, fields: [...] },\n guest: { access: { roles: ['member', 'admin'] }, fields: [...] },\n },\n},\n```\n\nA guest who's in your org as `member` can hit the endpoint and the firewall filters them down to events they're guests of. Cross-tenant access is impossible because the org filter is the outermost AND.\n\n### Cross-tenant \"my events\" dashboards are NOT this\n\nA common adjacent pattern — \"logged-in user wants `GET /my-events` returning events they're a guest of *across all tenants*\" — is **not** solved by relationship-roles. The tenant firewall is enforced at the outermost AND, so a guest of an event in another tenant remains correctly blocked.\n\nFor cross-tenant aggregation, use one of:\n\n- **User-scoped firewall**: `firewall: { owner: { column: 'userId' } }` — a flat per-user table.\n- **A standalone action that walks the relationship table itself** — see worked example below.\n\nDon't reach for relationship-roles first and then get confused when the tenant firewall blocks. The two patterns serve different problems.\n\n#### Worked example: `GET /my-events` standalone action\n\nThe cleanest expression of the cross-tenant attendee dashboard is a standalone action with a custom path that does its own join against the relationship table. The action is gated by `roles: ['AUTHENTICATED']` (any signed-in user can hit it; per-row scoping is the query itself), and the SQL filters by `ctx.userId` so each caller sees exactly the events they're a guest of:\n\n```ts\n// features/dashboard/actions/myEvents.ts\n\nexport default defineAction({\n description: \"List events the caller is a confirmed guest of, across all tenants.\",\n path: '/my-events',\n method: 'GET',\n input: z.object({}),\n // Any signed-in user. Row visibility comes from the query, not the role.\n access: { roles: ['AUTHENTICATED'] },\n async execute({ db, ctx }) {\n // 1. Find every event the caller has a confirmed guest row for.\n const guestRows = await db\n .select({ eventId: guests.eventId })\n .from(guests)\n .where(\n and(\n eq(guests.userId, ctx.userId!),\n eq(guests.status, 'confirmed'),\n // guests.organizationId is NOT filtered here — that's the whole\n // point of the cross-tenant lane. The relationship row's org is\n // ambient information that this action explicitly traverses.\n )\n );\n\n if (guestRows.length === 0) return { events: [] };\n\n // 2. Pull the matching events. NOTE: this query also bypasses\n // `events.organizationId` scope — by design — so explicitly filter\n // out soft-deleted rows yourself if your `events` table uses them.\n const eventIds = guestRows.map((r) => r.eventId);\n const rows = await db\n .select()\n .from(events)\n .where(inArray(events.id, eventIds));\n\n return { events: rows };\n },\n});\n```\n\nWhy this is a standalone action and not a CRUD route:\n\n- **Tenant firewall would block it.** The default `firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }]` on `events` is correct for every other read — only the cross-tenant dashboard wants to step outside it, and that's a deliberate, explicit step taken in handler code.\n- **The join is the access control.** A relationship-role at the firewall layer can't express \"filter by this user's relationships, ignoring the org context.\" The handler does that join directly.\n- **Audit-logged automatically.** Standalone actions are mandatorily audit-logged in the runtime — the cross-tenant traversal is recorded with `ctx.userId`, IP, and timing.\n\nTwo important guardrails when you write one of these:\n\n1. **Always filter by `ctx.userId` in the relationship lookup.** If you accept a `userId` from the request body and trust it, you've built an IDOR. The example above uses `ctx.userId!` directly so the only events returned are the caller's.\n2. **You take responsibility for soft-delete and other invariants the firewall would otherwise apply.** Add the `deletedAt` filter, status checks, and any other row-level predicates by hand. The action is OUTSIDE the firewall pipeline by design — the cost is that you can't lean on the auto-applied predicates.\n\nIf you find yourself writing more than one of these per project, that's usually a signal to revisit the schema (could a user-owned `userEvents` materialized view replace the join?) rather than a sign Quickback should ship a higher-level abstraction. Cross-tenant lanes are intentionally explicit.\n\n### Compile-time refusals (consolidated)\n\nThe validator and resolver reject:\n\n- Unknown key in `authz` block (typo guard — `realtionships` would otherwise silently produce a permanently-denied role).\n- Reserved role-name (auth-provider-derived). Names like `guest`, `speaker`, `attendee` are free; `admin`/`owner`/`member` are reserved when the BA org plugin is on.\n- Cycle in role composition (`a → b → a`).\n- Relationship `from` references unknown table.\n- Relationship-role used on a resource missing the `resource.column`.\n- Relationship table with `firewall: { exception: true }` (would let cross-tenant grants slip through).\n- `lowering: 'session'` (reserved for v2 — staleness/invalidation ergonomics not yet shipped).\n- `+` hierarchy suffix on a relationship-role name (terminal, like pseudo-roles).\n- Relationship-roles in `masking.show` / `actions.access` (deferred surfaces — see the table above).\n\n## Namespace mounts (hoisted relationship middleware)\n\nWhen several standalone actions share a path prefix and the same relationship gate — `/event/:eventId/announce`, `/event/:eventId/cancel`, `/event/:eventId/respond` — declaring the gate per-action means writing the same `roles: ['attendee']` over and over AND paying the relationship-resolver cost N times per request (one subquery + one row-load, multiplied by the number of actions).\n\nNamespace mounts hoist the resolver into one Hono middleware that runs once per request. Every action under the prefix skips the inline gate; `ctx.<exposeAs>` is hydrated by the middleware before the action's `execute()` runs. With the per-namespace helper (v0.27+, [below](#narrow-ctxexposeas-typing-v027)), that field is also statically typed as the loaded row.\n\n### When to use roles vs. relationships\n\nA user is authorized for a row when **any** of the following is true:\n\n- they have a **per-row relationship** to it (e.g. an attendee row, a named organizer row), or\n- they have a **role on the row's tenant** (org admin/owner of the row's `organizationId`), or\n- they have **team membership** matching the row's `teamId`.\n\nUse **relationships** when membership is specific to *this row* — external collaborators who aren't in your org, attendees, anyone connected to the resource by virtue of data rather than payroll. Use **roles / team** when staff at your org/team should see everything in their scope by default.\n\nThe two compose at the action level (`access.or` accepts both relationship-roles and tenant roles) and — as of v0.25 — at the namespace level too: `namespace.via` accepts an array of lanes, first match wins.\n\n> **Rule of thumb.** If the answer is *\"yes if you work here,\"* reach for org/team roles. If the answer is *\"yes if you have something to do with **this** row,\"* reach for a per-row relationship. Reach for both together — at the namespace or via `access.or` — when an action should let either side in.\n\nTwo declaration sites depending on whether the participating actions live in one feature or many:\n\n### Single feature: `defineTable({ namespace })` (v0.23+)\n\nUse when every action under the prefix lives in the same feature directory. The namespace travels with the table that owns it — no addition to `quickback.config.ts` needed.\n\n```typescript\n// features/events/events.ts\nexport default defineTable(events, {\n firewall: [...],\n crud: { ... },\n namespace: {\n prefix: '/event/:eventId', // absolute URL path\n via: 'attendeeOf', // relationship gate (must exist in authz.relationships)\n },\n});\n\n// features/events/actions/post-announcement.ts\nexport default defineAction({\n path: '/event/:eventId/announcements',\n method: 'POST',\n // No gate boilerplate. ctx.event is typed inside execute().\n});\n```\n\nThe compiler emits one `app.use(...)` on the events feature's Hono app. Every standalone action in `features/events/actions/` whose path starts with `/event/:eventId/` joins the namespace automatically.\n\nMulti-lane via (v0.25+) and bulk-grant lanes (v0.26+) work identically on the table-level declaration — `via:` accepts the same shapes documented below for the project-level form.\n\n### Cross-feature: `authz.namespaces` (v0.24+)\n\nUse when the namespace spans multiple features. The declaration sits next to your other authz config in `quickback.config.ts`.\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n namespaces: {\n eventScope: { prefix: '/event/:eventId', via: 'attendeeOf' },\n },\n}\n```\n\nWith the namespace declared, any standalone action whose `path:` matches the prefix joins the gate — regardless of which feature owns it:\n\n```typescript\n// features/feeds/actions/feed-moments.ts (in one feature)\nexport default defineAction({\n path: '/event/:eventId/feed-moments',\n method: 'POST',\n});\n\n// features/rsvp/actions/respond.ts (in a different feature)\nexport default defineAction({\n path: '/event/:eventId/respond',\n method: 'POST',\n});\n```\n\nThe compiler emits one synthetic `src/routes/__namespace-event-scope.routes.ts` that imports each contributing feature's `actions` map under a distinct alias, mounts the resolver middleware once, and dispatches to the matching action. Worker-root mount order ensures the middleware fires before any per-feature route handler under the prefix.\n\n### Multi-lane via (v0.25+) — first match wins\n\nWhen more than one relationship can authorize a caller for the namespaced resource, pass `via:` as an array. The middleware tries each lane in declaration order and stops at the first match — `ctx.<exposeAs>` is hydrated from whichever lane fired.\n\n```typescript\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'linkedUserId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events',\n exposeAs: 'event',\n },\n // Named per-event organizers (potentially EXTERNAL — these users may\n // not be a member of the event's org. That's the point: lets you grant\n // event-level access to freelancers / partner staff without adding\n // them to the org's member list.)\n organizerOf: {\n from: 'eventOrganizers',\n subject: { column: 'linkedUserId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n namespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: ['attendeeOf', 'organizerOf'],\n },\n },\n}\n```\n\nAll relationship lanes in a namespace **must agree on `loads:` + `exposeAs:`** — that's what guarantees `ctx.event` has the same shape regardless of which lane matched. The compiler rejects heterogeneous lanes at parse time.\n\n### Bulk-grant lanes (v0.26+)\n\nRelationship lanes cover \"specifically connected to this row.\" Bulk-grant lanes cover \"anyone with this role / team membership in the row's tenant\" — the case where an org admin or a team member should see every event in their scope without writing per-event relationship rows.\n\n```typescript\nnamespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: [\n 'attendeeOf',\n 'organizerOf',\n { roles: ['admin', 'owner'] }, // org-role bulk grant\n { team: true }, // active-team-membership bulk grant\n ],\n },\n}\n```\n\nEach bulk-grant lane:\n\n- **`{ roles: [...] }`** — passes when the caller's BA org-role for the loaded resource's tenant includes any listed role. Short-circuits the relationship loop entirely; the role check is in-memory and cheap. Use for the \"company admin sees everything\" case.\n- **`{ team: true }`** — passes when `ctx.activeTeamId` is set. The loads-table firewall does the actual `events.teamId === ctx.activeTeamId` check during hydration. Use when the resource is team-scoped and you want active-team membership to grant access.\n\nBoth bulk-grant lanes piggyback on the namespace's relationship lane(s) for hydration — they don't fetch a separate per-row subject; they just gate access and let the loads-table firewall handle the tenant scoping. **At least one relationship lane is required** alongside bulk-grant lanes in v0.26 (to anchor `loads:` + `exposeAs:`).\n\nWhen a request misses every lane, the 403 deny payload lists every authorization path the caller could have taken — relationship names, role names, and `\"team-membership\"` for `{ team: true }` lanes — so a developer debugging an unexpected 403 sees the full surface they need to satisfy.\n\n### Discovery is path-prefix-only\n\nActions opt in by matching `path:` against a declared namespace prefix. There's no `namespace: 'foo'` field on `defineAction` — the path string is the discoverable surface, consistent with how `path:` already determines an action's URL.\n\n### Requirements (enforced at compile time)\n\nBoth forms share the same shape checks:\n\n- **`via:` accepts one of three shapes.** A single relationship name (v0.23+), an array of relationship names (v0.25+, first match wins), or — as of v0.26 — an array mixing relationship names with bulk-grant guards (`{ roles: [...] }`, `{ team: true }`).\n- **Every relationship lane must declare `loads + exposeAs`.** Without `loads` there's nothing for the middleware to hydrate; the namespace gate would be indistinguishable from a per-action access rule.\n- **All relationship lanes in one namespace must agree on `loads:` + `exposeAs:`.** Otherwise `ctx.<exposeAs>` would change shape depending on which lane matched.\n- **Bulk-grant lanes inherit `loads:` + `exposeAs:` from sibling relationship lanes.** Pure bulk-grant namespaces (no relationship lane at all) are also accepted — set `loads:` + `exposeAs:` directly on the namespace declaration so hydration has somewhere to anchor.\n- **`prefix:` must contain at least one `:param` segment** (e.g. `/event/:eventId`). The middleware reads the relationship key from `c.req.param()` because no request body has been parsed at middleware time.\n- **One declaration per namespace name.** The same name in both `defineTable({ namespace })` and `authz.namespaces` is rejected. The project-level form is canonical for cross-feature; the table-level form is the single-feature shorthand.\n\nProject-level only:\n\n- **Ambiguous prefixes** like `/a/:x` and `/a/:y` (same shape, different `:param` names) are rejected. Strict super/sub-set relationships (`/event/:e` vs `/event/:e/admin`) are fine — the harvester routes each action to the longest matching prefix.\n- **Unused namespace** emits a `[quickback:authz]` warning when no action's path matches the declared prefix. Not a hard error — the namespace may be staged ahead of the actions.\n\n### What namespace actions get for free\n\nInside a namespace action's `execute()`:\n\n- `ctx.<exposeAs>` is populated by the middleware with the loaded resource row. Statically `any` by default — narrowed to `typeof <loadsTable>.$inferSelect` when the action's import points at the per-namespace helper (see [below](#narrow-ctxexposeas-typing-v027)).\n- Tenant context (`ctx.activeOrgId` / `ctx.activeTeamId`) is stamped from the matched relationship row when its `from` table carries those columns. Downstream scoped queries work without further setup.\n- The action's own `access:` block (additional roles, userRole, record predicates, OTHER relationship arms) still runs after the namespace gate — namespace handles entry, per-action gates further.\n\n### Narrow `ctx.<exposeAs>` typing (v0.27+)\n\nThe namespace middleware hydrates `ctx.<exposeAs>` at runtime — that's been true since v0.23. The static type of that field, though, is `any` via the `AppContext` index signature: useful for not blocking access, but a missed opportunity for autocomplete and typo-catching.\n\nv0.27 emits one **per-namespace `defineAction` helper** alongside the standard `<feature>/.quickback/define-action.ts`. Importing from the narrowed helper retypes `ctx.<exposeAs>` inside `execute({ ctx })` to the loaded row's `$inferSelect` shape. Nothing else changes — runtime behavior, action discovery, and the `path:` namespace match are identical.\n\n```ts title=\"features/feeds/actions/feed-moments.ts\"\n// One-line flip per namespace-scoped action:\n\n// └──────┬──────┘\n// kebab(namespaceName)\n\nexport default defineAction({\n path: '/event/:eventId/feed-moments',\n method: 'POST',\n input: z.object({ body: z.string() }),\n access: { roles: ['attendee'] },\n async execute({ ctx, input }) {\n ctx.event.id // ✓ string\n ctx.event.startsAt // ✓ Date — autocomplete works\n ctx.event.organizerId // ✓ narrows on the field's declared type\n\n ctx.event.idd // ✗ TS2339 — typo caught at compile time\n },\n});\n```\n\nThe compiler emits one helper per `(feature, namespace)` pair where the feature owns at least one action whose `path:` falls under the namespace prefix. Filename is `define-action.<kebab(namespaceName)>.ts` — `eventScope` becomes `define-action.event-scope.ts`. Helpers live next to the standard `define-action.ts` in `<feature>/.quickback/`, so the relative import is the same shape as every other action file in your project.\n\n#### Opt-in, not breaking\n\nActions that keep their existing `import { defineAction } from '../.quickback/define-action'` continue to compile unchanged — `ctx.<exposeAs>` is `any` via the `AppContext` index signature, which is exactly the v0.23–v0.26 behavior. You flip imports per action at your own pace.\n\n#### Compile-time advisory\n\nWhen `quickback compile` sees a namespace-scoped action still importing the generic helper, it emits a one-line advisory pointing at the narrowed path:\n\n```text\n[quickback:typing] action \"feedMoments\" in feature \"feeds\" lives under\n namespace \"eventScope\" — switch its import to\n `../.quickback/define-action.event-scope` for narrow ctx.<exposeAs> typing.\n (Runtime behavior is unchanged; the narrowed helper only refines TS types.)\n```\n\nNon-blocking — same `[quickback:typing]` family as `[quickback:authz]`. The advisory only mentions actions the compiler can be confident about (namespace-claimed actions whose source still imports the generic helper).\n\n#### Multi-namespace features\n\nA single feature can contribute actions to several namespaces — say, an `interviews` feature with actions under both `interviewScope` and `eventScope`. The compiler emits one narrowed helper per namespace the feature participates in, and each action picks the import that matches its path.\n\n```text\nsrc/features/interviews/.quickback/\n├── define-action.ts # generic — standard fallback\n├── define-action.interview-scope.ts # ctx.interview typed\n└── define-action.event-scope.ts # ctx.event typed\n```\n\n#### Why per-namespace and not per-action\n\nA `defineAction` helper that's narrow to *one* exposed key (the namespace's `exposeAs`) is enough — every action under a namespace sees the same hydrated key. The alternative (per-action emit) duplicates the same prelude N times for the same shape; per-namespace keeps emission proportional to the number of distinct hydration shapes in the project.\n\n## Read & Write Configuration\n\nReads (`GET /` and `GET /:id`) live under `read:`; mutations live under top-level `create:`, `update:`, `delete:`, and `upsert:`. See [Read](/compiler/definitions/read) for the full read pipeline reference.\n\n```typescript\nread: {\n // LIST + GET - GET /resource and GET /resource/:id\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n pageSize: 25, // Default page size\n maxPageSize: 100, // Client can't exceed this\n views: { // Per-view field projections\n summary: {\n fields: ['id', 'candidateId', 'jobId', 'stage'],\n access: { roles: [\"interviewer\"] },\n },\n },\n}\n\ncreate: {\n // CREATE - POST /resource\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] },\n defaults: { // Default values for new records\n stage: 'applied',\n },\n},\n\nupdate: {\n // UPDATE - PATCH /resource/:id\n access: {\n or: [\n { roles: [\"hiring-manager\", \"recruiter\"] },\n { roles: [\"interviewer\"], record: { stage: { equals: \"interview\" } } }\n ]\n },\n},\n\ndelete: {\n // DELETE - DELETE /resource/:id\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"soft\", // 'soft' (default) or 'hard'\n},\n\nupsert: {\n // PUT - PUT /resource/:id (only when generateId: false + guards: false)\n access: { roles: [\"hiring-manager\", \"sync-service\"] },\n}\n```\n\n## Evaluation Order\n\nGenerated `/:id` and batch handlers evaluate access in this fixed order:\n\n1. **Auth gate** — 401 if unauthenticated\n2. **Pre-record access** — role-only check (skips `access.record` predicates)\n3. **Firewall query** — `WHERE` clause filters by ownership\n4. **Post-record access** — full check including record-level predicates\n5. **Masking** — applied to the response\n\nStep 2 closes the 404-vs-403 ID-probe channel: an unauthorized caller without\na matching role gets 403 before the database is touched, so they can't tell\napart \"row exists out-of-scope\" from \"row doesn't exist.\" A caller with the\nright role but the wrong tenant gets 403 by default (firewall reveals via\nthe access layer); set\n[`firewallErrorMode: 'hide'`](/compiler/definitions/firewall) to return an\nopaque 404 instead.\n\nFunction-form access (`access: async (ctx, record) => ...`) is opaque to\nthe pre-record phase and always passes there; it's fully evaluated post-record.\n\n## List Filtering (Query Parameters)\n\nThe LIST endpoint automatically supports filtering via query params:\n\n```\nGET /jobs?status=open # Exact match\nGET /jobs?salaryMin.gt=50000 # Greater than\nGET /jobs?salaryMin.gte=50000 # Greater than or equal\nGET /jobs?salaryMax.lt=200000 # Less than\nGET /jobs?salaryMax.lte=200000 # Less than or equal\nGET /jobs?status.ne=closed # Not equal\nGET /jobs?title.like=Engineer # Pattern match (LIKE %value%)\nGET /jobs?status.in=open,draft # IN clause\n```\n\n| Operator | Query Param | SQL Equivalent |\n|----------|-------------|----------------|\n| Equals | `?field=value` | `WHERE field = value` |\n| Not equals | `?field.ne=value` | `WHERE field != value` |\n| Greater than | `?field.gt=value` | `WHERE field > value` |\n| Greater or equal | `?field.gte=value` | `WHERE field >= value` |\n| Less than | `?field.lt=value` | `WHERE field < value` |\n| Less or equal | `?field.lte=value` | `WHERE field <= value` |\n| Pattern match | `?field.like=value` | `WHERE field LIKE '%value%'` |\n| In list | `?field.in=a,b,c` | `WHERE field IN ('a','b','c')` |\n\n## Sorting & Pagination\n\n```\nGET /jobs?sort=createdAt&order=desc # Sort by field\nGET /jobs?limit=25&offset=50 # Pagination\n```\n\n- **Default limit**: 50\n- **Max limit**: 100 (or `maxPageSize` if configured)\n- **Default order**: `asc`\n\n## Delete Modes\n\n```typescript\ndelete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"soft\", // Sets deletedAt/deletedBy, record stays in DB\n}\n\ndelete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"hard\", // Permanent deletion from database\n}\n```\n\n## Context Variables\n\nUse `$ctx.` prefix to reference context values in conditions:\n\n```typescript\n// User can only view their own records\naccess: {\n record: { userId: { equals: \"$ctx.userId\" } }\n}\n\n// Nested path support for complex context objects\naccess: {\n record: { ownerId: { equals: \"$ctx.user.id\" } }\n}\n```\n\n### AppContext Reference\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `$ctx.userId` | `string` | Current authenticated user's ID |\n| `$ctx.activeOrgId` | `string` | User's active organization ID |\n| `$ctx.activeTeamId` | `string \\| null` | User's active team ID (if applicable) |\n| `$ctx.roles` | `string[]` | User's roles in current context |\n| `$ctx.isAnonymous` | `boolean` | Whether user is anonymous |\n| `$ctx.user` | `object` | Full user object from auth provider |\n| `$ctx.user.id` | `string` | User ID (nested path example) |\n| `$ctx.user.email` | `string` | User's email address |\n| `$ctx.{property}` | `any` | Any custom context property |\n\n## Function-Based Access\n\nFor complex access logic that can't be expressed declaratively, use a function:\n\n```typescript\nupdate: {\n access: async (ctx, record) => {\n // Custom logic - return true to allow, false to deny\n if (ctx.roles.includes('admin')) return true;\n if (record.ownerId === ctx.userId) return true;\n\n // Check custom business logic\n const membership = await checkTeamMembership(ctx.userId, record.teamId);\n return membership.canEdit;\n }\n}\n```\n\nFunction access receives:\n- `ctx`: The full AppContext object\n- `record`: The record being accessed (for get/update/delete operations)"
78
+ "content": "Define who can perform read and write operations and under what conditions.\n\n## Basic Usage\n\n```typescript\n// features/applications/applications.ts\n\nexport const applications = sqliteTable('applications', {\n id: text('id').primaryKey(),\n candidateId: text('candidate_id').notNull(),\n jobId: text('job_id').notNull(),\n stage: text('stage').notNull(),\n notes: text('notes'),\n organizationId: text('organization_id').notNull(),\n});\n\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: { createable: [\"candidateId\", \"jobId\", \"notes\"], updatable: [\"notes\"] },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n});\n```\n\n## Role Hierarchy\n\nIf your project uses a tiered role system (e.g., `member` < `admin` < `owner`), you can define a hierarchy in your config and use the `+` suffix to mean \"this role and above\":\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n name: \"my-app\",\n auth: {\n roleHierarchy: ['member', 'admin', 'owner'], // lowest → highest\n },\n // ...\n});\n```\n\nThen in your resource definitions:\n\n```typescript\nread: { access: { roles: [\"member+\"] } }, // member, admin, owner\ncreate: { access: { roles: [\"admin+\"] } }, // admin, owner\ndelete: { access: { roles: [\"owner\"] } }, // owner only (no +)\n```\n\nThe `+` suffix expands at compile time — `\"member+\"` becomes `[\"member\", \"admin\", \"owner\"]` in the generated code. You can mix hierarchical and exact roles: `roles: [\"member+\", \"finance\"]` expands to `[\"member\", \"admin\", \"owner\", \"finance\"]`.\n\n- Roles without `+` are exact matches (no expansion)\n- Pseudo-roles / reserved markers (`PUBLIC`, `AUTHENTICATED`, `USER`, `ADMIN`, `SYSADMIN`) cannot use the `+` suffix — they're terminal markers\n- Using `+` with a role not in the hierarchy throws a compile error\n- Using `+` without configuring `auth.roleHierarchy` throws a compile error\n\n## Custom org roles\n\nYou're not limited to Better Auth's built-in `owner` / `admin` / `member` —\nany lowercase role name you reference in an access tree (`\"recruiter\"`,\n`\"hiring-manager\"`, `\"support\"`, …) is a custom org-membership role, matched\nagainst `ctx.roles` like the built-ins.\n\nAs of v0.46, custom roles declared in access trees are **auto-registered\nwith the Better Auth organization plugin**, so members can actually be\nprovisioned into them: `invite-member` and `update-member-role` accept them\n(previously they rejected custom roles with `400 ROLE_NOT_FOUND`).\nAuto-registered roles carry member-equivalent Better Auth permissions —\nregistration is about assignability; your access trees remain the\nauthorization model. If you pass your own `roles` / `ac` to the organization\nplugin options, those win and auto-registration is skipped.\n\n## Configuration Options\n\n```typescript\ninterface Access {\n // Org-membership roles (OR logic — user needs at least one)\n // Matched against ctx.roles. Use \"role+\" suffix for hierarchy expansion.\n roles?: string[];\n\n // User-table role (OR logic). Matched against ctx.userRole from the\n // user.role column — independent of org membership. See userRole below.\n userRole?: string[];\n\n // Record-level conditions\n record?: {\n [field: string]: FieldCondition;\n };\n\n // Combinators\n or?: Access[];\n and?: Access[];\n}\n```\n\n## `userRole` vs `roles`\n\n`roles` and `userRole` check **two different fields** and are often confused — get this wrong and you'll grant access too broadly.\n\n| Primitive | Checks | Source | Example values |\n|-----------|--------|--------|----------------|\n| `roles` | `ctx.roles` | Org membership roles | `\"owner\"`, `\"admin\"`, `\"member\"` |\n| `userRole` | `ctx.userRole` | The `user.role` column (Better Auth / platform control-plane roles) | `\"user\"`, `\"appmanager\"`, `\"sysadmin\"` |\n\nIn multi-tenant mode, **`roles: [\"admin\"]` means \"org admin\" — not a platform-wide role.** An org-admin of Acme Corp has no elevated rights across other orgs. If you want platform control-plane operators through regardless of org membership (CMS, Better Auth admin surfaces, support tooling), use `userRole: [\"appmanager\"]`. If you need true cross-tenant data-plane access, use `roles: [\"SYSADMIN\"]` (with `cms: { sysadmin: true }`).\n\nPinned organization mode does not change this split. `roles` still come from organization membership in the pinned org, while `userRole` still comes from Better Auth's `user.role` column.\n\n### When to use `userRole`\n\n```typescript\n// Platform control-plane users can see SSNs on every customer record, regardless of org\nmasking: {\n ssn: { type: 'ssn', show: { userRole: ['appmanager'] } },\n}\n\n// Platform ops (user.role === 'appmanager') OR the org owner can refund\naccess: {\n or: [\n { userRole: ['appmanager'] },\n { roles: ['owner'] },\n ],\n}\n\n// CMS-internal resource: only platform control-plane users\nread: { access: { userRole: ['appmanager'] } },\ncreate: { access: { userRole: ['appmanager'] } },\nupdate: { access: { userRole: ['appmanager'] } },\ndelete: { access: { userRole: ['appmanager'] } },\n```\n\nWhen `roles` and `userRole` both appear in a single `Access` node, they're combined with AND — the user must satisfy both. Use `or:` to express \"one or the other\".\n\n`userRole` doesn't expand with the `+` hierarchy suffix — user-table roles are flat (typically just `\"user\"`, `\"appmanager\"`, and `\"sysadmin\"`). If you've added custom user-table roles via Better Auth, list them explicitly.\n\n### Pseudo-roles\n\nQuickback ships five reserved UPPERCASE markers. Four are real pseudo-roles handled directly by the compiler; `ADMIN` is retained only as a reserved legacy marker so the compiler can fail loudly with migration guidance. The casing carries the boundary: UPPERCASE = compiler-owned marker, lowercase = real role from a plugin's table (e.g. `members.role` from the org plugin).\n\n| Role | Auth gate | Compile-time requirement | Runtime check |\n|------|-----------|-------------------------|---------------|\n| `PUBLIC` | bypassed | none — explicit opt-in for unauthenticated access | always passes (auth skipped) |\n| `AUTHENTICATED` | required | none | `ctx.authenticated === true` |\n| `USER` | required | resource firewall **must** scope by `userId` | `ctx.authenticated` AND (`ctx.userRole` is unset OR `ctx.userRole === \"user\"`) |\n| `ADMIN` | required | reserved legacy marker — compiler rejects it | `false` |\n| `SYSADMIN` | required | `cms: { sysadmin: true }` **must** be set on the project | `ctx.authenticated && ctx.userRole === \"sysadmin\"` |\n\nYou can mix pseudo-roles with real roles in the same list — they're OR'd together.\n\n#### `PUBLIC` — unauthenticated access\n\nUse `roles: [\"PUBLIC\"]` for public-facing endpoints like contact forms, public listings, or webhooks. Skips both the auth gate and the role check.\n\n```typescript\naccess: { roles: [\"PUBLIC\"] }\n```\n\n**Important:**\n- `PUBLIC` skips authentication and role checks — anyone can call the endpoint\n- **`PUBLIC` is the explicit, uppercase opt-in for unauthenticated access.** It works on every access node — reads, top-level writes (`create`/`update`/`delete`/`upsert`), views, and actions. The compiler trusts the marker; row-level safety comes from the firewall, masking, and (for token-gated endpoints like RSVP confirm, magic-link redemption, List-Unsubscribe-Post, webhook ingest) your handler's own validation. Anonymous write endpoints typically pair `roles: [\"PUBLIC\"]` with `firewall: { exception: true }` on the resource so the row predicate doesn't reject every unauthenticated caller.\n- **Firewall still applies** — data is scoped by the firewall (organization, owner, team)\n- **Tree semantics:** `PUBLIC` admits anonymous callers from anywhere in the access tree, not just a flat `roles` list. An `or:` arm containing `PUBLIC` admits anonymous callers past the authentication gate; an `and:` group admits them only when *every* arm does. The access, org, and firewall layers still evaluate the full tree afterwards. (Before v0.46 the emitted auth gate only honored `PUBLIC` in a flat `roles` list — a nested `PUBLIC` arm incorrectly answered `401`.)\n- Every `PUBLIC` action invocation is **mandatory audit logged** to the security audit table (IP address, input, result, timing)\n- The wildcard `\"*\"` is **not supported** — using it throws a compile-time error\n- Tables with no isolation columns and any `PUBLIC` route do not require `firewall: [{ exception: true }]`\n\nFor org-scoped tables, `PUBLIC` routes still filter by organization. Since the user isn't authenticated, the organization ID must be passed as a query parameter:\n\n```\nGET /api/v1/listings?organizationId=org_abc123\n```\n\nThe firewall WHERE clause is always enforced. If no `organizationId` is provided, the API returns a `403` with code `ORG_REQUIRED`.\n\n```typescript\n// Public listing page — anyone can browse, but scoped to an org\nexport default defineTable(listings, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: { access: { roles: [\"PUBLIC\"] } }, // Public browsing + detail\n create: { access: { roles: [\"admin\", \"member\"] } }, // Auth required to create\n});\n```\n\n#### `AUTHENTICATED` — any signed-in user\n\nUse `roles: [\"AUTHENTICATED\"]` for endpoints that any logged-in user can hit, regardless of role or org membership. No plugin context required.\n\n```typescript\n// Public events feed — any signed-in user can list/read; anonymous gets 401\nread: { access: { roles: [\"AUTHENTICATED\"] } }\n```\n\n#### `USER` — per-user records\n\nUse `roles: [\"USER\"]` for resources where each user only sees their own records. **Requires the firewall to scope by `userId`** — the role marker is the access half of the pair, the firewall is the row-filter half.\n\n```typescript\n// \"My todos\" — each caller sees only their own rows\nexport default defineTable(todos, {\n firewall: [{ field: 'userId', equals: 'ctx.userId' }],\n read: { access: { roles: [\"USER\"] } },\n create: { access: { roles: [\"USER\"] } },\n update: { access: { roles: [\"USER\"] } },\n delete: { access: { roles: [\"USER\"] } },\n});\n```\n\nIf you forget the `userId` firewall predicate, the compiler throws:\n\n> `roles: [\"USER\"]` requires the resource to be scoped per-user. Add a `userId` column (auto-scoped) or an explicit owner predicate. If you want any signed-in user to read all records, use `roles: [\"AUTHENTICATED\"]` instead.\n\nWhen the Better Auth admin plugin is enabled, `USER` matches `user.role === \"user\"` specifically — appmanagers and sysadmins are excluded. If the same route should serve both, express it explicitly with `or: [{ roles: [\"USER\"] }, { userRole: [\"appmanager\"] }]`.\n\n#### `ADMIN` — legacy reserved marker (compile-time error)\n\n`roles: [\"ADMIN\"]` is no longer supported. The compiler fails hard on any use of `ADMIN` so platform and tenant roles can't be confused.\n\n```typescript\n// Platform control-plane audit log\nread: { access: { userRole: [\"appmanager\"] } }\n```\n\nUse one of these instead:\n\n- `userRole: [\"appmanager\"]` for platform control-plane access\n- `roles: [\"admin\"]` for org-membership admin access\n- `roles: [\"SYSADMIN\"]` for true cross-tenant access\n\n#### `SYSADMIN` — cross-tenant DB-admin tier\n\nUse `roles: [\"SYSADMIN\"]` for endpoints that should only be reachable by platform sysadmins — the cross-tenant DB-admin tier introduced in v0.15.0. Compiles to `ctx.userRole === \"sysadmin\"`. **Requires `cms: { sysadmin: true }` on the project config**; without that flag, using `SYSADMIN` fails the compile so the role can't sit as dead code.\n\n```typescript\n// Cross-tenant audit dashboard, sysadmin-only\nread: { access: { roles: [\"SYSADMIN\"] } }\n```\n\n`SYSADMIN` is distinct from `userRole: [\"appmanager\"]`. Appmanager is the platform control-plane tier (CMS shell, Better Auth admin surfaces, support tooling); sysadmin is the cross-tenant data-plane tier. The one place sysadmin gets implicit extra powers is **the firewall escape hatch**: when `cms.sysadmin: true`, every `buildFirewallConditions` emits an `if (ctx.userRole === 'sysadmin') return undefined;` (or just the soft-delete predicate when present) at the top — so sysadmins see every tenant's rows, not just their own org's. That escape hatch does NOT fire for `userRole === 'appmanager'`; appmanagers still go through the firewall like everyone else.\n\nThis separation exists so Better Auth admin-plugin powers (user management, impersonation, org creation) and DB-admin powers (cross-tenant data inspection) stay decoupled. A user can have `user.role === 'appmanager'` without DB-level cross-tenant access; a user can have `user.role === 'sysadmin'` without org-membership context. See [CMS Configuration](/compiler/config#cms-configuration) for the `cms.sysadmin` flag, the cross-tenant `/auth/v1/admin/list-organizations` endpoint, and the SPA's \"All organizations\" sentinel.\n\n#### Mixing pseudo-roles with real roles\n\nPseudo-roles and lowercase real roles compose with OR:\n\n```typescript\n// Record owner OR a platform control-plane user can read\nread: { access: { or: [{ roles: [\"USER\"] }, { userRole: [\"appmanager\"] }] } }\n\n// Org owner OR sysadmin\ndelete: { access: { or: [{ roles: [\"owner\"] }, { roles: [\"SYSADMIN\"] }] } }\n```\n\n> Note: `userRole: [\"appmanager\"]` never bypasses a `userId` firewall scope. If you need cross-user visibility, expose a separate route with `firewall: { exception: true }` or a `SYSADMIN`-gated cross-tenant surface.\n\n#### Quick reference\n\n```typescript\n// Unauthenticated public\naccess: { roles: [\"PUBLIC\"] }\n\n// Any signed-in user, no scoping\naccess: { roles: [\"AUTHENTICATED\"] }\n\n// Per-user records (requires userId firewall scope)\naccess: { roles: [\"USER\"] }\n\n// Platform control-plane\naccess: { userRole: [\"appmanager\"] }\n\n// Cross-tenant DB-admin tier\naccess: { roles: [\"SYSADMIN\"] }\n\n// Org-membership roles with hierarchy expansion\naccess: { roles: [\"member+\"] } // expands to [\"member\", \"admin\", \"owner\"]\naccess: { roles: [\"admin+\"] } // expands to [\"admin\", \"owner\"]\naccess: { roles: [\"admin\"] } // exact match (no expansion)\n```\n\n```typescript\n// Field conditions - value can be string | number | boolean\ntype FieldCondition =\n | { equals: value | '$ctx.userId' | '$ctx.activeOrgId' }\n | { notEquals: value }\n | { in: value[] }\n | { notIn: value[] }\n | { lessThan: number }\n | { greaterThan: number }\n | { lessThanOrEqual: number }\n | { greaterThanOrEqual: number };\n```\n\n## Relationship-based authorization\n\nBeyond Better Auth roles (org membership, user-table role) and pseudo-roles, Quickback supports **relationship-based authorization roles** — names that bind to a declared relationship between the caller and a resource. Use these when access should follow a domain-table membership (\"user is a confirmed guest of this event\") rather than an org/admin gate.\n\n### `authz.relationships`\n\nDeclare relationships once in `quickback.config.ts`:\n\n```typescript\n// quickback.config.ts\n\nexport default defineConfig({\n // ...providers...\n authz: {\n relationships: {\n guestOf: {\n from: 'event_guests', // table name string\n subject: { column: 'userId', equals: 'ctx.userId' }, // caller side\n resource: { column: 'eventId' }, // resource side\n where: { status: 'confirmed' }, // optional filter\n },\n },\n roles: {\n guest: { via: 'guestOf' },\n // Composite: any guest OR an org owner/admin\n eventStaff: {\n or: [\n { via: 'guestOf' },\n { roles: ['admin', 'owner'] },\n ],\n },\n },\n },\n});\n```\n\n### Using relationship-roles in resources\n\nResource definitions reference declared roles by name in `roles: [...]` arrays exactly like BA roles or pseudo-roles. The compiler rewrites the access tree at build time so the runtime route does an inline relationship lookup against the declared table.\n\n**Today (v1) this works on:**\n\n| Surface | Status | Notes |\n|---|---|---|\n| `firewall:` `via:` predicate | ✓ Supported | Subquery composes as outermost AND |\n| `crud.*.access` `roles: ['guest']` | ✓ Supported | Inline async lookup per request |\n| `read.access` / `read.views.*.access` `roles: ['guest']` | ✓ Supported | Same inline path |\n| `masking.<field>.show` `roles: ['guest']` | ⚠ Refused at compile | v1 limitation — async/batched mask functions deferred |\n| **Standalone** `actions.<name>.access` `roles: ['guest']` | ✓ Supported (v0.19+) | Inline gate; surface must expose `resource.column` as path param or input field |\n| **Record-based** `actions.<name>.access` `roles: ['guest']` | ⚠ Fail-closed at runtime | Runtime helper denies; inline emission is a planned follow-up. Use `firewall: { exception: true }` or move the check into `execute()` until then |\n\nFor the surfaces that are not yet supported, the compiler refuses at build time with a clear error pointing to a workaround. The runtime evaluator fails closed on relationship arms regardless, so silent grants are impossible.\n\n### Standalone actions: surface keys and `loads` / `exposeAs` (v0.19+)\n\nWhen a standalone action's `access.roles` references a relationship-role, the compiler emits a runtime gate between input validation and `execute()`. The gate reads the relationship's `resource.column` value from the action surface — either a path parameter (`:eventId`) or an input field (`input.eventId`). If neither is present, the compiler:\n\n- **v0.19** — emits a `[quickback:authz]` warning and skips resolver emission. The action's own hand-rolled gate (if any) keeps the route working at runtime.\n- **v0.20** — hard compile error. Set `firewall: { exception: true }` to opt out (cross-tenant/admin routes only).\n\nPair the relationship with `loads` + `exposeAs` to hydrate the loaded resource onto `ctx`:\n\n```typescript\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events', // ← v0.19+: load matching event row\n exposeAs: 'event', // ← onto ctx.event for the action body\n },\n },\n roles: {\n attendee: { via: 'attendeeOf' },\n },\n}\n```\n\nThe resolver (v0.20):\n\n1. **Cheap in-memory role check** first — `ctx.roles?.includes('admin')` and friends. If the caller has a qualifying role, this short-circuits and no DB queries fire for the access gate.\n2. **Firewall-gated relationship match** if the role check failed — `SELECT { organizationId, teamId } FROM guests WHERE userId=ctx.userId AND eventId=input.eventId AND status='confirmed'` with the `guests` table's full firewall AND-applied. If neither role nor relationship qualifies → 403.\n3. **Tenant stamping from the matched row** — for any tenant column the `from` table carries (`organizationId`, `teamId`), the resolver stamps `ctx.activeOrgId ??= matchedRow.organizationId` (and similar for team). This is **in-memory mutation of the request-scoped ctx only** — no JWT remint, no session-record write, no persistent grant.\n4. **Firewall-gated load of the loaded resource** — `SELECT * FROM events WHERE id = :eventId AND buildEventsFirewallConditions(ctx, db)`. The events firewall is applied as normal; it succeeds for attendees because tenant was just stamped from the relationship row.\n5. Assigns the loaded row to `ctx.event` for the action body.\n\n**No firewall bypass anywhere.** Both queries run with their respective tables' full firewalls. The relationship row's existence is the proof that the caller is authorized; its tenant columns are the source of the stamped claim.\n\n### Conditional tenant preconditions (v0.20+)\n\nStandalone actions in features with org/team-scoped tables previously emitted unconditional preconditions:\n\n```ts\nif (!ctx.activeOrgId) return c.json(AccessErrors.noOrg(), 403);\nif (!ctx.activeTeamId) return c.json(AccessErrors.noTeam(), 403);\n```\n\nThese ran **before** the relationship resolver, which 403'd attendees whose sessions don't carry an active tenant claim (the canonical event-attendee shape).\n\nv0.20 makes these preconditions **conditional on relationship supply**. If the access tree contains a relationship arm whose `from` table carries the matching tenant column, the precondition is skipped — the resolver runs first and stamps the value. Pseudo-role short-circuits (PUBLIC / AUTHENTICATED / USER / SYSADMIN) and `firewall: { exception: true }` still bypass the preconditions as before. `ADMIN` is now rejected at compile time.\n\nTypical event-attendee setup (`guests` table carries `organizationId`): the org precondition is dropped on every action whose access references `attendee` or `eventStaff`. Org admins still get `ctx.activeOrgId` from their session as today; attendees get it from the relationship row, mid-request. Both paths converge on a valid tenant claim before `execute()` runs.\n\n### Requirement on the relationship's `from` table\n\nFor the v0.20 tenant-stamping to work, the relationship's `from` table must carry tenant columns:\n\n- For org stamping: an `organizationId` column (or whatever spelling the project's auth-provider defaults pick).\n- For team stamping: a `teamId` column.\n\nWhen the `from` table has **neither**, the compiler emits a `[quickback:authz]` warning at compile time:\n\n```\nRelationship \"X\" at authz.relationships.X has no organization or team columns\non its `from` table (\"guests\"). Action \"Y\" will compile, but downstream\nscoped-db queries inside execute() may 403 because ctx.activeOrgId /\nactiveTeamId cannot be stamped from the match row. Either add the tenant\ncolumn to \"guests\", or set firewall: { exception: true } on the action.\n```\n\nThe relationship match still works (existence check), but no tenant gets stamped — so the conventional precondition still fires and the action still 403s for callers without a session-resident tenant claim. Add the tenant column (or denormalize it onto the relationship table during writes) to enable the stamping path.\n\nThe body can then trust `ctx.event` and drop the hand-rolled `SELECT … FROM guests WHERE …` boilerplate:\n\n```ts\n// features/chat/actions/getInbox.ts\nexport default defineAction({\n path: '/chat/get-inbox',\n input: z.object({ eventId: z.number().int().positive() }),\n access: { roles: ['admin', 'member', 'attendee'] }, // attendee is a relationship-role\n execute: async ({ db, ctx, input }) => {\n // No hand-rolled attendance check needed — the resolver already ran.\n // ctx.event is the loaded events row. Typed as `any` here because the\n // hand-rolled `roles: ['attendee']` action gates per-action, not per-\n // namespace — see \"Narrow ctx.<exposeAs> typing\" below for the typed\n // import flip available when the same hydration runs through a\n // namespace mount.\n const event = ctx.event as typeof events.$inferSelect;\n // … domain logic only.\n },\n});\n```\n\n`loads` and `exposeAs` are co-required (set both or neither). `exposeAs` must be a valid JS identifier and must not collide with built-in `ctx` fields (`userId`, `activeOrgId`, `activeTeamId`, `db`, etc.).\n\n### Action firewall escape hatch (v0.19+)\n\n`defineAction({ firewall: { exception: true } })` opts the action out of the inherited session-key preconditions (`ctx.activeOrgId` / `ctx.activeTeamId` requirements) AND the relationship resolver. The handler receives `unsafeDb` for raw Drizzle access. Use for cross-tenant or admin routes whose surface intentionally doesn't name a session/relationship key:\n\n```ts\ndefineAction({\n path: '/admin/cross-tenant-report',\n firewall: { exception: true },\n unsafe: { reason: 'cross-tenant audit', adminOnly: true, targetScope: 'all' },\n access: { roles: ['ADMIN'] },\n execute: async ({ unsafeDb, ctx }) => { /* cross-org query */ },\n});\n```\n\n`firewall: { exception: true }` is the declarative twin of `unsafe: true` — they're conceptually distinct: `firewall.exception` opts out of the gate-emission pillars; `unsafe` signals audit/cross-tenant intent (and still applies for logging). Most cross-tenant actions set both.\n\n### Recommended pattern: gate at the firewall layer\n\nMost of the time, relationship-based row visibility is what you want, and putting it at the **firewall** layer is the cleanest expression. The firewall is row-filter; the access layer is route/role-filter; let each do its job:\n\n```typescript\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' }, // ← row visibility\n],\nread: {\n access: { roles: ['admin', 'member'] }, // ← who can hit the route\n views: {\n cms: { access: { roles: ['admin', 'member'] }, fields: [...] },\n guest: { access: { roles: ['member', 'admin'] }, fields: [...] },\n },\n},\n```\n\nA guest who's in your org as `member` can hit the endpoint and the firewall filters them down to events they're guests of. Cross-tenant access is impossible because the org filter is the outermost AND.\n\n### Cross-tenant \"my events\" dashboards are NOT this\n\nA common adjacent pattern — \"logged-in user wants `GET /my-events` returning events they're a guest of *across all tenants*\" — is **not** solved by relationship-roles. The tenant firewall is enforced at the outermost AND, so a guest of an event in another tenant remains correctly blocked.\n\nFor cross-tenant aggregation, use one of:\n\n- **User-scoped firewall**: `firewall: { owner: { column: 'userId' } }` — a flat per-user table.\n- **A standalone action that walks the relationship table itself** — see worked example below.\n\nDon't reach for relationship-roles first and then get confused when the tenant firewall blocks. The two patterns serve different problems.\n\n#### Worked example: `GET /my-events` standalone action\n\nThe cleanest expression of the cross-tenant attendee dashboard is a standalone action with a custom path that does its own join against the relationship table. The action is gated by `roles: ['AUTHENTICATED']` (any signed-in user can hit it; per-row scoping is the query itself), and the SQL filters by `ctx.userId` so each caller sees exactly the events they're a guest of:\n\n```ts\n// features/dashboard/actions/myEvents.ts\n\nexport default defineAction({\n description: \"List events the caller is a confirmed guest of, across all tenants.\",\n path: '/my-events',\n method: 'GET',\n input: z.object({}),\n // Any signed-in user. Row visibility comes from the query, not the role.\n access: { roles: ['AUTHENTICATED'] },\n async execute({ db, ctx }) {\n // 1. Find every event the caller has a confirmed guest row for.\n const guestRows = await db\n .select({ eventId: guests.eventId })\n .from(guests)\n .where(\n and(\n eq(guests.userId, ctx.userId!),\n eq(guests.status, 'confirmed'),\n // guests.organizationId is NOT filtered here — that's the whole\n // point of the cross-tenant lane. The relationship row's org is\n // ambient information that this action explicitly traverses.\n )\n );\n\n if (guestRows.length === 0) return { events: [] };\n\n // 2. Pull the matching events. NOTE: this query also bypasses\n // `events.organizationId` scope — by design — so explicitly filter\n // out soft-deleted rows yourself if your `events` table uses them.\n const eventIds = guestRows.map((r) => r.eventId);\n const rows = await db\n .select()\n .from(events)\n .where(inArray(events.id, eventIds));\n\n return { events: rows };\n },\n});\n```\n\nWhy this is a standalone action and not a CRUD route:\n\n- **Tenant firewall would block it.** The default `firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }]` on `events` is correct for every other read — only the cross-tenant dashboard wants to step outside it, and that's a deliberate, explicit step taken in handler code.\n- **The join is the access control.** A relationship-role at the firewall layer can't express \"filter by this user's relationships, ignoring the org context.\" The handler does that join directly.\n- **Audit-logged automatically.** Standalone actions are mandatorily audit-logged in the runtime — the cross-tenant traversal is recorded with `ctx.userId`, IP, and timing.\n\nTwo important guardrails when you write one of these:\n\n1. **Always filter by `ctx.userId` in the relationship lookup.** If you accept a `userId` from the request body and trust it, you've built an IDOR. The example above uses `ctx.userId!` directly so the only events returned are the caller's.\n2. **You take responsibility for soft-delete and other invariants the firewall would otherwise apply.** Add the `deletedAt` filter, status checks, and any other row-level predicates by hand. The action is OUTSIDE the firewall pipeline by design — the cost is that you can't lean on the auto-applied predicates.\n\nIf you find yourself writing more than one of these per project, that's usually a signal to revisit the schema (could a user-owned `userEvents` materialized view replace the join?) rather than a sign Quickback should ship a higher-level abstraction. Cross-tenant lanes are intentionally explicit.\n\n### Compile-time refusals (consolidated)\n\nThe validator and resolver reject:\n\n- Unknown key in `authz` block (typo guard — `realtionships` would otherwise silently produce a permanently-denied role).\n- Reserved role-name (auth-provider-derived). Names like `guest`, `speaker`, `attendee` are free; `admin`/`owner`/`member` are reserved when the BA org plugin is on.\n- Cycle in role composition (`a → b → a`).\n- Relationship `from` references unknown table.\n- Relationship-role used on a resource missing the `resource.column`.\n- Relationship table with `firewall: { exception: true }` (would let cross-tenant grants slip through).\n- `lowering: 'session'` (reserved for v2 — staleness/invalidation ergonomics not yet shipped).\n- `+` hierarchy suffix on a relationship-role name (terminal, like pseudo-roles).\n- Relationship-roles in `masking.show` / `actions.access` (deferred surfaces — see the table above).\n\n## Namespace mounts (hoisted relationship middleware)\n\nWhen several standalone actions share a path prefix and the same relationship gate — `/event/:eventId/announce`, `/event/:eventId/cancel`, `/event/:eventId/respond` — declaring the gate per-action means writing the same `roles: ['attendee']` over and over AND paying the relationship-resolver cost N times per request (one subquery + one row-load, multiplied by the number of actions).\n\nNamespace mounts hoist the resolver into one Hono middleware that runs once per request. Every action under the prefix skips the inline gate; `ctx.<exposeAs>` is hydrated by the middleware before the action's `execute()` runs. With the per-namespace helper (v0.27+, [below](#narrow-ctxexposeas-typing-v027)), that field is also statically typed as the loaded row.\n\n### When to use roles vs. relationships\n\nA user is authorized for a row when **any** of the following is true:\n\n- they have a **per-row relationship** to it (e.g. an attendee row, a named organizer row), or\n- they have a **role on the row's tenant** (org admin/owner of the row's `organizationId`), or\n- they have **team membership** matching the row's `teamId`.\n\nUse **relationships** when membership is specific to *this row* — external collaborators who aren't in your org, attendees, anyone connected to the resource by virtue of data rather than payroll. Use **roles / team** when staff at your org/team should see everything in their scope by default.\n\nThe two compose at the action level (`access.or` accepts both relationship-roles and tenant roles) and — as of v0.25 — at the namespace level too: `namespace.via` accepts an array of lanes, first match wins.\n\n> **Rule of thumb.** If the answer is *\"yes if you work here,\"* reach for org/team roles. If the answer is *\"yes if you have something to do with **this** row,\"* reach for a per-row relationship. Reach for both together — at the namespace or via `access.or` — when an action should let either side in.\n\nTwo declaration sites depending on whether the participating actions live in one feature or many:\n\n### Single feature: `defineTable({ namespace })` (v0.23+)\n\nUse when every action under the prefix lives in the same feature directory. The namespace travels with the table that owns it — no addition to `quickback.config.ts` needed.\n\n```typescript\n// features/events/events.ts\nexport default defineTable(events, {\n firewall: [...],\n crud: { ... },\n namespace: {\n prefix: '/event/:eventId', // absolute URL path\n via: 'attendeeOf', // relationship gate (must exist in authz.relationships)\n },\n});\n\n// features/events/actions/post-announcement.ts\nexport default defineAction({\n path: '/event/:eventId/announcements',\n method: 'POST',\n // No gate boilerplate. ctx.event is typed inside execute().\n});\n```\n\nThe compiler emits one `app.use(...)` on the events feature's Hono app. Every standalone action in `features/events/actions/` whose path starts with `/event/:eventId/` joins the namespace automatically.\n\nMulti-lane via (v0.25+) and bulk-grant lanes (v0.26+) work identically on the table-level declaration — `via:` accepts the same shapes documented below for the project-level form.\n\n### Cross-feature: `authz.namespaces` (v0.24+)\n\nUse when the namespace spans multiple features. The declaration sits next to your other authz config in `quickback.config.ts`.\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n namespaces: {\n eventScope: { prefix: '/event/:eventId', via: 'attendeeOf' },\n },\n}\n```\n\nWith the namespace declared, any standalone action whose `path:` matches the prefix joins the gate — regardless of which feature owns it:\n\n```typescript\n// features/feeds/actions/feed-moments.ts (in one feature)\nexport default defineAction({\n path: '/event/:eventId/feed-moments',\n method: 'POST',\n});\n\n// features/rsvp/actions/respond.ts (in a different feature)\nexport default defineAction({\n path: '/event/:eventId/respond',\n method: 'POST',\n});\n```\n\nThe compiler emits one synthetic `src/routes/__namespace-event-scope.routes.ts` that imports each contributing feature's `actions` map under a distinct alias, mounts the resolver middleware once, and dispatches to the matching action. Worker-root mount order ensures the middleware fires before any per-feature route handler under the prefix.\n\n### Multi-lane via (v0.25+) — first match wins\n\nWhen more than one relationship can authorize a caller for the namespaced resource, pass `via:` as an array. The middleware tries each lane in declaration order and stops at the first match — `ctx.<exposeAs>` is hydrated from whichever lane fired.\n\n```typescript\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'linkedUserId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events',\n exposeAs: 'event',\n },\n // Named per-event organizers (potentially EXTERNAL — these users may\n // not be a member of the event's org. That's the point: lets you grant\n // event-level access to freelancers / partner staff without adding\n // them to the org's member list.)\n organizerOf: {\n from: 'eventOrganizers',\n subject: { column: 'linkedUserId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n namespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: ['attendeeOf', 'organizerOf'],\n },\n },\n}\n```\n\nAll relationship lanes in a namespace **must agree on `loads:` + `exposeAs:`** — that's what guarantees `ctx.event` has the same shape regardless of which lane matched. The compiler rejects heterogeneous lanes at parse time.\n\n### Bulk-grant lanes (v0.26+)\n\nRelationship lanes cover \"specifically connected to this row.\" Bulk-grant lanes cover \"anyone with this role / team membership in the row's tenant\" — the case where an org admin or a team member should see every event in their scope without writing per-event relationship rows.\n\n```typescript\nnamespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: [\n 'attendeeOf',\n 'organizerOf',\n { roles: ['admin', 'owner'] }, // org-role bulk grant\n { team: true }, // active-team-membership bulk grant\n ],\n },\n}\n```\n\nEach bulk-grant lane:\n\n- **`{ roles: [...] }`** — passes when the caller's BA org-role for the loaded resource's tenant includes any listed role. Short-circuits the relationship loop entirely; the role check is in-memory and cheap. Use for the \"company admin sees everything\" case.\n- **`{ team: true }`** — passes when `ctx.activeTeamId` is set. The loads-table firewall does the actual `events.teamId === ctx.activeTeamId` check during hydration. Use when the resource is team-scoped and you want active-team membership to grant access.\n\nBoth bulk-grant lanes piggyback on the namespace's relationship lane(s) for hydration — they don't fetch a separate per-row subject; they just gate access and let the loads-table firewall handle the tenant scoping. **At least one relationship lane is required** alongside bulk-grant lanes in v0.26 (to anchor `loads:` + `exposeAs:`).\n\nWhen a request misses every lane, the 403 deny payload lists every authorization path the caller could have taken — relationship names, role names, and `\"team-membership\"` for `{ team: true }` lanes — so a developer debugging an unexpected 403 sees the full surface they need to satisfy.\n\n### Discovery is path-prefix-only\n\nActions opt in by matching `path:` against a declared namespace prefix. There's no `namespace: 'foo'` field on `defineAction` — the path string is the discoverable surface, consistent with how `path:` already determines an action's URL.\n\n### Requirements (enforced at compile time)\n\nBoth forms share the same shape checks:\n\n- **`via:` accepts one of three shapes.** A single relationship name (v0.23+), an array of relationship names (v0.25+, first match wins), or — as of v0.26 — an array mixing relationship names with bulk-grant guards (`{ roles: [...] }`, `{ team: true }`).\n- **Every relationship lane must declare `loads + exposeAs`.** Without `loads` there's nothing for the middleware to hydrate; the namespace gate would be indistinguishable from a per-action access rule.\n- **All relationship lanes in one namespace must agree on `loads:` + `exposeAs:`.** Otherwise `ctx.<exposeAs>` would change shape depending on which lane matched.\n- **Bulk-grant lanes inherit `loads:` + `exposeAs:` from sibling relationship lanes.** Pure bulk-grant namespaces (no relationship lane at all) are also accepted — set `loads:` + `exposeAs:` directly on the namespace declaration so hydration has somewhere to anchor.\n- **`prefix:` must contain at least one `:param` segment** (e.g. `/event/:eventId`). The middleware reads the relationship key from `c.req.param()` because no request body has been parsed at middleware time.\n- **One declaration per namespace name.** The same name in both `defineTable({ namespace })` and `authz.namespaces` is rejected. The project-level form is canonical for cross-feature; the table-level form is the single-feature shorthand.\n\nProject-level only:\n\n- **Ambiguous prefixes** like `/a/:x` and `/a/:y` (same shape, different `:param` names) are rejected. Strict super/sub-set relationships (`/event/:e` vs `/event/:e/admin`) are fine — the harvester routes each action to the longest matching prefix.\n- **Unused namespace** emits a `[quickback:authz]` warning when no action's path matches the declared prefix. Not a hard error — the namespace may be staged ahead of the actions.\n\n### What namespace actions get for free\n\nInside a namespace action's `execute()`:\n\n- `ctx.<exposeAs>` is populated by the middleware with the loaded resource row. Statically `any` by default — narrowed to `typeof <loadsTable>.$inferSelect` when the action's import points at the per-namespace helper (see [below](#narrow-ctxexposeas-typing-v027)).\n- Tenant context (`ctx.activeOrgId` / `ctx.activeTeamId`) is stamped from the matched relationship row when its `from` table carries those columns. Downstream scoped queries work without further setup.\n- The action's own `access:` block (additional roles, userRole, record predicates, OTHER relationship arms) still runs after the namespace gate — namespace handles entry, per-action gates further.\n\n### Narrow `ctx.<exposeAs>` typing (v0.27+)\n\nThe namespace middleware hydrates `ctx.<exposeAs>` at runtime — that's been true since v0.23. The static type of that field, though, is `any` via the `AppContext` index signature: useful for not blocking access, but a missed opportunity for autocomplete and typo-catching.\n\nv0.27 emits one **per-namespace `defineAction` helper** alongside the standard `<feature>/.quickback/define-action.ts`. Importing from the narrowed helper retypes `ctx.<exposeAs>` inside `execute({ ctx })` to the loaded row's `$inferSelect` shape. Nothing else changes — runtime behavior, action discovery, and the `path:` namespace match are identical.\n\n```ts title=\"features/feeds/actions/feed-moments.ts\"\n// One-line flip per namespace-scoped action:\n\n// └──────┬──────┘\n// kebab(namespaceName)\n\nexport default defineAction({\n path: '/event/:eventId/feed-moments',\n method: 'POST',\n input: z.object({ body: z.string() }),\n access: { roles: ['attendee'] },\n async execute({ ctx, input }) {\n ctx.event.id // ✓ string\n ctx.event.startsAt // ✓ Date — autocomplete works\n ctx.event.organizerId // ✓ narrows on the field's declared type\n\n ctx.event.idd // ✗ TS2339 — typo caught at compile time\n },\n});\n```\n\nThe compiler emits one helper per `(feature, namespace)` pair where the feature owns at least one action whose `path:` falls under the namespace prefix. Filename is `define-action.<kebab(namespaceName)>.ts` — `eventScope` becomes `define-action.event-scope.ts`. Helpers live next to the standard `define-action.ts` in `<feature>/.quickback/`, so the relative import is the same shape as every other action file in your project.\n\n#### Opt-in, not breaking\n\nActions that keep their existing `import { defineAction } from '../.quickback/define-action'` continue to compile unchanged — `ctx.<exposeAs>` is `any` via the `AppContext` index signature, which is exactly the v0.23–v0.26 behavior. You flip imports per action at your own pace.\n\n#### Compile-time advisory\n\nWhen `quickback compile` sees a namespace-scoped action still importing the generic helper, it emits a one-line advisory pointing at the narrowed path:\n\n```text\n[quickback:typing] action \"feedMoments\" in feature \"feeds\" lives under\n namespace \"eventScope\" — switch its import to\n `../.quickback/define-action.event-scope` for narrow ctx.<exposeAs> typing.\n (Runtime behavior is unchanged; the narrowed helper only refines TS types.)\n```\n\nNon-blocking — same `[quickback:typing]` family as `[quickback:authz]`. The advisory only mentions actions the compiler can be confident about (namespace-claimed actions whose source still imports the generic helper).\n\n#### Multi-namespace features\n\nA single feature can contribute actions to several namespaces — say, an `interviews` feature with actions under both `interviewScope` and `eventScope`. The compiler emits one narrowed helper per namespace the feature participates in, and each action picks the import that matches its path.\n\n```text\nsrc/features/interviews/.quickback/\n├── define-action.ts # generic — standard fallback\n├── define-action.interview-scope.ts # ctx.interview typed\n└── define-action.event-scope.ts # ctx.event typed\n```\n\n#### Why per-namespace and not per-action\n\nA `defineAction` helper that's narrow to *one* exposed key (the namespace's `exposeAs`) is enough — every action under a namespace sees the same hydrated key. The alternative (per-action emit) duplicates the same prelude N times for the same shape; per-namespace keeps emission proportional to the number of distinct hydration shapes in the project.\n\n## Read & Write Configuration\n\nReads (`GET /` and `GET /:id`) live under `read:`; mutations live under top-level `create:`, `update:`, `delete:`, and `upsert:`. See [Read](/compiler/definitions/read) for the full read pipeline reference.\n\n```typescript\nread: {\n // LIST + GET - GET /resource and GET /resource/:id\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n pageSize: 25, // Default page size\n maxPageSize: 100, // Client can't exceed this\n views: { // Per-view field projections\n summary: {\n fields: ['id', 'candidateId', 'jobId', 'stage'],\n access: { roles: [\"interviewer\"] },\n },\n },\n}\n\ncreate: {\n // CREATE - POST /resource\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] },\n defaults: { // Default values for new records\n stage: 'applied',\n },\n},\n\nupdate: {\n // UPDATE - PATCH /resource/:id\n access: {\n or: [\n { roles: [\"hiring-manager\", \"recruiter\"] },\n { roles: [\"interviewer\"], record: { stage: { equals: \"interview\" } } }\n ]\n },\n},\n\ndelete: {\n // DELETE - DELETE /resource/:id\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"soft\", // 'soft' (default) or 'hard'\n},\n\nupsert: {\n // PUT - PUT /resource/:id (only when generateId: false + guards: false)\n access: { roles: [\"hiring-manager\", \"sync-service\"] },\n}\n```\n\n## Evaluation Order\n\nGenerated `/:id` and batch handlers evaluate access in this fixed order:\n\n1. **Auth gate** — 401 if unauthenticated\n2. **Pre-record access** — role-only check (skips `access.record` predicates)\n3. **Firewall query** — `WHERE` clause filters by ownership\n4. **Post-record access** — full check including record-level predicates\n5. **Masking** — applied to the response\n\nStep 2 closes the 404-vs-403 ID-probe channel: an unauthorized caller without\na matching role gets 403 before the database is touched, so they can't tell\napart \"row exists out-of-scope\" from \"row doesn't exist.\" A caller with the\nright role but the wrong tenant gets 403 by default (firewall reveals via\nthe access layer); set\n[`firewallErrorMode: 'hide'`](/compiler/definitions/firewall) to return an\nopaque 404 instead.\n\nFunction-form access (`access: async (ctx, record) => ...`) is opaque to\nthe pre-record phase and always passes there; it's fully evaluated post-record.\n\n## List Filtering (Query Parameters)\n\nThe LIST endpoint automatically supports filtering via query params:\n\n```\nGET /jobs?status=open # Exact match\nGET /jobs?salaryMin.gt=50000 # Greater than\nGET /jobs?salaryMin.gte=50000 # Greater than or equal\nGET /jobs?salaryMax.lt=200000 # Less than\nGET /jobs?salaryMax.lte=200000 # Less than or equal\nGET /jobs?status.ne=closed # Not equal\nGET /jobs?title.like=Engineer # Pattern match (LIKE %value%)\nGET /jobs?status.in=open,draft # IN clause\n```\n\n| Operator | Query Param | SQL Equivalent |\n|----------|-------------|----------------|\n| Equals | `?field=value` | `WHERE field = value` |\n| Not equals | `?field.ne=value` | `WHERE field != value` |\n| Greater than | `?field.gt=value` | `WHERE field > value` |\n| Greater or equal | `?field.gte=value` | `WHERE field >= value` |\n| Less than | `?field.lt=value` | `WHERE field < value` |\n| Less or equal | `?field.lte=value` | `WHERE field <= value` |\n| Pattern match | `?field.like=value` | `WHERE field LIKE '%value%'` |\n| In list | `?field.in=a,b,c` | `WHERE field IN ('a','b','c')` |\n\n## Sorting & Pagination\n\n```\nGET /jobs?sort=createdAt&order=desc # Sort by field\nGET /jobs?limit=25&offset=50 # Pagination\n```\n\n- **Default limit**: 50\n- **Max limit**: 100 (or `maxPageSize` if configured)\n- **Default order**: `asc`\n\n## Delete Modes\n\n```typescript\ndelete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"soft\", // Sets deletedAt/deletedBy, record stays in DB\n}\n\ndelete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"hard\", // Permanent deletion from database\n}\n```\n\n## Context Variables\n\nUse `$ctx.` prefix to reference context values in conditions:\n\n```typescript\n// User can only view their own records\naccess: {\n record: { userId: { equals: \"$ctx.userId\" } }\n}\n\n// Nested path support for complex context objects\naccess: {\n record: { ownerId: { equals: \"$ctx.user.id\" } }\n}\n```\n\n### AppContext Reference\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `$ctx.userId` | `string` | Current authenticated user's ID |\n| `$ctx.activeOrgId` | `string` | User's active organization ID |\n| `$ctx.activeTeamId` | `string \\| null` | User's active team ID (if applicable) |\n| `$ctx.roles` | `string[]` | User's roles in current context |\n| `$ctx.isAnonymous` | `boolean` | Whether user is anonymous |\n| `$ctx.user` | `object` | Full user object from auth provider |\n| `$ctx.user.id` | `string` | User ID (nested path example) |\n| `$ctx.user.email` | `string` | User's email address |\n| `$ctx.{property}` | `any` | Any custom context property |\n\n## Function-Based Access\n\nFor complex access logic that can't be expressed declaratively, use a function:\n\n```typescript\nupdate: {\n access: async (ctx, record) => {\n // Custom logic - return true to allow, false to deny\n if (ctx.roles.includes('admin')) return true;\n if (record.ownerId === ctx.userId) return true;\n\n // Check custom business logic\n const membership = await checkTeamMembership(ctx.userId, record.teamId);\n return membership.canEdit;\n }\n}\n```\n\nFunction access receives:\n- `ctx`: The full AppContext object\n- `record`: The record being accessed (for get/update/delete operations)"
79
79
  },
80
80
  "compiler/definitions/actions": {
81
81
  "title": "Actions",
82
- "content": "Actions are custom API endpoints for business logic beyond CRUD operations. They enable workflows, integrations, and complex operations.\n\n## Overview\n\nQuickback supports two types of actions:\n\n| Aspect | Record-Based | Standalone |\n|--------|--------------|------------|\n| Route | `{METHOD} /:id/{actionName}` | Custom `path` (required) |\n| Record fetching | Automatic | None (`record` is `undefined`) |\n| Firewall applied | Yes | No |\n| Preconditions | Supported via `access.record` | Not applicable |\n| Response types | JSON only | JSON, stream, file |\n| Use case | Advance application, reject candidate | AI chat, bulk import from job board, webhooks |\n\nStandalone actions are signalled by the presence of a `path:` field in the action config. Record-based actions omit `path` and bind to the feature's primary table.\n\n## Where do actions live?\n\n**One file per action.** Each action is its own module under the feature's\n`actions/` directory:\n\n```\nfeatures/applications/\n├── applications.ts ← defineTable (primary table)\n├── candidates.ts ← defineTable (sibling table)\n├── actions/\n│ ├── advance.ts ← defineAction, binds to applications\n│ ├── reject.ts ← defineAction, binds to applications\n│ ├── stats.ts ← defineAction, standalone (has `path:`)\n│ └── candidates/\n│ └── disqualify.ts ← defineAction, binds to candidates\n└── lib/\n └── inputs.ts ← shared schemas (optional, copied verbatim)\n```\n\n| Layout | Binds to |\n|--------|----------|\n| `actions/<name>.ts` | The feature's primary table (table file matching the feature name), or standalone if `path:` is set. |\n| `actions/<table>/<name>.ts` | The sibling table file `<table>.ts` at the feature root. Standalone actions inside a subdir ignore the binding. |\n\nThe action's filename (sans `.ts`) is the action name and the URL segment.\nUniqueness is enforced per `(bound table, name)` pair — sibling-bound\nactions on **different** tables may share a verb (`actions/episodes/publish.ts`\nand `actions/shows/publish.ts` mount at `/episodes/:id/publish` and\n`/shows/:id/publish` and compile cleanly). The compiler errors only when\ntwo action files would mount at the same URL — for example, a flat\n`actions/foo.ts` (binds to primary) plus `actions/<primary>/foo.ts`, or\ntwo standalones with the same `(method, path)`. Standalone actions are\nunique per `(method, path)`.\n\nTableless features have no top-level `*.ts` files; every action under\n`actions/` must be standalone (have `path:`). Use this for utility endpoints\nlike webhooks, reports, or integrations that don't operate on a specific\nrecord.\n\n### Retired layouts\n\nThese are rejected at load time with migration guidance:\n\n- **`actions.ts`** (bundled multi-action file)\n- **`_feature.ts`** (shared schemas + non-table-bound actions)\n- **`handlers/`** (separate handler-file directory)\n- **`defineActions(table, {...})`** (the multi-action factory)\n- **`defineActions(null, {...})`** (tableless variant)\n- **`*-actions.ts` / `*.actions.ts`** filename patterns\n\nFor shared Zod schemas or helpers, put them under `<feature>/lib/` and import\nfrom each action file. Files under `lib/` are copied verbatim into the\ngenerated output.\n\n## Defining Actions\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n notes: z.string().max(2000).optional(),\n }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: {\n applied: [\"screening\"],\n screening: [\"interview\"],\n interview: [\"offer\"],\n },\n },\n async execute({ db, record, input, whereTransition }) {\n const [updated] = await db\n .update(applications)\n .set({\n status: input.nextStatus,\n notes: input.notes ?? record.notes,\n })\n .where(whereTransition!(applications))\n .returning();\n return updated;\n },\n});\n```\n\n> **`defineAction` import.** Import from `\"../.quickback/define-action\"` —\n> the `.quickback/` directory is generated alongside your feature with a\n> typed helper that infers `record` and `input` types from the rest of the\n> action config. Audit fields (`createdAt`, `createdBy`, `modifiedAt`,\n> `modifiedBy`) are hard-stamped by the audit DB wrapper on every\n> `db.insert().values()` and `db.update().set()` — handlers don't pass\n> them and can't override them.\n\n### Configuration Options\n\n| Option | Required | Description |\n|--------|----------|-------------|\n| `description` | Yes | Human-readable description of the action |\n| `input` | Yes | Zod schema for request validation |\n| `access` | Yes | Access control (roles, record conditions, or function) |\n| `execute` | Yes | Inline async arrow function (`async (ctx) => { … }`) |\n| `path` | Standalone only | Custom route path. Presence of `path` makes the action standalone. |\n| `method` | No | HTTP method: GET, POST, PUT, PATCH, DELETE (default: POST). GET actions parse `input` from query params; all other methods parse from the JSON body. See [GET vs POST for input](#get-vs-post-for-input). |\n| `responseType` | No | Response format: json, stream, file (default: json) |\n| `sideEffects` | No | Hint for AI tools: `'sync'`, `'async'`, or `'fire-and-forget'` |\n| `allowRawSql` | No | Explicit compile-time opt-in for raw SQL in execute code |\n| `unsafe` | No | Unsafe raw DB mode. Object config (`reason`, `adminOnly`, `crossTenant`, `targetScope`). |\n| `transition` | No | State-machine policy enforcing the from/to pair (record-based actions). See [Transitions](#transition-state-machine-policy) |\n| `bulkVariant` | No | Auto-generate a `POST /:resource/batch/{action}` route alongside the per-record route (record-based actions). See [Bulk Variant](#bulk-variant) |\n| `cms` | No | Pass-through metadata blob for CMS surfaces |\n\n`execute` must be an `async (ctx) => { … }` arrow function. `async function`\ndeclarations and non-async forms are rejected at parse time.\n\n## Record-Based Actions\n\nRecord-based actions operate on an existing record. The record is automatically loaded and validated before your action executes.\n\n**Route pattern:** `{METHOD} /:id/{actionName}`\n\n```\nPOST /applications/:id/advance\nPOST /applications/:id/reject\nPOST /applications/:id/schedule-interview\n```\n\n### Runtime Flow\n\n1. **Authentication** - User token is validated\n2. **Record Loading** - The record is fetched by ID\n3. **Firewall Check** - Ensures user can access this record\n4. **Access Check** - Validates roles and preconditions\n5. **Input Validation** - Request body validated against Zod schema\n6. **Execution** - Your action handler runs\n7. **Response** - Result is returned to client\n\n### Example: Advance Application Stage\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move application to the next pipeline stage\",\n input: z.object({\n stage: z.enum([\"screening\", \"interview\", \"offer\", \"hired\"]),\n notes: z.string().optional(),\n }),\n access: {\n roles: [\"owner\", \"hiring-manager\"],\n record: { stage: { notEquals: \"rejected\" } },\n },\n async execute({ db, record, input }) {\n const [updated] = await db\n .update(applications)\n .set({\n stage: input.stage,\n notes: input.notes ?? record.notes,\n })\n .where(eq(applications.id, record.id))\n .returning();\n return updated;\n },\n});\n```\n\n### Request Example\n\n```\nPOST /applications/app_123/advance\nContent-Type: application/json\n\n{\n \"stage\": \"interview\",\n \"notes\": \"Strong technical background, moving to interview\"\n}\n```\n\n### Response Example\n\n```json\n{\n \"data\": {\n \"id\": \"app_123\",\n \"stage\": \"interview\",\n \"notes\": \"Strong technical background, moving to interview\"\n }\n}\n```\n\n### Bulk variant\n\nSet `bulkVariant: true` to auto-generate a bulk version of the action at\n`POST /:resource/batch/{action}`. The compiler emits a second route alongside\nthe per-record one, looping the same access + transition + execute pipeline\nover an array of ids. This is the answer to \"I need to advance 50\napplications at once\" — you don't have to hand-roll a parallel standalone\naction that duplicates the per-record logic.\n\n```typescript\n// features/applications/actions/advance.ts\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n bulkVariant: true,\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: { applied: [\"screening\"], screening: [\"interview\"], interview: [\"offer\"] },\n },\n async execute({ db, record, input, whereTransition }) {\n const [updated] = await db\n .update(applications)\n .set({ status: input.nextStatus })\n .where(whereTransition!(applications))\n .returning();\n if (!updated) throw new TransitionLostError(\"status\", record.status, input.nextStatus);\n return updated;\n },\n});\n```\n\n**Request shape:**\n\n```http\nPOST /applications/batch/advance\nContent-Type: application/json\n\n{\n \"ids\": [\"app_001\", \"app_002\", \"app_003\"],\n \"input\": { \"nextStatus\": \"interview\" },\n \"failFast\": false\n}\n```\n\nThe `input` is shared across the batch — the action's Zod schema is\nvalidated once, not per id. For per-record input variation, use the\nsingle-record endpoint (`POST /:id/{action}`) or write a standalone action.\n\n**Response (207 Multi-Status when any record fails, 200 when clean):**\n\n```json\n{\n \"success\": [{ \"id\": \"app_001\", \"status\": \"interview\" }],\n \"errors\": [\n {\n \"index\": 1,\n \"id\": \"app_002\",\n \"error\": {\n \"error\": \"Action not allowed for current state\",\n \"code\": \"ACCESS_ACTION_NOT_ALLOWED_FOR_STATE\",\n \"details\": { \"field\": \"status\", \"currentValue\": \"rejected\" }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"failFast\": false,\n \"transactional\": false\n }\n}\n```\n\n**Per-record pipeline** mirrors the single-record route exactly — the same\nfirewall fetch, access reason split (403 vs 409), transition pre-check,\n`whereTransition` factory, and `TransitionLostError` handling. Per-record\nfailures land in `errors[]` with their original index; successful records\nland in `success[]` masked the same way the single-record response is.\n\n**Transactional matrix** (same as `PATCH /batch`):\n\n| Provider | failFast | transactional | Behavior |\n|---|---|---|---|\n| neon (Postgres via Hyperdrive) | `true` | `true` | `db.transaction()` wraps the loop; any throw rolls back all writes |\n| (any) | `false` | `false` | Independent per-record outcomes, partial success |\n| cloudflare-d1 | `true` | `false` | Fail-fast loop without rollback — earlier records stay committed (D1 has no `db.transaction`) |\n\n**Constraints:**\n\n- Record-based actions only. Standalone actions reject `bulkVariant: true`\n at compile time (no record context to loop over).\n- `unsafe` actions reject `bulkVariant: true` in v1 — the cross-tenant\n per-record audit story is not yet wired through.\n- Method is forced to POST regardless of the action's `method` setting. The\n semantic asymmetry (one row → many rows) makes inheriting GET/DELETE\n confusing.\n- Max batch size is 100 ids per request.\n\n## Standalone Actions\n\nStandalone actions are independent endpoints that don't require a record context. Set a `path:` to declare the action standalone.\n\n**Route pattern:** Custom `path`\n\n```\nPOST /chat\nGET /reports/summary\nPOST /webhooks/stripe\n```\n\n### Example: AI Chat with Streaming\n\n```typescript\n// features/sessions/actions/chat.ts\n\nexport default defineAction({\n description: \"Send a message to AI\",\n path: \"/chat\",\n method: \"POST\",\n responseType: \"stream\",\n input: z.object({\n message: z.string().min(1).max(2000),\n }),\n access: { roles: [\"recruiter\", \"hiring-manager\"] },\n async execute({ input, c }) {\n // Stream response back to client...\n return c.newResponse(/* ReadableStream */);\n },\n});\n```\n\n### Streaming Response Example\n\nFor actions with `responseType: 'stream'`:\n\n```\nContent-Type: text/event-stream\n\ndata: {\"type\": \"start\"}\ndata: {\"type\": \"chunk\", \"content\": \"Hello\"}\ndata: {\"type\": \"chunk\", \"content\": \"! I'm\"}\ndata: {\"type\": \"chunk\", \"content\": \" here to help.\"}\ndata: {\"type\": \"done\"}\n```\n\n### Tableless Features\n\nA feature directory with no top-level `*.ts` files is \"tableless\" — every\naction under `actions/` must be standalone. Use this for utility endpoints\nlike reports, integrations, or webhooks that don't map to a specific\nresource.\n\n```\nquickback/features/\n└── reports/\n └── actions/\n ├── trial-balance.ts ← standalone (has path:)\n └── profit-loss.ts ← standalone (has path:)\n```\n\n```typescript\n// features/reports/actions/trial-balance.ts\n\nexport default defineAction({\n description: \"Generate trial balance report\",\n path: \"/reports/trial-balance\",\n method: \"GET\",\n input: z.object({\n startDate: z.string(),\n endDate: z.string(),\n }),\n access: { roles: [\"admin\", \"accountant\"] },\n async execute({ db, input }) {\n // ... build report\n return { rows: [] };\n },\n});\n```\n\n### GET vs POST for input\n\nGET actions read `input` from URL query parameters; every other method (POST,\nPUT, PATCH, DELETE) reads from the JSON body. The Zod schema is the same in\nboth cases — the compiler picks the right parser based on `method`.\n\n```typescript\n// GET — input populated from ?q=…&limit=…\ndefineAction({\n method: \"GET\",\n path: \"/search\",\n input: z.object({\n q: z.string(),\n limit: z.coerce.number().int().positive().max(100).default(20),\n }),\n access: { roles: [\"AUTHENTICATED\"] },\n async execute({ input }) {\n // input is { q: string, limit: number } — fully typed.\n },\n});\n```\n\nRepeated query keys (`?tag=a&tag=b`) come through as arrays automatically;\nsingle values stay as strings. Use Zod's `.coerce.number()` /\n`.coerce.boolean()` when you want typed primitives from the parsed strings.\n\n**Use POST when input is structured.** GET requests cannot carry a JSON body\nin any of the surfaces Quickback APIs are commonly called from:\n\n- Browsers throw on `fetch(url, { method: 'GET', body })`.\n- CDNs and caches key on URL+method; a GET with a body either gets the body\n stripped at the edge or cache-collides with semantically different requests.\n- OpenAPI client generators (axios, openapi-fetch, openapi-typescript-codegen)\n refuse to emit GET-with-body, so the generated SDKs break.\n- The MCP agent surface treats GET as parameter-only — agents calling a GET\n action will only see what the URL exposes.\n\nIf your action takes nested objects, arrays of objects, or large inputs that\ndon't serialize cleanly to a query string, set `method: \"POST\"`. POST doesn't\nimply \"this writes data\" — it's the right method whenever the request body is\nload-bearing. Use the response shape (`responseType: \"json\"`, or just the data\nyour handler returns) to convey read semantics; HTTP method choice is about\ninput transport, not action intent.\n\n## Access Configuration\n\nAccess controls who can execute an action and under what conditions.\n\n### Role-Based Access\n\n```typescript\naccess: {\n roles: [\"hiring-manager\", \"recruiter\"] // OR logic: user needs any of these roles\n}\n```\n\n### Public Access\n\nUse `roles: [\"PUBLIC\"]` for unauthenticated endpoints (contact forms, webhooks, public APIs). Every invocation is **mandatory audit logged** with IP address, input, result, and timing.\n\n```typescript\n// features/contact/actions/submit.ts\n\nexport default defineAction({\n description: \"Public contact form submission\",\n path: \"/submit\",\n input: z.object({\n name: z.string().min(1),\n email: z.string().email(),\n message: z.string().min(10),\n }),\n access: { roles: [\"PUBLIC\"] },\n async execute({ db, input }) {\n // ... persist submission\n return { ok: true };\n },\n});\n```\n\nThe wildcard `\"*\"` is not supported and will throw a compile-time error. Use `\"PUBLIC\"` explicitly.\n\n### Record Conditions\n\nFor record-based actions, you can require the record to be in a specific state:\n\n```typescript\naccess: {\n roles: [\"hiring-manager\"],\n record: {\n stage: { equals: \"screening\" } // Precondition\n }\n}\n```\n\n**Supported operators:**\n\n| Operator | Description |\n|----------|-------------|\n| `equals` | Field must equal value |\n| `notEquals` | Field must not equal value |\n| `in` | Field must be one of the values |\n| `notIn` | Field must not be one of the values |\n\n### Context Substitution\n\nUse `$ctx` to reference the current user's context:\n\n```typescript\naccess: {\n record: {\n ownerId: { equals: \"$ctx.userId\" },\n organizationId: { equals: \"$ctx.activeOrgId\" }\n }\n}\n```\n\n### OR/AND Combinations\n\n```typescript\naccess: {\n or: [\n { roles: [\"hiring-manager\"] },\n {\n roles: [\"recruiter\"],\n record: { ownerId: { equals: \"$ctx.userId\" } }\n }\n ]\n}\n```\n\n### Function Access\n\nFor complex logic, use an access function:\n\n```typescript\naccess: async (ctx, record) => {\n return ctx.roles.includes('admin') || record.ownerId === ctx.userId;\n}\n```\n\n### Relationship-roles in actions\n\n**v0.19+** — standalone actions now support relationship-roles in `access.roles` directly. Declare the relationship under `authz.relationships` with optional `loads` / `exposeAs` for ctx hydration, and reference the role by name on the action:\n\n```ts\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n roles: { attendee: { via: 'attendeeOf' } },\n}\n\n// features/chat/actions/getInbox.ts\nexport default defineAction({\n path: '/chat/get-inbox',\n input: z.object({ eventId: z.number().int().positive() }),\n access: { roles: ['admin', 'member', 'attendee'] },\n execute: async ({ db, ctx, input }) => {\n // The resolver already verified attendance and loaded ctx.event.\n // No hand-rolled `SELECT … FROM guests WHERE …` needed.\n },\n});\n```\n\nThe action's surface (path params + input fields) must expose the relationship's `resource.column`. At v0.19 a missing key emits a `[quickback:authz]` warning and skips resolver emission; at v0.20 it becomes a compile error. See [Access — standalone actions](/compiler/definitions/access#standalone-actions-surface-keys-and-loads--exposeas-v019) for the full mechanism.\n\n**Record-based actions** are NOT yet supported — the runtime evaluator fail-closes (403) on relationship arms reached without an inline gate. Until inline emission for record-based actions lands, either:\n\n- Set `firewall: { exception: true }` on the action and gate manually in `execute()`, OR\n- Apply the relationship at the resource's firewall layer (worked example below).\n\n**Resource-layer workaround for record-based actions**: gate the action on BA roles only and apply the relationship at the resource layer via a firewall `via:` predicate:\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n },\n },\n}\n\n// features/sessions/sessions.ts — firewall scopes rows; action gates on BA role\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' }, // ← row-level relationship check\n],\nactions: {\n comment: defineAction({\n access: { roles: ['member', 'admin'] }, // ← BA role only on the action\n input: z.object({ text: z.string() }),\n execute: async (input, ctx, db, record) => {\n // record is already filtered by the firewall — guest membership\n // is enforced before this handler runs.\n return db.insert(comments).values({ ... });\n },\n }),\n}\n```\n\nThis pattern composes cleanly: the firewall guarantees the caller has the relationship to the record being acted on; the action's access list keeps the role surface obvious.\n\nSee [Access — relationship authorization](/compiler/definitions/access#relationship-based-authorization) for the full picture, including `loads` / `exposeAs` and the `firewall: { exception: true }` escape hatch.\n\n## Scoped Database\n\nAll actions receive a **scoped `db`** instance that automatically enforces security:\n\n| Operation | Org Scoping | Owner Scoping | Soft Delete Filter | Auto-inject on INSERT |\n|-----------|-------------|---------------|--------------------|-----------------------|\n| `SELECT` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n| `INSERT` | n/a | n/a | n/a | `organizationId`, `ownerId` from ctx |\n| `UPDATE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n| `DELETE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n\nScoping is duck-typed at runtime — tables with an `organizationId` column get org scoping, tables with `ownerId` get owner scoping, tables with `deletedAt` get soft delete filtering.\n\n```typescript\nasync execute({ db, ctx, input }) {\n // This query automatically includes WHERE organizationId = ? AND deletedAt IS NULL\n const items = await db.select().from(applications).where(eq(applications.stage, 'interview'));\n\n // Inserts automatically include organizationId\n await db.insert(applications).values({ candidateId: input.candidateId, jobId: input.jobId, stage: 'applied' });\n\n return items;\n}\n```\n\n**Not enforced** in scoped DB (by design):\n- **Guards** — actions ARE the authorized way to modify guarded fields\n- **Masking** — actions are backend code that may need raw data\n- **Access** — already checked before action execution\n\n### Unsafe Mode\n\nActions that need to bypass scoped DB filters (for example, platform-level support operations) can enable unsafe mode.\n\nUse object form for explicit policy and mandatory audit metadata:\n\n```typescript\n// features/admin/actions/cross-tenant-report.ts\n\nexport default defineAction({\n description: \"Generate cross-org hiring report\",\n path: \"/admin/cross-tenant-report\",\n input: z.object({ startDate: z.string() }),\n access: { roles: [\"owner\"] },\n unsafe: {\n reason: \"Support investigation for enterprise customer\",\n adminOnly: true, // default true\n crossTenant: true, // default true\n targetScope: \"all\", // \"all\" | \"organization\"\n },\n async execute({ unsafeDb, input }) {\n // unsafeDb bypasses scoped filters\n const allOrgs = await unsafeDb.select().from(applications);\n return allOrgs;\n },\n});\n```\n\nUnsafe cross-tenant actions are generated with:\n\n- Better Auth authentication required (no unauthenticated path)\n- sysadmin gate (`ctx.userRole === \"sysadmin\"`)\n- mandatory audit logging on deny/success/error\n\n`PUBLIC` actions also receive mandatory audit logging (same audit table), since unauthenticated endpoints are high-risk by nature.\n\nWithout unsafe mode, `unsafeDb` is `undefined` in the executor params.\n\n### Raw SQL Policy\n\nBy default, the compiler rejects raw SQL in action code. Use Drizzle query-builder syntax whenever possible.\n\nIf a specific action must use raw SQL, opt in explicitly:\n\n```typescript\n// features/ledgers/actions/reconcile.ts\n\nexport default defineAction({\n description: \"Run custom reconciliation query\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n allowRawSql: true,\n async execute({ db }) {\n return db.execute(sql`select 1`);\n },\n});\n```\n\nWithout `allowRawSql: true`, compilation fails with a loud error pointing to the action and snippet.\n\nThe detector checks for SQL keywords in string arguments, so non-SQL method calls like `headers.get(\"X-Forwarded-For\")` or `map.get(\"key\")` will not trigger false positives.\n\n## Sharing Code Between Actions\n\nFor Zod schemas, helpers, or constants used across multiple actions in a\nfeature, put them under `<feature>/lib/` and import from each action file.\nFiles under `lib/` are copied verbatim into the generated output.\n\n```\nfeatures/applications/\n├── applications.ts\n├── actions/\n│ ├── advance.ts\n│ └── reject.ts\n└── lib/\n ├── inputs.ts ← shared Zod schemas\n └── transitions.ts ← state-machine helpers\n```\n\n```typescript\n// features/applications/lib/inputs.ts\n\nexport const advanceInput = z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n notes: z.string().max(2000).optional(),\n});\n```\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move forward\",\n input: advanceInput,\n access: { roles: [\"owner\"] },\n async execute({ db, record, input }) { /* … */ },\n});\n```\n\n### Importing Tables\n\nAction files import tables from their own feature or other features. The compiler generates alias files for each table, so you import by the table's file name:\n\n```typescript\n// features/applications/actions/advance.ts\n\n// Same feature — import from parent directory using the table's file name\n\n// Cross-feature — go up to the features directory, then into the other feature\n\n```\n\n**Path pattern from `features/{name}/actions/`:**\n- Same feature table: `../{table-file-name}` (e.g., `../applications`)\n- Other feature table: `../../{other-feature}/{table-file-name}` (e.g., `../../candidates/candidates`)\n- Generated lib files: `../../../lib/{module}` (e.g., `../../../lib/realtime`, `../../../lib/webhooks`)\n\n### Executor Parameters\n\n```typescript\n\ninterface ActionExecutorParams {\n db: DrizzleDB; // Scoped database (auto-applies org/owner/soft-delete filters)\n unsafeDb?: DrizzleDB; // Unscoped database (only available when unsafe mode is enabled)\n ctx: AppContext; // User context (userId, roles, activeOrgId, activeTeamId, userRole)\n record?: TRecord; // The record (record-based only, undefined for standalone)\n input: TInput; // Validated input from Zod schema\n services: TServices; // Configured integrations (billing, notifications, etc.)\n c: HonoContext; // Raw Hono context for advanced use\n env: Env; // Runtime bindings (Cloudflare env / process env). Alias for c.env.\n auth: Auth; // Better Auth instance — call auth.api.getSession(...) etc. Lazy on Cloudflare.\n whereRecord?: (table) => SQL; // Pre-built WHERE: firewall + soft-delete + eq(table.id, record.id). Record-based actions only.\n whereTransition?: (table) => SQL; // whereRecord plus the transition's \"from\" precondition. Transition actions only.\n}\n```\n\n#### `auth` — Better Auth instance\n\n`auth` is the Better Auth instance, ready to call from inside an action\nhandler. Use it for things like minting an OAuth access token, fetching the\ncurrent session in a custom way, or invoking a Better Auth plugin method\nthat isn't already exposed by the generated middleware.\n\n```typescript\n// features/integrations/actions/connect-google-drive.ts\n\nexport default defineAction({\n description: \"Get a fresh Google Drive access token for the signed-in user\",\n input: z.object({}),\n access: { roles: [\"AUTHENTICATED\"] },\n async execute({ auth, ctx, c }) {\n // genericOAuth plugin method — needs a cast since the default-generic\n // `Auth` type doesn't carry plugin-specific API surface.\n const token = await (auth.api as any).getAccessToken({\n headers: c.req.raw.headers,\n body: { providerId: \"google\", userId: ctx.userId },\n });\n return { accessToken: token.accessToken };\n },\n});\n```\n\n**Lazy on Cloudflare**: the generated handler emits a `Proxy` so\n`createAuth(c.env, c.req.raw.cf)` only runs the first time you read a\nproperty on `auth`. Actions that never touch `auth` pay zero construction\ncost. On Bun/Node `auth` is the imported singleton (an IIFE that lazy-loads\nthe database adapter) wrapped in the same proxy shape — call sites are\nidentical across runtimes.\n\n**Typing**: `auth` is typed as `Auth` from `better-auth`. The base API\n(`getSession`, `signOut`, `signInEmail`, etc.) is fully typed. Plugin-only\nmethods (`getAccessToken` from `genericOAuth`, admin-plugin methods, etc.)\nneed a cast at the call site — the default-generic `Auth` doesn't infer\nthe project's specific plugin set.\n\n#### `whereRecord` — explicit, scope-safe WHERE\n\nFor protected-field writes inside record-based actions, prefer\n`whereRecord(table)` over `eq(table.id, record.id)`. It returns a Drizzle\nexpression that AND-merges the resource's firewall and soft-delete predicates\nwith the record id, so the WHERE is explicit even if a future refactor swaps\n`db` back to an unscoped client:\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Advance\",\n input: /* … */,\n access: { roles: [\"owner\"] },\n async execute({ db, record, input, whereRecord }) {\n const [updated] = await db\n .update(applications)\n .set({\n status: input.nextStatus,\n notes: input.notes ?? record.notes,\n })\n .where(whereRecord!(applications)) // firewall + soft-delete + id, all in one\n .returning();\n return updated;\n },\n});\n```\n\nThe audit DB wrapper hard-stamps `modifiedAt`/`modifiedBy` on every\n`.set()` call, so handlers don't write them. The same wrapper hard-stamps\n`createdAt`/`createdBy`/`modifiedAt`/`modifiedBy` on every `.values()`.\nCaller-supplied audit fields are dropped on the floor — the audit log\nalways reflects the real actor and the real moment.\n\n`whereRecord` is undefined for standalone actions (they have no record), so\nthe parameter is typed as optional. `whereTransition` extends `whereRecord`\nwith the transition's \"from\" precondition for transition actions.\n\n#### Reaching Better Auth tables (`authDb`)\n\nThe scoped `db` only sees your feature tables. To read Better Auth tables —\nusers, organizations, members — use the auth database connection from the\nHono context plus the generated `lib/org-access.ts` helper:\n\n```typescript\n// features/projects/actions/assign.ts — validate a userId is an org member\n\nexport default defineAction({\n description: \"Assign a project to an org member\",\n input: z.object({ assigneeId: z.string() }),\n access: { roles: [\"member\", \"admin\"] },\n async execute({ db, record, input, ctx, c, whereRecord }) {\n // getOrgMemberRole(authDb, userId, organizationId) → role string | null\n const role = await getOrgMemberRole(c.get(\"authDb\"), input.assigneeId, ctx.activeOrgId!);\n if (!role) {\n throw new ActionError(\"Assignee is not a member of this organization\", \"NOT_A_MEMBER\", 400);\n }\n const [updated] = await db\n .update(projects)\n .set({ assigneeId: input.assigneeId })\n .where(whereRecord!(projects))\n .returning();\n return updated;\n },\n});\n```\n\n`c.get(\"authDb\")` is the Drizzle connection to the auth database (in dual-DB\nmode it's a separate D1 from your features). For richer queries, import the\nauth schema tables from `../../../auth/schema` and query `authDb` directly.\n\n## HTTP API Reference\n\n### Request Format\n\n| Method | Input Source | Use Case |\n|--------|--------------|----------|\n| `GET` | Query parameters | Read-only operations, fetching data |\n| `POST` | JSON body | Default, state-changing operations |\n| `PUT` | JSON body | Full replacement operations |\n| `PATCH` | JSON body | Partial updates |\n| `DELETE` | JSON body | Deletion with optional payload |\n\n### Response Formats\n\n| Type | Content-Type | Use Case |\n|------|--------------|----------|\n| `json` | `application/json` | Standard API responses (default) |\n| `stream` | `text/event-stream` | Real-time streaming (AI chat, live updates) |\n| `file` | Varies | File downloads (reports, exports) |\n\n### Error Codes\n\n| Status | Description |\n|--------|-------------|\n| `400` | Invalid input / validation error (also `GUARD_FIELD_PROTECTED` for direct protected-field writes) |\n| `401` | Not authenticated |\n| `403` | Access role check failed (`ACCESS_ROLE_REQUIRED`) |\n| `404` | Record not found (record-based actions) |\n| `409` | Record is in the wrong state for this action — `access.record` predicate or `transition` policy failed (`ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`) |\n| `500` | Handler execution error |\n\n### Validation Error Response\n\n```json\n{\n \"error\": \"Invalid request data\",\n \"layer\": \"validation\",\n \"code\": \"VALIDATION_FAILED\",\n \"details\": {\n \"fields\": {\n \"amount\": \"Expected positive number\"\n }\n },\n \"hint\": \"Check the input schema for this action\"\n}\n```\n\n### Error Handling\n\n**Option 1: Return a JSON error response** (recommended for most cases)\n\nSince action handlers receive the Hono context (`c`), you can return error responses directly:\n\n```typescript\nasync execute({ ctx, record, input, c }) {\n if (record.stage === 'hired') {\n return c.json({\n error: 'Cannot modify a hired application',\n code: 'ALREADY_HIRED',\n details: { currentStage: record.stage },\n }, 400);\n }\n // ... continue\n}\n```\n\n**Option 2: Throw an ActionError**\n\n```typescript\n\nasync execute({ ctx, record, input }) {\n if (record.stage === 'hired') {\n throw new ActionError('Cannot modify a hired application', 'ALREADY_HIRED', 400, {\n currentStage: record.stage,\n });\n }\n // ... continue\n}\n```\n\nThe `ActionError` constructor signature is `(message, code, statusCode = 400, details?)`. The compile step rewrites the `@quickback/compiler` import to the generated runtime class (`src/lib/types.ts`), and the route handler catches it by name and returns `{ error, code, details }` with your `statusCode`.\n\n## Protected Fields\n\nActions can modify fields that are protected from regular CRUD operations:\n\n```typescript\n// In the table file (defineTable config)\nguards: {\n protected: {\n status: [\"advance\", \"reject\", \"hire\", \"withdraw\"], // Only these actions can modify status\n }\n}\n```\n\nThis allows the `advance` action to set `status = \"interview\"` even though the field is protected from regular PATCH requests. Direct `PATCH /:id` attempts to set `status` are rejected by the guards layer with **400 GUARD_FIELD_PROTECTED**, and the field is omitted from the generated POST/PATCH body Zod schemas — clients cannot even send it past validation.\n\n## Transition (state-machine policy)\n\nFor protected fields that follow a state machine — application status, invoice\nlifecycle, order fulfilment — use `transition` on the action so the compiler\ngenerates a runtime guard that enforces the *from/to pair*, not just the\ncurrent state. Without it, an `advance` action whose input enum allows\n`[\"screening\", \"interview\", \"offer\"]` and whose `access.record` allows\n`status in [\"applied\", \"screening\", \"interview\"]` will happily run\n`applied → offer` (a skip) or `interview → screening` (a regression).\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\", // read target from input.nextStatus\n fromTo: {\n applied: [\"screening\"],\n screening: [\"interview\"],\n interview: [\"offer\"],\n },\n },\n async execute({ db, record, input, whereTransition }) { /* … */ },\n});\n```\n\n```typescript\n// features/applications/actions/hire.ts\n\nexport default defineAction({\n description: \"Finalize an offer.\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n transition: {\n field: \"status\",\n to: \"hired\", // fixed target — same value every call\n fromTo: { offer: [\"hired\"] },\n },\n async execute({ db, record, whereTransition }) { /* … */ },\n});\n```\n\n| Field | Required | Description |\n|---|---|---|\n| `field` | Yes | Record column to validate (e.g. `\"status\"`) |\n| `fromTo` | Yes | Map of current value → permitted next values. Keys also enumerate the legal source states. |\n| `via` | Yes (or `to`) | Input key that carries the target value. Use for variable-target actions like `advance`. |\n| `to` | Yes (or `via`) | Literal target value the action always writes. Use for fixed-target actions like `hire`/`reject`. |\n\nExactly one of `via` or `to` must be provided. The compiler rejects both at\nvalidate time. When `to` is set, it must appear in some `fromTo[*]` array —\notherwise the action would be unreachable, which is almost certainly a bug.\n\n### Wire-level errors\n\nThe compiled guard returns **409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`** with\nthe field, the current value, the requested target, and the allowed set:\n\n```json\n{\n \"error\": \"Action not allowed for current record state\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ACTION_NOT_ALLOWED_FOR_STATE\",\n \"details\": {\n \"field\": \"status\",\n \"current\": \"interview\",\n \"target\": \"screening\",\n \"allowedTargets\": [\"offer\"]\n },\n \"hint\": \"From \\\"interview\\\", status can transition to: offer\"\n}\n```\n\nThis is distinct from a role failure: if the caller has the wrong role they\nget **403 `ACCESS_ROLE_REQUIRED`** as before. Splitting the two lets clients\ntell *\"you can't do this\"* from *\"you can't do this *yet*\"* — the latter is\nrecoverable by the user, the former isn't.\n\nThe same 409 code is used when an `access.record` predicate (without\n`transition`) fails — for example `record: { status: { equals: \"pending\" } }`\ncalled against a paid invoice now returns 409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`,\nnot a misleading 403.\n\n## Examples\n\n### Bulk Import (Standalone, No Record)\n\n```typescript\n// features/candidates/actions/bulk-import.ts\n\nexport default defineAction({\n description: \"Import candidates from job board CSV\",\n path: \"/candidates/import\",\n input: z.object({\n data: z.array(z.object({\n email: z.string().email(),\n name: z.string(),\n })),\n }),\n access: { roles: [\"hiring-manager\", \"recruiter\"] },\n async execute({ db, input }) {\n const inserted = await db\n .insert(candidates)\n .values(input.data)\n .returning();\n return { imported: inserted.length };\n },\n});\n```"
82
+ "content": "Actions are custom API endpoints for business logic beyond CRUD operations. They enable workflows, integrations, and complex operations.\n\n## Overview\n\nQuickback supports two types of actions:\n\n| Aspect | Record-Based | Standalone |\n|--------|--------------|------------|\n| Route | `{METHOD} /:id/{actionName}` | Custom `path` (required) |\n| Record fetching | Automatic | None (`record` is `undefined`) |\n| Firewall applied | Yes | No |\n| Preconditions | Supported via `access.record` | Not applicable |\n| Response types | JSON only | JSON, stream, file |\n| Use case | Advance application, reject candidate | AI chat, bulk import from job board, webhooks |\n\nStandalone actions are signalled by the presence of a `path:` field in the action config. Record-based actions omit `path` and bind to the feature's primary table.\n\n## Where do actions live?\n\n**One file per action.** Each action is its own module under the feature's\n`actions/` directory:\n\n```\nfeatures/applications/\n├── applications.ts ← defineTable (primary table)\n├── candidates.ts ← defineTable (sibling table)\n├── actions/\n│ ├── advance.ts ← defineAction, binds to applications\n│ ├── reject.ts ← defineAction, binds to applications\n│ ├── stats.ts ← defineAction, standalone (has `path:`)\n│ └── candidates/\n│ └── disqualify.ts ← defineAction, binds to candidates\n└── lib/\n └── inputs.ts ← shared schemas (optional, copied verbatim)\n```\n\n| Layout | Binds to |\n|--------|----------|\n| `actions/<name>.ts` | The feature's primary table (table file matching the feature name), or standalone if `path:` is set. |\n| `actions/<table>/<name>.ts` | The sibling table file `<table>.ts` at the feature root. Standalone actions inside a subdir ignore the binding. |\n\nThe action's filename (sans `.ts`) is the action name and the URL segment.\nUniqueness is enforced per `(bound table, name)` pair — sibling-bound\nactions on **different** tables may share a verb (`actions/episodes/publish.ts`\nand `actions/shows/publish.ts` mount at `/episodes/:id/publish` and\n`/shows/:id/publish` and compile cleanly). The compiler errors only when\ntwo action files would mount at the same URL — for example, a flat\n`actions/foo.ts` (binds to primary) plus `actions/<primary>/foo.ts`, or\ntwo standalones with the same `(method, path)`. Standalone actions are\nunique per `(method, path)`.\n\nTableless features have no top-level `*.ts` files; every action under\n`actions/` must be standalone (have `path:`). Use this for utility endpoints\nlike webhooks, reports, or integrations that don't operate on a specific\nrecord.\n\n### Retired layouts\n\nThese are rejected at load time with migration guidance:\n\n- **`actions.ts`** (bundled multi-action file)\n- **`_feature.ts`** (shared schemas + non-table-bound actions)\n- **`handlers/`** (separate handler-file directory)\n- **`defineActions(table, {...})`** (the multi-action factory)\n- **`defineActions(null, {...})`** (tableless variant)\n- **`*-actions.ts` / `*.actions.ts`** filename patterns\n\nFor shared Zod schemas or helpers, put them under `<feature>/lib/` and import\nfrom each action file. Files under `lib/` are copied verbatim into the\ngenerated output.\n\n## Defining Actions\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n notes: z.string().max(2000).optional(),\n }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: {\n applied: [\"screening\"],\n screening: [\"interview\"],\n interview: [\"offer\"],\n },\n },\n async execute({ db, record, input, whereTransition }) {\n const [updated] = await db\n .update(applications)\n .set({\n status: input.nextStatus,\n notes: input.notes ?? record.notes,\n })\n .where(whereTransition!(applications))\n .returning();\n return updated;\n },\n});\n```\n\n> **`defineAction` import.** Import from `\"../.quickback/define-action\"` —\n> the `.quickback/` directory is generated alongside your feature with a\n> typed helper that infers `record` and `input` types from the rest of the\n> action config. Audit fields (`createdAt`, `createdBy`, `modifiedAt`,\n> `modifiedBy`) are hard-stamped by the audit DB wrapper on every\n> `db.insert().values()` and `db.update().set()` — handlers don't pass\n> them and can't override them.\n\n### Configuration Options\n\n| Option | Required | Description |\n|--------|----------|-------------|\n| `description` | Yes | Human-readable description of the action |\n| `input` | Yes | Zod schema for request validation |\n| `access` | Yes | Access control (roles, record conditions, or function) |\n| `execute` | Yes | Inline async arrow function (`async (ctx) => { … }`) |\n| `path` | Standalone only | Custom route path. Presence of `path` makes the action standalone. |\n| `method` | No | HTTP method: GET, POST, PUT, PATCH, DELETE (default: POST). GET actions parse `input` from query params; all other methods parse from the JSON body. See [GET vs POST for input](#get-vs-post-for-input). |\n| `responseType` | No | Response format: json, stream, file (default: json) |\n| `sideEffects` | No | Hint for AI tools: `'sync'`, `'async'`, or `'fire-and-forget'` |\n| `allowRawSql` | No | Explicit compile-time opt-in for raw SQL in execute code |\n| `unsafe` | No | Unsafe raw DB mode. Object config (`reason`, `adminOnly`, `crossTenant`, `targetScope`). |\n| `transition` | No | State-machine policy enforcing the from/to pair (record-based actions). See [Transitions](#transition-state-machine-policy) |\n| `bulkVariant` | No | Auto-generate a `POST /:resource/batch/{action}` route alongside the per-record route (record-based actions). See [Bulk Variant](#bulk-variant) |\n| `cms` | No | Pass-through metadata blob for CMS surfaces |\n\n`execute` must be an `async (ctx) => { … }` arrow function. `async function`\ndeclarations and non-async forms are rejected at parse time.\n\n## Record-Based Actions\n\nRecord-based actions operate on an existing record. The record is automatically loaded and validated before your action executes.\n\n**Route pattern:** `{METHOD} /:id/{actionName}`\n\n```\nPOST /applications/:id/advance\nPOST /applications/:id/reject\nPOST /applications/:id/schedule-interview\n```\n\n### Runtime Flow\n\n1. **Authentication** - User token is validated\n2. **Input Validation** - Request body validated against Zod schema\n3. **Role Gate** - The access roles are checked *before* the record is\n fetched (v0.46+), so a wrong-role caller gets a uniform\n `403 ACCESS_ROLE_REQUIRED` whether or not the record exists — the\n response can't be used to probe for record ids\n4. **Record Loading** - The record is fetched by ID **through the firewall**\n (a cross-tenant or missing id is a standard firewall miss)\n5. **Access Check** - Record preconditions (`access.record`) and transition\n policy are validated against the loaded record\n6. **Execution** - Your action handler runs\n7. **Response** - Result is returned to client\n\n### Example: Advance Application Stage\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move application to the next pipeline stage\",\n input: z.object({\n stage: z.enum([\"screening\", \"interview\", \"offer\", \"hired\"]),\n notes: z.string().optional(),\n }),\n access: {\n roles: [\"owner\", \"hiring-manager\"],\n record: { stage: { notEquals: \"rejected\" } },\n },\n async execute({ db, record, input }) {\n const [updated] = await db\n .update(applications)\n .set({\n stage: input.stage,\n notes: input.notes ?? record.notes,\n })\n .where(eq(applications.id, record.id))\n .returning();\n return updated;\n },\n});\n```\n\n### Request Example\n\n```\nPOST /applications/app_123/advance\nContent-Type: application/json\n\n{\n \"stage\": \"interview\",\n \"notes\": \"Strong technical background, moving to interview\"\n}\n```\n\n### Response Example\n\n```json\n{\n \"data\": {\n \"id\": \"app_123\",\n \"stage\": \"interview\",\n \"notes\": \"Strong technical background, moving to interview\"\n }\n}\n```\n\n### Bulk variant\n\nSet `bulkVariant: true` to auto-generate a bulk version of the action at\n`POST /:resource/batch/{action}`. The compiler emits a second route alongside\nthe per-record one, looping the same access + transition + execute pipeline\nover an array of ids. This is the answer to \"I need to advance 50\napplications at once\" — you don't have to hand-roll a parallel standalone\naction that duplicates the per-record logic.\n\n```typescript\n// features/applications/actions/advance.ts\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n bulkVariant: true,\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: { applied: [\"screening\"], screening: [\"interview\"], interview: [\"offer\"] },\n },\n async execute({ db, record, input, whereTransition }) {\n const [updated] = await db\n .update(applications)\n .set({ status: input.nextStatus })\n .where(whereTransition!(applications))\n .returning();\n if (!updated) throw new TransitionLostError(\"status\", record.status, input.nextStatus);\n return updated;\n },\n});\n```\n\n**Request shape:**\n\n```http\nPOST /applications/batch/advance\nContent-Type: application/json\n\n{\n \"ids\": [\"app_001\", \"app_002\", \"app_003\"],\n \"input\": { \"nextStatus\": \"interview\" },\n \"failFast\": false\n}\n```\n\nThe `input` is shared across the batch — the action's Zod schema is\nvalidated once, not per id. For per-record input variation, use the\nsingle-record endpoint (`POST /:id/{action}`) or write a standalone action.\n\n**Response (207 Multi-Status when any record fails, 200 when clean):**\n\n```json\n{\n \"success\": [{ \"id\": \"app_001\", \"status\": \"interview\" }],\n \"errors\": [\n {\n \"index\": 1,\n \"id\": \"app_002\",\n \"error\": {\n \"error\": \"Action not allowed for current state\",\n \"code\": \"ACCESS_ACTION_NOT_ALLOWED_FOR_STATE\",\n \"details\": { \"field\": \"status\", \"currentValue\": \"rejected\" }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"failFast\": false,\n \"transactional\": false\n }\n}\n```\n\n**Per-record pipeline** mirrors the single-record route exactly — the same\nfirewall fetch, access reason split (403 vs 409), transition pre-check,\n`whereTransition` factory, and `TransitionLostError` handling. Per-record\nfailures land in `errors[]` with their original index; successful records\nland in `success[]` masked the same way the single-record response is.\n\n**Transactional matrix** (same as `PATCH /batch`):\n\n| Provider | failFast | transactional | Behavior |\n|---|---|---|---|\n| neon (Postgres via Hyperdrive) | `true` | `true` | `db.transaction()` wraps the loop; any throw rolls back all writes |\n| (any) | `false` | `false` | Independent per-record outcomes, partial success |\n| cloudflare-d1 | `true` | `false` | Fail-fast loop without rollback — earlier records stay committed (D1 has no `db.transaction`) |\n\n**Constraints:**\n\n- Record-based actions only. Standalone actions reject `bulkVariant: true`\n at compile time (no record context to loop over).\n- `unsafe` actions reject `bulkVariant: true` in v1 — the cross-tenant\n per-record audit story is not yet wired through.\n- Method is forced to POST regardless of the action's `method` setting. The\n semantic asymmetry (one row → many rows) makes inheriting GET/DELETE\n confusing.\n- Max batch size is 100 ids per request.\n\n## Standalone Actions\n\nStandalone actions are independent endpoints that don't require a record context. Set a `path:` to declare the action standalone.\n\n**Route pattern:** Custom `path`\n\n```\nPOST /chat\nGET /reports/summary\nPOST /webhooks/stripe\n```\n\n### Example: AI Chat with Streaming\n\n```typescript\n// features/sessions/actions/chat.ts\n\nexport default defineAction({\n description: \"Send a message to AI\",\n path: \"/chat\",\n method: \"POST\",\n responseType: \"stream\",\n input: z.object({\n message: z.string().min(1).max(2000),\n }),\n access: { roles: [\"recruiter\", \"hiring-manager\"] },\n async execute({ input, c }) {\n // Stream response back to client...\n return c.newResponse(/* ReadableStream */);\n },\n});\n```\n\n### Streaming Response Example\n\nFor actions with `responseType: 'stream'`:\n\n```\nContent-Type: text/event-stream\n\ndata: {\"type\": \"start\"}\ndata: {\"type\": \"chunk\", \"content\": \"Hello\"}\ndata: {\"type\": \"chunk\", \"content\": \"! I'm\"}\ndata: {\"type\": \"chunk\", \"content\": \" here to help.\"}\ndata: {\"type\": \"done\"}\n```\n\n### Tableless Features\n\nA feature directory with no top-level `*.ts` files is \"tableless\" — every\naction under `actions/` must be standalone. Use this for utility endpoints\nlike reports, integrations, or webhooks that don't map to a specific\nresource.\n\n```\nquickback/features/\n└── reports/\n └── actions/\n ├── trial-balance.ts ← standalone (has path:)\n └── profit-loss.ts ← standalone (has path:)\n```\n\n```typescript\n// features/reports/actions/trial-balance.ts\n\nexport default defineAction({\n description: \"Generate trial balance report\",\n path: \"/reports/trial-balance\",\n method: \"GET\",\n input: z.object({\n startDate: z.string(),\n endDate: z.string(),\n }),\n access: { roles: [\"admin\", \"accountant\"] },\n async execute({ db, input }) {\n // ... build report\n return { rows: [] };\n },\n});\n```\n\n### GET vs POST for input\n\nGET actions read `input` from URL query parameters; every other method (POST,\nPUT, PATCH, DELETE) reads from the JSON body. The Zod schema is the same in\nboth cases — the compiler picks the right parser based on `method`.\n\n```typescript\n// GET — input populated from ?q=…&limit=…\ndefineAction({\n method: \"GET\",\n path: \"/search\",\n input: z.object({\n q: z.string(),\n limit: z.coerce.number().int().positive().max(100).default(20),\n }),\n access: { roles: [\"AUTHENTICATED\"] },\n async execute({ input }) {\n // input is { q: string, limit: number } — fully typed.\n },\n});\n```\n\nRepeated query keys (`?tag=a&tag=b`) come through as arrays automatically;\nsingle values stay as strings. Use Zod's `.coerce.number()` /\n`.coerce.boolean()` when you want typed primitives from the parsed strings.\n\n**Use POST when input is structured.** GET requests cannot carry a JSON body\nin any of the surfaces Quickback APIs are commonly called from:\n\n- Browsers throw on `fetch(url, { method: 'GET', body })`.\n- CDNs and caches key on URL+method; a GET with a body either gets the body\n stripped at the edge or cache-collides with semantically different requests.\n- OpenAPI client generators (axios, openapi-fetch, openapi-typescript-codegen)\n refuse to emit GET-with-body, so the generated SDKs break.\n- The MCP agent surface treats GET as parameter-only — agents calling a GET\n action will only see what the URL exposes.\n\nIf your action takes nested objects, arrays of objects, or large inputs that\ndon't serialize cleanly to a query string, set `method: \"POST\"`. POST doesn't\nimply \"this writes data\" — it's the right method whenever the request body is\nload-bearing. Use the response shape (`responseType: \"json\"`, or just the data\nyour handler returns) to convey read semantics; HTTP method choice is about\ninput transport, not action intent.\n\n## Access Configuration\n\nAccess controls who can execute an action and under what conditions.\n\n### Role-Based Access\n\n```typescript\naccess: {\n roles: [\"hiring-manager\", \"recruiter\"] // OR logic: user needs any of these roles\n}\n```\n\n### Public Access\n\nUse `roles: [\"PUBLIC\"]` for unauthenticated endpoints (contact forms, webhooks, public APIs). Every invocation is **mandatory audit logged** with IP address, input, result, and timing.\n\n```typescript\n// features/contact/actions/submit.ts\n\nexport default defineAction({\n description: \"Public contact form submission\",\n path: \"/submit\",\n input: z.object({\n name: z.string().min(1),\n email: z.string().email(),\n message: z.string().min(10),\n }),\n access: { roles: [\"PUBLIC\"] },\n async execute({ db, input }) {\n // ... persist submission\n return { ok: true };\n },\n});\n```\n\nThe wildcard `\"*\"` is not supported and will throw a compile-time error. Use `\"PUBLIC\"` explicitly.\n\n### Record Conditions\n\nFor record-based actions, you can require the record to be in a specific state:\n\n```typescript\naccess: {\n roles: [\"hiring-manager\"],\n record: {\n stage: { equals: \"screening\" } // Precondition\n }\n}\n```\n\n**Supported operators:**\n\n| Operator | Description |\n|----------|-------------|\n| `equals` | Field must equal value |\n| `notEquals` | Field must not equal value |\n| `in` | Field must be one of the values |\n| `notIn` | Field must not be one of the values |\n\n### Context Substitution\n\nUse `$ctx` to reference the current user's context:\n\n```typescript\naccess: {\n record: {\n ownerId: { equals: \"$ctx.userId\" },\n organizationId: { equals: \"$ctx.activeOrgId\" }\n }\n}\n```\n\n### OR/AND Combinations\n\n```typescript\naccess: {\n or: [\n { roles: [\"hiring-manager\"] },\n {\n roles: [\"recruiter\"],\n record: { ownerId: { equals: \"$ctx.userId\" } }\n }\n ]\n}\n```\n\n### Function Access\n\nFor complex logic, use an access function:\n\n```typescript\naccess: async (ctx, record) => {\n return ctx.roles.includes('admin') || record.ownerId === ctx.userId;\n}\n```\n\n### Relationship-roles in actions\n\n**v0.19+** — standalone actions now support relationship-roles in `access.roles` directly. Declare the relationship under `authz.relationships` with optional `loads` / `exposeAs` for ctx hydration, and reference the role by name on the action:\n\n```ts\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n roles: { attendee: { via: 'attendeeOf' } },\n}\n\n// features/chat/actions/getInbox.ts\nexport default defineAction({\n path: '/chat/get-inbox',\n input: z.object({ eventId: z.number().int().positive() }),\n access: { roles: ['admin', 'member', 'attendee'] },\n execute: async ({ db, ctx, input }) => {\n // The resolver already verified attendance and loaded ctx.event.\n // No hand-rolled `SELECT … FROM guests WHERE …` needed.\n },\n});\n```\n\nThe action's surface (path params + input fields) must expose the relationship's `resource.column`. At v0.19 a missing key emits a `[quickback:authz]` warning and skips resolver emission; at v0.20 it becomes a compile error. See [Access — standalone actions](/compiler/definitions/access#standalone-actions-surface-keys-and-loads--exposeas-v019) for the full mechanism.\n\n**Record-based actions** are NOT yet supported — the runtime evaluator fail-closes (403) on relationship arms reached without an inline gate. Until inline emission for record-based actions lands, either:\n\n- Set `firewall: { exception: true }` on the action and gate manually in `execute()`, OR\n- Apply the relationship at the resource's firewall layer (worked example below).\n\n**Resource-layer workaround for record-based actions**: gate the action on BA roles only and apply the relationship at the resource layer via a firewall `via:` predicate:\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n },\n },\n}\n\n// features/sessions/sessions.ts — firewall scopes rows; action gates on BA role\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' }, // ← row-level relationship check\n],\nactions: {\n comment: defineAction({\n access: { roles: ['member', 'admin'] }, // ← BA role only on the action\n input: z.object({ text: z.string() }),\n execute: async (input, ctx, db, record) => {\n // record is already filtered by the firewall — guest membership\n // is enforced before this handler runs.\n return db.insert(comments).values({ ... });\n },\n }),\n}\n```\n\nThis pattern composes cleanly: the firewall guarantees the caller has the relationship to the record being acted on; the action's access list keeps the role surface obvious.\n\nSee [Access — relationship authorization](/compiler/definitions/access#relationship-based-authorization) for the full picture, including `loads` / `exposeAs` and the `firewall: { exception: true }` escape hatch.\n\n## Scoped Database\n\nAll actions receive a **scoped `db`** instance that automatically enforces security:\n\n| Operation | Org Scoping | Owner Scoping | Soft Delete Filter | Auto-inject on INSERT |\n|-----------|-------------|---------------|--------------------|-----------------------|\n| `SELECT` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n| `INSERT` | n/a | n/a | n/a | `organizationId`, `ownerId` from ctx |\n| `UPDATE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n| `DELETE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n\nScoping is duck-typed at runtime — tables with an `organizationId` column get org scoping, tables with `ownerId` get owner scoping, tables with `deletedAt` get soft delete filtering.\n\n```typescript\nasync execute({ db, ctx, input }) {\n // This query automatically includes WHERE organizationId = ? AND deletedAt IS NULL\n const items = await db.select().from(applications).where(eq(applications.stage, 'interview'));\n\n // Inserts automatically include organizationId\n await db.insert(applications).values({ candidateId: input.candidateId, jobId: input.jobId, stage: 'applied' });\n\n return items;\n}\n```\n\n**Not enforced** in scoped DB (by design):\n- **Guards** — actions ARE the authorized way to modify guarded fields\n- **Masking** — actions are backend code that may need raw data\n- **Access** — already checked before action execution\n\n### Unsafe Mode\n\nActions that need to bypass scoped DB filters (for example, platform-level support operations) can enable unsafe mode.\n\nUse object form for explicit policy and mandatory audit metadata:\n\n```typescript\n// features/admin/actions/cross-tenant-report.ts\n\nexport default defineAction({\n description: \"Generate cross-org hiring report\",\n path: \"/admin/cross-tenant-report\",\n input: z.object({ startDate: z.string() }),\n access: { roles: [\"owner\"] },\n unsafe: {\n reason: \"Support investigation for enterprise customer\",\n adminOnly: true, // default true\n crossTenant: true, // default true\n targetScope: \"all\", // \"all\" | \"organization\"\n },\n async execute({ unsafeDb, input }) {\n // unsafeDb bypasses scoped filters\n const allOrgs = await unsafeDb.select().from(applications);\n return allOrgs;\n },\n});\n```\n\nUnsafe cross-tenant actions are generated with:\n\n- Better Auth authentication required (no unauthenticated path)\n- sysadmin gate (`ctx.userRole === \"sysadmin\"`)\n- mandatory audit logging on deny/success/error\n\n`PUBLIC` actions also receive mandatory audit logging (same audit table), since unauthenticated endpoints are high-risk by nature.\n\nWithout unsafe mode, `unsafeDb` is `undefined` in the executor params.\n\n### Raw SQL Policy\n\nBy default, the compiler rejects raw SQL in action code. Use Drizzle query-builder syntax whenever possible.\n\nIf a specific action must use raw SQL, opt in explicitly:\n\n```typescript\n// features/ledgers/actions/reconcile.ts\n\nexport default defineAction({\n description: \"Run custom reconciliation query\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n allowRawSql: true,\n async execute({ db }) {\n return db.execute(sql`select 1`);\n },\n});\n```\n\nWithout `allowRawSql: true`, compilation fails with a loud error pointing to the action and snippet.\n\nThe detector checks for SQL keywords in string arguments, so non-SQL method calls like `headers.get(\"X-Forwarded-For\")` or `map.get(\"key\")` will not trigger false positives.\n\n## Sharing Code Between Actions\n\nFor Zod schemas, helpers, or constants used across multiple actions in a\nfeature, put them under `<feature>/lib/` and import from each action file.\nFiles under `lib/` are copied verbatim into the generated output.\n\n```\nfeatures/applications/\n├── applications.ts\n├── actions/\n│ ├── advance.ts\n│ └── reject.ts\n└── lib/\n ├── inputs.ts ← shared Zod schemas\n └── transitions.ts ← state-machine helpers\n```\n\n```typescript\n// features/applications/lib/inputs.ts\n\nexport const advanceInput = z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n notes: z.string().max(2000).optional(),\n});\n```\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move forward\",\n input: advanceInput,\n access: { roles: [\"owner\"] },\n async execute({ db, record, input }) { /* … */ },\n});\n```\n\n### Importing Tables\n\nAction files import tables from their own feature or other features. The compiler generates alias files for each table, so you import by the table's file name:\n\n```typescript\n// features/applications/actions/advance.ts\n\n// Same feature — import from parent directory using the table's file name\n\n// Cross-feature — go up to the features directory, then into the other feature\n\n```\n\n**Path pattern from `features/{name}/actions/`:**\n- Same feature table: `../{table-file-name}` (e.g., `../applications`)\n- Other feature table: `../../{other-feature}/{table-file-name}` (e.g., `../../candidates/candidates`)\n- Generated lib files: `../../../lib/{module}` (e.g., `../../../lib/realtime`, `../../../lib/webhooks`)\n\n### Executor Parameters\n\n```typescript\n\ninterface ActionExecutorParams {\n db: DrizzleDB; // Scoped database (auto-applies org/owner/soft-delete filters)\n unsafeDb?: DrizzleDB; // Unscoped database (only available when unsafe mode is enabled)\n ctx: AppContext; // User context (userId, roles, activeOrgId, activeTeamId, userRole)\n record?: TRecord; // The record (record-based only, undefined for standalone)\n input: TInput; // Validated input from Zod schema\n services: TServices; // Configured integrations (billing, notifications, etc.)\n c: HonoContext; // Raw Hono context for advanced use\n env: Env; // Runtime bindings (Cloudflare env / process env). Alias for c.env.\n auth: Auth; // Better Auth instance — call auth.api.getSession(...) etc. Lazy on Cloudflare.\n whereRecord?: (table) => SQL; // Pre-built WHERE: firewall + soft-delete + eq(table.id, record.id). Record-based actions only.\n whereTransition?: (table) => SQL; // whereRecord plus the transition's \"from\" precondition. Transition actions only.\n}\n```\n\n#### `auth` — Better Auth instance\n\n`auth` is the Better Auth instance, ready to call from inside an action\nhandler. Use it for things like minting an OAuth access token, fetching the\ncurrent session in a custom way, or invoking a Better Auth plugin method\nthat isn't already exposed by the generated middleware.\n\n```typescript\n// features/integrations/actions/connect-google-drive.ts\n\nexport default defineAction({\n description: \"Get a fresh Google Drive access token for the signed-in user\",\n input: z.object({}),\n access: { roles: [\"AUTHENTICATED\"] },\n async execute({ auth, ctx, c }) {\n // genericOAuth plugin method — needs a cast since the default-generic\n // `Auth` type doesn't carry plugin-specific API surface.\n const token = await (auth.api as any).getAccessToken({\n headers: c.req.raw.headers,\n body: { providerId: \"google\", userId: ctx.userId },\n });\n return { accessToken: token.accessToken };\n },\n});\n```\n\n**Lazy on Cloudflare**: the generated handler emits a `Proxy` so\n`createAuth(c.env, c.req.raw.cf)` only runs the first time you read a\nproperty on `auth`. Actions that never touch `auth` pay zero construction\ncost. On Bun/Node `auth` is the imported singleton (an IIFE that lazy-loads\nthe database adapter) wrapped in the same proxy shape — call sites are\nidentical across runtimes.\n\n**Typing**: `auth` is typed as `Auth` from `better-auth`. The base API\n(`getSession`, `signOut`, `signInEmail`, etc.) is fully typed. Plugin-only\nmethods (`getAccessToken` from `genericOAuth`, admin-plugin methods, etc.)\nneed a cast at the call site — the default-generic `Auth` doesn't infer\nthe project's specific plugin set.\n\n#### `whereRecord` — explicit, scope-safe WHERE\n\nFor protected-field writes inside record-based actions, prefer\n`whereRecord(table)` over `eq(table.id, record.id)`. It returns a Drizzle\nexpression that AND-merges the resource's firewall and soft-delete predicates\nwith the record id, so the WHERE is explicit even if a future refactor swaps\n`db` back to an unscoped client:\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Advance\",\n input: /* … */,\n access: { roles: [\"owner\"] },\n async execute({ db, record, input, whereRecord }) {\n const [updated] = await db\n .update(applications)\n .set({\n status: input.nextStatus,\n notes: input.notes ?? record.notes,\n })\n .where(whereRecord!(applications)) // firewall + soft-delete + id, all in one\n .returning();\n return updated;\n },\n});\n```\n\nThe audit DB wrapper hard-stamps `modifiedAt`/`modifiedBy` on every\n`.set()` call, so handlers don't write them. The same wrapper hard-stamps\n`createdAt`/`createdBy`/`modifiedAt`/`modifiedBy` on every `.values()`.\nCaller-supplied audit fields are dropped on the floor — the audit log\nalways reflects the real actor and the real moment.\n\n`whereRecord` is undefined for standalone actions (they have no record), so\nthe parameter is typed as optional. `whereTransition` extends `whereRecord`\nwith the transition's \"from\" precondition for transition actions.\n\n#### Reaching Better Auth tables (`authDb`)\n\nThe scoped `db` only sees your feature tables. To read Better Auth tables —\nusers, organizations, members — use the auth database connection from the\nHono context plus the generated `lib/org-access.ts` helper:\n\n```typescript\n// features/projects/actions/assign.ts — validate a userId is an org member\n\nexport default defineAction({\n description: \"Assign a project to an org member\",\n input: z.object({ assigneeId: z.string() }),\n access: { roles: [\"member\", \"admin\"] },\n async execute({ db, record, input, ctx, c, whereRecord }) {\n // getOrgMemberRole(authDb, userId, organizationId) → role string | null\n const role = await getOrgMemberRole(c.get(\"authDb\"), input.assigneeId, ctx.activeOrgId!);\n if (!role) {\n throw new ActionError(\"Assignee is not a member of this organization\", \"NOT_A_MEMBER\", 400);\n }\n const [updated] = await db\n .update(projects)\n .set({ assigneeId: input.assigneeId })\n .where(whereRecord!(projects))\n .returning();\n return updated;\n },\n});\n```\n\n`c.get(\"authDb\")` is the Drizzle connection to the auth database (in dual-DB\nmode it's a separate D1 from your features). For richer queries, import the\nauth schema tables from `../../../auth/schema` and query `authDb` directly.\n\n## HTTP API Reference\n\n### Request Format\n\n| Method | Input Source | Use Case |\n|--------|--------------|----------|\n| `GET` | Query parameters | Read-only operations, fetching data |\n| `POST` | JSON body | Default, state-changing operations |\n| `PUT` | JSON body | Full replacement operations |\n| `PATCH` | JSON body | Partial updates |\n| `DELETE` | JSON body | Deletion with optional payload |\n\n### Response Formats\n\n| Type | Content-Type | Use Case |\n|------|--------------|----------|\n| `json` | `application/json` | Standard API responses (default) |\n| `stream` | `text/event-stream` | Real-time streaming (AI chat, live updates) |\n| `file` | Varies | File downloads (reports, exports) |\n\n### Error Codes\n\n| Status | Description |\n|--------|-------------|\n| `400` | Invalid input / validation error (also `GUARD_FIELD_PROTECTED` for direct protected-field writes) |\n| `401` | Not authenticated |\n| `403` | Access role check failed (`ACCESS_ROLE_REQUIRED`) |\n| `404` | Record not found (record-based actions) |\n| `409` | Record is in the wrong state for this action — `access.record` predicate or `transition` policy failed (`ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`) |\n| `500` | Handler execution error |\n\n### Validation Error Response\n\n```json\n{\n \"error\": \"Invalid request data\",\n \"layer\": \"validation\",\n \"code\": \"VALIDATION_FAILED\",\n \"details\": {\n \"fields\": {\n \"amount\": \"Expected positive number\"\n }\n },\n \"hint\": \"Check the input schema for this action\"\n}\n```\n\n### Error Handling\n\n**Option 1: Return a JSON error response** (recommended for most cases)\n\nSince action handlers receive the Hono context (`c`), you can return error responses directly:\n\n```typescript\nasync execute({ ctx, record, input, c }) {\n if (record.stage === 'hired') {\n return c.json({\n error: 'Cannot modify a hired application',\n code: 'ALREADY_HIRED',\n details: { currentStage: record.stage },\n }, 400);\n }\n // ... continue\n}\n```\n\n**Option 2: Throw an ActionError**\n\n```typescript\n\nasync execute({ ctx, record, input }) {\n if (record.stage === 'hired') {\n throw new ActionError('Cannot modify a hired application', 'ALREADY_HIRED', 400, {\n currentStage: record.stage,\n });\n }\n // ... continue\n}\n```\n\nThe `ActionError` constructor signature is `(message, code, statusCode = 400, details?)`. The compile step rewrites the `@quickback/compiler` import to the generated runtime class (`src/lib/types.ts`), and the route handler catches it by name and returns `{ error, code, details }` with your `statusCode`.\n\n## Protected Fields\n\nActions can modify fields that are protected from regular CRUD operations:\n\n```typescript\n// In the table file (defineTable config)\nguards: {\n protected: {\n status: [\"advance\", \"reject\", \"hire\", \"withdraw\"], // Only these actions can modify status\n }\n}\n```\n\nThis allows the `advance` action to set `status = \"interview\"` even though the field is protected from regular PATCH requests. Direct `PATCH /:id` attempts to set `status` are rejected by the guards layer with **400 GUARD_FIELD_PROTECTED**, and the field is omitted from the generated POST/PATCH body Zod schemas — clients cannot even send it past validation.\n\n## Transition (state-machine policy)\n\nFor protected fields that follow a state machine — application status, invoice\nlifecycle, order fulfilment — use `transition` on the action so the compiler\ngenerates a runtime guard that enforces the *from/to pair*, not just the\ncurrent state. Without it, an `advance` action whose input enum allows\n`[\"screening\", \"interview\", \"offer\"]` and whose `access.record` allows\n`status in [\"applied\", \"screening\", \"interview\"]` will happily run\n`applied → offer` (a skip) or `interview → screening` (a regression).\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\", // read target from input.nextStatus\n fromTo: {\n applied: [\"screening\"],\n screening: [\"interview\"],\n interview: [\"offer\"],\n },\n },\n async execute({ db, record, input, whereTransition }) { /* … */ },\n});\n```\n\n```typescript\n// features/applications/actions/hire.ts\n\nexport default defineAction({\n description: \"Finalize an offer.\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n transition: {\n field: \"status\",\n to: \"hired\", // fixed target — same value every call\n fromTo: { offer: [\"hired\"] },\n },\n async execute({ db, record, whereTransition }) { /* … */ },\n});\n```\n\n| Field | Required | Description |\n|---|---|---|\n| `field` | Yes | Record column to validate (e.g. `\"status\"`) |\n| `fromTo` | Yes | Map of current value → permitted next values. Keys also enumerate the legal source states. |\n| `via` | Yes (or `to`) | Input key that carries the target value. Use for variable-target actions like `advance`. |\n| `to` | Yes (or `via`) | Literal target value the action always writes. Use for fixed-target actions like `hire`/`reject`. |\n\nExactly one of `via` or `to` must be provided. The compiler rejects both at\nvalidate time. When `to` is set, it must appear in some `fromTo[*]` array —\notherwise the action would be unreachable, which is almost certainly a bug.\n\n### Wire-level errors\n\nThe compiled guard returns **409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`** with\nthe field, the current value, the requested target, and the allowed set:\n\n```json\n{\n \"error\": \"Action not allowed for current record state\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ACTION_NOT_ALLOWED_FOR_STATE\",\n \"details\": {\n \"field\": \"status\",\n \"current\": \"interview\",\n \"target\": \"screening\",\n \"allowedTargets\": [\"offer\"]\n },\n \"hint\": \"From \\\"interview\\\", status can transition to: offer\"\n}\n```\n\nThis is distinct from a role failure: if the caller has the wrong role they\nget **403 `ACCESS_ROLE_REQUIRED`** as before. Splitting the two lets clients\ntell *\"you can't do this\"* from *\"you can't do this *yet*\"* — the latter is\nrecoverable by the user, the former isn't.\n\nThe same 409 code is used when an `access.record` predicate (without\n`transition`) fails — for example `record: { status: { equals: \"pending\" } }`\ncalled against a paid invoice now returns 409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`,\nnot a misleading 403.\n\n## Examples\n\n### Bulk Import (Standalone, No Record)\n\n```typescript\n// features/candidates/actions/bulk-import.ts\n\nexport default defineAction({\n description: \"Import candidates from job board CSV\",\n path: \"/candidates/import\",\n input: z.object({\n data: z.array(z.object({\n email: z.string().email(),\n name: z.string(),\n })),\n }),\n access: { roles: [\"hiring-manager\", \"recruiter\"] },\n async execute({ db, input }) {\n const inserted = await db\n .insert(candidates)\n .values(input.data)\n .returning();\n return { imported: inserted.length };\n },\n});\n```"
83
83
  },
84
84
  "compiler/definitions/arrows": {
85
85
  "title": "Arrows",
@@ -195,7 +195,7 @@ export const DOCS = {
195
195
  },
196
196
  "compiler/targets/hono-api/database/neon": {
197
197
  "title": "Neon",
198
- "content": "Neon provides serverless PostgreSQL that works with Cloudflare Workers via HTTP connections. Choose Neon when you need PostgreSQL features (JSON operators, full-text search, advanced indexing) or want database-level Row Level Security alongside the generated Hono API.\n\n## Why Neon\n\n- **Full PostgreSQL** — Advanced queries, joins, PostGIS, full-text search\n- **Database-level security** — RLS policies enforce access even if the API is bypassed\n- **Serverless** — HTTP connection mode for Cloudflare Workers\n- **Neon Authorize** — JWT-based RLS via the `auth.user_id()` function\n- **Better Auth integration** — Works seamlessly with the Quickback auth provider\n\n## Configuration\n\n```typescript title=\"quickback/quickback.config.ts\"\n\nexport default defineConfig({\n name: \"my-app\",\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"neon\", {\n connectionMode: \"auto\", // detects runtime\n pooled: true,\n }),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## Connection modes\n\n| Mode | Best for | How it works |\n|------|----------|--------------|\n| **HTTP** | Cloudflare Workers, edge functions | Stateless HTTP queries via `@neondatabase/serverless` |\n| **WebSocket** | Node.js, Bun | Persistent WebSocket connection for lower latency |\n| **Auto** (default) | Mixed environments | Detects runtime and picks the best mode |\n\n## Environment variables\n\n```bash\n# For Cloudflare Workers\nnpx wrangler secret put DATABASE_URL\n# Paste: postgresql://user:pwd@ep-xxx.region.neon.tech/db?sslmode=require\n\n# For local development (.env)\nDATABASE_URL=postgresql://user:pwd@ep-xxx.region.neon.tech/db?sslmode=require\n```\n\n## Migrations\n\nNeon uses PostgreSQL migrations, distinct from D1's SQLite migrations:\n\n```bash\nquickback compile # generates migrations under quickback/drizzle/\nnpm run db:migrate # applies them\n```\n\n## Row Level Security\n\nQuickback emits RLS policies from your `firewall` and `access` config. The Neon target uses Neon Authorize's `auth.user_id()` JWT claim function (the Supabase target uses `auth.uid()` instead — same pattern, different function).\n\n```typescript\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n]\n```\n\n```sql\nCREATE POLICY \"documents_select\" ON documents FOR SELECT\nUSING (\n organization_id = get_active_org_id()\n AND (has_any_role(ARRAY['admin']) OR user_id = auth.user_id())\n);\n```\n\n### Firewall patterns\n\n**Organization-scoped:**\n\n```sql\nCREATE POLICY \"projects_select\" ON projects FOR SELECT\nUSING (organization_id = public.get_active_org_id());\n```\n\n**User-scoped:**\n\n```sql\nCREATE POLICY \"preferences_select\" ON preferences FOR SELECT\nUSING (user_id = auth.user_id());\n```\n\n**Public tables:**\n\n```sql\nCREATE POLICY \"categories_deny_anon\" ON categories FOR ALL TO anon USING (false);\nCREATE POLICY \"categories_all\" ON categories FOR ALL TO authenticated USING (true) WITH CHECK (true);\n```\n\n### Helper functions\n\n| Function | Purpose |\n|----------|---------|\n| `get_active_org_id()` | Returns the user's active organization from `user_sessions` |\n| `has_any_role(roles[])` | Checks if the user has any specified role |\n| `has_org_role(role)` | Checks for a single specific role |\n| `is_org_member()` | Checks org membership |\n| `is_owner(owner_id)` | Checks record ownership |\n\n## Setting up Neon Authorize\n\n1. Open **Project Settings → Authorize** in the Neon console\n2. Add your JWKS URL: `https://your-api.example.com/auth/v1/.well-known/jwks.json`\n3. The `auth.user_id()` function will return the authenticated user's ID from the JWT\n\n## Generated files\n\n```\nquickback/drizzle/\n├── migrations/\n│ ├── 0100_create_rls_helpers.sql\n│ ├── 0101_create_rls_policies.sql\n│ └── 0102_create_indexes.sql\nsrc/\n├── db/schema.ts # Drizzle schema\n├── auth/schema.ts # Better Auth schema\n└── lib/neon.ts # Connection helper\n```\n\n## When to choose Neon vs D1\n\n| Factor | Neon | D1 |\n|--------|------|-----|\n| SQL dialect | PostgreSQL | SQLite |\n| Security model | RLS + application-layer | Application-layer only |\n| Multi-region | Built-in replication | Single region per database |\n| Pricing | Free tier, then usage-based | Free tier, then usage-based |\n| Best for | Complex queries, existing Postgres apps | Edge-first, simple schemas |\n\n## See also\n\n- [D1](/compiler/targets/hono-api/database/d1) — SQLite at the edge\n- [Providers](/compiler/config/providers) — All database provider options"
198
+ "content": "Neon provides serverless PostgreSQL that works with Cloudflare Workers via HTTP connections. Choose Neon when you need PostgreSQL features (JSON operators, full-text search, advanced indexing) or want database-level Row Level Security alongside the generated Hono API.\n\n## Why Neon\n\n- **Full PostgreSQL** — Advanced queries, joins, PostGIS, full-text search\n- **Database-level security** — RLS policies enforce access even if the API is bypassed\n- **Serverless** — HTTP connection mode for Cloudflare Workers\n- **Neon Authorize** — JWT-based RLS via the `auth.user_id()` function\n- **Better Auth integration** — Works seamlessly with the Quickback auth provider\n\n## Configuration\n\n```typescript title=\"quickback/quickback.config.ts\"\n\nexport default defineConfig({\n name: \"my-app\",\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"neon\", {\n connectionMode: \"auto\", // detects runtime\n pooled: true,\n }),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## Connection modes\n\n| Mode | Best for | How it works |\n|------|----------|--------------|\n| **HTTP** | Cloudflare Workers, edge functions | Stateless HTTP queries via `@neondatabase/serverless` |\n| **WebSocket** | Node.js, Bun | Persistent WebSocket connection for lower latency |\n| **Auto** (default) | Mixed environments | Detects runtime and picks the best mode |\n\n## Environment variables\n\n```bash\n# For Cloudflare Workers\nnpx wrangler secret put DATABASE_URL\n# Paste: postgresql://user:pwd@ep-xxx.region.neon.tech/db?sslmode=require\n\n# For local development (.env)\nDATABASE_URL=postgresql://user:pwd@ep-xxx.region.neon.tech/db?sslmode=require\n```\n\n## Migrations\n\nNeon uses PostgreSQL migrations, distinct from D1's SQLite migrations:\n\n```bash\nquickback compile # generates migrations under quickback/drizzle/\nnpm run db:migrate # applies them — schema AND the RLS layer\n```\n\nThe RLS layer (helper functions, policies, triggers) rides the same\njournaled migration set as your schema (v0.45+): the compiler appends a\ncontent-addressed `<idx>_quickback_rls_<hash>` migration, so one\n`db:migrate` applies everything in order. The RLS migration is idempotent\n(`DROP POLICY IF EXISTS` + re-create) and only a *changed* security config\nappends a new entry — recompiles with unchanged security append nothing. No\nmanual SQL application step exists anymore.\n\n## Row Level Security\n\nQuickback emits RLS policies from your `firewall` and `access` config. The Neon target uses Neon Authorize's `auth.user_id()` JWT claim function (the Supabase target uses `auth.uid()` instead — same pattern, different function).\n\n```typescript\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n]\n```\n\n```sql\nCREATE POLICY \"documents_select\" ON documents FOR SELECT\nUSING (\n organization_id = get_active_org_id()\n AND (has_any_role(ARRAY['admin']) OR user_id = auth.user_id())\n);\n```\n\n### Firewall patterns\n\n**Organization-scoped:**\n\n```sql\nCREATE POLICY \"projects_select\" ON projects FOR SELECT\nUSING (organization_id = public.get_active_org_id());\n```\n\n**User-scoped:**\n\n```sql\nCREATE POLICY \"preferences_select\" ON preferences FOR SELECT\nUSING (user_id = auth.user_id());\n```\n\n**Public tables:**\n\n```sql\nCREATE POLICY \"categories_deny_anon\" ON categories FOR ALL TO anon USING (false);\nCREATE POLICY \"categories_all\" ON categories FOR ALL TO authenticated USING (true) WITH CHECK (true);\n```\n\n### Helper functions\n\n| Function | Purpose |\n|----------|---------|\n| `get_active_org_id()` | Returns the user's active organization from `user_sessions` |\n| `has_any_role(roles[])` | Checks if the user has any specified role |\n| `has_org_role(role)` | Checks for a single specific role |\n| `is_org_member()` | Checks org membership |\n| `is_owner(owner_id)` | Checks record ownership |\n\nAll helpers are TEXT-typed to match Better Auth's prefixed ids\n(`org_abc123`). The `user_sessions` table the org helpers read is\ncompiler-owned migration state (`src/db/rls-support.schema.ts`), created by\nthe journaled migrations and kept in sync automatically: generated Better\nAuth session hooks mirror the session's active organization (and team) into\nit on every session create/update. Switching to \"no org\" revokes SQL-side\naccess — fail closed.\n\nRLS coverage includes Better Auth's own tables — including those the\ncompiler force-enables (organization, admin, `apikeys`; plus the OAuth/agent\ntable families when those surfaces are on, locked to service-role only).\n\n## Setting up Neon Authorize\n\n1. Open **Project Settings → Authorize** in the Neon console\n2. Add your JWKS URL: `https://your-api.example.com/auth/v1/.well-known/jwks.json`\n3. The `auth.user_id()` function will return the authenticated user's ID from the JWT\n\n## Generated files\n\n```\nquickback/drizzle/\n├── 0000_<name>.sql # schema migrations (drizzle-kit)\n├── 0001_quickback_rls_<hash>.sql # journaled RLS layer (content-addressed)\n└── meta/_journal.json # one journal covers both\nsrc/\n├── db/schema.ts # Drizzle schema barrel\n├── db/rls-support.schema.ts # user_sessions + RLS support tables\n└── auth/schema.ts # Better Auth schema (owned by the BA CLI)\n```\n\n## When to choose Neon vs D1\n\n| Factor | Neon | D1 |\n|--------|------|-----|\n| SQL dialect | PostgreSQL | SQLite |\n| Security model | RLS + application-layer | Application-layer only |\n| Multi-region | Built-in replication | Single region per database |\n| Pricing | Free tier, then usage-based | Free tier, then usage-based |\n| Best for | Complex queries, existing Postgres apps | Edge-first, simple schemas |\n\n## See also\n\n- [D1](/compiler/targets/hono-api/database/d1) — SQLite at the edge\n- [Providers](/compiler/config/providers) — All database provider options"
199
199
  },
200
200
  "compiler/targets/hono-api/database/using-d1": {
201
201
  "title": "Using D1",
@@ -231,7 +231,7 @@ export const DOCS = {
231
231
  },
232
232
  "compiler/targets/hono-api/using-the-api/openapi": {
233
233
  "title": "OpenAPI Spec",
234
- "content": "The compiler generates an [OpenAPI 3.1](https://spec.openapis.org/oas/v3.1.0) specification from your feature definitions. By default it's both written to `openapi.json` at your project root and served as a runtime route.\n\n## Endpoint\n\n```\nGET /openapi.json\n```\n\nReturns the full OpenAPI spec as JSON.\n\n```bash\ncurl https://your-api.example.com/openapi.json\n```\n\n## What's included\n\nThe generated spec documents every route the compiler produces:\n\n- CRUD endpoints (list, get, create, update, delete)\n- Batch operations\n- Views\n- Actions (including standalone actions)\n- Auth routes (`/api/auth/**`)\n- Storage, embeddings, and webhook routes (when configured)\n\nEach endpoint includes request/response schemas derived from your Drizzle column types, access control metadata, and error responses.\n\n### Schema fidelity\n\nThe generated component schemas carry enough type information that strict validators (zod, openapi-typescript, openapi-fetch) produce non-optional, narrowed types out of the box:\n\n- **`required[]` on response components** — every non-nullable column is listed, so generated SDKs treat them as guaranteed-present rather than optional.\n- **Closed enums on `text(_, { enum: [...] })` columns** — emitted as `{ type: \"string\", enum: [...] }`, narrowing to a literal union in TS.\n- **`Error.code` is a closed enum** — every `code` value the API can emit (`AUTH_MISSING`, `DB_UNIQUE_VIOLATION`, `BATCH_SIZE_EXCEEDED`, …) is enumerated so consumers can `switch` exhaustively.\n- **ID `format`** — only emitted as `format: \"uuid\"` when your project's `generateId` actually produces UUIDs. cuid2 / prefixed / nanoid / serial generators get plain `{ type: \"string\" }`, keeping strict OpenAPI validators happy.\n\n### Action input schemas\n\nActions defined with [`defineAction({ input: z.object(...) })`](/compiler/definitions/actions) get their full input schema lifted into the operation's `requestBody`. 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 so the OpenAPI request body and the MCP tool's `inputSchema` round-trip exactly what your Zod expression declares — no static translator to maintain.\n\n## Configuration\n\nBoth generation and publishing default to `true`. You can control them independently in `quickback.config.ts`:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n // ...\n openapi: {\n generate: true, // write openapi.json to project root\n publish: true, // serve GET /openapi.json at runtime\n },\n});\n```\n\n| Option | Default | Description |\n|--------|---------|-------------|\n| `generate` | `true` | Write `openapi.json` to the project root during compilation |\n| `publish` | `true` | Serve the spec at `GET /openapi.json` (requires `generate: true`) |\n| `docs` | `false` | Mount an interactive API browser at `GET /docs` — `\"scalar\"`, `\"swagger\"`, or `false` |\n\nOmitting the `openapi` key entirely is equivalent to `generate: true, publish: true, docs: false`.\n\n### Generate only (no runtime route)\n\n```typescript\nopenapi: {\n generate: true,\n publish: false,\n}\n```\n\nThe file is still written so you can use it in CI or commit it to your repo, but no route is added to the app.\n\n### Disable entirely\n\n```typescript\nopenapi: {\n generate: false,\n}\n```\n\nNo file is written and no route is served.\n\n### Interactive API browser at `/docs`\n\nMount an in-browser API reference by setting `openapi.docs`:\n\n```typescript\nopenapi: {\n docs: 'scalar', // or 'swagger'\n}\n```\n\n| Value | UI | Notes |\n|---|---|---|\n| `\"scalar\"` | [Scalar API Reference](https://scalar.com/) — modern, lightweight | Recommended default |\n| `\"swagger\"` | [Swagger UI](https://swagger.io/tools/swagger-ui/) — the familiar standard | Good if your team expects it |\n| `false` / unset | No `/docs` route | Default |\n\nBoth UIs are loaded from CDN in a generated static HTML route — **no npm package is added to your project, no Hono middleware is installed, and the runtime bundle stays the same size**. The flag is purely compile-time: it toggles whether a `/docs` route is emitted.\n\nRequires `publish: true` (the default). When `publish` is off, `/docs` is silently skipped — there's no spec for it to read.\n\n## Usage with tools\n\n### Import into Postman\n\n1. Open Postman and click **Import**\n2. Paste the URL `https://your-api.example.com/openapi.json` or upload the file\n3. Postman creates a collection with every endpoint pre-configured\n\n### Generated TypeScript types (`api-types.gen.ts`)\n\nThe compiler emits `api-types.gen.ts` next to `openapi.json` by default — a fully typed view of every route, request body, and response, ready to import in client code:\n\n```typescript\n\ntype Job = components['schemas']['Job'];\ntype ListJobsResponse = paths['/api/v1/jobs']['get']['responses']['200']['content']['application/json'];\n```\n\nPair it with [`openapi-fetch`](https://github.com/openapi-ts/openapi-typescript/tree/main/packages/openapi-fetch) for a fully typed client:\n\n```typescript\n\nconst client = createClient<paths>({ baseUrl: 'https://your-api.example.com' });\nconst { data, error } = await client.GET('/api/v1/jobs', { params: { query: { limit: 25 } } });\n```\n\n#### Configuration\n\n| `openapi.types` | Behavior |\n|---|---|\n| `true` (default) | Write `api-types.gen.ts` to the project root |\n| `false` | Don't emit the types file |\n| `\"src/lib/api-types.ts\"` | Custom output path (relative to project root) |\n| `[\"api-types.gen.ts\", \"apps/web/src/lib/api-types.gen.ts\"]` | Write the same generated types to multiple paths in one compile |\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n // ...\n openapi: {\n types: ['api-types.gen.ts', 'apps/web/src/lib/api-types.gen.ts'],\n },\n});\n```\n\nThe file is generated by piping the in-memory spec through [openapi-typescript](https://github.com/openapi-ts/openapi-typescript) — you can keep running it manually if you want a different output path or version, but for the typical case there's nothing to wire up. If your API project and SPA live in the same repo, prefer multiple `openapi.types` outputs over a second manual `codegen:api` step so one `quickback compile` keeps both copies in sync. Skipped automatically when `openapi.generate` is `false`.\n\nThe bundled Quickback CMS and Account SPAs do not import `api-types.gen.ts`. CMS is driven by `schema-registry.json`, and Account uses Better Auth plus small hand-written fetch helpers. Use `openapi.types` for your own colocated client apps.\n\n### External viewer\n\nPoint any OpenAPI-compatible viewer at the endpoint:\n\n```\nhttps://petstore.swagger.io/?url=https://your-api.example.com/openapi.json\n```\n\nOr enable the in-project browser via the [`docs` config option](#interactive-api-browser-at-docs) above and visit `/docs` directly.\n\n## Example output (excerpt)\n\n```json\n{\n \"openapi\": \"3.1.0\",\n \"info\": {\n \"title\": \"my-app API\",\n \"version\": \"1.0.0\"\n },\n \"paths\": {\n \"/api/v1/jobs\": {\n \"get\": {\n \"summary\": \"List jobs\",\n \"operationId\": \"listJobs\",\n \"parameters\": [\n { \"name\": \"limit\", \"in\": \"query\", \"schema\": { \"type\": \"integer\" } },\n { \"name\": \"offset\", \"in\": \"query\", \"schema\": { \"type\": \"integer\" } }\n ],\n \"responses\": {\n \"200\": {\n \"description\": \"Success\",\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"data\": { \"type\": \"array\", \"items\": { \"$ref\": \"#/components/schemas/Job\" } }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n## Operations manifest\n\nAlongside the spec, every compile writes `reports/operations.manifest.json` — a\nstable, machine-readable index of the full route surface (resource, action,\nview, and auth routes):\n\n```json\n[\n { \"operationId\": \"listCustomers\", \"method\": \"GET\", \"path\": \"/api/v1/customers\", \"auth\": \"session\", \"feature\": \"customers\", \"kind\": \"crud\" }\n]\n```\n\nThe manifest is a public contract: entries are sorted by `operationId`, carry\nno timestamps, and the shape is extend-only — new fields may be added, existing\nones won't change meaning. `operationId`s are stable across compiles for the\nsame configuration, which makes the manifest the recommended integration point\nfor agent/MCP tooling, route inventories, and diff-based change review.\n\nA sibling artifact, `reports/conformance.manifest.json`, enumerates the\nexpected authorization outcome for every route × principal class (derived from\nthe same compiler model that emits the enforcement code). The compiler's own CI\nexecutes it against a running build on every change."
234
+ "content": "The compiler generates an [OpenAPI 3.1](https://spec.openapis.org/oas/v3.1.0) specification from your feature definitions. By default it's both written to `openapi.json` at your project root and served as a runtime route.\n\n## Endpoint\n\n```\nGET /openapi.json\n```\n\nReturns the full OpenAPI spec as JSON.\n\n```bash\ncurl https://your-api.example.com/openapi.json\n```\n\n## What's included\n\nThe generated spec documents every route the compiler produces:\n\n- CRUD endpoints (list, get, create, update, delete)\n- Batch operations\n- Views\n- Actions (including standalone actions)\n- Auth routes (`/api/auth/**`)\n- Storage, embeddings, and webhook routes (when configured)\n\nEach endpoint includes request/response schemas derived from your Drizzle column types, access control metadata, and error responses.\n\n### Schema fidelity\n\nThe generated component schemas carry enough type information that strict validators (zod, openapi-typescript, openapi-fetch) produce non-optional, narrowed types out of the box:\n\n- **`required[]` on response components** — every non-nullable column is listed, so generated SDKs treat them as guaranteed-present rather than optional.\n- **Closed enums on `text(_, { enum: [...] })` columns** — emitted as `{ type: \"string\", enum: [...] }`, narrowing to a literal union in TS.\n- **`Error.code` is a closed enum** — every `code` value the API can emit (`AUTH_MISSING`, `DB_UNIQUE_VIOLATION`, `BATCH_SIZE_EXCEEDED`, …) is enumerated so consumers can `switch` exhaustively.\n- **ID `format`** — only emitted as `format: \"uuid\"` when your project's `generateId` actually produces UUIDs. cuid2 / prefixed / nanoid / serial generators get plain `{ type: \"string\" }`, keeping strict OpenAPI validators happy.\n\n### Action input schemas\n\nActions defined with [`defineAction({ input: z.object(...) })`](/compiler/definitions/actions) get their full input schema lifted into the operation's `requestBody`. 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 so the OpenAPI request body and the MCP tool's `inputSchema` round-trip exactly what your Zod expression declares — no static translator to maintain.\n\n## Configuration\n\nBoth generation and publishing default to `true`. You can control them independently in `quickback.config.ts`:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n // ...\n openapi: {\n generate: true, // write openapi.json to project root\n publish: true, // serve GET /openapi.json at runtime\n },\n});\n```\n\n| Option | Default | Description |\n|--------|---------|-------------|\n| `generate` | `true` | Write `openapi.json` to the project root during compilation |\n| `publish` | `true` | Serve the spec at `GET /openapi.json` (requires `generate: true`) |\n| `docs` | `false` | Mount an interactive API browser at `GET /docs` — `\"scalar\"`, `\"swagger\"`, or `false` |\n\nOmitting the `openapi` key entirely is equivalent to `generate: true, publish: true, docs: false`.\n\n### Generate only (no runtime route)\n\n```typescript\nopenapi: {\n generate: true,\n publish: false,\n}\n```\n\nThe file is still written so you can use it in CI or commit it to your repo, but no route is added to the app.\n\n### Disable entirely\n\n```typescript\nopenapi: {\n generate: false,\n}\n```\n\nNo file is written and no route is served.\n\n### Interactive API browser at `/docs`\n\nMount an in-browser API reference by setting `openapi.docs`:\n\n```typescript\nopenapi: {\n docs: 'scalar', // or 'swagger'\n}\n```\n\n| Value | UI | Notes |\n|---|---|---|\n| `\"scalar\"` | [Scalar API Reference](https://scalar.com/) — modern, lightweight | Recommended default |\n| `\"swagger\"` | [Swagger UI](https://swagger.io/tools/swagger-ui/) — the familiar standard | Good if your team expects it |\n| `false` / unset | No `/docs` route | Default |\n\nBoth UIs are loaded from CDN in a generated static HTML route — **no npm package is added to your project, no Hono middleware is installed, and the runtime bundle stays the same size**. The flag is purely compile-time: it toggles whether a `/docs` route is emitted.\n\nRequires `publish: true` (the default). When `publish` is off, `/docs` is silently skipped — there's no spec for it to read.\n\n## Usage with tools\n\n### Import into Postman\n\n1. Open Postman and click **Import**\n2. Paste the URL `https://your-api.example.com/openapi.json` or upload the file\n3. Postman creates a collection with every endpoint pre-configured\n\n### Generated TypeScript types (`api-types.gen.ts`)\n\nThe compiler emits `api-types.gen.ts` next to `openapi.json` by default — a fully typed view of every route, request body, and response, ready to import in client code:\n\n```typescript\n\ntype Job = components['schemas']['Job'];\ntype ListJobsResponse = paths['/api/v1/jobs']['get']['responses']['200']['content']['application/json'];\n```\n\nPair it with [`openapi-fetch`](https://github.com/openapi-ts/openapi-typescript/tree/main/packages/openapi-fetch) for a fully typed client:\n\n```typescript\n\nconst client = createClient<paths>({ baseUrl: 'https://your-api.example.com' });\nconst { data, error } = await client.GET('/api/v1/jobs', { params: { query: { limit: 25 } } });\n```\n\n#### Configuration\n\n| `openapi.types` | Behavior |\n|---|---|\n| `true` (default) | Write `api-types.gen.ts` to the project root |\n| `false` | Don't emit the types file |\n| `\"src/lib/api-types.ts\"` | Custom output path (relative to project root) |\n| `[\"api-types.gen.ts\", \"apps/web/src/lib/api-types.gen.ts\"]` | Write the same generated types to multiple paths in one compile |\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n // ...\n openapi: {\n types: ['api-types.gen.ts', 'apps/web/src/lib/api-types.gen.ts'],\n },\n});\n```\n\nThe file is generated by piping the in-memory spec through [openapi-typescript](https://github.com/openapi-ts/openapi-typescript) — you can keep running it manually if you want a different output path or version, but for the typical case there's nothing to wire up. If your API project and SPA live in the same repo, prefer multiple `openapi.types` outputs over a second manual `codegen:api` step so one `quickback compile` keeps both copies in sync. Skipped automatically when `openapi.generate` is `false`.\n\nThe bundled Quickback CMS and Account SPAs do not import `api-types.gen.ts`. CMS is driven by `schema-registry.json`, and Account uses Better Auth plus small hand-written fetch helpers. Use `openapi.types` for your own colocated client apps.\n\n### External viewer\n\nPoint any OpenAPI-compatible viewer at the endpoint:\n\n```\nhttps://petstore.swagger.io/?url=https://your-api.example.com/openapi.json\n```\n\nOr enable the in-project browser via the [`docs` config option](#interactive-api-browser-at-docs) above and visit `/docs` directly.\n\n## Example output (excerpt)\n\n```json\n{\n \"openapi\": \"3.1.0\",\n \"info\": {\n \"title\": \"my-app API\",\n \"version\": \"1.0.0\"\n },\n \"paths\": {\n \"/api/v1/jobs\": {\n \"get\": {\n \"summary\": \"List jobs\",\n \"operationId\": \"listJobs\",\n \"parameters\": [\n { \"name\": \"limit\", \"in\": \"query\", \"schema\": { \"type\": \"integer\" } },\n { \"name\": \"offset\", \"in\": \"query\", \"schema\": { \"type\": \"integer\" } }\n ],\n \"responses\": {\n \"200\": {\n \"description\": \"Success\",\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"data\": { \"type\": \"array\", \"items\": { \"$ref\": \"#/components/schemas/Job\" } }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n## Operations manifest\n\nAlongside the spec, every compile writes `reports/operations.manifest.json` — a\nstable, machine-readable index of the full route surface (resource, action,\nview, and auth routes; since v0.47 also the realtime, storage, and FGA\nsurfaces):\n\n```json\n[\n { \"operationId\": \"listCustomers\", \"method\": \"GET\", \"path\": \"/api/v1/customers\", \"auth\": \"session\", \"feature\": \"customers\", \"kind\": \"crud\" }\n]\n```\n\nThe manifest is a public contract: entries are sorted by `operationId`, carry\nno timestamps, and the shape is extend-only — new fields may be added, existing\nones won't change meaning. `operationId`s are stable across compiles for the\nsame configuration, which makes the manifest the recommended integration point\nfor agent/MCP tooling, route inventories, and diff-based change review.\n\nA sibling artifact, `reports/conformance.manifest.json`, enumerates the\nexpected authorization outcome for every route × principal class (derived from\nthe same compiler model that emits the enforcement code). The compiler's own CI\nexecutes it against a running build on every change."
235
235
  },
236
236
  "compiler/targets/hono-api/using-the-api/query-params": {
237
237
  "title": "Query Parameters",
@@ -283,7 +283,7 @@ export const DOCS = {
283
283
  },
284
284
  "stack/account-ui/features/organizations": {
285
285
  "title": "Organizations",
286
- "content": "Account UI provides a complete organization management interface when `VITE_ENABLE_ORGANIZATIONS=true`. Teams are a separate opt-in (`VITE_ENABLE_ORG_TEAMS`), surfaced when the compiler detects `organization({ teams: { enabled: true } })` in the Better Auth config.\n\n## Organization CRUD\n\n- Create new organizations, with `checkSlug` debounce on the slug field\n- Update name, **slug** (rename navigates to the new URL), **metadata** (JSON object), and logo\n- Delete organizations — gated on the `organization:delete` permission (default: owner)\n\n## Member Management\n\n- Invite members by email (with an optional team picker when teams are enabled)\n- Assign roles: **owner**, **admin**, **member**\n- Change roles and remove members — actions are filtered per-target by the role hierarchy (non-owners can't manage owner-role members)\n- Leave the organization\n\n> **Note:** These three roles (`owner`, `admin`, `member`) are Better Auth's built-in organization roles and map directly to Account UI's role picker. Use the same roles in your Quickback [Access](/compiler/definitions/access) rules — with [`auth.roleHierarchy`](/compiler/definitions/access#role-hierarchy) configured, you can write `roles: [\"member+\"]` to mean \"member and above.\"\n\n## Invitations\n\n- Pending invitation list, per organization\n- Resend, cancel (per-org), accept, and reject (per-user)\n- Pending invites across organizations land on the user's `/dashboard`\n- Invitations carry an optional `teamId` when teams are enabled — the invitee joins that team on accept\n\n## Teams\n\nSet `organization({ teams: { enabled: true } })` in your Better Auth config. The compiler emits `VITE_ENABLE_ORG_TEAMS=true` and the SPA exposes:\n\n- **Teams tab** on each organization, split into \"Your teams\" and \"Other teams\"\n- **Team detail** page with member roster, add/remove members\n- **Active-team picker** in the organization header — switches `session.activeTeamId` via `setActiveTeam`, so server-side handlers can scope by team\n- **Team-aware invitations** — when sending an invite, optionally pick a team; the member is added on accept\n\nPer-team actions (create / rename / delete / add-member / remove-member) gate on the `team:create`, `team:update`, and `team:delete` permissions from Better Auth's default statements.\n\n## Permission-aware UI\n\nAccount UI uses Better Auth's `checkRolePermission` API instead of hardcoded role checks. The `OrganizationContext` exposes a `can(resource, action)` helper that handles the default statements (`organization`, `member`, `invitation`, `team`, `ac`) and respects any custom roles you've registered via the BA `ac` option.\n\nMulti-role users — Better Auth stores multiple roles as a comma-separated string — are handled by checking each role independently; the action is allowed if any one of them grants it.\n\nThis means projects that ship custom roles get a UI that matches what their server actually authorizes, without modifying the Account SPA.\n\n## Related\n\n- [Environment Variables](/stack/account-ui/environment-variables)\n- [Account UI Overview](/stack/account-ui)"
286
+ "content": "Account UI provides a complete organization management interface when `VITE_ENABLE_ORGANIZATIONS=true`. Teams are a separate opt-in (`VITE_ENABLE_ORG_TEAMS`), surfaced when the compiler detects `organization({ teams: { enabled: true } })` in the Better Auth config.\n\n## Organization CRUD\n\n- Create new organizations, with `checkSlug` debounce on the slug field\n- Update name, **slug** (rename navigates to the new URL), **metadata** (JSON object), and logo\n- Delete organizations — gated on the `organization:delete` permission (default: owner)\n\n## Member Management\n\n- Invite members by email (with an optional team picker when teams are enabled)\n- Assign roles: **owner**, **admin**, **member**\n- Change roles and remove members — actions are filtered per-target by the role hierarchy (non-owners can't manage owner-role members)\n- Leave the organization\n\n> **Note:** These three roles (`owner`, `admin`, `member`) are Better Auth's built-in organization roles and map directly to Account UI's role picker. Use the same roles in your Quickback [Access](/compiler/definitions/access) rules — with [`auth.roleHierarchy`](/compiler/definitions/access#role-hierarchy) configured, you can write `roles: [\"member+\"]` to mean \"member and above.\" [Custom org roles](/compiler/definitions/access#custom-org-roles) declared in your access trees are auto-registered with the organization plugin (v0.46+), so `invite-member` / `update-member-role` accept them too.\n\n## Invitations\n\n- Pending invitation list, per organization\n- Resend, cancel (per-org), accept, and reject (per-user)\n- Pending invites across organizations land on the user's `/dashboard`\n- Invitations carry an optional `teamId` when teams are enabled — the invitee joins that team on accept\n\n## Teams\n\nSet `organization({ teams: { enabled: true } })` in your Better Auth config. The compiler emits `VITE_ENABLE_ORG_TEAMS=true` and the SPA exposes:\n\n- **Teams tab** on each organization, split into \"Your teams\" and \"Other teams\"\n- **Team detail** page with member roster, add/remove members\n- **Active-team picker** in the organization header — switches `session.activeTeamId` via `setActiveTeam`, so server-side handlers can scope by team\n- **Team-aware invitations** — when sending an invite, optionally pick a team; the member is added on accept\n\nPer-team actions (create / rename / delete / add-member / remove-member) gate on the `team:create`, `team:update`, and `team:delete` permissions from Better Auth's default statements.\n\n## Permission-aware UI\n\nAccount UI uses Better Auth's `checkRolePermission` API instead of hardcoded role checks. The `OrganizationContext` exposes a `can(resource, action)` helper that handles the default statements (`organization`, `member`, `invitation`, `team`, `ac`) and respects any custom roles you've registered via the BA `ac` option.\n\nMulti-role users — Better Auth stores multiple roles as a comma-separated string — are handled by checking each role independently; the action is allowed if any one of them grants it.\n\nThis means projects that ship custom roles get a UI that matches what their server actually authorizes, without modifying the Account SPA.\n\n## Related\n\n- [Environment Variables](/stack/account-ui/environment-variables)\n- [Account UI Overview](/stack/account-ui)"
287
287
  },
288
288
  "stack/account-ui/features/passkeys": {
289
289
  "title": "Passkeys",
@@ -375,7 +375,7 @@ export const DOCS = {
375
375
  },
376
376
  "stack/cms/pages": {
377
377
  "title": "Custom Pages",
378
- "content": "# Custom Pages\n\nCustom pages extend the CMS beyond standard table views. Define split-panel layouts, matching rules for record reconciliation, drag-and-drop interactions, and page-level actions — all from a single `definePage()` call.\n\n## Defining a Page\n\nPages are defined in your feature directory under a `pages/` folder:\n\n```\nquickback/definitions/features/\n banking/\n bank-accounts.ts # One table per file — any filename\n bank-transactions.ts\n actions.ts\n pages/\n bank-reconciliation.ts\n```\n\nEach page file exports a `definePage()` call:\n\n```typescript title=\"features/banking/pages/bank-reconciliation.ts\"\n\nexport default definePage({\n slug: 'bank-reconciliation',\n title: 'Bank Reconciliation',\n description: 'Match bank transactions to ledger entries',\n icon: 'landmark',\n feature: 'banking',\n\n access: { roles: ['owner', 'admin'] },\n\n dataSources: {\n bankTransactions: {\n table: 'bankTransaction',\n defaultSort: { field: 'date', order: 'desc' },\n displayColumns: ['date', 'description', 'amount'],\n },\n ledgerEntries: {\n table: 'ledgerEntry',\n defaultSort: { field: 'date', order: 'desc' },\n displayColumns: ['date', 'memo', 'amount'],\n },\n },\n\n layout: {\n type: 'split-panel',\n panels: [\n {\n id: 'bank',\n title: 'Bank Transactions',\n dataSource: 'bankTransactions',\n position: 'left',\n features: ['drag-source'],\n },\n {\n id: 'ledger',\n title: 'Ledger Entries',\n dataSource: 'ledgerEntries',\n position: 'right',\n features: ['drop-target'],\n },\n ],\n },\n\n matching: {\n enabled: true,\n confidenceThreshold: 0.5,\n rules: [\n {\n name: 'Amount Match',\n weight: 0.5,\n condition: {\n left: 'bankTransactions.amount',\n right: 'ledgerEntries.amount',\n operator: 'abs-equals',\n },\n },\n {\n name: 'Date Proximity',\n weight: 0.3,\n condition: {\n left: 'bankTransactions.date',\n right: 'ledgerEntries.date',\n operator: 'within-days',\n value: 7,\n },\n },\n {\n name: 'Description Match',\n weight: 0.2,\n condition: {\n left: 'bankTransactions.description',\n right: 'ledgerEntries.memo',\n operator: 'fuzzy-match',\n },\n },\n ],\n },\n\n pageActions: {\n reconcile: {\n table: 'bankTransaction',\n action: 'reconcile',\n label: 'Reconcile',\n icon: 'check-circle',\n confirm: 'Match this bank transaction to the selected ledger entry?',\n inputMapping: {\n transactionId: 'bankTransactions.$id',\n ledgerEntryId: 'ledgerEntries.$id',\n amount: 'bankTransactions.$amount',\n },\n },\n },\n});\n```\n\n## Data Sources\n\nEach page declares one or more named data sources that bind to tables in your schema:\n\n```typescript\ndataSources: {\n bankTransactions: {\n table: 'bankTransaction', // Table name from your schema\n defaultFilters: { status: 'pending' }, // Applied on load\n defaultSort: { field: 'date', order: 'desc' },\n displayColumns: ['date', 'description', 'amount'],\n },\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `table` | `string` | Table name to query (required) |\n| `defaultFilters` | `Record<string, unknown>` | Filters applied on initial load |\n| `defaultSort` | `{ field, order }` | Default sort column and direction |\n| `displayColumns` | `string[]` | Columns shown in the panel (defaults to `[\"id\"]`) |\n\n## Layout\n\nPages use a layout configuration to arrange panels. Currently the only layout type is `split-panel`:\n\n```typescript\nlayout: {\n type: 'split-panel',\n panels: [\n { id: 'bank', title: 'Bank Txs', dataSource: 'bankTransactions', position: 'left', features: ['drag-source'] },\n { id: 'ledger', title: 'Ledger', dataSource: 'ledgerEntries', position: 'right', features: ['drop-target'] },\n ],\n}\n```\n\n### Panel Features\n\nPanels can enable interactive features:\n\n| Feature | Description |\n|---------|-------------|\n| `drag-source` | Rows in this panel can be dragged |\n| `drop-target` | Rows in this panel accept drops |\n\nWhen a row is dragged from one panel and dropped onto a row in the other panel, the first page action is triggered with both records as context.\n\n## Matching Engine\n\nThe matching engine compares records across two panels and computes confidence scores for potential matches. Matched rows display a colored confidence badge.\n\n### Rules\n\nEach rule defines a comparison between fields from two data sources:\n\n```typescript\nmatching: {\n enabled: true,\n confidenceThreshold: 0.5, // Minimum score to show (0-1)\n rules: [\n {\n name: 'Amount Match',\n weight: 0.5, // Weight in final score (0-1)\n condition: {\n left: 'bankTransactions.amount', // dataSourceName.fieldName\n right: 'ledgerEntries.amount',\n operator: 'abs-equals',\n },\n },\n ],\n}\n```\n\n### Operators\n\n| Operator | Description | Returns |\n|----------|-------------|---------|\n| `abs-equals` | Absolute values are equal | `1.0` if match, `0` otherwise |\n| `within-days` | Dates are within N days | `1 - (daysDiff / maxDays)`, clamped to 0 |\n| `fuzzy-match` | Word overlap between strings | Overlap ratio (0-1) |\n\nThe `within-days` operator uses the `value` parameter to set the maximum number of days (defaults to 7).\n\n### Confidence Scoring\n\nThe final confidence score is the weighted average of all rule scores:\n\n```\nscore = sum(ruleScore * ruleWeight) / sum(ruleWeights)\n```\n\nOnly matches above `confidenceThreshold` are shown. Confidence badges are color-coded:\n\n| Score | Color |\n|-------|-------|\n| 80%+ | Green |\n| 50-79% | Yellow |\n| Below 50% | Orange |\n\n## Page Actions\n\nPage actions trigger table actions using data from both the source (dragged) and target (dropped-on) records:\n\n```typescript\npageActions: {\n reconcile: {\n table: 'bankTransaction', // Target table for the action\n action: 'reconcile', // Action name on that table\n label: 'Reconcile',\n icon: 'check-circle',\n confirm: 'Match this transaction?',\n inputMapping: {\n transactionId: 'bankTransactions.$id',\n ledgerEntryId: 'ledgerEntries.$id',\n amount: 'bankTransactions.$amount',\n },\n },\n}\n```\n\n### Input Mapping\n\nInput mapping resolves field references from the source and target records into the action's input fields. The format is `\"dataSourceName.$fieldName\"`:\n\n- `bankTransactions.$id` — resolves to the `id` field of the dragged record from the `bankTransactions` data source\n- `ledgerEntries.$amount` — resolves to the `amount` field of the drop-target record from the `ledgerEntries` data source\n\nThe `$` prefix denotes a field reference on the record. The data source name determines which record (source or target) to read from.\n\n## Access Control\n\nRestrict page access by role:\n\n```typescript\naccess: { roles: ['owner', 'admin'] }\n```\n\nWhen set, only users with the specified roles can view the page. The page link is hidden from the sidebar for unauthorized users.\n\n## Sidebar Navigation\n\nCustom pages appear in the CMS sidebar under their feature group. Each page is listed alongside the feature's tables, making them easily discoverable.\n\n## Validation\n\nThe compiler validates page definitions at compile time:\n\n- `slug` must start with a lowercase letter and contain only lowercase letters, digits, and hyphens\n- At least one data source is required\n- Every panel's `dataSource` must reference a declared data source\n- Matching rule weights must be between 0 and 1\n- `confidenceThreshold` must be between 0 and 1\n\n## Next Steps\n\n- **[Dashboard](/stack/cms/dashboard)** — The CMS home page with schema stats\n- **[Components Reference](/stack/cms/components)** — Page-related component details\n- **[Schema Format Reference](/stack/cms/schema-format)** — PageMeta type definition"
378
+ "content": "# Custom Pages\n\nCustom pages extend the CMS beyond standard table views. Define split-panel layouts, matching rules for record reconciliation, drag-and-drop interactions, and page-level actions — all from a single `definePage()` call.\n\n## Defining a Page\n\nPages are defined in your feature directory under a `pages/` folder:\n\n```\nquickback/features/\n banking/\n bank-accounts.ts # One table per file — any filename\n bank-transactions.ts\n actions.ts\n pages/\n bank-reconciliation.ts\n```\n\nEach page file exports a `definePage()` call:\n\n```typescript title=\"features/banking/pages/bank-reconciliation.ts\"\n\nexport default definePage({\n slug: 'bank-reconciliation',\n title: 'Bank Reconciliation',\n description: 'Match bank transactions to ledger entries',\n icon: 'landmark',\n feature: 'banking',\n\n access: { roles: ['owner', 'admin'] },\n\n dataSources: {\n bankTransactions: {\n table: 'bankTransaction',\n defaultSort: { field: 'date', order: 'desc' },\n displayColumns: ['date', 'description', 'amount'],\n },\n ledgerEntries: {\n table: 'ledgerEntry',\n defaultSort: { field: 'date', order: 'desc' },\n displayColumns: ['date', 'memo', 'amount'],\n },\n },\n\n layout: {\n type: 'split-panel',\n panels: [\n {\n id: 'bank',\n title: 'Bank Transactions',\n dataSource: 'bankTransactions',\n position: 'left',\n features: ['drag-source'],\n },\n {\n id: 'ledger',\n title: 'Ledger Entries',\n dataSource: 'ledgerEntries',\n position: 'right',\n features: ['drop-target'],\n },\n ],\n },\n\n matching: {\n enabled: true,\n confidenceThreshold: 0.5,\n rules: [\n {\n name: 'Amount Match',\n weight: 0.5,\n condition: {\n left: 'bankTransactions.amount',\n right: 'ledgerEntries.amount',\n operator: 'abs-equals',\n },\n },\n {\n name: 'Date Proximity',\n weight: 0.3,\n condition: {\n left: 'bankTransactions.date',\n right: 'ledgerEntries.date',\n operator: 'within-days',\n value: 7,\n },\n },\n {\n name: 'Description Match',\n weight: 0.2,\n condition: {\n left: 'bankTransactions.description',\n right: 'ledgerEntries.memo',\n operator: 'fuzzy-match',\n },\n },\n ],\n },\n\n pageActions: {\n reconcile: {\n table: 'bankTransaction',\n action: 'reconcile',\n label: 'Reconcile',\n icon: 'check-circle',\n confirm: 'Match this bank transaction to the selected ledger entry?',\n inputMapping: {\n transactionId: 'bankTransactions.$id',\n ledgerEntryId: 'ledgerEntries.$id',\n amount: 'bankTransactions.$amount',\n },\n },\n },\n});\n```\n\n## Data Sources\n\nEach page declares one or more named data sources that bind to tables in your schema:\n\n```typescript\ndataSources: {\n bankTransactions: {\n table: 'bankTransaction', // Table name from your schema\n defaultFilters: { status: 'pending' }, // Applied on load\n defaultSort: { field: 'date', order: 'desc' },\n displayColumns: ['date', 'description', 'amount'],\n },\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `table` | `string` | Table name to query (required) |\n| `defaultFilters` | `Record<string, unknown>` | Filters applied on initial load |\n| `defaultSort` | `{ field, order }` | Default sort column and direction |\n| `displayColumns` | `string[]` | Columns shown in the panel (defaults to `[\"id\"]`) |\n\n## Layout\n\nPages use a layout configuration to arrange panels. Currently the only layout type is `split-panel`:\n\n```typescript\nlayout: {\n type: 'split-panel',\n panels: [\n { id: 'bank', title: 'Bank Txs', dataSource: 'bankTransactions', position: 'left', features: ['drag-source'] },\n { id: 'ledger', title: 'Ledger', dataSource: 'ledgerEntries', position: 'right', features: ['drop-target'] },\n ],\n}\n```\n\n### Panel Features\n\nPanels can enable interactive features:\n\n| Feature | Description |\n|---------|-------------|\n| `drag-source` | Rows in this panel can be dragged |\n| `drop-target` | Rows in this panel accept drops |\n\nWhen a row is dragged from one panel and dropped onto a row in the other panel, the first page action is triggered with both records as context.\n\n## Matching Engine\n\nThe matching engine compares records across two panels and computes confidence scores for potential matches. Matched rows display a colored confidence badge.\n\n### Rules\n\nEach rule defines a comparison between fields from two data sources:\n\n```typescript\nmatching: {\n enabled: true,\n confidenceThreshold: 0.5, // Minimum score to show (0-1)\n rules: [\n {\n name: 'Amount Match',\n weight: 0.5, // Weight in final score (0-1)\n condition: {\n left: 'bankTransactions.amount', // dataSourceName.fieldName\n right: 'ledgerEntries.amount',\n operator: 'abs-equals',\n },\n },\n ],\n}\n```\n\n### Operators\n\n| Operator | Description | Returns |\n|----------|-------------|---------|\n| `abs-equals` | Absolute values are equal | `1.0` if match, `0` otherwise |\n| `within-days` | Dates are within N days | `1 - (daysDiff / maxDays)`, clamped to 0 |\n| `fuzzy-match` | Word overlap between strings | Overlap ratio (0-1) |\n\nThe `within-days` operator uses the `value` parameter to set the maximum number of days (defaults to 7).\n\n### Confidence Scoring\n\nThe final confidence score is the weighted average of all rule scores:\n\n```\nscore = sum(ruleScore * ruleWeight) / sum(ruleWeights)\n```\n\nOnly matches above `confidenceThreshold` are shown. Confidence badges are color-coded:\n\n| Score | Color |\n|-------|-------|\n| 80%+ | Green |\n| 50-79% | Yellow |\n| Below 50% | Orange |\n\n## Page Actions\n\nPage actions trigger table actions using data from both the source (dragged) and target (dropped-on) records:\n\n```typescript\npageActions: {\n reconcile: {\n table: 'bankTransaction', // Target table for the action\n action: 'reconcile', // Action name on that table\n label: 'Reconcile',\n icon: 'check-circle',\n confirm: 'Match this transaction?',\n inputMapping: {\n transactionId: 'bankTransactions.$id',\n ledgerEntryId: 'ledgerEntries.$id',\n amount: 'bankTransactions.$amount',\n },\n },\n}\n```\n\n### Input Mapping\n\nInput mapping resolves field references from the source and target records into the action's input fields. The format is `\"dataSourceName.$fieldName\"`:\n\n- `bankTransactions.$id` — resolves to the `id` field of the dragged record from the `bankTransactions` data source\n- `ledgerEntries.$amount` — resolves to the `amount` field of the drop-target record from the `ledgerEntries` data source\n\nThe `$` prefix denotes a field reference on the record. The data source name determines which record (source or target) to read from.\n\n## Access Control\n\nRestrict page access by role:\n\n```typescript\naccess: { roles: ['owner', 'admin'] }\n```\n\nWhen set, only users with the specified roles can view the page. The page link is hidden from the sidebar for unauthorized users.\n\n## Sidebar Navigation\n\nCustom pages appear in the CMS sidebar under their feature group. Each page is listed alongside the feature's tables, making them easily discoverable.\n\n## Validation\n\nThe compiler validates page definitions at compile time:\n\n- `slug` must start with a lowercase letter and contain only lowercase letters, digits, and hyphens\n- At least one data source is required\n- Every panel's `dataSource` must reference a declared data source\n- Matching rule weights must be between 0 and 1\n- `confidenceThreshold` must be between 0 and 1\n\n## Next Steps\n\n- **[Dashboard](/stack/cms/dashboard)** — The CMS home page with schema stats\n- **[Components Reference](/stack/cms/components)** — Page-related component details\n- **[Schema Format Reference](/stack/cms/schema-format)** — PageMeta type definition"
379
379
  },
380
380
  "stack/cms/record-layouts": {
381
381
  "title": "Record Layouts",
@@ -415,7 +415,7 @@ export const DOCS = {
415
415
  },
416
416
  "stack/realtime/durable-objects": {
417
417
  "title": "Realtime",
418
- "content": "Quickback can generate realtime notification helpers for broadcasting changes to connected clients. This enables live updates via WebSocket using Cloudflare Durable Objects.\n\nThe targeting model is shared across ws tickets, websocket attachment, and server-side broadcasts:\n\n- string target: historical `organizationId` shorthand\n- object target: `{ scopeKey?, organizationId?, userId? }`\n\nThat means the same mental model drives both `createRealtime()` and the generated Broadcaster filter path.\n\n## Enabling Realtime\n\nAdd `realtime` configuration to individual table definitions:\n\n```typescript\n// features/applications/applications.ts\n\nexport const applications = sqliteTable(\"applications\", {\n id: text(\"id\").primaryKey(),\n candidateId: text(\"candidate_id\").notNull(),\n jobId: text(\"job_id\").notNull(),\n stage: text(\"stage\").notNull(),\n organizationId: text(\"organization_id\").notNull(),\n});\n\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n realtime: {\n enabled: true, // Enable realtime for this table\n onInsert: true, // Broadcast on INSERT (default: true)\n onUpdate: true, // Broadcast on UPDATE (default: true)\n onDelete: true, // Broadcast on DELETE (default: true)\n requiredRoles: [\"recruiter\", \"hiring-manager\"], // Who receives broadcasts\n fields: [\"id\", \"candidateId\", \"stage\"], // Fields to include (optional)\n },\n // ... guards, crud\n});\n```\n\nWhen any table has realtime enabled, the compiler generates `src/lib/realtime.ts` with helper functions for sending notifications.\n\nAt the project level, `providers.database.config.realtime` can stay boolean or become object-shaped when you need relationship-authorized resource tickets:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: {\n wsTicket: {\n role: \"attendee\",\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n },\n }),\n}\n```\n\nThat tells `/broadcast/v1/ws-ticket` to authenticate with Better Auth, verify the `attendee` relationship role against `body.eventId`, and mint a short-lived ticket scoped to the resolved `events:<id>` lane.\n\n### Namespace-backed tickets (per-matched-lane)\n\nThe single-`role` form above authorizes the ticket through **one** relationship.\nWhen the room is gated by an [authz namespace](/compiler/definitions/scopes#mintscope-mint-the-scope-token-from-the-namespace-resolver)\nwith a **multi-lane `via:`** — e.g. an event reachable by attendees, organizers,\ncontractors, *and* org admins — point the ticket at the namespace instead, and it\nauthorizes through the namespace's full `via` (per-matched-lane):\n\n```typescript\nrealtime: {\n wsTicket: {\n namespace: \"eventScope\", // authorize via this namespace's full multi-lane `via`\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n},\n```\n\n`/broadcast/v1/ws-ticket` now runs the **same first-match-wins gate** the\nnamespace uses, and issues the ticket for whichever lane matched:\n\n| Caller matched via | Ticket role |\n|---|---|\n| `attendeeOf` (relationship lane) | `attendee` |\n| `organizerOf` | `organizer` |\n| `contractorOf` | `contractor` |\n| `{ roles: [\"admin\",\"owner\"] }` (bulk lane) | the caller's **org/membership roles** — no scope role |\n\nThis closes the gap where the single-`role` form denied (`403`) an org admin who\ncould legitimately reach the room through the bulk lane but isn't a confirmed\nattendee — their realtime socket now opens.\n\n## When auto-broadcast fires (and when you call it manually)\n\nQuickback emits auto-broadcasts in **only one place**: the generated CRUD route handlers (`POST /` create, `PATCH /:id` update, `DELETE /:id` delete) for resources with `realtime.enabled` (or covered by `dbConfig.realtime: true`'s project-level default). Those handlers wrap each successful write with a `realtime.insert / update / delete` call before responding.\n\nEverywhere else — action handlers, queue consumers, scheduled jobs, custom Hono routes — you broadcast manually. In action handlers on realtime-enabled projects, Quickback now injects a typed `realtime` helper directly into `execute(...)`; outside actions you still call `createRealtime(env)` yourself.\n\n| Mutation site | Auto-broadcast? | Why |\n|---|---|---|\n| Generated CRUD route (`POST /`, `PATCH /:id`, `DELETE /:id`) | Yes | The compiler emits the call after the write returns. |\n| Generated batch route (`/batch/...`) | Yes | Same pattern, emitted per record. |\n| `scoped.insert/update/delete` inside an action handler | No — manual | Scoped-db is a query-shape wrapper (firewall + soft-delete WHERE injection). It deliberately has no side-effects so explicit handlers can write multiple records, conditionally roll back, etc. without surprise broadcasts. |\n| `unsafeDb` writes in actions (or any custom route) | No — manual | Same reasoning — `unsafeDb` is the un-wrapped escape hatch. |\n| Queue consumers, cron jobs, webhook handlers | No — manual | These run outside the CRUD path entirely. |\n\nThe rule of thumb: if your code calls `db.insert(...)` / `scoped.insert(...)` directly, you also call `realtime.insert(...)` directly on the next line. Otherwise the cross-tab live-update you wired up in the SPA won't fire.\n\n## Generated Helper\n\nAction handlers on realtime-enabled projects receive a typed `realtime` param. The underlying `createRealtime()` factory still powers it and remains the API to use from queues, cron jobs, and other non-action code:\n\n```typescript\nexport const execute: ActionExecutor = async ({ db, ctx, input, realtime }) => {\n // After creating a record\n await realtime.insert('applications', newApplication, ctx.activeOrgId!);\n\n // After updating a record\n await realtime.update('applications', newApplication, oldApplication, ctx.activeOrgId!);\n\n // After deleting a record\n await realtime.delete('applications', { id: applicationId }, ctx.activeOrgId!);\n\n return { success: true };\n};\n```\n\n`env` is also typed in action handlers, so custom bindings like R2, D1, Queues, Durable Objects, and auth env vars no longer need `(env as any)` casts.\n\nFor explicit targeting, pass an object instead of the historical org string:\n\n```typescript\nawait realtime.broadcast(\"event-page-updated\", payload, {\n scopeKey: `events:${input.eventId}`,\n});\n\nawait realtime.broadcast(\"dm\", payload, {\n userId: recipientId,\n});\n```\n\n## Event Format\n\nQuickback broadcasts events in a structured JSON format for easy client-side handling.\n\n### Insert Event\n\n```typescript\nawait realtime.insert('applications', {\n id: 'app_123',\n candidateId: 'cnd_456',\n stage: 'applied'\n}, ctx.activeOrgId!);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"INSERT\",\n \"schema\": \"public\",\n \"new\": {\n \"id\": \"app_123\",\n \"candidateId\": \"cnd_456\",\n \"stage\": \"applied\"\n },\n \"old\": null\n}\n```\n\n### Update Event\n\n```typescript\nawait realtime.update('applications',\n { id: 'app_123', stage: 'interview' }, // new\n { id: 'app_123', stage: 'screening' }, // old\n ctx.activeOrgId!\n);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"UPDATE\",\n \"schema\": \"public\",\n \"new\": { \"id\": \"app_123\", \"stage\": \"interview\" },\n \"old\": { \"id\": \"app_123\", \"stage\": \"screening\" }\n}\n```\n\n### Delete Event\n\n```typescript\nawait realtime.delete('applications',\n { id: 'app_123' },\n ctx.activeOrgId!\n);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"DELETE\",\n \"schema\": \"public\",\n \"new\": null,\n \"old\": { \"id\": \"app_123\" }\n}\n```\n\n## Custom Broadcasts\n\nFor arbitrary events that don't map to CRUD operations:\n\n```typescript\nawait realtime.broadcast('screening-complete', {\n applicationId: 'app_123',\n candidateId: 'cnd_456',\n stage: 'interview'\n}, ctx.activeOrgId!);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"broadcast\",\n \"event\": \"screening-complete\",\n \"payload\": {\n \"applicationId\": \"app_123\",\n \"candidateId\": \"cnd_456\",\n \"stage\": \"interview\"\n }\n}\n```\n\n## User-Specific Broadcasts\n\nTarget a specific user instead of the entire organization:\n\n```typescript\n// Only this user receives the notification\nawait realtime.insert('notifications', newNotification, ctx.activeOrgId!, {\n userId: ctx.userId\n});\n\n// Notify a hiring manager of a new application\nawait realtime.broadcast('application-received', {\n applicationId: 'app_123',\n jobId: 'job_789'\n}, ctx.activeOrgId!, {\n userId: hiringManagerId\n});\n```\n\n## Role-Based Filtering\n\nLimit which roles receive a broadcast using `targetRoles`:\n\n```typescript\n// Only hiring managers and recruiters receive this broadcast\nawait realtime.insert('applications', application, ctx.activeOrgId!, {\n targetRoles: ['hiring-manager', 'recruiter']\n});\n\n// Interviewers only see applications assigned to them\nawait realtime.update('applications', newRecord, oldRecord, ctx.activeOrgId!, {\n targetRoles: ['hiring-manager']\n});\n```\n\nIf `targetRoles` is not specified, all authenticated subscribers in the chosen scope receive the broadcast.\n\n## Per-Role Field Masking\n\nApply different field masking based on the subscriber's role using `maskingConfig`:\n\n```typescript\nawait realtime.insert('candidates', newCandidate, ctx.activeOrgId!, {\n maskingConfig: {\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n email: { type: 'email', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n resumeUrl: { type: 'redact', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n },\n});\n```\n\n**How masking works:**\n- Each subscriber receives a payload masked according to their role\n- Roles in the `show.roles` array see unmasked values\n- All other roles see the masked version\n- Masking is pre-computed per-role (O(roles) not O(subscribers))\n\n**Available mask types:**\n| Type | Example Output |\n|------|----------------|\n| `email` | `j***@y*********.com` |\n| `phone` | `******4567` |\n| `ssn` | `*****6789` |\n| `creditCard` | `**** **** **** 1111` |\n| `name` | `J***` |\n| `redact` | `[REDACTED]` |\n\n### Owner-Based Masking\n\nShow unmasked data to the record owner:\n\n```typescript\nmaskingConfig: {\n phone: {\n type: 'phone',\n show: { roles: ['hiring-manager'], or: 'owner' } // Hiring manager OR owner sees unmasked\n },\n}\n```\n\n## Client-Side Subscription\n\n### WebSocket Authentication\n\nQuickback uses **ticket-based authentication** for WebSocket connections. The client first obtains a short-lived ticket from the main API, then connects with it as a URL parameter. The Broadcaster verifies the ticket cryptographically at upgrade time — no HTTP round-trip needed.\n\n```typescript\n// 1. Get a ws-ticket from your API (requires session auth)\nconst response = await fetch('/broadcast/v1/ws-ticket', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${sessionToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ eventId: 'evt_123' }),\n});\nconst { wsTicket } = await response.json();\n\n// 2. Connect with ticket as URL param\nconst ws = new WebSocket(\n `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}`\n);\n\nws.onopen = () => {\n console.log('Connected and authenticated!');\n // No auth message needed — pre-authenticated at upgrade\n};\n```\n\nTickets expire after 60 seconds, so fetch a fresh one before each connection or reconnection.\n\n### Handling Messages\n\n```typescript\nws.onmessage = (event) => {\n const msg = JSON.parse(event.data);\n\n // Handle CRUD events\n if (msg.type === 'postgres_changes') {\n const { table, eventType, new: newRecord, old: oldRecord } = msg;\n\n if (eventType === 'INSERT') {\n addRecord(table, newRecord);\n } else if (eventType === 'UPDATE') {\n updateRecord(table, newRecord);\n } else if (eventType === 'DELETE') {\n removeRecord(table, oldRecord.id);\n }\n }\n\n // Handle custom broadcasts\n if (msg.type === 'broadcast') {\n const { event, payload } = msg;\n\n if (event === 'screening-complete') {\n refreshApplication(payload.applicationId);\n } else if (event === 'interview-scheduled') {\n showInterviewNotification(payload.applicationId);\n }\n }\n};\n```\n\n## Environment\n\nNo additional environment variables are needed for realtime. The Broadcaster DO runs inline in your main worker and uses `BETTER_AUTH_SECRET` (already required for auth) to sign and verify WebSocket tickets.\n\n| Variable | Description |\n|----------|-------------|\n| `BETTER_AUTH_SECRET` | Signs/verifies WebSocket tickets (already set for auth) |\n\nThe `BROADCASTER` binding is a `DurableObjectNamespace` — the compiler generates this in your `wrangler.toml` automatically:\n\n```toml\n[[durable_objects.bindings]]\nname = \"BROADCASTER\"\nclass_name = \"Broadcaster\"\n\n[[migrations]]\ntag = \"v1\"\nnew_classes = [\"Broadcaster\"]\n```\n\n## Architecture\n\n```\n 1. POST /ws-ticket\n┌───────────────────────────────────────────────┐ ┌─────────────────┐\n│ Quickback Worker │ ◄──│ Browser Client │\n│ │ ──►│ │\n│ ┌──────────┐ DO binding ┌────────────────┐ │ └───────┬─────────┘\n│ │ Hono API │ ───────────► │ Broadcaster DO │ │ │\n│ └──────────┘ (in-process)└───────┬────────┘ │ 2. WS ?ws_ticket=...\n│ │ │ │\n└────────────────────────────────────┼──────────┘ │\n │◄──────────────────────┘\n WebSocket (verified at upgrade)\n```\n\n1. **Client gets a ticket** — `POST /broadcast/v1/ws-ticket` on the main API (session-authenticated). Returns a 60-second HMAC-signed ticket.\n2. **Client connects** — Opens WebSocket with `?ws_ticket=<ticket>`. The Durable Object verifies the ticket cryptographically at upgrade and attaches the socket to the ticket's `scopeKey`, `organizationId`, or `userId`.\n3. **API broadcasts** — After CRUD ops, or from custom handlers, the API calls the Broadcaster DO directly via its binding (in-process, no network hop) using the same target model.\n\n## Best Practices\n\n### Broadcast After Commit\n\nAlways broadcast after the database operation succeeds:\n\n```typescript\n// Good - broadcast after successful insert\nconst [newApp] = await db.insert(applications).values(data).returning();\nawait realtime.insert('applications', newApp, ctx.activeOrgId!);\n\n// Bad - don't broadcast before confirming success\nawait realtime.insert('applications', data, ctx.activeOrgId!);\nawait db.insert(applications).values(data); // Could fail!\n```\n\n### Minimal Payloads\n\nOnly include necessary data in broadcasts:\n\n```typescript\n// Good - minimal payload\nawait realtime.update('applications',\n { id: record.id, stage: 'interview' },\n { id: record.id, stage: 'screening' },\n ctx.activeOrgId!\n);\n\n// Avoid - sending entire record with large content\nawait realtime.update('applications', fullRecord, oldRecord, ctx.activeOrgId!);\n```\n\n### Use Broadcasts for Complex Events\n\nFor events that don't map cleanly to CRUD:\n\n```typescript\n// Hiring pipeline stage completed\nawait realtime.broadcast('pipeline-stage-complete', {\n applicationId: application.id,\n stages: ['applied', 'screening', 'interview'],\n currentStage: 'offer',\n candidateId: application.candidateId\n}, ctx.activeOrgId!);\n```\n\n## Custom Event Namespaces\n\nFor complex applications with many custom events, you can define typed event namespaces using `defineRealtime`. This generates strongly-typed helper methods for your custom events.\n\n### Defining Event Namespaces\n\nCreate a file in `services/realtime/`:\n\n```typescript\n// services/realtime/screening.ts\n\nexport default defineRealtime({\n name: 'screening',\n events: ['started', 'progress', 'completed', 'failed'],\n description: 'Candidate screening pipeline events',\n});\n```\n\n### Generated Helper Methods\n\nAfter compilation, the `createRealtime()` helper includes your custom namespace:\n\n```typescript\n\nexport const execute: ActionExecutor = async ({ ctx, input }) => {\n const realtime = createRealtime(ctx.env);\n\n // Type-safe custom event methods\n await realtime.screening.started({\n applicationId: input.applicationId,\n }, ctx.activeOrgId!);\n\n // Progress updates\n await realtime.screening.progress({\n applicationId: input.applicationId,\n percent: 50,\n step: 'background-check',\n }, ctx.activeOrgId!);\n\n // Completion\n await realtime.screening.completed({\n applicationId: input.applicationId,\n result: 'passed',\n duration: 1234,\n }, ctx.activeOrgId!);\n\n return { success: true };\n};\n```\n\n### Event Format\n\nCustom namespace events use the `broadcast` type with namespaced event names:\n\n```json\n{\n \"type\": \"broadcast\",\n \"event\": \"screening:started\",\n \"payload\": {\n \"applicationId\": \"app_123\"\n }\n}\n```\n\n### Multiple Namespaces\n\nDefine multiple namespaces for different parts of your application:\n\n```typescript\n// services/realtime/notifications.ts\nexport default defineRealtime({\n name: 'notifications',\n events: ['interview-reminder', 'offer-update', 'application-received'],\n description: 'Recruitment notification events',\n});\n\n// services/realtime/presence.ts\nexport default defineRealtime({\n name: 'presence',\n events: ['joined', 'left', 'reviewing', 'idle'],\n description: 'Who is reviewing which candidate',\n});\n```\n\nUsage:\n```typescript\nconst realtime = createRealtime(ctx.env);\n\n// Notification events\nawait realtime.notifications['interview-reminder']({ ... }, ctx.activeOrgId!);\n\n// Presence events — who's reviewing which candidate\nawait realtime.presence.reviewing({ userId: ctx.userId, candidateId: 'cnd_456' }, ctx.activeOrgId!);\n```\n\n### Namespace vs Generic Broadcast\n\n| Use Case | Approach |\n|----------|----------|\n| One-off custom event | `realtime.broadcast('event-name', payload, orgId)` |\n| Repeated event patterns | `defineRealtime` namespace |\n| Type-safe events | `defineRealtime` namespace |\n| Event discovery | `defineRealtime` (appears in generated types) |"
418
+ "content": "Quickback can generate realtime notification helpers for broadcasting changes to connected clients. This enables live updates via WebSocket using Cloudflare Durable Objects.\n\nThe targeting model is shared across ws tickets, websocket attachment, and server-side broadcasts:\n\n- string target: historical `organizationId` shorthand\n- object target: `{ scopeKey?, organizationId?, userId? }`\n\nThat means the same mental model drives both `createRealtime()` and the generated Broadcaster filter path.\n\n## Enabling Realtime\n\nAdd `realtime` configuration to individual table definitions:\n\n```typescript\n// features/applications/applications.ts\n\nexport const applications = sqliteTable(\"applications\", {\n id: text(\"id\").primaryKey(),\n candidateId: text(\"candidate_id\").notNull(),\n jobId: text(\"job_id\").notNull(),\n stage: text(\"stage\").notNull(),\n organizationId: text(\"organization_id\").notNull(),\n});\n\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n realtime: {\n enabled: true, // Enable realtime for this table\n onInsert: true, // Broadcast on INSERT (default: true)\n onUpdate: true, // Broadcast on UPDATE (default: true)\n onDelete: true, // Broadcast on DELETE (default: true)\n requiredRoles: [\"recruiter\", \"hiring-manager\"], // Who receives broadcasts\n fields: [\"id\", \"candidateId\", \"stage\"], // Fields to include (optional)\n },\n // ... guards, crud\n});\n```\n\nWhen any table has realtime enabled, the compiler generates `src/lib/realtime.ts` with helper functions for sending notifications.\n\nAt the project level, `providers.database.config.realtime` can stay boolean or become object-shaped when you need relationship-authorized resource tickets:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: {\n wsTicket: {\n role: \"attendee\",\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n },\n }),\n}\n```\n\nThat tells `/broadcast/v1/ws-ticket` to authenticate with Better Auth, verify the `attendee` relationship role against `body.eventId`, and mint a short-lived ticket scoped to the resolved `events:<id>` lane.\n\n### Namespace-backed tickets (per-matched-lane)\n\nThe single-`role` form above authorizes the ticket through **one** relationship.\nWhen the room is gated by an [authz namespace](/compiler/definitions/scopes#mintscope-mint-the-scope-token-from-the-namespace-resolver)\nwith a **multi-lane `via:`** — e.g. an event reachable by attendees, organizers,\ncontractors, *and* org admins — point the ticket at the namespace instead, and it\nauthorizes through the namespace's full `via` (per-matched-lane):\n\n```typescript\nrealtime: {\n wsTicket: {\n namespace: \"eventScope\", // authorize via this namespace's full multi-lane `via`\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n},\n```\n\n`/broadcast/v1/ws-ticket` now runs the **same first-match-wins gate** the\nnamespace uses, and issues the ticket for whichever lane matched:\n\n| Caller matched via | Ticket role |\n|---|---|\n| `attendeeOf` (relationship lane) | `attendee` |\n| `organizerOf` | `organizer` |\n| `contractorOf` | `contractor` |\n| `{ roles: [\"admin\",\"owner\"] }` (bulk lane) | the caller's **org/membership roles** — no scope role |\n\nThis closes the gap where the single-`role` form denied (`403`) an org admin who\ncould legitimately reach the room through the bulk lane but isn't a confirmed\nattendee — their realtime socket now opens.\n\n## When auto-broadcast fires (and when you call it manually)\n\nQuickback emits auto-broadcasts in **only one place**: the generated CRUD route handlers (`POST /` create, `PATCH /:id` update, `DELETE /:id` delete) for resources with `realtime.enabled` (or covered by `dbConfig.realtime: true`'s project-level default). Those handlers wrap each successful write with a `realtime.insert / update / delete` call before responding.\n\nAuto-broadcasts carry the table's declared gates (v0.46+): the\n`realtime.requiredRoles` list becomes the broadcast's `targetRoles` (with\nrole-hierarchy `+` expanded), and the table's effective masking config —\ndeclared plus auto-detected sensitive columns — is applied per subscriber\nrole at fanout, matching what the HTTP routes mask. A `type: 'custom'` mask\nfunction can't be replicated by the Broadcaster, so those columns broadcast\nas `[REDACTED]` (fail closed). Tables that declare neither broadcast openly,\nas before.\n\nEverywhere else — action handlers, queue consumers, scheduled jobs, custom Hono routes — you broadcast manually. In action handlers on realtime-enabled projects, Quickback now injects a typed `realtime` helper directly into `execute(...)`; outside actions you still call `createRealtime(env)` yourself.\n\n| Mutation site | Auto-broadcast? | Why |\n|---|---|---|\n| Generated CRUD route (`POST /`, `PATCH /:id`, `DELETE /:id`) | Yes | The compiler emits the call after the write returns. |\n| Generated batch route (`/batch/...`) | Yes | Same pattern, emitted per record. |\n| `scoped.insert/update/delete` inside an action handler | No — manual | Scoped-db is a query-shape wrapper (firewall + soft-delete WHERE injection). It deliberately has no side-effects so explicit handlers can write multiple records, conditionally roll back, etc. without surprise broadcasts. |\n| `unsafeDb` writes in actions (or any custom route) | No — manual | Same reasoning — `unsafeDb` is the un-wrapped escape hatch. |\n| Queue consumers, cron jobs, webhook handlers | No — manual | These run outside the CRUD path entirely. |\n\nThe rule of thumb: if your code calls `db.insert(...)` / `scoped.insert(...)` directly, you also call `realtime.insert(...)` directly on the next line. Otherwise the cross-tab live-update you wired up in the SPA won't fire.\n\n## Generated Helper\n\nAction handlers on realtime-enabled projects receive a typed `realtime` param. The underlying `createRealtime()` factory still powers it and remains the API to use from queues, cron jobs, and other non-action code:\n\n```typescript\nexport const execute: ActionExecutor = async ({ db, ctx, input, realtime }) => {\n // After creating a record\n await realtime.insert('applications', newApplication, ctx.activeOrgId!);\n\n // After updating a record\n await realtime.update('applications', newApplication, oldApplication, ctx.activeOrgId!);\n\n // After deleting a record\n await realtime.delete('applications', { id: applicationId }, ctx.activeOrgId!);\n\n return { success: true };\n};\n```\n\n`env` is also typed in action handlers, so custom bindings like R2, D1, Queues, Durable Objects, and auth env vars no longer need `(env as any)` casts.\n\nFor explicit targeting, pass an object instead of the historical org string:\n\n```typescript\nawait realtime.broadcast(\"event-page-updated\", payload, {\n scopeKey: `events:${input.eventId}`,\n});\n\nawait realtime.broadcast(\"dm\", payload, {\n userId: recipientId,\n});\n```\n\n## Event Format\n\nQuickback broadcasts events in a structured JSON format for easy client-side handling.\n\n### Insert Event\n\n```typescript\nawait realtime.insert('applications', {\n id: 'app_123',\n candidateId: 'cnd_456',\n stage: 'applied'\n}, ctx.activeOrgId!);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"INSERT\",\n \"schema\": \"public\",\n \"new\": {\n \"id\": \"app_123\",\n \"candidateId\": \"cnd_456\",\n \"stage\": \"applied\"\n },\n \"old\": null\n}\n```\n\n### Update Event\n\n```typescript\nawait realtime.update('applications',\n { id: 'app_123', stage: 'interview' }, // new\n { id: 'app_123', stage: 'screening' }, // old\n ctx.activeOrgId!\n);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"UPDATE\",\n \"schema\": \"public\",\n \"new\": { \"id\": \"app_123\", \"stage\": \"interview\" },\n \"old\": { \"id\": \"app_123\", \"stage\": \"screening\" }\n}\n```\n\n### Delete Event\n\n```typescript\nawait realtime.delete('applications',\n { id: 'app_123' },\n ctx.activeOrgId!\n);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"DELETE\",\n \"schema\": \"public\",\n \"new\": null,\n \"old\": { \"id\": \"app_123\" }\n}\n```\n\n## Custom Broadcasts\n\nFor arbitrary events that don't map to CRUD operations:\n\n```typescript\nawait realtime.broadcast('screening-complete', {\n applicationId: 'app_123',\n candidateId: 'cnd_456',\n stage: 'interview'\n}, ctx.activeOrgId!);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"broadcast\",\n \"event\": \"screening-complete\",\n \"payload\": {\n \"applicationId\": \"app_123\",\n \"candidateId\": \"cnd_456\",\n \"stage\": \"interview\"\n }\n}\n```\n\n## User-Specific Broadcasts\n\nTarget a specific user instead of the entire organization:\n\n```typescript\n// Only this user receives the notification\nawait realtime.insert('notifications', newNotification, ctx.activeOrgId!, {\n userId: ctx.userId\n});\n\n// Notify a hiring manager of a new application\nawait realtime.broadcast('application-received', {\n applicationId: 'app_123',\n jobId: 'job_789'\n}, ctx.activeOrgId!, {\n userId: hiringManagerId\n});\n```\n\n## Role-Based Filtering\n\nLimit which roles receive a broadcast using `targetRoles`:\n\n```typescript\n// Only hiring managers and recruiters receive this broadcast\nawait realtime.insert('applications', application, ctx.activeOrgId!, {\n targetRoles: ['hiring-manager', 'recruiter']\n});\n\n// Interviewers only see applications assigned to them\nawait realtime.update('applications', newRecord, oldRecord, ctx.activeOrgId!, {\n targetRoles: ['hiring-manager']\n});\n```\n\nIf `targetRoles` is not specified, all authenticated subscribers in the chosen scope receive the broadcast.\n\n## Per-Role Field Masking\n\nApply different field masking based on the subscriber's role using `maskingConfig`:\n\n```typescript\nawait realtime.insert('candidates', newCandidate, ctx.activeOrgId!, {\n maskingConfig: {\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n email: { type: 'email', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n resumeUrl: { type: 'redact', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n },\n});\n```\n\n**How masking works:**\n- Each subscriber receives a payload masked according to their role\n- Roles in the `show.roles` array see unmasked values\n- All other roles see the masked version\n- Masking is pre-computed per-role (O(roles) not O(subscribers))\n\n**Available mask types:**\n| Type | Example Output |\n|------|----------------|\n| `email` | `j***@y*********.com` |\n| `phone` | `******4567` |\n| `ssn` | `*****6789` |\n| `creditCard` | `**** **** **** 1111` |\n| `name` | `J***` |\n| `redact` | `[REDACTED]` |\n\n### Owner-Based Masking\n\nShow unmasked data to the record owner:\n\n```typescript\nmaskingConfig: {\n phone: {\n type: 'phone',\n show: { roles: ['hiring-manager'], or: 'owner' } // Hiring manager OR owner sees unmasked\n },\n}\n```\n\n## Client-Side Subscription\n\n### WebSocket Authentication\n\nQuickback uses **ticket-based authentication** for WebSocket connections. The client first obtains a short-lived ticket from the main API, then connects with it as a URL parameter. The Broadcaster verifies the ticket cryptographically at upgrade time — no HTTP round-trip needed.\n\n```typescript\n// 1. Get a ws-ticket from your API (requires session auth)\nconst response = await fetch('/broadcast/v1/ws-ticket', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${sessionToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ eventId: 'evt_123' }),\n});\nconst { wsTicket } = await response.json();\n\n// 2. Connect with ticket as URL param\nconst ws = new WebSocket(\n `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}`\n);\n\nws.onopen = () => {\n console.log('Connected and authenticated!');\n // No auth message needed — pre-authenticated at upgrade\n};\n```\n\nTickets expire after 60 seconds, so fetch a fresh one before each connection or reconnection.\n\n### Handling Messages\n\n```typescript\nws.onmessage = (event) => {\n const msg = JSON.parse(event.data);\n\n // Handle CRUD events\n if (msg.type === 'postgres_changes') {\n const { table, eventType, new: newRecord, old: oldRecord } = msg;\n\n if (eventType === 'INSERT') {\n addRecord(table, newRecord);\n } else if (eventType === 'UPDATE') {\n updateRecord(table, newRecord);\n } else if (eventType === 'DELETE') {\n removeRecord(table, oldRecord.id);\n }\n }\n\n // Handle custom broadcasts\n if (msg.type === 'broadcast') {\n const { event, payload } = msg;\n\n if (event === 'screening-complete') {\n refreshApplication(payload.applicationId);\n } else if (event === 'interview-scheduled') {\n showInterviewNotification(payload.applicationId);\n }\n }\n};\n```\n\n## Environment\n\nNo additional environment variables are needed for realtime. The Broadcaster DO runs inline in your main worker and uses `BETTER_AUTH_SECRET` (already required for auth) to sign and verify WebSocket tickets.\n\n| Variable | Description |\n|----------|-------------|\n| `BETTER_AUTH_SECRET` | Signs/verifies WebSocket tickets (already set for auth) |\n\nThe `BROADCASTER` binding is a `DurableObjectNamespace` — the compiler generates this in your `wrangler.toml` automatically:\n\n```toml\n[[durable_objects.bindings]]\nname = \"BROADCASTER\"\nclass_name = \"Broadcaster\"\n\n[[migrations]]\ntag = \"v1\"\nnew_classes = [\"Broadcaster\"]\n```\n\n## Architecture\n\n```\n 1. POST /ws-ticket\n┌───────────────────────────────────────────────┐ ┌─────────────────┐\n│ Quickback Worker │ ◄──│ Browser Client │\n│ │ ──►│ │\n│ ┌──────────┐ DO binding ┌────────────────┐ │ └───────┬─────────┘\n│ │ Hono API │ ───────────► │ Broadcaster DO │ │ │\n│ └──────────┘ (in-process)└───────┬────────┘ │ 2. WS ?ws_ticket=...\n│ │ │ │\n└────────────────────────────────────┼──────────┘ │\n │◄──────────────────────┘\n WebSocket (verified at upgrade)\n```\n\n1. **Client gets a ticket** — `POST /broadcast/v1/ws-ticket` on the main API (session-authenticated). Returns a 60-second HMAC-signed ticket.\n2. **Client connects** — Opens WebSocket with `?ws_ticket=<ticket>`. The Durable Object verifies the ticket cryptographically at upgrade and attaches the socket to the ticket's `scopeKey`, `organizationId`, or `userId`.\n3. **API broadcasts** — After CRUD ops, or from custom handlers, the API calls the Broadcaster DO directly via its binding (in-process, no network hop) using the same target model.\n\n## Best Practices\n\n### Broadcast After Commit\n\nAlways broadcast after the database operation succeeds:\n\n```typescript\n// Good - broadcast after successful insert\nconst [newApp] = await db.insert(applications).values(data).returning();\nawait realtime.insert('applications', newApp, ctx.activeOrgId!);\n\n// Bad - don't broadcast before confirming success\nawait realtime.insert('applications', data, ctx.activeOrgId!);\nawait db.insert(applications).values(data); // Could fail!\n```\n\n### Minimal Payloads\n\nOnly include necessary data in broadcasts:\n\n```typescript\n// Good - minimal payload\nawait realtime.update('applications',\n { id: record.id, stage: 'interview' },\n { id: record.id, stage: 'screening' },\n ctx.activeOrgId!\n);\n\n// Avoid - sending entire record with large content\nawait realtime.update('applications', fullRecord, oldRecord, ctx.activeOrgId!);\n```\n\n### Use Broadcasts for Complex Events\n\nFor events that don't map cleanly to CRUD:\n\n```typescript\n// Hiring pipeline stage completed\nawait realtime.broadcast('pipeline-stage-complete', {\n applicationId: application.id,\n stages: ['applied', 'screening', 'interview'],\n currentStage: 'offer',\n candidateId: application.candidateId\n}, ctx.activeOrgId!);\n```\n\n## Custom Event Namespaces\n\nFor complex applications with many custom events, you can define typed event namespaces using `defineRealtime`. This generates strongly-typed helper methods for your custom events.\n\n### Defining Event Namespaces\n\nCreate a file in `services/realtime/`:\n\n```typescript\n// services/realtime/screening.ts\n\nexport default defineRealtime({\n name: 'screening',\n events: ['started', 'progress', 'completed', 'failed'],\n description: 'Candidate screening pipeline events',\n});\n```\n\n### Generated Helper Methods\n\nAfter compilation, the `createRealtime()` helper includes your custom namespace:\n\n```typescript\n\nexport const execute: ActionExecutor = async ({ ctx, input }) => {\n const realtime = createRealtime(ctx.env);\n\n // Type-safe custom event methods\n await realtime.screening.started({\n applicationId: input.applicationId,\n }, ctx.activeOrgId!);\n\n // Progress updates\n await realtime.screening.progress({\n applicationId: input.applicationId,\n percent: 50,\n step: 'background-check',\n }, ctx.activeOrgId!);\n\n // Completion\n await realtime.screening.completed({\n applicationId: input.applicationId,\n result: 'passed',\n duration: 1234,\n }, ctx.activeOrgId!);\n\n return { success: true };\n};\n```\n\n### Event Format\n\nCustom namespace events use the `broadcast` type with namespaced event names:\n\n```json\n{\n \"type\": \"broadcast\",\n \"event\": \"screening:started\",\n \"payload\": {\n \"applicationId\": \"app_123\"\n }\n}\n```\n\n### Multiple Namespaces\n\nDefine multiple namespaces for different parts of your application:\n\n```typescript\n// services/realtime/notifications.ts\nexport default defineRealtime({\n name: 'notifications',\n events: ['interview-reminder', 'offer-update', 'application-received'],\n description: 'Recruitment notification events',\n});\n\n// services/realtime/presence.ts\nexport default defineRealtime({\n name: 'presence',\n events: ['joined', 'left', 'reviewing', 'idle'],\n description: 'Who is reviewing which candidate',\n});\n```\n\nUsage:\n```typescript\nconst realtime = createRealtime(ctx.env);\n\n// Notification events\nawait realtime.notifications['interview-reminder']({ ... }, ctx.activeOrgId!);\n\n// Presence events — who's reviewing which candidate\nawait realtime.presence.reviewing({ userId: ctx.userId, candidateId: 'cnd_456' }, ctx.activeOrgId!);\n```\n\n### Namespace vs Generic Broadcast\n\n| Use Case | Approach |\n|----------|----------|\n| One-off custom event | `realtime.broadcast('event-name', payload, orgId)` |\n| Repeated event patterns | `defineRealtime` namespace |\n| Type-safe events | `defineRealtime` namespace |\n| Event discovery | `defineRealtime` (appears in generated types) |"
419
419
  },
420
420
  "stack/realtime": {
421
421
  "title": "Realtime",
@@ -423,7 +423,7 @@ export const DOCS = {
423
423
  },
424
424
  "stack/realtime/live-views": {
425
425
  "title": "Live Views",
426
- "content": "A **live view** is a named *surface*: a root row plus the related data a screen\nshows around it — forward foreign-key display values and reverse-FK child\ncollections. When a client subscribes to a live view, the open surface stays\nwhole in realtime: any write to the root row **or** a related row that shares a\nforeign key is pushed as a `view_changes` delta the client splices in place.\n\nThis is the difference from table-level [`postgres_changes`](/stack/realtime/using-realtime)\nbroadcasts, which are single-row, single-table. A person-detail screen that\nshows a `people` row plus rows from a normalized `phone_numbers` table would\notherwise have to stitch together separate per-table events and figure out that\na `phone_numbers` insert with `personId = X` belongs to the person it has open.\nLive views do that mapping for you.\n\n> Live views ride the realtime Broadcaster. You must have realtime enabled\n> (`providers.database.config.realtime: true`). Declaring a view without\n> realtime is a compile-time error.\n\n## Defining a view\n\nViews live in `services/views/<name>.ts`:\n\n```typescript\n// services/views/person-detail.ts\n\nexport default defineView({\n name: 'person-detail',\n root: 'people',\n include: [\n { relation: 'companyId' }, // forward FK → company display value\n { relation: 'phone_numbers' }, // reverse FK → phoneNumbers[] collection\n ],\n});\n```\n\n- **`root`** — the table the surface is keyed by. Must be a `defineTable`\n resource (its firewall + read access gate the surface).\n- **`include[].relation`** — a forward-FK column on the root (`companyId`), or\n the name of a child table that references the root (`phone_numbers`). The\n compiler auto-detects the direction from the foreign-key graph; pass\n `kind: 'forward' | 'reverse'` to disambiguate.\n- **`as`** — the response key the related data is spliced under. Defaults to a\n derived name: forward strips a trailing `Id` (`companyId` → `company`),\n reverse uses the child table name (`phone_numbers` → `phoneNumbers`).\n- **`fields`** — optional column projection on the included table.\n\nThe materialized surface looks like:\n\n```jsonc\n{\n \"id\": \"person_123\",\n \"name\": \"Ada Lovelace\",\n \"email\": \"ad***@example.com\", // masked per the people table's masking config\n \"company\": \"Analytical Engines\", // forward display value\n \"phoneNumbers\": [ // reverse-FK child collection\n { \"id\": \"ph_1\", \"number\": \"+1...\" }\n ]\n}\n```\n\nEvery included table is read through **its own** `firewall` and `masking` — a\nsubscriber only ever sees related rows they're already allowed to read, masked\nexactly as they would be on a normal read.\n\n## Reading a surface\n\nThe compiler generates a read endpoint per view:\n\n```http\nGET /api/v1/views/person-detail/person_123\n→ { \"data\": { ...surface }, \"seq\": 7 }\n```\n\n`seq` is the surface's current monotonic sequence — the client uses it to detect\ndropped deltas. A `404` is returned when the caller can't read the root row\n(indistinguishable from \"doesn't exist\", closing the id-probe channel).\n\n## Subscribing (client)\n\nThe built-in CMS and Account SPAs ship a `useView` hook:\n\n```tsx\n\nfunction PersonDetail({ personId }: { personId: string }) {\n const { data, connected, loading } = useView('person-detail', personId);\n // `data` stays live: editing the person merges into the root; adding a phone\n // appends to data.phoneNumbers; deleting one removes it — no refetch.\n}\n```\n\nUnder the hood `useView` uses a **subscribe-then-snapshot** flow so no change\nslips through the gap between reading the surface and the socket going live:\n\n1. Requests a **view-scoped ws-ticket** (`POST /broadcast/v1/ws-ticket` with\n `{ view, rootId }`) — gated by the same root firewall as the read endpoint —\n and opens a WebSocket scoped to `view:<view>:<rootId>`.\n2. Once the socket is open, fetches the full surface via\n `GET /api/v1/views/<view>/:rootId`. Deltas arriving during that fetch are\n **buffered**, then replayed after the snapshot applies (the route reads the\n `seq` baseline *before* materializing, so the snapshot is at least as fresh\n as `seq`, and replay is idempotent — collections key by row `id`).\n3. Applies `view_changes` deltas in place (the **hybrid-delta** model):\n - `target: 'root'` + `UPDATE` → shallow-merge into the surface root\n - `target: 'root'` + `DELETE` → surface cleared\n - `target: 'collection'` → append / replace-by-key / remove-by-key on `data[as]`\n - `delta.resync` → refetch the surface (the stricter-child path above)\n4. Tracks `seq`. A gap (`seq !== last + 1`) or a WebSocket reconnect triggers a\n full **resync** — the safety net that heals any dropped delta (Cloudflare D1\n has no transactions, so emit is best-effort by design). If the server can't\n read the baseline it returns `seq: null`; the client then adopts the first\n delta's `seq` instead of treating it as `0`, so a transient read error never\n spirals into a resync loop. Overlapping resyncs are token-guarded so a slow\n earlier fetch can't clobber a newer surface.\n\nTo subscribe from a custom client, request a ticket with `{ view, rootId }` and\nconnect to `…/broadcast/v1/websocket?ws_ticket=<ticket>`. Messages are:\n\n```jsonc\n{\n \"type\": \"view_changes\",\n \"view\": \"person-detail\",\n \"rootId\": \"person_123\",\n \"seq\": 8,\n \"delta\": { \"target\": \"collection\", \"op\": \"INSERT\", \"as\": \"phoneNumbers\",\n \"key\": \"ph_2\", \"row\": { \"id\": \"ph_2\", \"number\": \"+1...\" } }\n}\n```\n\n## How changes are captured\n\nDeltas are emitted from the **write chokepoint** — the same wrapper that injects\naudit fields wraps every `db.insert/update/delete`. Because CRUD routes *and*\naction handlers write through that db, both emit deltas; there's no separate\nhook to wire. A write taps its result and, when it used `.returning()`, fans a\ndelta to each affected surface. Soft deletes (an `UPDATE` that sets `deletedAt`)\nare emitted as `DELETE` so the row leaves the surface.\n\n## Security\n\n- The **subscribe gate** reuses the view materializer: a ticket is only minted\n when the caller can read the root row.\n- Each included table's `firewall` + `masking` apply on both the initial\n materialize and the live deltas (masking is applied per subscriber role at\n fanout), so the two are consistent.\n- **Stricter-child guard.** When a reverse-FK child's firewall is *stricter*\n than the root's (e.g. an owner-scoped note under an org-scoped person), the\n raw child row is **never broadcast**. Instead the server emits a *resync\n signal* and the client refetches the surface through the materializer, which\n applies the child's own firewall per subscriber. Row-bearing deltas are sent\n only when the child is no stricter than the root.\n- **Masking fails closed.** A mask type the Broadcaster can't replicate —\n notably `type: 'custom'`, whose function is stripped during codegen — is\n fully redacted (`[REDACTED]`) in deltas rather than passed through.\n- **Projection parity.** An include's `fields` projection is applied to deltas\n too, so a delta never carries a column the surface deliberately omits.\n\n## v1 limitations\n\n- **Depth-1 includes only.** Nested includes are a compile-time error — flatten\n the surface or split into multiple views.\n- **Forward includes** (e.g. a company name on a person) are materialized into\n the surface and refreshed on resync, but a change to the *referenced parent*\n does not push a live delta — it surfaces on the next resync/reconnect.\n- **Writes without `.returning()`** (and raw action writes that don't return\n rows) don't push a live delta; resync-on-reconnect heals the surface."
426
+ "content": "A **live view** is a named *surface*: a root row plus the related data a screen\nshows around it — forward foreign-key display values and reverse-FK child\ncollections. When a client subscribes to a live view, the open surface stays\nwhole in realtime: any write to the root row **or** a related row that shares a\nforeign key is pushed as a `view_changes` delta the client splices in place.\n\nThis is the difference from table-level [`postgres_changes`](/stack/realtime/using-realtime)\nbroadcasts, which are single-row, single-table. A person-detail screen that\nshows a `people` row plus rows from a normalized `phone_numbers` table would\notherwise have to stitch together separate per-table events and figure out that\na `phone_numbers` insert with `personId = X` belongs to the person it has open.\nLive views do that mapping for you.\n\n> Live views ride the realtime Broadcaster. You must have realtime enabled\n> (`providers.database.config.realtime: true`). Declaring a view without\n> realtime is a compile-time error.\n\n## Defining a view\n\nViews live in `services/views/<name>.ts`:\n\n```typescript\n// services/views/person-detail.ts\n\nexport default defineView({\n name: 'person-detail',\n root: 'people',\n include: [\n { relation: 'companyId' }, // forward FK → company display value\n { relation: 'phone_numbers' }, // reverse FK → phoneNumbers[] collection\n ],\n});\n```\n\n- **`root`** — the table the surface is keyed by. Must be a `defineTable`\n resource (its firewall + read access gate the surface).\n- **`include[].relation`** — a forward-FK column on the root (`companyId`), or\n the name of a child table that references the root (`phone_numbers`). The\n compiler auto-detects the direction from the foreign-key graph; pass\n `kind: 'forward' | 'reverse'` to disambiguate.\n- **`as`** — the response key the related data is spliced under. Defaults to a\n derived name: forward strips a trailing `Id` (`companyId` → `company`),\n reverse uses the child table name (`phone_numbers` → `phoneNumbers`).\n- **`fields`** — optional column projection on the included table.\n\nThe materialized surface looks like:\n\n```jsonc\n{\n \"id\": \"person_123\",\n \"name\": \"Ada Lovelace\",\n \"email\": \"ad***@example.com\", // masked per the people table's masking config\n \"company\": \"Analytical Engines\", // forward display value\n \"phoneNumbers\": [ // reverse-FK child collection\n { \"id\": \"ph_1\", \"number\": \"+1...\" }\n ]\n}\n```\n\nEvery included table is read through **its own** `firewall` and `masking` — a\nsubscriber only ever sees related rows they're already allowed to read, masked\nexactly as they would be on a normal read.\n\n## Reading a surface\n\nThe compiler generates a read endpoint per view:\n\n```http\nGET /api/v1/views/person-detail/person_123\n→ { \"data\": { ...surface }, \"seq\": 7 }\n```\n\n`seq` is the surface's current monotonic sequence — the client uses it to detect\ndropped deltas. A `404` is returned when the caller can't read the root row\n(indistinguishable from \"doesn't exist\", closing the id-probe channel).\n\n## Subscribing (client)\n\nThe built-in CMS and Account SPAs ship a `useView` hook:\n\n```tsx\n\nfunction PersonDetail({ personId }: { personId: string }) {\n const { data, connected, loading } = useView('person-detail', personId);\n // `data` stays live: editing the person merges into the root; adding a phone\n // appends to data.phoneNumbers; deleting one removes it — no refetch.\n}\n```\n\nUnder the hood `useView` uses a **subscribe-then-snapshot** flow so no change\nslips through the gap between reading the surface and the socket going live:\n\n1. Requests a **view-scoped ws-ticket** (`POST /broadcast/v1/ws-ticket` with\n `{ view, rootId }`) — gated by the same root firewall as the read endpoint —\n and opens a WebSocket scoped to `view:<view>:<rootId>`.\n2. Once the socket is open, fetches the full surface via\n `GET /api/v1/views/<view>/:rootId`. Deltas arriving during that fetch are\n **buffered**, then replayed after the snapshot applies (the route reads the\n `seq` baseline *before* materializing, so the snapshot is at least as fresh\n as `seq`, and replay is idempotent — collections key by row `id`).\n3. Applies `view_changes` deltas in place (the **hybrid-delta** model):\n - `target: 'root'` + `UPDATE` → shallow-merge into the surface root\n - `target: 'root'` + `DELETE` → surface cleared\n - `target: 'collection'` → append / replace-by-key / remove-by-key on `data[as]`\n - `delta.resync` → refetch the surface (the stricter-child path above)\n4. Tracks `seq`. A gap (`seq !== last + 1`) or a WebSocket reconnect triggers a\n full **resync** — the safety net that heals any dropped delta (Cloudflare D1\n has no transactions, so emit is best-effort by design). If the server can't\n read the baseline it returns `seq: null`; the client then adopts the first\n delta's `seq` instead of treating it as `0`, so a transient read error never\n spirals into a resync loop. Overlapping resyncs are token-guarded so a slow\n earlier fetch can't clobber a newer surface.\n\nTo subscribe from a custom client, request a ticket with `{ view, rootId }` and\nconnect to `…/broadcast/v1/websocket?ws_ticket=<ticket>`. Messages are:\n\n```jsonc\n{\n \"type\": \"view_changes\",\n \"view\": \"person-detail\",\n \"rootId\": \"person_123\",\n \"seq\": 8,\n \"delta\": { \"target\": \"collection\", \"op\": \"INSERT\", \"as\": \"phoneNumbers\",\n \"key\": \"ph_2\", \"row\": { \"id\": \"ph_2\", \"number\": \"+1...\" } }\n}\n```\n\n## How changes are captured\n\nDeltas are emitted from the **write chokepoint** — the same wrapper that injects\naudit fields wraps every `db.insert/update/delete`. Because CRUD routes *and*\naction handlers write through that db, both emit deltas; there's no separate\nhook to wire. A write taps its result and, when it used `.returning()`, fans a\ndelta to each affected surface. Soft deletes (an `UPDATE` that sets `deletedAt`)\nare emitted as `DELETE` so the row leaves the surface.\n\n## Security\n\n- The **subscribe gate** reuses the view materializer: a ticket is only minted\n when the caller can read the root row.\n- Each included table's `firewall` + `masking` apply on both the initial\n materialize and the live deltas (masking is applied per subscriber role at\n fanout), so the two are consistent.\n- A table-level `realtime.requiredRoles` declaration is honored on view\n deltas too (v0.46+): `view_changes` for that table fan out only to\n subscribers holding one of the required roles, exactly like its row-stream\n broadcasts. Tables without `requiredRoles` are unaffected.\n- **Stricter-child guard.** When a reverse-FK child's firewall is *stricter*\n than the root's (e.g. an owner-scoped note under an org-scoped person), the\n raw child row is **never broadcast**. Instead the server emits a *resync\n signal* and the client refetches the surface through the materializer, which\n applies the child's own firewall per subscriber. Row-bearing deltas are sent\n only when the child is no stricter than the root.\n- **Masking fails closed.** A mask type the Broadcaster can't replicate —\n notably `type: 'custom'`, whose function is stripped during codegen — is\n fully redacted (`[REDACTED]`) in deltas rather than passed through.\n- **Projection parity.** An include's `fields` projection is applied to deltas\n too, so a delta never carries a column the surface deliberately omits.\n\n## v1 limitations\n\n- **Depth-1 includes only.** Nested includes are a compile-time error — flatten\n the surface or split into multiple views.\n- **Forward includes** (e.g. a company name on a person) are materialized into\n the surface and refreshed on resync, but a change to the *referenced parent*\n does not push a live delta — it surfaces on the next resync/reconnect.\n- **Writes without `.returning()`** (and raw action writes that don't return\n rows) don't push a live delta; resync-on-reconnect heals the surface."
427
427
  },
428
428
  "stack/realtime/partyserver-rooms": {
429
429
  "title": "PartyServer Rooms",
@@ -431,7 +431,7 @@ export const DOCS = {
431
431
  },
432
432
  "stack/realtime/using-realtime": {
433
433
  "title": "Using Realtime",
434
- "content": "This page covers connecting to the Quickback realtime system from client applications — authentication, subscribing to events, and handling messages.\n\n## Connecting\n\nOpen a WebSocket connection to the realtime worker:\n\n```typescript\nconst ws = new WebSocket(\"wss://api.yourdomain.com/broadcast/v1/websocket\");\n```\n\n## Authentication\n\nQuickback uses **ticket-based authentication** for WebSocket connections. This is a two-step process:\n\n1. **Get a ticket** — Call the ws-ticket endpoint with your session auth\n2. **Connect with ticket** — Pass the ticket as a URL parameter when opening the WebSocket\n\nThis approach is faster and more secure than in-band auth messages — the connection is authenticated at upgrade time with no HTTP round-trip from the Durable Object.\n\n### Step 1: Get a WebSocket Ticket\n\n```typescript\nconst response = await fetch(\"/broadcast/v1/ws-ticket\", {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${sessionToken}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ eventId: \"evt_123\" }), // optional; used by resource-scoped wsTicket config\n});\nconst { wsTicket, expiresIn } = await response.json();\n// expiresIn = 60 (seconds)\n```\n\nThe ticket is a short-lived (60-second) HMAC-signed token containing your userId, roles, and the resolved subscription scope.\n\n### Step 2: Connect with Ticket\n\n```typescript\nconst ws = new WebSocket(\n `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}`\n);\n\nws.onopen = () => {\n console.log(\"Connected and authenticated!\");\n // No auth message needed — connection is pre-authenticated\n};\n```\n\nIf the ticket is invalid or expired, the WebSocket upgrade is rejected with a 401 status.\n\n## Handling Messages\n\n### CRUD Events\n\nCRUD events use the `postgres_changes` type:\n\n```typescript\nws.onmessage = (event) => {\n const msg = JSON.parse(event.data);\n\n if (msg.type === \"postgres_changes\") {\n const { table, eventType, new: newRecord, old: oldRecord } = msg;\n\n switch (eventType) {\n case \"INSERT\":\n addRecord(table, newRecord);\n break;\n case \"UPDATE\":\n updateRecord(table, newRecord);\n break;\n case \"DELETE\":\n removeRecord(table, oldRecord.id);\n break;\n }\n }\n};\n```\n\n**Event payload:**\n\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"schema\": \"public\",\n \"eventType\": \"INSERT\",\n \"new\": { \"id\": \"app_123\", \"candidateId\": \"cnd_456\", \"stage\": \"interview\" },\n \"old\": null\n}\n```\n\nFor UPDATE events, both `new` and `old` are populated. For DELETE events, only `old` is populated.\n\n### Custom Broadcasts\n\nCustom events use the `broadcast` type:\n\n```typescript\nif (msg.type === \"broadcast\") {\n const { event, payload } = msg;\n\n if (event === \"screening-complete\") {\n refreshApplication(payload.applicationId);\n } else if (event === \"screening:progress\") {\n updateProgressBar(payload.percent);\n }\n}\n```\n\n**Event payload:**\n\n```json\n{\n \"type\": \"broadcast\",\n \"event\": \"screening-complete\",\n \"payload\": {\n \"applicationId\": \"app_123\",\n \"candidateId\": \"cnd_456\",\n \"stage\": \"interview\"\n }\n}\n```\n\nCustom namespaces (from `defineRealtime()`) use the format `namespace:event` — e.g., `screening:started`, `screening:progress`.\n\n## Security\n\n### Role-Based Filtering\n\nEvents are only delivered to users whose role matches the broadcast's `targetRoles`. If a table's realtime config specifies `requiredRoles: [\"hiring-manager\", \"recruiter\"]`, only users with those roles receive the events.\n\n### Per-Role Masking\n\nField values are masked according to the subscriber's role. For example, with this masking config:\n\n```typescript\nmasking: {\n ssn: { type: \"ssn\", show: { roles: [\"owner\"] } },\n}\n```\n\n- **Owner sees:** `{ ssn: \"123-45-6789\" }`\n- **Recruiter sees:** `{ ssn: \"*****6789\" }`\n\nMasking is pre-computed per-role (O(roles), not O(subscribers)) for efficiency.\n\n### User-Specific Events\n\nEvents can target a specific user lane. Only that user receives the broadcast — all other connections on the same scope are skipped.\n\n### Scope Isolation\n\nEach WebSocket connection is attached to exactly one resolved scope: `scopeKey`, `organizationId`, or `userId`. Users can only subscribe to the scope stamped into their ws ticket, enforced during authentication and ticket minting.\n\n## Reconnection\n\nWebSocket connections can drop due to network issues. Implement reconnection logic in your client — note that you need to fetch a fresh ticket on each reconnect since tickets expire after 60 seconds:\n\n```typescript\nasync function connect() {\n // Get a fresh ticket each time\n const res = await fetch(\"/broadcast/v1/ws-ticket\", {\n method: \"POST\",\n headers: { Authorization: `Bearer ${sessionToken}` },\n body: JSON.stringify({ eventId: \"evt_123\" }),\n });\n const { wsTicket } = await res.json();\n\n const ws = new WebSocket(\n `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}`\n );\n\n ws.onclose = () => {\n // Reconnect after delay\n setTimeout(connect, 2000);\n };\n\n ws.onmessage = (event) => {\n const msg = JSON.parse(event.data);\n handleMessage(msg);\n };\n\n return ws;\n}\n```\n\n## Environment\n\nNo additional environment variables are needed for realtime. The Broadcaster Durable Object runs inline in your main worker and reuses `BETTER_AUTH_SECRET` for WebSocket ticket signing.\n\nThe compiler generates the required `wrangler.toml` bindings automatically:\n\n```toml\n[[durable_objects.bindings]]\nname = \"BROADCASTER\"\nclass_name = \"Broadcaster\"\n\n[[migrations]]\ntag = \"v1\"\nnew_classes = [\"Broadcaster\"]\n```\n\n## Cloudflare Only\n\nRealtime requires Cloudflare Durable Objects and is only available with the Cloudflare runtime.\n\n## See Also\n\n- [Durable Objects Setup](/stack/realtime/durable-objects) — Configuration, event formats, masking, and custom namespaces\n- [Masking](/compiler/definitions/masking) — Field masking configuration"
434
+ "content": "This page covers connecting to the Quickback realtime system from client applications — authentication, subscribing to events, and handling messages.\n\n## Connecting\n\nOpen a WebSocket connection to the realtime worker:\n\n```typescript\nconst ws = new WebSocket(\"wss://api.yourdomain.com/broadcast/v1/websocket\");\n```\n\n## Authentication\n\nQuickback uses **ticket-based authentication** for WebSocket connections. This is a two-step process:\n\n1. **Get a ticket** — Call the ws-ticket endpoint with your session auth\n2. **Connect with ticket** — Pass the ticket as a URL parameter when opening the WebSocket\n\nThis approach is faster and more secure than in-band auth messages — the connection is authenticated at upgrade time with no HTTP round-trip from the Durable Object.\n\n### Step 1: Get a WebSocket Ticket\n\n```typescript\nconst response = await fetch(\"/broadcast/v1/ws-ticket\", {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${sessionToken}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ eventId: \"evt_123\" }), // optional; used by resource-scoped wsTicket config\n});\nconst { wsTicket, expiresIn } = await response.json();\n// expiresIn = 60 (seconds)\n```\n\nThe ticket is a short-lived (60-second) HMAC-signed token containing your userId, roles, and the resolved subscription scope.\n\n### Step 2: Connect with Ticket\n\n```typescript\nconst ws = new WebSocket(\n `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}`\n);\n\nws.onopen = () => {\n console.log(\"Connected and authenticated!\");\n // No auth message needed — connection is pre-authenticated\n};\n```\n\nIf the ticket is invalid or expired, the WebSocket upgrade is rejected with a 401 status.\n\n## Handling Messages\n\n### CRUD Events\n\nCRUD events use the `postgres_changes` type:\n\n```typescript\nws.onmessage = (event) => {\n const msg = JSON.parse(event.data);\n\n if (msg.type === \"postgres_changes\") {\n const { table, eventType, new: newRecord, old: oldRecord } = msg;\n\n switch (eventType) {\n case \"INSERT\":\n addRecord(table, newRecord);\n break;\n case \"UPDATE\":\n updateRecord(table, newRecord);\n break;\n case \"DELETE\":\n removeRecord(table, oldRecord.id);\n break;\n }\n }\n};\n```\n\n**Event payload:**\n\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"schema\": \"public\",\n \"eventType\": \"INSERT\",\n \"new\": { \"id\": \"app_123\", \"candidateId\": \"cnd_456\", \"stage\": \"interview\" },\n \"old\": null\n}\n```\n\nFor UPDATE events, both `new` and `old` are populated. For DELETE events, only `old` is populated.\n\n### Custom Broadcasts\n\nCustom events use the `broadcast` type:\n\n```typescript\nif (msg.type === \"broadcast\") {\n const { event, payload } = msg;\n\n if (event === \"screening-complete\") {\n refreshApplication(payload.applicationId);\n } else if (event === \"screening:progress\") {\n updateProgressBar(payload.percent);\n }\n}\n```\n\n**Event payload:**\n\n```json\n{\n \"type\": \"broadcast\",\n \"event\": \"screening-complete\",\n \"payload\": {\n \"applicationId\": \"app_123\",\n \"candidateId\": \"cnd_456\",\n \"stage\": \"interview\"\n }\n}\n```\n\nCustom namespaces (from `defineRealtime()`) use the format `namespace:event` — e.g., `screening:started`, `screening:progress`.\n\n## Security\n\n### Role-Based Filtering\n\nEvents are only delivered to users whose role matches the broadcast's `targetRoles`. If a table's realtime config specifies `requiredRoles: [\"hiring-manager\", \"recruiter\"]`, only users with those roles receive the events. This applies to generated CRUD broadcasts and to [live view](/stack/realtime/live-views) `view_changes` deltas alike, enforced at fanout (v0.46+ — recompile and redeploy to pick up the enforcement).\n\n### Per-Role Masking\n\nField values are masked according to the subscriber's role. For example, with this masking config:\n\n```typescript\nmasking: {\n ssn: { type: \"ssn\", show: { roles: [\"owner\"] } },\n}\n```\n\n- **Owner sees:** `{ ssn: \"123-45-6789\" }`\n- **Recruiter sees:** `{ ssn: \"*****6789\" }`\n\nMasking is pre-computed per-role (O(roles), not O(subscribers)) for efficiency. A `type: 'custom'` mask function can't run inside the Broadcaster — those columns broadcast as `[REDACTED]` (fail closed).\n\n### User-Specific Events\n\nEvents can target a specific user lane. Only that user receives the broadcast — all other connections on the same scope are skipped.\n\n### Scope Isolation\n\nEach WebSocket connection is attached to exactly one resolved scope: `scopeKey`, `organizationId`, or `userId`. Users can only subscribe to the scope stamped into their ws ticket, enforced during authentication and ticket minting.\n\n## Reconnection\n\nWebSocket connections can drop due to network issues. Implement reconnection logic in your client — note that you need to fetch a fresh ticket on each reconnect since tickets expire after 60 seconds:\n\n```typescript\nasync function connect() {\n // Get a fresh ticket each time\n const res = await fetch(\"/broadcast/v1/ws-ticket\", {\n method: \"POST\",\n headers: { Authorization: `Bearer ${sessionToken}` },\n body: JSON.stringify({ eventId: \"evt_123\" }),\n });\n const { wsTicket } = await res.json();\n\n const ws = new WebSocket(\n `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}`\n );\n\n ws.onclose = () => {\n // Reconnect after delay\n setTimeout(connect, 2000);\n };\n\n ws.onmessage = (event) => {\n const msg = JSON.parse(event.data);\n handleMessage(msg);\n };\n\n return ws;\n}\n```\n\n## Environment\n\nNo additional environment variables are needed for realtime. The Broadcaster Durable Object runs inline in your main worker and reuses `BETTER_AUTH_SECRET` for WebSocket ticket signing.\n\nThe compiler generates the required `wrangler.toml` bindings automatically:\n\n```toml\n[[durable_objects.bindings]]\nname = \"BROADCASTER\"\nclass_name = \"Broadcaster\"\n\n[[migrations]]\ntag = \"v1\"\nnew_classes = [\"Broadcaster\"]\n```\n\n## Cloudflare Only\n\nRealtime requires Cloudflare Durable Objects and is only available with the Cloudflare runtime.\n\n## See Also\n\n- [Durable Objects Setup](/stack/realtime/durable-objects) — Configuration, event formats, masking, and custom namespaces\n- [Masking](/compiler/definitions/masking) — Field masking configuration"
435
435
  },
436
436
  "stack/storage": {
437
437
  "title": "Storage",