@quickback-dev/cli 0.34.3 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/docs/content.d.ts.map +1 -1
  2. package/dist/docs/content.js +35 -5
  3. package/dist/docs/content.js.map +1 -1
  4. package/dist/index.js +1 -1
  5. package/dist/skill/SKILL.md +3 -3
  6. package/dist/skill/agents/quickback-specialist/AGENT.md +3 -3
  7. package/dist/skill/docs/changelog.md +442 -0
  8. package/dist/skill/docs/compiler/definitions/arrows.md +269 -0
  9. package/dist/skill/docs/compiler/definitions/diagnostics.md +136 -0
  10. package/dist/skill/docs/compiler/definitions/feature.md +3 -3
  11. package/dist/skill/docs/compiler/definitions/fga.md +314 -0
  12. package/dist/skill/docs/compiler/definitions/firewall.md +93 -6
  13. package/dist/skill/docs/compiler/definitions/permissions.md +145 -0
  14. package/dist/skill/docs/compiler/definitions/scopes.md +339 -0
  15. package/dist/skill/docs/compiler/definitions/views.md +66 -0
  16. package/dist/skill/docs/stack/realtime/durable-objects.md +43 -0
  17. package/dist/skill/docs/stack/realtime/live-views.md +168 -0
  18. package/dist/skill/docs/stack/realtime/partyserver-rooms.md +22 -2
  19. package/package.json +1 -1
  20. package/src/skill/SKILL.md +3 -3
  21. package/src/skill/agents/quickback-specialist/AGENT.md +3 -3
  22. package/src/skill/docs/changelog.md +442 -0
  23. package/src/skill/docs/compiler/definitions/arrows.md +269 -0
  24. package/src/skill/docs/compiler/definitions/diagnostics.md +136 -0
  25. package/src/skill/docs/compiler/definitions/feature.md +3 -3
  26. package/src/skill/docs/compiler/definitions/fga.md +314 -0
  27. package/src/skill/docs/compiler/definitions/firewall.md +93 -6
  28. package/src/skill/docs/compiler/definitions/permissions.md +145 -0
  29. package/src/skill/docs/compiler/definitions/scopes.md +339 -0
  30. package/src/skill/docs/compiler/definitions/views.md +66 -0
  31. package/src/skill/docs/stack/realtime/durable-objects.md +43 -0
  32. package/src/skill/docs/stack/realtime/live-views.md +168 -0
  33. package/src/skill/docs/stack/realtime/partyserver-rooms.md +22 -2
@@ -3,7 +3,7 @@
3
3
  export const DOCS = {
4
4
  "changelog": {
5
5
  "title": "Changelog",
6
- "content": "## v0.34.1 — May 24, 2026\n\nPatch fixing a silent-skip bug in drizzle migration emission, plus a new\nCLI subcommand for inspecting and repairing migration-state drift.\n\n### Compiler now fails loud on drizzle migration state drift\n\nWhen `quickback/drizzle/<dialect>/meta/_journal.json` fell out of sync\nwith the on-disk `.sql` files — typically because someone hand-rolled a\nmigration without a journal bump, or because a prior compile collided\nwith an existing tag — drizzle-kit's diff base became stale and it\nsilently skipped emission. The compile reported success, no new `.sql`\nwas written for newly defined tables, and the next `wrangler deploy`\nshipped a Worker that 500'd on every request touching those tables.\n\nThe compiler now runs a precheck before any drizzle-kit invocation and\nrefuses to compile when it detects any of:\n\n- `.sql` files on disk with no matching entry in `_journal.json`\n- journal entries that reference missing `.sql` files\n- non-sequential `idx` values in `_journal.json`\n- two `.sql` files sharing the same `idx`\n- (for `auth/` and `features/` only) journal entries with no matching\n `<idx>_snapshot.json` — drizzle-kit needs the snapshot as a diff base\n\nSnapshot/journal drift that the previous `console.warn` only logged\nserver-side is now propagated to the CLI and printed under\n\"Compilation warnings\".\n\n### New `quickback migrations doctor` CLI command\n\nTwo modes:\n\n```bash\nquickback migrations doctor # diagnose\nquickback migrations doctor --rebuild-journal # repair\n```\n\nDiagnose walks `quickback/drizzle/{auth,features,files,webhooks,audit}/`,\nprints a per-dir table (`.sql files`, `journal entries`, `snapshots`),\nand flags every drift kind the compiler precheck enforces. Repair\nrewrites `_journal.json` from on-disk `.sql` filenames in sorted order —\nthis is the recovery recipe users were applying by hand. Snapshot drift\non drizzle-kit dirs (`auth/`, `features/`) can only be repaired by\nrunning `drizzle-kit introspect` against the live DB; the doctor prints\nthe exact command.\n\n### Upgrade path for projects in the broken state\n\nProjects with existing drift will get a clear error message and an\nexplicit fix command on the next compile against v0.34.1:\n\n```\n✖ Drizzle migration state is inconsistent — refusing to compile.\n Causes:\n - quickback/drizzle/features: 7 .sql file(s) have no matching journal entry: ...\n Fixes:\n - Run `quickback migrations doctor` to diagnose, then\n `quickback migrations doctor --rebuild-journal` to repair.\n```\n\nNo action needed for projects whose journals are already in sync.\n\n## v0.34.0 — May 23, 2026\n\nCustomizable email-OTP templates and a dedicated admin-create-user hook\n— closes a longstanding gap where projects on `email.provider: 'aws-ses'`\nhad to live with the generic \"Your password reset code is ...\" copy for\nadmin-bootstrapped accounts.\n\n### Per-type email-OTP template overrides\n\nDrop a `.ts` file at `quickback/email-templates/<name>.ts` that\ndefault-exports `(input) => ({ subject, html, text })`, then reference\nit from the new `plugins.emailOtp.templates` map. Missing keys fall\nthrough to the package defaults from `@quickback-dev/better-auth-aws-ses`\n— this is purely additive; existing `emailOtp: true` projects emit the\nsame code they did before.\n\n```ts title=\"quickback/quickback.config.ts\"\ndefineAuth(\"better-auth\", {\n plugins: {\n emailOtp: {\n templates: {\n 'forget-password': './email-templates/forget-password',\n 'welcome': './email-templates/welcome',\n },\n },\n },\n});\n```\n\n```ts title=\"quickback/email-templates/welcome.ts\"\nexport default function welcome({ otp, name, appName, appUrl }) {\n const greeting = name ? `Hi ${name},` : 'Hi,';\n return {\n subject: `Welcome to ${appName} — set your password`,\n html: `<h1>Welcome to ${appName}</h1><p>${greeting} use this code: <b>${otp}</b></p>`,\n text: `${greeting}\\n\\nYour ${appName} code: ${otp}`,\n };\n}\n```\n\nRecognized keys: `'sign-in' | 'email-verification' | 'forget-password' |\n'welcome'`. The first three map 1:1 to Better Auth's emailOTP `type`\nenum.\n\n### Synthetic `welcome` routing — credential-row lookup\n\n`'welcome'` has no native Better Auth OTP type. When configured, the\ngenerated `sendVerificationOTP` callback queries the `account` table\nfor a `credential`-provider row for the recipient *before* rendering;\nif the user has none (typical of an admin-plugin-created account\nwithout a password), the send is rerouted through the welcome\ntemplate. Without a welcome template, those sends fall through to\n`forget-password` — same behavior as before. DB-error path fails open\nto the normal forget-password flow so a transient failure can't\ndeadlock the password-reset surface.\n\nProvider scope: overrides are only honored on `email.provider:\n'aws-ses'`. The Cloudflare Email path uses the helper's own template\npipeline and ignores the new config.\n\n### New recognized hook: `after-admin-user-create.ts`\n\nA virtual event that wires into the same Better Auth\n`databaseHooks.user.create.after` slot as the generic\n`after-user-create.ts`, but the generator gates the call on\n`_baCtx?.context?.path` matching `/admin/create-user` so it only fires\nwhen the row came from the admin plugin's create-user endpoint. Use it\nfor first-time-user provisioning (welcome email, default org\nassignment, audit-log writes) without inspecting the BA context by\nhand. The generic `after-user-create.ts` still runs for every signup,\nincluding admin-created ones; the two coexist in a single merged\n`after:` handler.\n\n```\nquickback/hooks/\n after-user-create.ts # every signup\n after-admin-user-create.ts # admin-plugin /admin/create-user only\n```\n\n### File transport mirrors existing slots\n\nThe new `quickback/email-templates/` directory follows the same\npattern as `quickback/plugins/`, `quickback/hooks/`, and\n`quickback/lib/`: the CLI walks the folder and uploads each `.ts` file\nin a new `projectEmailTemplates` field on the compile request; the\nbetter-auth provider stages referenced files into\n`src/email-templates/<name>.ts` and emits default imports in\n`src/lib/auth.ts`. Files not referenced by any template entry are\nignored — the CLI uploads the whole directory; the compiler picks only\nwhat's needed. A relative path pointing at a file the CLI never\nshipped fails compile fast with a \"place the file at … and rerun\"\nhint.\n\nSee [AWS SES Plugin → Per-Type Template Overrides](/stack/auth/plugins/aws-ses#per-type-template-overrides)\nand [Account UI → Hooks](/stack/account-ui/hooks#recognized-events).\n\n## v0.33.6 — May 22, 2026\n\nTwo compiler-side fixes for the queue-consumer / embedding surface and one\nschema-emission bug that blocked `generateId: 'cuid'` projects.\n\n### Schema-emitted `createId()` now ships with a polyfill (no missing import)\n\nWhen `providers.database.config.generateId` is set to `'cuid'`, the audit-\nfield injector emits an id column like\n`id: text('id').primaryKey().$defaultFn(() => createId())`. Previously the\nschema source referenced `createId` but no import landed, so `tsc` on the\ngenerated project failed with `Cannot find name 'createId'`. Recurring\nbug — every recompile re-emitted the broken file (the \"do not edit\"\nbanner doesn't protect from regeneration).\n\nFix: the injector now prepends a top-of-file polyfill backed by\n`crypto.randomUUID()` — a Workers / Node 19+ / Bun global — instead of\ntrying to import `@paralleldrive/cuid2`. The package isn't bundled by\nQuickback (per the [hooks doc](/stack/account-ui/hooks)'s \"stick to\nbuilt-ins\" guidance) and the schema-gen sandbox can't resolve project\nnode_modules anyway, so the polyfill is the only path that works\nout-of-the-box.\n\n```ts title=\"Generated schema header (cuid strategy)\"\n\n// Polyfill — Quickback compiler does not ship @paralleldrive/cuid2 in\n// generated projects, and the schema-gen sandbox can't see node_modules.\n// crypto.randomUUID() is a Workers / Node 19+ / Bun global.\nconst createId = () => crypto.randomUUID();\n\nexport const widgets = sqliteTable('widgets', {\n id: text('id').primaryKey().$defaultFn(() => createId()),\n // ...\n});\n```\n\nIf you want real cuid2 strings (collision-resistant, shorter than UUIDs)\nyou can still install `@paralleldrive/cuid2` and add the import yourself —\nthe injector honours an existing import and skips the polyfill.\n\n### queue-consumer.ts header reflects what the file actually does\n\nBefore v0.33.6 the generated `src/queue-consumer.ts` always carried the\npreamble:\n\n```\n* Queue Consumer for Embedding Jobs & Custom Queue Handlers\n*\n* Processes embedding jobs asynchronously using Workers AI and Vectorize.\n* Also supports custom queue handlers defined in services/queues/.\n```\n\n— even on projects with zero embedding features. Users on\ncustom-queue-only deployments would search for `EMBEDDINGS_QUEUE` /\nVectorize bindings that wrangler.toml correctly didn't emit, wasting\ndiagnostic time.\n\nThe preamble now reflects the actual surface:\n\n| `hasEmbeddings` | `hasCustomHandlers` | Header |\n|---|---|---|\n| ✓ | ✓ | \"Queue Consumer for Embedding Jobs & Custom Queue Handlers\" |\n| ✓ | — | \"Queue Consumer for Embedding Jobs\" |\n| — | ✓ | \"Queue Consumer for Custom Queue Handlers\" + explicit \"No embedding bindings (EMBEDDINGS_QUEUE / Vectorize / AI) are referenced\" |\n| — | — | \"Queue Consumer Stub\" (additionalQueues with no handler yet) |\n\n### Symmetric embedding detection prevents silent drift\n\nThe wrangler.toml emit path (`EMBEDDINGS_QUEUE` producer/consumer\ndeclaration) and the queue-consumer.ts emit path (embedding handler code)\npreviously used two different functions to detect \"this project has\nembeddings\": `hasEmbeddingsConfig` checked both `feature.resource.\nembeddings` and `feature.tables[].resource.embeddings`;\n`extractEmbeddingFeatures` only iterated the tables array. A feature\nshape with feature-level embeddings sugar but no populated tables would\nland in the wrangler binding while NOT landing in the consumer file\n— silent drift.\n\n`hasEmbeddingsConfig` is now defined as\n`extractEmbeddingFeatures(...).length > 0`. The two stay in lock-step\nby construction. `extractEmbeddingFeatures` now reads from both shapes\n(tables-level when present, feature-level otherwise).\n\n## v0.33.5 — May 22, 2026\n\nTwo structural fixes that resolve recurring classes of bug for projects with\ninteger primary keys and for projects whose audit columns drift between\nschema and database.\n\n### URL `:id` params coerce to Number when the PK column is integer\n\nPer-id CRUD handlers (`GET /:id`, `PATCH /:id`, `DELETE /:id`, `PUT /:id`)\nextracted the URL param as a string and passed it straight into\n`eq(table.id, id)`. For resources with `integer().primaryKey()` columns —\ntriggered either by `generateId: 'serial'` on the database config or by\nimported legacy schemas — every per-id route raised a downstream tsc\ntype error (integer ≠ string). One production project reported 249 such\nerrors across 30+ generated `*.routes.ts` files.\n\nGenerated handlers for integer-PK resources now emit:\n\n```ts\nconst __idRaw = c.req.param('id');\nconst id = Number(__idRaw);\nif (!Number.isInteger(id)) {\n return c.json(ValidationErrors.invalidInput([{\n path: ['id'],\n message: `Expected integer, got \"${__idRaw}\"`,\n code: 'invalid_type',\n }]), 400);\n}\n```\n\nText-PK resources (the default and the recommended path) are unchanged.\n\nA soft-deprecation warning now fires at compile time when\n`providers.database.config.generateId === 'serial'` is set, nudging new\nprojects toward text-PK strategies (`'cuid'`, `'uuid'`, `'prefixed'`, or\nthe default). Existing serial-PK projects keep working.\n\n### Audit-field injection now runs for every dialect\n\nThe compiler auto-injects `created_at`, `modified_at`, `created_by`, and\n`modified_by` columns into every feature table, and the scoped-db\nruntime auto-fills them on insert. Until v0.33.5, the early injection\nstep in `parseCompilerInput` was gated on `targetDialect ===\n'postgresql'`. SQLite/D1 projects fell back to a later injection inside\n`generateFeature`, which only fired when `feature.tables.length > 0` —\nfeatures arriving without a populated tables array (raw-drizzle shapes,\ncertain legacy migration tables) silently skipped audit injection.\n\nSymptom: schemas claimed the columns existed (so the scoped-db proxy\ntried to fill them on insert), but the database table didn't have them.\nInserts failed with \"column doesn't exist.\" Users reported this for the\n`user_preferences` table and, earlier, for `chat_reads` (the\n`0028_chat_reads_id_column.sql` incident).\n\nThe early injection now runs for all dialects. `injectAuditFields` is\nalready idempotent, so the subsequent per-target injections in\n`compilePureSQLTarget` and `feature-generator.ts` are no-ops when the\ncolumns are already present. Net: every feature's schema source has\naudit columns by the time drizzle-kit reads it, regardless of dialect\nor feature shape.\n\nUpgrade path: recompile against v0.33.5, commit the generated migration\nthat adds the missing audit columns, then `wrangler d1 migrations apply`.\n\n## v0.33.4 — May 21, 2026\n\nPatch fixes covering upgrade-path bugs and OpenAPI spec/route divergence. No\nnew features or breaking changes.\n\n### OpenAPI emits CRUD endpoints only when the route emitter registers them\n\nThe OpenAPI emitter previously advertised `GET /`, `POST /`, `GET /:id`,\n`PATCH /:id`, `DELETE /:id`, and the corresponding `/batch` operations on\nevery resource, regardless of which CRUD verbs were actually declared.\nClients generated from `openapi.json` then issued requests that fell\nthrough to `ROUTE_NOT_FOUND` from the firewall layer — a silent contract\nbreak for anyone whose code path was driven by openapi-typescript or\nsimilar codegen.\n\nEach gate now mirrors the route emitter exactly. A resource that only\ndeclares `read + create + delete` (no `update`) gets no PATCH operations\nin the spec. A write-only sink (`create` only, no `read`) gets no GET\noperations. Same for batch variants — `POST /batch` only when\n`crud.create` is set, `DELETE /batch` only when `crud.delete` is set,\netc.\n\nIf your generated client was calling these spurious endpoints, those\ncalls were already failing at runtime; this just removes them from the\nspec.\n\n### Legacy D1 audit-timestamp migrations rewritten in place\n\nCompilers ≤ v0.33.1 emitted\n`DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))` for audit columns\n(`created_at`, `modified_at`, etc.). Cloudflare D1 rejects this in\n`ALTER TABLE ADD COLUMN` with `SQLITE_ERROR [code: 7500] \"Cannot add a\ncolumn with non-constant default\"`. v0.33.2 stopped emitting the\nnon-constant form, but pending unapplied legacy migration files on\nupgrading projects still poisoned `wrangler d1 migrations apply` and\nleft the deploy stuck.\n\nThe D1 migration safety pass now retrofits these files in place,\nreplacing the strftime expression with the same `'1970-01-01T00:00:00.000Z'`\nconstant v0.33.2+ uses. The compile-time warning lists the affected\ncolumns:\n\n```\n⚠ D1 helper adjusted features migrations for Cloudflare D1 safety:\n 0004_early_dracula.sql [rewrote=applied_at,created_at,modified_at]\n```\n\nUpgrade path: recompile against v0.33.4, commit the rewritten SQL, then\n`wrangler d1 migrations apply` proceeds.\n\n### D1 helper warning is now actionable\n\nThe same migration safety pass auto-prepends `PRAGMA defer_foreign_keys\n= on` to every drizzle table-rebuild migration — required on D1\nbecause it doesn't honour `PRAGMA foreign_keys=OFF/ON` mid-migration the\nway SQLite does. The pass used to surface this insertion as a warning\non every recompile, training users to ignore the warning entirely.\n\nThe PRAGMA is still inserted (it has to be), but no longer fires the\nwarning. Stripped Better Auth cleanup, reordered child-first DROPs, and\nthe new `rewrote=…` annotation above still warn — those are cases where\na human should look.\n\n### Reference: `account.appUrl` / `account.tenantPattern`\n\nv0.33's redesigned dashboard org-card uses two new optional fields on\nthe `account` config to deep-link into the tenant's own app:\n\n```ts\n// quickback.config.ts\naccount: {\n // …existing fields\n appUrl: 'https://app.example.com',\n tenantPattern: '/{slug}',\n}\n```\n\nBoth are typed in the config schema and baked into the Account SPA at\nbuild time as `VITE_QUICKBACK_APP_URL` and `VITE_TENANT_URL_PATTERN`.\nWithout them, the dashboard falls back to a single-target card that\nlinks to the account org-settings page (legacy v0.32 behaviour). Adding\nthem enables the two-zone layout with the external deep-link affordance.\n\n(No code change in v0.33.4 — the fields shipped with v0.33.0 but weren't\ncalled out in the changelog.)\n\n## v0.33.0 — May 21, 2026\n\n### Dedicated hostnames for `/auth/v1/*` and `/api/v1/*` (Shape 1)\n\nTwo new optional overrides let you carve specific backend surfaces onto dedicated hostnames, served by the same Worker:\n\n```ts\n// quickback.config.ts\nauth: { domain: 'auth.example.com' }, // /auth/v1/* lives here too\napi: { domain: 'api.example.com' }, // /api/v1/* lives here too\n```\n\nOn the dedicated hostname, the hostname IS the namespace — `/v1/*` is a shortcut that the Worker-entry rewriter prepends with `/auth` or `/api` before route matching. So `https://api.example.com/v1/users` reaches the same handler as `https://quickback.example.com/api/v1/users`. Both forms work; the long form is also accepted on the dedicated host. Non-matching paths return a JSON 404 (\"Not found on api.domain — this hostname serves /api/v1/* and the /v1/* shortcut only\") — each hostname stays dedicated to its surface. `/health` and `/openapi.json` are explicit exceptions because monitoring/discovery agents expect them everywhere.\n\nBoth new domains:\n- Get a `{ pattern, custom_domain: true }` route in `wrangler.toml`\n- Join `trustedOrigins` (CORS allowlist)\n- Join the cross-subdomain cookie inference (auto-enables `crossSubDomainCookies` when ≥2 same-parent subdomains are configured)\n- Join CSP `connect-src` so SPAs can fetch from them\n\n**Dual-reach:** all routes remain reachable at the unified backend host (see below) regardless of which dedicated hostnames are configured. The dedicated hostnames are aliases, never replacements.\n\n### `quickback.{baseDomain}` codified as the always-present unified backend\n\nThe compiler has always auto-inferred a `quickback.{baseDomain}` hostname when any subdomain is configured. v0.33 promotes this from inferred fallback to **load-bearing contract**:\n\n- The unified backend hostname is GUARANTEED to exist when any custom subdomain (`account.domain`, `cms.domain`, `auth.domain`, `api.domain`, `apps.<n>.domain`) is set.\n- Every compiler-emitted backend route (api, auth, storage, health, openapi, realtime, mcp, bundled SPAs, sysadmin endpoints) is reachable at the unified host, always.\n- Per-surface domain overrides are additive (Shape 1) — they create more hostnames, never remove routes from the unified host.\n\nThis is forward-pointing: the future management layer can rely on a single discovery URL pattern (`https://quickback.{baseDomain}/...`) to find any backend regardless of how the operator split their surfaces onto subdomains.\n\nInference also extends to consider `auth.domain` and `api.domain` as domain sources, so a project configuring only one of them still derives `quickback.{baseDomain}` automatically. Explicit `config.domain` still wins over inference.\n\n### `compiler.routes` config block (scaffold — partial)\n\nOptional path-prefix overrides for compiler-emitted system routes:\n\n```ts\ncompiler: {\n routes: {\n storage: '/files', // default '/storage'\n broadcast: '/realtime', // default '/broadcast/v1'\n mcp: '/agent', // default '/mcp'\n health: '/_health', // default '/health'\n openapi: '/openapi.yaml', // default '/openapi.json'\n },\n}\n```\n\n**Status:** the config is validated and reaches the reserved-prefix registry (so SPA pass-through and compile-time collision detection already honor overrides), but the per-section route emitters still hardcode the defaults. Setting a non-default value today will produce a misconfigured Worker — the registry knows the new path but the actual `app.route('/storage/v1', …)` mount uses the old one. **Don't set these in production yet.** Per-section emit wiring lands in a follow-up.\n\n`/api/v1/` and `/auth/v1/` are NOT configurable here — those are deep contracts touched by feature emitters, OpenAPI generation, generated clients, and BA's own basePath. The Shape 1 hostname overrides above are the supported way to relocate them.\n\n## v0.32.0 — May 21, 2026\n\n### Single-origin path-routed architecture\n\nA modern Quickback project now runs on **one Cloudflare Worker behind one custom domain**, with the bundled Account and CMS SPAs path-mounted at `/account/` and `/cms/`, system routes at `/api/`, `/auth/`, `/storage/`, and the user's own SPAs anywhere else they want. No cross-subdomain cookies, zero CORS preflights, no separate `api.`/`account.`/`cms.` subdomains required:\n\n```ts\n// quickback.config.ts\napps: { www: { domain: 'app.example.com' } }, // user's root SPA\naccount: true, // bundled at /account/\ncms: true, // bundled at /cms/\n// /api/, /auth/, /storage/, /openapi.json, /health all live here too\n```\n\nThe bug that previously broke this shape: when a hostname-mounted root SPA was configured (`apps.www.domain`), its middleware swallowed every path that wasn't in a hardcoded list (`/api/`, `/auth/`, `/admin/`, `/storage/`, `/health`). Requests to `/account/profile` got remapped to `/www/account/profile`, 404'd, then SPA-fallback'd to the wrong SPA. v0.32 introduces a **reserved-prefix registry** (`resolveReservedPrefixes` in `apps/compiler/src/generators/core/reserved-prefixes.ts`) as the single source of truth for what every catchall middleware must pass through:\n\n- **System** (always present): `/api/`, `/auth/`, `/storage/`, `/health`, `/openapi.json`\n- **Conditional** (only when feature is on): `/account/` (when `account: true`), `/cms/` (when `cms: true`), `/broadcast/v1/` (realtime), `/mcp` (MCP server)\n- **User-contributed**: every `apps.<name>.path` for path-mounted apps\n\nPath-mounted apps that collide with a system or bundled-SPA reservation throw a compile-time error naming both owners. `apps.api = { path: '/api' }` errors clearly instead of silently hijacking feature routes at runtime.\n\n### Admin URL namespace migration: `/admin/v1/*` → `/auth/v1/admin/*`\n\nQuickback's legacy admin tier emitted three things under `/admin/v1/*`:\n\n1. A role-admit middleware that admitted both `'admin'` and `'sysadmin'` — contradicting the pseudo-role evaluator's strict-independence model (`ADMIN` admits `'admin'` only; `SYSADMIN` admits `'sysadmin'` only).\n2. `GET /admin/v1/organizations` — a thin proxy to Better Auth's own `/auth/v1/organization/list`.\n3. `GET /admin/v1/sysadmin/organizations` — cross-tenant org listing, sysadmin-only.\n\nIn v0.32, the first two are **removed** and the third **renames** to `GET /auth/v1/admin/list-organizations`. The new path sits under Better Auth's admin URL namespace (sibling of `/auth/v1/admin/list-users`, `/auth/v1/admin/ban-user`, etc.), follows BA's verb-noun convention, and keeps its sysadmin-only gate inside the handler — Quickback-emitted, not BA-mounted.\n\nWhat this enables: `/admin/*` is no longer a reserved system prefix. Projects can mount their own admin SPA via `apps.admin = { path: '/admin' }` without colliding with anything.\n\nWhat changes for callers:\n- The bundled CMS SPA's sysadmin org switcher is updated in lockstep (no migration needed for projects using the SPA as-is).\n- External callers of `/admin/v1/organizations` should migrate to BA's `/auth/v1/organization/list` (same behavior — caller's memberships).\n- External callers of `/admin/v1/sysadmin/organizations` should migrate to `/auth/v1/admin/list-organizations`.\n- Features that previously relied on the \"admit both admin AND sysadmin\" middleware should declare `access: { roles: ['ADMIN', 'SYSADMIN'] }` explicitly on each route.\n\nThe `ADMIN_ROUTE_FEATURES` carve-out in the compiler is also removed — feature routes always mount at `/api/v1/<feature>`, and admin-only behavior is enforced by per-operation `access: { roles: ['ADMIN'] }` at the resource level.\n\n### Two compiler bug fixes\n\n- **Soft-delete index callback parameter bug.** The auto-index injector emitted hardcoded `t.<col>` references regardless of the existing extras callback's parameter name. When a user (or upstream transform) wrote `(table3) => ({ … })`, the appended composite-index entries referenced `t.organizationId, t.deletedAt` — `t` undefined inside the arrow scope, `ReferenceError` at module load. Fixed in `apps/compiler/src/utils/auto-indexes.ts` by capturing and reusing the callback's parameter name.\n- **Reserved-word action filename collision.** Action discovery walks `actions/*.ts` and emits `import <name> from './actions/<name>'`. A user filename of `import.ts`, `delete.ts`, `await.ts`, `export.ts`, etc. produced `import import from './actions/import';` — a SyntaxError on module load. Fixed in `apps/compiler/src/codegen/discovered-actions.ts` by aliasing reserved-word and invalid-identifier filenames to `__action_<sanitized>` bindings while preserving the public action key (route emitters use bracket notation, so reserved-word keys are fine in the lookup map).\n\n## v0.29.0 — May 19, 2026\n\n### Opt-in `id` auto-injection (`compiler.injectId: 'auto'`)\n\nQuickback's generated CRUD routes, FK extractor, relationship resolver, and `/:id` mount points all assume every feature table has an `id` primary key column. Authoring a table without one — common when porting an existing schema, or when a domain genuinely uses a compound or non-`id` PK — produced silent failures: routes that 404, batch operations that targeted the wrong rows, FK lookups that returned empty.\n\nv0.29 adds an opt-in flag that auto-injects an `id` column into every feature table that doesn't already declare one. Same mechanism as the existing `createdAt`/`modifiedAt` injection — early-pass, idempotent, dialect-aware.\n\n```ts\n// quickback.config.ts\ncompiler: {\n injectId: 'auto', // off by default; opt in per project\n}\n```\n\nWhen `'auto'`:\n- Tables with no `.primaryKey()` declared get `id: text(\"id\").primaryKey().$defaultFn(() => createId())` (or the matching shape for `dbConfig.generateId` — `serial`, `uuid`, `prefixed`).\n- Tables that already declare an `id` column (in any shape) are no-op — the injector is idempotent.\n- Tables with a `.primaryKey()` on a non-`id` column raise a clear compile error that names the offending column and points at the v0.30 follow-up which will rewrite custom PKs to unique indexes automatically. v0.29 surfaces the conflict; v0.30 fixes it.\n\nDefault stays `false` so existing projects don't get migration churn. Opt in when you want to lean on every-table-has-id semantics across your schema.\n\n### Why this is opt-in (and what v0.30 changes)\n\nThe \"every table has `id`\" assumption is load-bearing across 68+ sites in the compiler — every CRUD emitter, the FK regex (`.references(() => target.id)`), the relationship resolver hydration block, the `/:id` route mounts. v0.29 only injects the column; v0.30 will close the remaining gaps:\n\n- FK extraction migrates from `.id` regex to schema-aware metadata lookup, so tables with non-`id` PKs participate in FK display + relationship resolution.\n- The PK→unique-index rewrite lands — tables with explicit non-`id` PKs auto-keep their uniqueness as a constraint while gaining the auto-injected `id`.\n- The flag flips to default-on; opting out becomes the rare path.\n\nv0.29 ships the foundation so projects can opt in today without waiting for the full structural pass.\n\n## v0.28.0 — May 19, 2026\n\n### INTERNAL pseudo-role: server-only schemas, unforgeable from HTTP\n\nv0.27 had five pseudo-roles — `PUBLIC`, `AUTHENTICATED`, `USER`, `ADMIN`, `SYSADMIN` — and one structural gap: there was no way to mark a schema as \"the server enumerates this; no user-facing route should ever read across tenants.\" Push subscriptions, personal access tokens, OAuth tokens, broadcast job tables — anywhere the server needs full visibility but users should only see their own row. The workaround was `firewall: { exception: true }` plus an out-of-band convention, which left auth on the schema looking incidental.\n\nv0.28 adds **`INTERNAL`** as the sixth pseudo-role. Schemas with `roles: ['INTERNAL']` are reachable only by `AppContext` values where `ctx.internal === true` — a flag the HTTP auth middleware **never** sets. No session, JWT, header, query parameter, or body field populates it. The flag is reserved for compiler-emitted server-internal entry points (queue consumers, cron workers, server-side helpers that bypass HTTP entirely).\n\n```ts\n// features/comms/push-subscriptions.ts\nexport default defineTable(push_subscriptions, {\n firewall: [{ field: 'ownerId', equals: 'ctx.userId' }],\n // User reads their own subscriptions via the standard CRUD route.\n read: { access: { roles: ['USER'] } },\n // Server enumerates ALL subscriptions for a broadcast — INTERNAL only.\n crud: {\n delete: { access: { roles: ['INTERNAL'] } },\n },\n});\n```\n\nThe split-surface pattern is the recommended shape: a user-facing access node uses `USER` / `AUTHENTICATED` / a real role; a server-only access node uses `INTERNAL`. Mixing INTERNAL with a user-facing pseudo-role on the **same** access node is a compile error — it almost always means the developer is confused about which side of the trust boundary they're on. The error names the cohabiting markers explicitly and points at the fix (split into separate access blocks).\n\nThe runtime stamping (queue consumer ctx, cron worker ctx) lands in a follow-up; v0.28 ships the declarative surface so projects can mark schemas accurately today. Until the stamping ships, server-internal code uses `unsafeDb` to enumerate INTERNAL surfaces — the security guarantee is in place because no HTTP-derived context can ever carry `ctx.internal === true`.\n\n### Reserved-name fix: SYSADMIN and INTERNAL added to ALWAYS_RESERVED\n\n`SYSADMIN` was previously omitted from the `ALWAYS_RESERVED` set in `authz-schema.ts`. The runtime validator rejected `roles: ['SYSADMIN']` when `cms.sysadmin: true` wasn't set, but the **shadow-declaration path** — user code writing `authz.roles.SYSADMIN: { roles: [...] }` to silently change the pseudo-role's meaning — wasn't blocked. v0.28 closes that gap by adding both `SYSADMIN` and `INTERNAL` to the unconditionally-reserved set.\n\n### Per-table OWNER_SCOPE_RULES: explicit owner predicates no longer over-scope\n\nWhen a user declared a non-canonical owner predicate on one table — e.g. `firewall: [{ field: 'linkedUserId', equals: 'ctx.userId' }]` — that column got promoted into the **project-global** `OWNER_SCOPE_RULES` list. Any other table in the project that happened to have a `linkedUserId` column (even as a plain FK reference, not for scoping) had the same `WHERE linkedUserId = ctx.userId` injected on every read, update, and delete. Silent over-scoping that surfaced only when a query returned the wrong rows.\n\nv0.28 narrows the global list to the **canonical owner column** — the one matching `authDefaults.owner.column` (default `ownerId`). Explicit predicates on custom-named columns are honored on their declaring table via that table's own `buildFirewallConditions` helper, but stay per-table. Reads on other tables with the same column name are unaffected.\n\n```ts\n// Before v0.28: linkedUserId on `comments` ALSO got the WHERE\n// because `event_organizers` declared an explicit owner predicate.\nexport default defineTable(event_organizers, {\n firewall: [{ field: 'linkedUserId', equals: 'ctx.userId' }],\n});\nexport default defineTable(comments, {\n // comments.linkedUserId is just an FK reference; we don't want it scoped.\n firewall: [{ field: 'eventId', equals: 'ctx.activeOrgId' }],\n});\n```\n\nIn v0.28, `event_organizers` queries get the per-table `linkedUserId = ctx.userId` predicate as before; `comments` queries are no longer mis-scoped.\n\nIf you genuinely want the same column to scope multiple tables (rare), declare the explicit firewall predicate on each table. The implicit \"every table with this column gets scoped\" behavior was the bug — explicit-per-table is the cure.\n\n## v0.27.0 — May 19, 2026\n\n### Narrow `ctx.<exposeAs>` typing for namespace-scoped actions\n\nSince v0.23 the namespace middleware has hydrated `ctx.<exposeAs>` with the loaded resource row before each action runs. The static type of that field stayed `any` — runtime safety was solid, but autocomplete and typo-catching were missed opportunities.\n\nv0.27 ships the second half: one **per-namespace `defineAction` helper** emitted alongside the standard one. Importing from the narrowed helper retypes `ctx.<exposeAs>` inside `execute({ ctx })` to the loaded row's `$inferSelect` shape. Nothing about discovery, routing, or runtime behavior changes — this is purely TypeScript ergonomics.\n\n```ts title=\"features/feeds/actions/feed-moments.ts\"\n// Before — ctx.event is `any`\n\n// After — ctx.event is `typeof events.$inferSelect`\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, autocomplete works\n ctx.event.startsAt // ✓ Date\n ctx.event.idd // ✗ TS2339 — typo caught at compile time\n },\n});\n```\n\n#### Where the file lives\n\nThe compiler emits one narrowed 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` → `define-action.event-scope.ts`), sibling to the standard `define-action.ts`:\n\n```text\nsrc/features/feeds/.quickback/\n├── define-action.ts # generic — standard fallback\n└── define-action.event-scope.ts # ctx.event narrowed\n```\n\nA feature contributing to multiple namespaces gets one helper per namespace. Each action picks the import that matches its path.\n\n#### Opt-in, no breaking change\n\nActions that keep their existing `import { defineAction } from '../.quickback/define-action'` continue to compile unchanged. The `AppContext` index signature still admits `ctx.event` at type `any`; runtime hydration is unaffected. 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 logs a one-line `[quickback:typing]` 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 family as `[quickback:authz]`.\n\n#### Side fix\n\nRepaired a latent off-by-one in the inlined `AppContext` import path that landed in the v0.26 helper prelude but hadn't been exercised against a recompiled project yet (`\"../../lib/types\"` → `\"../../../lib/types\"`). New compiles produce a helper whose `AppContext` import actually resolves.\n\n#### Out of scope\n\nNon-namespace standalone actions with relationship-based access keep their existing `(ctx.event as typeof events.$inferSelect)` body cast. Same per-relationship helper pattern would apply if the demand surfaces — defer until requested.\n\n## v0.26.0 — May 19, 2026\n\n### Bulk-grant namespace lanes: org admins and team members in one line\n\nv0.25 widened `via:` to accept an array of relationship lanes — attendeeOf OR organizerOf, first match wins. That covers per-row authorization paths. v0.26 adds the missing piece: **bulk-grant lanes** for the \"you work here, so you see everything in your scope\" case. Org admins, team members, and other tenant-scoped staff no longer need a per-event relationship row to be authorized for a namespace.\n\n```ts\nauthz: {\n namespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: [\n 'attendeeOf', // per-event relationship\n 'organizerOf', // per-event relationship\n { roles: ['admin', 'owner'] }, // org-role bulk grant\n { team: true }, // active-team-membership bulk grant\n ],\n },\n },\n}\n```\n\nLanes resolve in declaration order, first match wins. Per-row relationships and bulk-grant guards compose freely.\n\n#### What each bulk-grant lane does\n\n- **`{ roles: [...] }`** — passes when the caller's BA org-role for the namespace's loaded resource includes any listed role. The check is in-memory and short-circuits the relationship loop entirely. The loads-table firewall (scoped by `ctx.activeOrgId`) does the tenant isolation; this lane just adds the role precondition on top.\n- **`{ team: true }`** — passes when `ctx.activeTeamId` is set. The loads-table firewall (which scopes by team for team-scoped tables) does the actual `events.teamId === ctx.activeTeamId` match during hydration. If the firewall returns no row, the request gets a contextual 404 explaining the row isn't visible to the current session — same ambiguous-by-design phrasing the firewall has always used to prevent cross-tenant ID probing.\n\n#### Why this matters\n\nUntil v0.26, the only way to authorize an org admin for a namespace was to write `access.or: [{ via: 'attendeeOf' }, { roles: ['admin', 'owner'] }]` on every individual action under it. That OR-arm shim worked but defeated the purpose of namespaces — the whole point of hoisting the gate was to write the auth rule once. Now you do.\n\n#### Rich deny payloads\n\nThe 403 response when every lane misses lists every path the caller could have taken — relationship names, role names, and `\"team-membership\"` for `{ team: true }` lanes — in the `required` field. A developer hitting an unexpected 403 sees the full set of authorization options they need to satisfy, not a generic \"Insufficient permissions\" wall.\n\nThe 404 from hydration (when the loads-table firewall filters the request out) now includes a hint explaining that the row may exist out of scope, and a `details` field with the resource name and key, so a developer working in their own environment has enough to debug.\n\n#### Compile-time guards\n\n- **Pure bulk-grant namespaces** (no relationship lane at all) are accepted as long as `loads:` + `exposeAs:` are declared directly on the namespace. With at least one relationship lane present, those fields are inherited from the relationship — declare them on the namespace itself only when no relationship lane is available to anchor hydration.\n- **Heterogeneous `loads:` between relationship lanes is rejected** — `ctx.<exposeAs>` must always hydrate the same table regardless of which lane matched.\n- **`namespace.loads` that disagrees with the inherited value is rejected** with a clear \"drop one or align the other\" message.\n\n## v0.25.0 — May 19, 2026\n\n### Multi-lane namespace gates: more than one way to be authorized\n\nv0.24 lets you hoist a namespace gate to the project level via `authz.namespaces.<name>.via: 'attendeeOf'` — one relationship-resolver middleware running once per request for every action under `/event/:eventId/*`. That works when there's exactly one way to be authorized for the resource. It breaks the moment you have **two**: an attendee row and a per-event organizer row, say. The shim today is to OR the second check inside every individual action's `access` block, which puts you back to writing the gate over and over.\n\nv0.25 widens `via:` to accept an array of relationship lanes. The middleware tries each in declaration order, and the first one whose subject row matches authorizes the request and hydrates `ctx.<exposeAs>`.\n\n```ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'linkedUserId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events',\n exposeAs: 'event',\n },\n // Per-event named organizers. The subject can be a user OUTSIDE\n // the event's organization — e.g. a freelance event manager.\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'], // first match wins\n },\n },\n}\n```\n\nThe thing this actually unlocks isn't \"two checks instead of one.\" It's **per-event grants for users outside the owning organization** — external co-organizers, freelance event managers, partner staff. They don't need a `member` row in the event's org; they just need a row in `event_organizers` for that specific event. The horizontal axis (org / team membership) stays for \"staff at this company\"; the new vertical axis (per-event relationships) handles \"specifically connected to this event,\" regardless of payroll.\n\n#### Backward compatible\n\nThe string form keeps working — `via: 'attendeeOf'` is sugar for `via: ['attendeeOf']`. No existing namespaces break; opt into multi-lane by switching to the array form when you actually need it.\n\n#### Compile-time guards\n\nThe validator rejects three things at parse time:\n\n- **Undeclared lane names** — every entry in the array must resolve to an `authz.relationships[*]` declaration.\n- **Lanes that disagree on `loads:` or `exposeAs:`** — if attendeeOf loads `events` as `ctx.event` and organizerOf loads `agendaItems` as `ctx.agendaItem`, downstream handlers can't predict what's in `ctx.<exposeAs>`. Lanes in one namespace must hydrate the same shape.\n- **Empty arrays** — at least one lane is required (otherwise the namespace gate is meaningless).\n\n#### Follow-up: v0.26 bulk-grant lanes (shipped same day — see above)\n\nThe full 4-lane shape adds heterogeneous `via:` arrays accepting `{ roles: ['admin', 'owner'] }` and `{ team: true }` entries, so org admins and team members get the gate without writing relationship rows. v0.25 was the foundation; [v0.26](#v0260--may-19-2026) lifted the existing per-action `access.or: [..., { roles: [...] }]` shim into the namespace and landed same-day.\n\n## v0.24.0 — May 19, 2026\n\n### Cross-feature namespaces: one hoisted gate, many features\n\nv0.23 shipped `defineTable({ namespace: { prefix, via } })` — a hoisted relationship-resolver middleware that gates every standalone action in *one feature's* Hono app. That covers the 95% case where a domain concept (events) and the actions under it all live in the same feature directory.\n\nv0.24 lifts the namespace to the project level so it can span multiple features. A new `authz.namespaces` block on `quickback.config.ts` declares a path-prefix gate that any feature's standalone action can participate in by matching the prefix in its `path:`. One synthetic routes file, one resolver mount, one relationship match per request — regardless of how many feature directories contribute actions.\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 loads: 'events',\n exposeAs: 'event',\n },\n },\n namespaces: {\n eventScope: { prefix: '/event/:eventId', via: 'attendeeOf' },\n },\n}\n\n// features/feeds/actions/feed-moments.ts (cross-feature)\nexport default defineAction({\n path: '/event/:eventId/feed-moments',\n method: 'POST',\n // No gate boilerplate. ctx.event is typed.\n});\n\n// features/rsvp/actions/respond.ts (different feature, same namespace)\nexport default defineAction({\n path: '/event/:eventId/respond',\n method: 'POST',\n});\n```\n\nThe compiler emits one `src/routes/__namespace-event-scope.routes.ts` mounted at `/api/v1/event/:eventId/*`. The file imports each contributing feature's `actions` map under a distinct alias (`feedsActions`, `rsvpActions`), runs the `attendeeOf` resolver once per request at the head of the file, and dispatches to the matching action handler.\n\n#### Discovery is path-prefix-only\n\nNo new `namespace: 'eventScope'` field on `defineAction`. Actions opt in by matching `path:` against a declared namespace prefix — same model the table-level v0.23 form uses, just lifted to the project level. This means actions move in/out of the namespace based on their path strings, which is the simplest discovery story and matches today's convention (filenames and paths are already the discoverable surface).\n\n#### Source-feature stays the action's home for metadata\n\nOpenAPI tags, MCP tool grouping, and CMS form discovery continue to bucket each action under its source feature. Only the *runtime routes file* moves to the synthetic location — the feed-moments action is still tagged \"feeds\" in OpenAPI, the response shape doesn't change, and your generated SDK reads identically. The URL conveys the namespace membership without forcing every layer of the compiler to re-anchor the action.\n\n#### Worker-root mount order\n\nSynthetic namespace routes files register at priority `20` — ahead of per-feature mounts (priority `0`/`10`). `sortRoutesBySpecificity` keeps the order stable, and the namespace prefix's path parameter makes it sort more specific than `/api/v1/<feature>` anyway, so the middleware fires first for every request under its prefix.\n\n#### Compile-time guardrails\n\nThe same v0.23 invariants apply at the project level, with two additions:\n\n- **`via:` must point at a declared `authz.relationships[*]` entry**, and that relationship must declare `loads + exposeAs` — without `loads` there's nothing for the middleware to hydrate, and a namespace that only gates without hydrating is indistinguishable from a per-action access rule.\n- **`prefix:` must contain at least one `:param` segment** — middleware runs before input parsing, so the relationship key comes from `c.req.param()`.\n- **Same-name conflict** between `defineTable({ namespace })` and `authz.namespaces.<sameName>` is rejected. Pick one declaration site.\n- **Ambiguous prefixes** like `/a/:x` and `/a/:y` (same shape, different `:param` names) error at compile time. Strict super/sub-set relationships (e.g. `/event/:e` and `/event/:e/admin`) are fine — the harvester routes each action to the longest matching prefix.\n- **Unused namespace warning** emits `[quickback:authz]` when no standalone action's path matches a declared prefix. Not a hard error — the namespace may be staged ahead of the actions.\n\n#### Picking the right declaration site\n\nThe table-level v0.23 form is now the **single-feature shorthand**. The project-level v0.24 form is **canonical for cross-feature**.\n\n- **Use `defineTable({ namespace })`** when every action under the prefix lives in the same feature directory. The namespace travels with the table that owns it; nothing to add to `quickback.config.ts`.\n- **Use `authz.namespaces`** when the namespace spans features. The declaration sits next to your `authz.relationships` and `authz.roles` — the canonical home for cross-cutting authz config.\n\nThe two forms can't coexist for the same namespace name. If a v0.23 table-level namespace is starting to attract cross-feature actions, lift it to `authz.namespaces` — same shape, just at the project level, and the matching paths in other features will join automatically.\n\n#### Migration\n\nZero breaking changes. Nothing in v0.23 needs to change for v0.24 to land. The new field is opt-in; existing projects pick it up the moment they declare an `authz.namespaces` entry.\n\nThe harvester runs after Zod schema validation but before route generation, so unused or misconfigured namespaces surface immediately as errors or warnings rather than as silently-broken routes.\n\n#### Fixes shipped alongside\n\nThe first two were load-bearing for v0.23 namespaces to actually work — projects upgrading from a pre-fix v0.23 will see crashes/compile errors disappear on the v0.24 recompile.\n\n- **No more dual emission of namespace-claimed standalone routes.** Pre-fix, an action with a cross-feature path like `/event/:eventId/agenda/list-my-agenda` emitted into both `src/index.ts` (without the namespace resolver) and the synthetic file (with it). The plain root copy in `src/index.ts` won every URL match and `ctx.<exposeAs>` was never hydrated — every request 500'd with `Cannot read properties of undefined (reading 'id')`. `extractStandaloneActions` now skips namespace-claimed actions; the synthetic namespace file is the sole emission.\n- **Stripped-path validator no longer rejects namespace-claimed actions.** The synthetic file mounts at `/api/v1${namespace.prefix}` and strips the prefix from each action's local path. The per-action relationship-resolver was validating the *stripped* path for `:eventId`, finding nothing, and rejecting every namespace-mounted action with \"action's surface exposes neither a path parameter ':eventId' nor an input field 'eventId'\". `planRelationshipResolver` now receives the namespace's `via` and skips its surface-key check entirely — the hoisted middleware is the single source of truth.\n- **Broadcaster DO migration tag consistent across `realtime.mode`.** Inline-mode emission was already going through `qb-do-${className}` + `new_sqlite_classes`. Separate-mode was still hardcoded `tag = \"v1\"` + `new_classes`, so flipping `realtime: { mode }` produced different migration tags for the same DO class and tripped CF error 10074 (\"class already depended on\") on cross-mode deploys. Both modes now emit `tag = \"qb-do-Broadcaster\"` + `new_sqlite_classes`.\n- **Batch handler id arrays type-derive from the input parser.** Pre-fix, `validIds`, `recordMap`, and `validEntries` in bulk-delete / bulk-update / bulk-upsert were hardcoded `string[]` / `Map<string, any>` even when the table's PK column was `integer(\"id\")` — 274× TS2769 in projects mixing string and integer PKs. Handlers now declare `type IdT = typeof ids[number]` (or `typeof records[number]['id']`) and use it for the local id types. Strings stay strings, integers stay integers, no emitter knowledge of the PK column type required.\n- **`ctx` in action handlers is now `AppContext`, not `any`.** Both `StandaloneExecuteParams.ctx` and `RecordExecuteParams.ctx` in the generated `<feature>/.quickback/define-action.ts` are typed `AppContext`. AppContext keeps its `[key: string]: any` index signature so hydrated namespace keys (`ctx.event`, `ctx.<exposeAs>`) stay accessible without TS2339; named fields (`userId`, `activeOrgId`, `roles`, `authenticated`, `user`) get autocomplete and type-checking. Cleared ~49× TS2339 in generated projects.\n- **`c.get('ctx') as AppContext` in every emitted route handler.** Pre-fix, `const ctx = c.get('ctx')` returned `any`, so `ctx.roles?.some(r => …)` left the callback parameter implicitly `any` — 16× TS7006. Now `ctx.roles` is `string[] | undefined`, `r` is `string`, no callback annotation needed.\n\n#### Deferred (tracked, not blocking)\n\n- Per-namespace narrow typing of `ctx.<exposeAs>` (so `ctx.event` resolves to `typeof events.$inferSelect` instead of `any`). The compiler emits a typed cast at the `execute()` call site in the routes file today, which type-checks the call but not the handler body. Full narrow typing requires per-namespace helper emission (one `define-action.<namespace>.ts` per namespace, or a generic param threading through the action config). Tracked separately.\n\n---\n\n## v0.23.0 — May 19, 2026\n\n### Authz relationships: compile-time guarantees, less boilerplate, hoisted middleware\n\nThis release closes the gap between what `authz.relationships` *promised* in v0.19 and what it actually enforced. Every documented invariant is now a real compile-time check; every per-action ergonomic friction has a fix. Net effect: relationship-based authorization feels native — declare the relationship once, use the role anywhere, the compiler does the wiring.\n\n#### Compile-time guarantees (the authz `firewall` parity)\n\nThe org/owner/team firewall has always been compile-time-checked: a routed resource without a scope fails the compile, full stop. As of this release, `authz.relationships` carries the same guarantees:\n\n- **Bad `via:` names fail at parse time.** A typo in a firewall predicate (`firewall: [{ field: 'eventId', via: 'guestOff' }]`) used to surface deep inside the firewall generator after most validation had passed. It's now caught alongside the `authz.roles` `via:` validation, same layer, same error format.\n- **Relationship-from tables can't opt out.** The doc at `define/types/authz.ts:73-74` always said a relationship `from:` table with `firewall: { exception: true }` \"refuses to compile\" — that's now enforced. Without this check, every `via:` subquery that pivots through an exception-marked table loses tenant isolation and can return rows from other tenants.\n- **`allowResourceMigration` is now mandatory** when the relationship's `resource.column` is on a writable update endpoint. A guest doing `PATCH /messages/:id { eventId: <other-event-id> }` to migrate a row out of their access scope used to slip past the runtime — it now fails compile with a three-option remediation (set the flag, mark the column immutable, or drop it from the guards.updatable allowlist).\n- **`via: string[]` in firewall predicates.** \"Member of attendees OR speakers\" no longer requires inventing a composite role just to use it once in a firewall — `firewall: [{ field: 'eventId', via: ['attendeeOf', 'speakerOf'] }]` lowers to an OR-combined subquery.\n\n#### Less boilerplate: auto-derivation + realtime resolver\n\n- **`resource.column` auto-derives from FKs.** Omit it and the compiler scans the relationship's `from:` table for foreign-key columns, drops the `subject.column`, and picks the remaining FK. One match → auto; zero or many → error with the candidate list. Pattern mirrors the existing firewall auto-detection.\n- **`realtime.requiredRoles` accepts authz roles.** Previously a relationship-role in `realtime.requiredRoles` fell through with a misleading \"unknown role\" error. The compiler now flattens declared authz roles into their composing Better Auth roles before the realtime ticket-handshake sees them. Relationship-only roles (no static BA fallback) emit a `[quickback:authz]` warning and fail-close at handshake — the row-stream firewall continues to enforce the relationship dimension on the data side.\n\n#### Record-based actions can finally use relationship-roles\n\nThe v0.19 fail-closed hardening had an unintended side effect: a record-based action with `access: { roles: ['attendee'] }` (where `attendee` was a relationship-role) 403'd every caller, including the legitimate ones. The runtime helper couldn't evaluate `relationship:` arms, so it fail-closed correctly — but the inline match expression that *would* evaluate the relationship was never wired up for record-based actions.\n\nThis release routes record-based actions with relationship arms through the same inline access generator the resource CRUD path already uses. `roles: ['attendee']` on `/applications/:id/recap` now actually checks whether the caller is an attendee, with the loaded record in scope. Non-relationship access trees keep the runtime path unchanged.\n\n#### Typed `ctx.<exposeAs>` in action handlers\n\nWhen a relationship declares `loads: 'events', exposeAs: 'event'`, the runtime hydrates `ctx.event` with the loaded row — but the static type was always `any`, so handlers had to write `const event = ctx.event as typeof events.$inferSelect`. As of this release, when an action's access references **exactly one** relationship with `loads + exposeAs`, the compiler emits the cast for you at the execute() call site. Handlers read `ctx.event` with the right shape; no per-handler boilerplate.\n\nMulti-arm OR actions (referencing two relationships with hydration) keep the `any` shape — we can't statically know which arm matched.\n\n#### New: `defineNamespace` — one mount, one resolver, many actions\n\nThe marquee Wave 3 change. Today's pattern for \"five standalone actions under `/event/:eventId/*` all gated by `attendeeOf`\" requires writing the same inline relationship resolver in each action — and pays the resolver cost (one subquery, one row-load) on every request, multiplied by N actions. The new `namespace` field on `defineTable` hoists the resolver into a single Hono middleware mount:\n\n```ts\n// features/events/events.ts\nexport default defineTable(events, {\n firewall: [...],\n crud: { ... },\n namespace: {\n prefix: '/event/:eventId', // absolute URL path the mount covers\n via: 'attendeeOf', // relationship gate\n },\n});\n\n// features/events/actions/post-announcement.ts\nexport default defineAction({\n path: '/event/:eventId/announcements',\n method: 'POST',\n // No relationship-gate boilerplate. ctx.event is typed\n // `typeof events.$inferSelect` inside execute().\n});\n```\n\nThe compiler:\n1. Emits one `app.use('/:eventId/*', async (c, next) => { /* relationship resolver */; await next(); })` at the head of the feature's standalone-routes file (path-prefix stripping handles the feature mount).\n2. Skips the inline relationship resolver in every per-action handler under the prefix — the middleware already ran it.\n3. Hydrates `ctx.event` once per request and threads the typed cast into every namespace action's execute() call.\n\n**Validation guardrails:**\n- `namespace.via` must point at a declared `authz.relationships[*]` entry.\n- The referenced relationship must declare `loads + exposeAs` — without `loads` there's nothing for the middleware to hydrate, and the namespace gate would be indistinguishable from a per-action access rule.\n- `namespace.prefix` must contain at least one `:param` segment — the middleware reads the relationship key from `c.req.param()`, not from request body (body parsing hasn't run at middleware time).\n\n**Scope (v1):**\n- Namespace lives within a single feature's Hono `app`; cross-feature shared namespaces are deferred to v2.\n- One namespace per `defineTable` declaration; multiple namespaces in a feature mount as siblings.\n- For namespace actions whose access references additional relationships beyond the namespace's via, the inline resolver still fires for those — namespace handles only its own.\n\n#### Migration\n\nNothing in v0.20 → v0.23 breaks existing code that compiles cleanly. The new errors fire only against patterns that were already latent bugs:\n\n- A `via:` typo that previously surfaced as a deep codegen error now surfaces at parse time, same message.\n- A `firewall: { exception: true }` on a relationship-from table now errors; this configuration was always documented as unsupported.\n- A relationship's `resource.column` writable on the resource's UPDATE endpoint now errors unless `allowResourceMigration: true` is set; previously this was a runtime escape hatch.\n- Record-based actions with `roles: ['<relationship-role>']` previously 403'd every caller; they now work as the v0.19 docs originally promised.\n\n#### Why this matters\n\nAuthz relationships are how Quickback expresses \"the caller is allowed to touch this resource because of a row in *that* table\" — guest-of-event, member-of-organization, scorer-of-interview. Until now, the feature worked but had sharp edges: typos surfaced late, the documented exception-not-allowed constraint wasn't enforced, and the namespace pattern (which most apps with nested resources end up wanting) required repeating the same gate in every action. This release brings authz to parity with the org/owner/team firewall: declare it once, the compiler enforces it everywhere, the runtime emits exactly one query per request.\n\n---\n\n## v0.22.0 — May 19, 2026\n\n### Quickback Stack is Cloudflare-only: one runtime, two databases, one auth provider\n\nWe've focused the platform on the stack we actually believe in: **Cloudflare Workers + Hono + Better Auth**, with **Cloudflare D1** or **Neon** as the database. Providers and modes that targeted non-Cloudflare backends are gone. The result is a smaller concept set, fewer footguns, and clearer docs.\n\n#### What's been removed\n\n- **Runtimes**: `bun` and `supabase-edge` are no longer supported. The only runtime is `cloudflare`. Local development for compiled projects has always used `wrangler dev` — that's unchanged.\n- **Databases**: `supabase`, `libsql`, `better-sqlite3`, `bun-sqlite` are removed. Use `cloudflare-d1` for SQLite at the edge or `neon` for PostgreSQL via Hyperdrive.\n- **Auth providers**: `supabase-auth` is removed. `better-auth` is the default; `external` (Cloudflare service binding) remains for advanced setups.\n- **Template**: `template: 'nextjs'` is removed from the public config type. It was never fully implemented. The only template is `'hono'`. If you need a Next.js frontend, bring it as a separate deploy and call the Quickback API, or drop a static export into the `apps:` mount.\n- **Quickback for Supabase RLS** product line is retired. The compiler no longer emits Supabase Row Level Security policies. The `/products/quickback-supabase-rls/` and `/for/supabase-users/` pages have been removed from the marketing site, and the `compiler/targets/supabase-rls/` docs section has been deleted.\n\n#### Account UI: one delivery mode\n\nThe standalone `quickback-better-auth-account-ui` npm package has been **deprecated** and the upstream GitHub repo (`Kardoe-com/quickback-better-auth-account-ui`) has been **archived**. Account UI is now exclusively delivered the way 99% of projects already use it: the compiler builds it from source and bundles it into your Worker.\n\n- `account: { domain: 'auth.example.com', ... }` in `quickback.config.ts` — that's the entire integration story.\n- The compiler builds the SPA inside Docker with your branding and feature flags baked in, emits hostname-based routing, and wires cross-subdomain cookies automatically.\n- The three standalone delivery-mode docs (`stack/account-ui/standalone`, `library-usage`, `worker`) are removed; the remaining pages explain the compiler-bundled flow.\n\nIf you previously deployed the standalone Account UI Worker against a Quickback backend, switch to `account: { domain }` in the config — same end result, one less deploy.\n\n#### `VITE_AUTH_ROUTE` hardcoded to Quickback\n\nThe `VITE_AUTH_ROUTE` env var (which used to switch between `quickback` and `better-auth` routing dialects) is gone. The auth-client always uses Quickback's namespaced routes (`/auth/v1`, `/api/v1`, `/storage/v1`). Generic Better Auth backends are no longer a supported target. Removing the var also closes a known footgun where setting the wrong value silently 404'd every auth call.\n\n#### New: every config option is now discoverable\n\nWhen you bootstrap a project, the kitchen-sink marker block in `quickback.config.ts` lists every option Quickback supports — with descriptions and sensible defaults — commented out for you to copy above the marker as needed. Three top-level options were missing from this discovery surface and are now included:\n\n- **`apps`** — mount your own prebuilt SPA on its own hostname (`apps: { www: { domain: 'www.example.com', aliasDomains: ['example.com'] } }`). Drop the build at `quickback/apps/<name>/` and the compiler serves it from your Worker alongside the API. Reserved names: `cms`, `account`, `public`.\n- **`security`** — HTTP security headers (CSP, COOP, COEP, HSTS, Referrer-Policy, Permissions-Policy, X-Frame-Options). Set `security: false` to suppress everything; defaults are sensible for the embedded SPAs.\n- **`authz`** — relationship-based authorization roles. Declare joins between the caller and a resource column, then bind role names to those joins for use in `access: { roles: [...] }`.\n\n#### Migration\n\nProjects that compile cleanly against v0.21 and use any of these providers will hit a clear error at compile time:\n\n```\nUnknown database provider: \"supabase\". Available: cloudflare-d1, neon\n```\n\nTo migrate:\n\n1. **From Supabase**: switch `providers.database` to `cloudflare-d1` or `neon`, and `providers.auth` to `better-auth`. Your `defineTable()` definitions transfer as-is; the security DSL (firewall, access, guards, masking) compiles to Better Auth + Drizzle queries instead of RLS policies.\n2. **From Bun runtime / `bun-sqlite`**: switch `providers.runtime` to `cloudflare` and `providers.database` to `cloudflare-d1`. Local dev becomes `wrangler dev`.\n3. **From libsql / Turso**: switch to `cloudflare-d1` or `neon`. Both run natively from Cloudflare Workers via the right binding.\n4. **From `template: 'nextjs'`**: deploy Next.js separately and call the Quickback API, or drop a static export into `apps:`.\n\n#### Why this matters\n\nThe Quickback Stack is the Supabase alternative for Cloudflare. Every Quickback project ships a Hono API, an Account SPA, a CMS SPA, optional realtime/storage/queues — all built from one config and bundled into one Worker. Keeping that promise focused is more valuable than supporting deployment targets that don't share the runtime.\n\n---\n\n## v0.21.0 — May 19, 2026\n\n### Auto-firewall column swap: `ownerId` is now canonical on feature tables, `userId` warns\n\nThe compiler's default auto-firewall column for feature tables flips from `userId` to `ownerId`. This closes a long-standing footgun where a `userId` column meaning \"a user this row references\" (a member, a contact, an invitee) got silently clobbered with `ctx.userId` on insert, because the wrapper matched purely on column name across every table in the project.\n\n**What changed in the compiler**\n\n- `BETTER_AUTH_DEFAULTS.owner.column`: `'userId'` → `'ownerId'`. Schemas with an `ownerId` column auto-resolve to `firewall: [{ field: 'ownerId', equals: 'ctx.userId' }]` and have `ownerId` auto-stamped on insert.\n- The generated `OWNER_SCOPE_RULES` in `src/lib/scoped-db.ts` is seeded with `ownerId` instead of `userId`. Schemas that don't explicitly name `userId` in a `firewall:` block no longer trigger the global `userId`-stamping rule — the most common collision goes away without renames.\n- A new compile-time warning fires when a feature table carries both an auto-resolved isolation column AND a `userId` column. The warning recommends renaming the column to `linkedUserId` (or similar) if it's informational, or declaring `firewall: [{ field: 'userId', equals: 'ctx.userId' }]` if it really is the access boundary on that table.\n- The targeted compile-time error for \"the only candidate column is `userId`\" now points users at `ownerId` and the explicit-firewall escape hatch. The previous error wording (which assumed `ownerId` was business-logic) is removed.\n\n**What stayed the same**\n\n- Better Auth's own internal tables (`session`, `account`, `member`, `passkey`, `subscriptions`) still use `userId` by convention. They aren't feature tables and don't pass through the auto-firewall.\n- Explicit `firewall: [{ field: 'userId', equals: 'ctx.userId' }]` declarations continue to work and are still recognized as the \"owner\" pattern in the generated comment header.\n- The `USER` pseudo-role validator behaviour is unchanged; only the error-message wording flips to lead with `ownerId` and list `userId` as the explicit fallback.\n- Audit-wrapper (`createdBy` / `modifiedBy`) behavior is untouched.\n\n**Migration**\n\nProjects that auto-firewalled on a `userId` column will see a hard error on next compile telling them which table is affected, with two suggested fixes:\n\n1. **Recommended**: rename the column to `ownerId` in the schema. Cleanest semantics — readers immediately understand the column is access-control.\n2. **Explicit firewall**: keep the `userId` column and add `firewall: [{ field: 'userId', equals: 'ctx.userId' }]` to the resource. The auto-stamping and auto-scoping still happen; you've just opted in by name.\n\nProjects that have a `userId` column meaning \"a user this row references\" no longer need the `linkedUserId` rename workaround — auto-stamping won't touch the column unless you name it in a firewall block. The new warning makes this audit-discoverable.\n\n**Caveat (deferred)**: explicit `firewall: { owner: { column: 'X' } }` declarations still populate the project-global `OWNER_SCOPE_RULES` list, so a hand-named owner column on one resource will still match by name on every other table that happens to have a column called `X`. A future release will make scope-rule resolution per-table rather than project-global. The warning text calls this out so callers know what to expect.\n\n---\n\n## v0.20.0 — May 19, 2026\n\n### CMS + Account SPAs: shadcn base-ui migration, central Tailwind config\n\nBoth first-party SPAs are now on the shadcn **base-ui** variants (`@base-ui/react`) instead of the Radix-based primitives, applied via shadcn preset **`bdvxIkMq`** (style `base-mira`, `baseColor: zinc`, `iconLibrary: remixicon`, Inter Variable font). The migration also collapses the previously duplicated per-SPA theme + `components.json` into a single source at `packages/ui/`.\n\n#### Single source of truth in `packages/ui/`\n\nBoth SPAs were independently declaring the same `@theme` / `:root` / `.dark` token blocks in their own `app.css`, and each had its own `components.json` pointing at non-existent local component directories. That's gone:\n\n- `packages/ui/styles/theme.css` — the only place tokens live. Includes the base-mira palette, sidebar + chart tokens, and the Inter font import.\n- `packages/ui/components.json` — the only shadcn config in the repo. Future `pnpm dlx shadcn@latest add <name>` runs from `packages/ui/`.\n- `packages/cms/app/app.css` and `packages/account/app/app.css` reduce to two imports plus SPA-specific layers (CMS keeps its AG Grid + richtext-display overrides). `packages/{cms,account}/components.json` deleted.\n\n#### Components, icons, deps\n\n- All 22 shadcn primitives regenerated against `@base-ui/react` (`@radix-ui/*` removed everywhere). `Drawer` stays on `vaul` — base-ui has no Drawer primitive.\n- Icons migrated from `lucide-react` to `@remixicon/react` line variants across ~100 source files (`Plus → RiAddLine`, `ChevronDown → RiArrowDownSLine`, `X → RiCloseLine`, etc.). `lucide-react` removed from all `package.json` + `deps-spa-*` files.\n- `pnpm.overrides` pin `@types/react ^19.2.0` workspace-wide to resolve the duplicate-React-types conflict introduced by `@base-ui/react`'s bundled type peer.\n- Per-SPA deps and the Docker build mirrors (`apps/compiler/deps-spa-{cms,account}-package.json`) both gain `@base-ui/react`, `@remixicon/react`, `@fontsource-variable/inter`, and bump `shadcn` to `^4.7.0`.\n\n#### Backwards-compat `asChild` shim\n\nBase-ui replaces Radix's `asChild` boolean with a `render={\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.38.0 — May 26, 2026\n\n**Per-matched-lane authorization** for multi-lane namespaces — across both the\nREST scope refresh/mint and the realtime ws-ticket. A namespace gated by several\n`via:` lanes (attendees *or* organizers *or* contractors *or* org admins) now\nconfers the scope role of **whichever lane the caller actually matched**, instead\nof suppressing the grant. This retires the v0.37.0 single-conferring-lane\nlimitation.\n\n### Scope refresh & `mintScope` — per matched lane\n\nA **multi-lane `via:`** now refreshes and mints the matched lane's role:\n`attendeeOf` → `scope.event.roles = ['attendee']`, `organizerOf` → `['organizer']`.\nThe resolver records which lane opened the gate (first-match-wins), so a caller\ncan only ever carry the role they proved this request. A **bulk-grant lane**\n(`{ roles: [...] }` / `{ team: true }`) still confers **no** scope role — it\nauthorizes via the caller's org role, with nothing to stamp. Previously any\nmulti-lane / bulk / mixed `via:` suppressed the stamp and mint entirely; that\nrestriction is lifted. See [Scopes](/compiler/definitions/scopes#mintscope-mint-the-scope-token-from-the-namespace-resolver).\n\n### Namespace-backed ws-ticket — realtime, per matched lane\n\n`realtime.wsTicket` accepts a **`namespace`** reference, so the\n`/broadcast/v1/ws-ticket` route authorizes through that namespace's full\nmulti-lane `via:` and issues a per-matched-lane WebSocket ticket — the socket\ngate and the REST gate stay identical, from a single source of truth.\n\n```typescript\nrealtime: {\n wsTicket: { namespace: \"eventScope\", requestField: \"eventId\", scopeTable: \"events\" },\n},\n```\n\nAn attendee gets an `attendee` ticket, an organizer an `organizer` ticket, and an\norg admin who reaches the room through the bulk lane now gets a ticket scoped to\ntheir org/membership roles — closing the gap where the single-`role` form `403`'d\na legitimate admin and left their realtime socket dead.\n\n**Tenant-bound, fail-closed.** Before minting, the route loads the `scopeTable`\nrow through *its own firewall*, so a ticket can only target a room whose resource\nresolves under the caller's tenant — an org-A admin requesting an org-B `eventId`\ngets `403`, never a cross-tenant socket. Because the room *is* the data (no\nfirewall sits between a ticket and a Durable Object room), the compiler **rejects\nat build time** a namespace-backed `wsTicket` whose `scopeTable` isn't\ntenant-scoped (`firewall: { exception: true }` or a literal-only firewall with no\norg/owner/team isolation). See\n[Realtime tickets](/stack/realtime/durable-objects#namespace-backed-tickets-per-matched-lane).\n\n## v0.37.0 — May 26, 2026\n\nThe **authz-as-compile-target** roadmap ships. Your authorization model —\nrelationships, named permissions, FK-traversal arrows, scope axes — compiles\ninto one normalized policy IR, lowers to SQL `WHERE` clauses / signed claims /\nguards, and is checked by a static analyzer before a single route is emitted.\nThis release lands milestones M0.1, M0.3, M1, M2, and M4, plus §5.3 namespace\nscope-minting.\n\n### Named permissions (`authz.permissions`) — M1\n\nA `via:` arm references **one** relationship. When the *same* grant rule recurs\nacross resources — \"organizer **or** confirmed attendee\" — name it **once**\nunder `authz.permissions` as a boolean expression and reference it everywhere\nwith a `{ permission }` firewall arm.\n\n```typescript\nauthz: {\n permissions: {\n 'event:view': { anyOf: ['organizerOf', 'attendeeOf'] },\n 'org:admin': { anyOf: [{ role: 'admin' }, { role: 'owner' }] },\n },\n}\n// then on a resource:\n// firewall: [ { field: 'eventId', permission: 'event:view' } ]\n```\n\n`anyOf` lowers to an OR of relationship subqueries, `allOf` to an AND, and a\n`{ permissionRef }` inlines another permission's arms — byte-identical to\nwriting the `via:` arms by hand. The full DSL (`anyOf` / `allOf` / `not`, bare\nstrings, and the object-leaf escape hatch) is accepted so configs stay\nforward-compatible; a firewall enforces the **SQL-pushable** subset (claim-site\nleaves like `{ role }` / `{ scopeRole }` and `not` over a SQL site are rejected\nat compile time — gate those on `access` instead). See\n[Permissions](/compiler/definitions/permissions).\n\n### FK-traversal arrows (`authz.arrows`) — M2\n\nAn **arrow** inherits authority across a foreign key: *\"you can see this row\nbecause you administer the organization it belongs to\"*, or *\"because you\ncontrol an ancestor in the tree.\"* Declare an FK hop, reference it from a\npermission as `{ arrowRef, permission }`, and it lowers to SQL.\n\n```typescript\nauthz: {\n arrows: {\n eventOrg: { from: 'event', fk: 'organizationId', to: 'organization' },\n folderTree: { from: 'folder', fk: 'parentId', to: 'folder', recursive: true },\n },\n permissions: {\n 'event:view': { anyOf: ['organizerOf', { arrowRef: 'eventOrg', permission: 'org:admin' }] },\n 'folder:read': { anyOf: [{ arrowRef: 'folderTree', permission: 'org:admin' }] },\n },\n}\n```\n\nA single hop lowers to an FK-hop subquery; a self-referential hop\n(`folder.parentId -> folder`) lowers to a **bounded `WITH RECURSIVE` CTE**\n(default depth 8, override per-arrow with `maxDepth` or per-permission with\n`permissionMaxDepth`). The seed and **every walked row** are re-constrained to\nthe caller's active-org claim, an absent claim fails closed (`1 = 0`), and the\nidentifiers are compile-time constants while the claim binds as a parameter —\nso an arrow is never an injection surface. An `unbounded: true` arrow with no\nclaim path is a hard compile error. Valid on both D1 and Neon. See\n[Arrows](/compiler/definitions/arrows).\n\n### Compile-time authz analyzer + diagnostics — M4\n\nThe compiler now projects your whole authorization model into a single policy\nIR and runs static checks over it, reporting on the existing\n**`[quickback:authz]`** console channel with stable, greppable codes:\n\n- `AUTHZ_EMPTY_PERMISSION` — a permission that can never be satisfied (e.g. `allOf(a, not(a))`).\n- `AUTHZ_SHADOWED_ARM` — an `anyOf` arm subsumed by a broader sibling.\n- `AUTHZ_UNREACHABLE_ROLE` / `AUTHZ_UNREACHABLE_VIEW` — dead scope config.\n- `AUTHZ_NOT_OVER_RESOURCE` — a `not` over a SQL site (the null-trap).\n- `AUTHZ_PUSHDOWN_COST` — an `info` report of each permission's subquery count and recursive-CTE depth.\n- `AUTHZ_CAPABILITY_CEILING` — **error** — a resource grants a `scope:<kind>:<role>` read beyond its `grants` profile.\n\nChecks are **warn-by-default, compile-continues** (so a new check never breaks\nan existing build on upgrade); set **`QUICKBACK_AUTHZ_STRICT=true`** to promote\nevery warning to a hard error. The analyzer is compile-time only — a defect in\na check downgrades to a single warning in the default path and can never take\ndown an otherwise-valid compile. See\n[Diagnostics](/compiler/definitions/diagnostics).\n\n### Aggregate-only views — M0.1\n\nA view can return a rollup and **nothing else** — no `data[]`, no per-row field\nselection — via `aggregateOnly: true`, with an optional `kMin` k-anonymity floor\nthat suppresses the aggregate below a threshold. This is what lets an F&B vendor\nread dietary **counts** for an event with zero attendee rows. See\n[Views](/compiler/definitions/views).\n\n### Scope leftovers — M0.3\n\nThe relationship-scope surface gains three pieces:\n\n- **Namespace scope-claim refresh** — a namespace gating `/event/:eventId/*` on a single conferring relationship lane refreshes `ctx.scope.<kind>` in memory for the request, so an attendee hitting an action under the prefix gets the scoped role stamped without a separate `/scope/v1/enter` round-trip.\n- **`q.scope()` autofill** — `q.scope('event')` auto-stamps a column from the verified scope claim (`ctx.scope.event.id`) on insert, the same way `q.scope('organization')` stamps the tenant column. Insert-only and null-safe; it adds no read-time `WHERE`.\n- **Set-valued sub-keys** — a `subKeys` entry ending in `[]` (e.g. `'shuttleId[]'`) projects **every** matched relationship row's value into the claim as a `string[]`, and the matching firewall arm is rewritten to an `inArray` row-slice (a driver covering multiple buses). An absent claim lowers to `inArray(col, [])` — a clean deny.\n\nSee [Scopes & capability grants](/compiler/definitions/scopes).\n\n### Namespace scope-minting (`mintScope`) — §5.3\n\nA namespace can now MINT a persisted scope JWT from its resolver. Set\n**`mintScope: true`** and, on a successful relationship probe, the resolver\nreturns a scope token via `set-auth-token` — so a native client hitting\n`/event/:eventId/*` carries the scoped role forward **without** calling\n`/scope/v1/enter`.\n\n```typescript\nauthz: {\n namespaces: {\n eventScope: { prefix: '/event/:eventId', via: ['attendeeOf'], mintScope: true },\n },\n}\n```\n\nThe mint fires **only** when `via:` confers exactly one scope role\nunambiguously (a single conferring relationship lane); a multi-lane,\nbulk-grant, or asymmetric `via:` **suppresses** the mint (fail-closed — those\ncallers use `/scope/v1/enter`). The token reuses the shared mint helper (TTL\nclamped to ≤180s, sibling scope kinds carried forward) and the mint is\n**best-effort** — a mint failure never fails the request, since the in-memory\nstamp already authorized it. Opt-in per namespace; defaults to `false`. See\n[Scopes — `mintScope`](/compiler/definitions/scopes#mintscope-mint-the-scope-token-from-the-namespace-resolver).\n\n> **Gotcha:** a namespace emits its resolver — and thus the refresh and the\n> mint — **only** when at least one *standalone* action's `path:` falls under\n> the prefix. A namespace containing only record-based actions (which mount\n> under their resource's CRUD routes, not the prefix) is **inert**. Add a\n> standalone action like `eventHome` at `/event/:eventId/home`. See\n> [Scopes — the resolver gotcha](/compiler/definitions/scopes#gotcha-a-namespace-only-emits-its-resolver-when-it-claims-a-standalone-action).\n\n## v0.36.3 — May 25, 2026\n\n### Fix: `/auth/v1/*` handler forwards `executionCtx` so OTP emails actually send\n\nThe generated `createAuth(env, cf?, executionCtx?)` schedules the fire-and-forget\nverification-OTP send through `executionCtx.waitUntil(...)` — Better Auth advises\n**not** awaiting the send so its latency doesn't leak into auth response timing.\nThat only works when `executionCtx` is passed. The composed Cloudflare worker\nindex emitted a **bare** `createAuth(c.env)` at the `app.all('/auth/v1/*')`\nhandler, so on Cloudflare the unawaited SES/SNS send was cancelled the moment the\nhandler returned — `send-verification-otp` returned 200 but no email went out.\n\nThe handler now threads `createAuth(c.env, c.req.raw.cf as any, c.executionCtx)`,\nmatching the action call-sites (`record-based`, `standalone`, `core/helpers`) and\nthe `getSession` call now passes the `cf` binding. (The earlier waitUntil fix had\nonly patched the legacy `providers/runtime` index emitter, not this composed one —\nthe two had drifted.) Recompile + redeploy to pick it up.\n\n## v0.36.2 — May 25, 2026\n\nTwo firewall fixes uncovered in a relationship-scoped (event-attendee) project:\nscoped reads stopped hiding rows behind a misclassified soft-delete column, and\nthe list route stopped rejecting org-optional callers before the firewall ran.\n\n### Fix: a firewall `isNull` predicate on a non-`deletedAt` column no longer globalizes as soft-delete\n\nThe scoped `db` wrapper used by actions enforces soft-delete by injecting\n`isNull(<col>)` into reads. It built its list of soft-delete columns by treating\n**any** firewall `{ field, isNull: true }` predicate as a project-wide soft-delete\nmarker — so an `isNull` predicate on a foreign-key column (e.g.\n`{ field: 'agendaItemId', isNull: true }`) was broadcast to **every** table that\nmerely had an `agendaItemId` column, rewriting scoped reads to\n`agenda_item_id IS NULL`. Real rows (non-null FK) became invisible, so an action\nthat read-before-write saw \"no row,\" attempted an insert, and 500'd on the\n`(agenda_item_id, guest_id)` unique constraint.\n\nOnly `deletedAt` — the column the compiler injects into every table — now enters\nthe project-global soft-delete list. A custom `isNull` predicate is still enforced\n**per-table** by that table's firewall (route layer); it is simply no longer\nbroadcast across the whole schema. This mirrors the v0.28 fix that made custom\nowner columns per-table rather than global.\n\n### Fix: list route no longer hard-requires an org when the firewall makes org optional\n\nThe generated CRUD **list** route emits an `ORG_REQUIRED` 400 (with a sysadmin\nescape) before the firewall runs. It fired whenever an org scope appeared\n**anywhere** in the firewall — including when org is just one arm of an `any:`\ngroup. So after the relationship-scope migration made a firewall org-optional\n(`any: [ { organizationId = ctx.activeOrgId }, { …via relationship } ]`), a\nplain-JWT caller with no `activeOrgId` (e.g. an event attendee scoped by\nrelationship) got an instant 400 — the org-optional firewall that would have\nscoped them correctly never even ran.\n\nThe gate now keys off org **mandatoriness** (`firewallRequiresOrg`): it fires\nonly when an org claim is genuinely required — a top-level (implicit-AND) or\n`all`-nested org predicate. When org is one arm of an `any:` group, the list\nroute skips the 400 and lets the null-safe firewall scope the caller: the org\narm drops when `activeOrgId` is absent, sibling arms (relationship/owner) bind,\nand `anyGuarded` denies (`1 = 0`) when every arm drops — so a no-org caller sees\nexactly what the declared policy grants, never an unbounded cross-tenant read.\n`?organizationId=` cross-tenant addressing and the sysadmin escape are unchanged,\nand a plain org-scoped resource (no `any:` group) keeps the `ORG_REQUIRED` gate\nbyte-for-byte. Write paths (create / put / batch) still require an org so new\nrows are always stamped with a tenant.\n\n## v0.36.1 — May 25, 2026\n\nRelationship-derived **scoped roles** — request-scoped authorization minted from\na verified relationship into a short-lived JWT.\n\n### `authz.scopes` — scoped roles via a relationship probe\n\nA new `authz.scopes` block turns a declared relationship into a request-scoped\nrole. Key the scope by a request field and back each role with a relationship:\n\n```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 },\n },\n scopes: {\n event: {\n requestField: 'eventId',\n roles: { attendee: { via: 'attendeeOf' } }, // shorthand: attendee: 'attendeeOf'\n },\n },\n}\n```\n\nThe compiler emits a `/scope/v1/enter` route that probes the relationship for the\ncaller (\"is this user a confirmed guest of `eventId`?\") and, on success, mints a\nshort-lived JWT carrying the verified scope. The auth middleware reads that claim\ninto `ctx.scope.<kind>` (e.g. `ctx.scope.event`).\n\nScoped roles then work everywhere roles do — `read.access`, view access,\n`masking.show`, action access — as `scope:<kind>:<role>`, and the firewall can\nscope rows by the verified id:\n\n```ts\nread: { access: { roles: ['admin', 'member', 'scope:event:attendee'] } },\nmasking: { email: { type: 'email', show: { roles: ['admin', 'scope:event:organizer'] } } },\nfirewall: { any: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', equals: 'ctx.scope.event' },\n] },\n```\n\nSo an attendee who \"enters\" an event reads that event's guest list — the `eventId`\nfirewall arm matches their verified scope — with no org-membership role, and\n`email` stays masked unless they hold `scope:event:organizer`.\n\n### Scoped-role name sugar\n\nWrite the bare role name and the compiler lowers it to canonical\n`scope:<kind>:<role>` when it resolves uniquely:\n\n```ts\naccess: { roles: ['attendee'] } // → scope:event:attendee\n```\n\nReserved names (`admin`, `member`, `owner`), pseudo-roles, and anything declared\nin `authz.roles` are never rewritten. A bare name that's ambiguous across scopes\nis a compile error pointing you to the explicit `scope:<kind>:<role>` form.\n\n## v0.36.0 — May 25, 2026\n\nProject-wide `id` generation now applies to every write path, action `db` is\ntyped on Cloudflare D1, and realtime rooms can be gated on a unique non-PK column.\n\n### `id` default moves to the column (`$defaultFn`)\n\nThe configured `generateId` strategy now lands on the `id` column itself —\n`id: text(\"id\").primaryKey().$defaultFn(() => createId())` — not just inside the\nauto-CRUD route handler. Previously a table with an explicit `text(\"id\").primaryKey()`\nkept a bare PK, so a hand-written action doing `db.insert(...).values({…})` got no\n`id` and failed at runtime with a `NOT NULL` 500 — invisible to `tsc` because the\nscoped `db` was `any`. The injector (which already did this for tables with no\ndeclared PK) now also appends the strategy's `$defaultFn` to an explicit `id` PK.\n`generateId: false` (client-supplied ids) and `serial`/integer PKs are left\nuntouched; the rewrite is idempotent. `$inferInsert` now marks `id` optional.\n\n### Action `db` is typed on Cloudflare D1\n\nThe scoped `db` passed to custom actions is no longer `any`. On D1 projects the\nper-feature `define-action` helper types it as a Drizzle client whose\n`.insert().values()` makes the org/owner/team scope columns optional (the runtime\nfills them from context), while every other column you declared stays required —\nso `tsc` catches a forgotten column, typos, and wrong types, and query results\ncome back typed. Neon/Postgres keep `db: any` for now.\n\n`ctx.userId` is also narrowed to `string` (not `string | undefined`) in actions\nwhose `access` requires authentication — so a trusted write like\n`db.insert(t).values({ ownerId: ctx.userId })` type-checks without a cast.\nActions reachable anonymously (a `PUBLIC` arm, including inside `or`/`and`) keep\n`ctx.userId` optional.\n\n### `access.resource` gains an optional `key`\n\nThe per-room authorization gate (`bindings.durableObjects[].access`) always\nmatched the WebSocket roomId against the backing table's primary key —\n`eq(table.id, rowId)`. Rooms addressed by a different unique column had no way\nto use it: a Yjs collaborative editor keyed by `event_pages.yjsRoomId`\n(`ns.idFromName(row.yjsRoomId)`) would never match on `id`, so projects dropped\nthe `access` block and hand-rolled enforcement in `onConnect` — or, more often,\nshipped no row-level check at all, leaving the room reachable by any\nauthenticated user who could guess a room id.\n\nThe long form now accepts `key`:\n\n```ts\naccess: { resource: { feature: 'event-pages', table: 'eventPages', key: 'yjsRoomId' } }\n```\n\nThe gate emits `eq(table.<key>, rowId)` against the named column. `key` defaults\nto `'id'`, so every existing pin is byte-for-byte unchanged, and it also works\ninside each `resources[kind].resource` of the multi-resource form. The compiler\nvalidates the column exists against the pinned table's schema at compile time.\n\nThe \"multi-table feature is ambiguous\" compile error now points at all three\nescapes — the long-form pin, the `key` option for non-id rooms, and declaring\nthe table's firewall with a `via:` relationship so membership gating runs in the\ngate with no hand-written `onConnect`. See\n[PartyServer rooms → per-room authorization](/stack/realtime/partyserver-rooms).\n\n## v0.35.0 — May 25, 2026\n\nNew **FGA pillar** — OpenFGA / Google Zanzibar Relationship-Based Access\nControl (ReBAC), compiled into your Worker. Plus a public-sharing surface\n(type-bound public access + signed share links) built on it.\n\n### Relationship-based access control (`authz.fga`)\n\nRole-based access and one-hop relationship joins can't express *graph-shaped*\npermissions: an `editor` who is automatically a `viewer`, a document that\ninherits viewers from its folder, a `team#member` group grant, or a per-record\nassignment that doesn't require a global role. The new `authz.fga` block adds a\ntrue ReBAC engine modeled on [OpenFGA](https://openfga.dev):\n\n- **Model** — declare object types, relations, and userset rewrites in the\n OpenFGA modeling DSL (`or` / `and` / `but not`, `[user:*]` public access,\n `[team#member]` usersets, `viewer from parent` tuple-to-userset). The compiler\n parses and semantically validates it at compile time — dangling type or\n relation references fail the compile loudly.\n- **Tuples** — stored in a compiler-owned, organization-scoped `fga_tuples`\n table the compiler emits and migrates. A Check never reads another tenant's\n tuples.\n- **Check engine** — resolved entirely inside the Worker (no external auth\n service): direct tuples, type-bound public access, userset subjects, computed\n usersets, tuple-to-userset, request-scoped contextual tuples, with cycle\n detection and a depth cap.\n- **`ctx.fga`** — `check` / `listObjects` / `expand` / `write` / `read`,\n org-scoped, available in every action and handler.\n- **`access: { fga: { relation, object } }`** — a new declarative access arm.\n The compiler fetches the record and emits an inline, fail-closed\n `ctx.fga.check('user:' + ctx.userId, relation, object)` gate (`object` is a\n `job:{id}` template over the record's columns).\n- **Collection-level FGA filtering** — an `fga` arm on `read.access` (or a named\n view) now filters the collection `GET /`, not just `GET /:id`. The compiler\n resolves the caller's authorized object ids via the engine's `ListObjects` and\n injects an `inArray(id, …)` into the list query, so pagination, `total`, and\n `hasMore` stay correct. Supported shapes are bare `{ fga }`,\n `or:[{ roles }, { fga }]`, and `and:[{ roles }, { fga }]`; deeper nesting is a\n compile error. The authorized set is bounded by `authz.fga.listObjects.maxIds`\n (default 1000) — past the cap the request fails with a hard 422\n (`FGA_LIST_TOO_LARGE`) pointing to `POST /fga/v1/list-objects` for paginated\n enumeration.\n- **REST API** — an OpenFGA-compatible surface at `/api/v1/fga/v1`\n (`check`, `list-objects`, `expand`, `read`, `write`), tenant-scoped; writes\n gated by `authz.fga.writeRoles` (default `['admin']`).\n\n### Public sharing\n\n`authz.fga.sharing` turns the FGA engine into a public-sharing mechanism:\n\n- **Type-bound public access** — a model relation listing `user:*` becomes\n shareable-to-everyone by writing one tuple.\n- **Signed share links** — `POST /api/v1/fga/v1/share` mints an HMAC-signed,\n opaque token for one `(object, relation)` grant; `GET /share/v1/:token` is a\n **public, unauthenticated** route that verifies the token and returns a\n configured public projection of the object (it leaks nothing beyond that\n object + relation).\n- **Share URL** — both a dedicated route (`/share/v1/:token`, always mounted)\n and an optional vanity base URL (`share.<your-domain>`, added to your runtime\n routes) are supported.\n\n### q-recruit showcase\n\nThe recruitment example now models `organization → job → application/interview`\nwith FGA: a `recruiter` is automatically a `viewer` and `can_manage` of a job,\napplications inherit viewers from their job, and a job can be made publicly\nshareable. New `assign-recruiter` and `make-public` actions demonstrate\n`ctx.fga.write`, and `jobs.update` gates on `{ or: [{ roles }, { fga }] }`.\n\n## v0.34.1 — May 24, 2026\n\nPatch fixing a silent-skip bug in drizzle migration emission, plus a new\nCLI subcommand for inspecting and repairing migration-state drift.\n\n### Compiler now fails loud on drizzle migration state drift\n\nWhen `quickback/drizzle/<dialect>/meta/_journal.json` fell out of sync\nwith the on-disk `.sql` files — typically because someone hand-rolled a\nmigration without a journal bump, or because a prior compile collided\nwith an existing tag — drizzle-kit's diff base became stale and it\nsilently skipped emission. The compile reported success, no new `.sql`\nwas written for newly defined tables, and the next `wrangler deploy`\nshipped a Worker that 500'd on every request touching those tables.\n\nThe compiler now runs a precheck before any drizzle-kit invocation and\nrefuses to compile when it detects any of:\n\n- `.sql` files on disk with no matching entry in `_journal.json`\n- journal entries that reference missing `.sql` files\n- non-sequential `idx` values in `_journal.json`\n- two `.sql` files sharing the same `idx`\n- (for `auth/` and `features/` only) journal entries with no matching\n `<idx>_snapshot.json` — drizzle-kit needs the snapshot as a diff base\n\nSnapshot/journal drift that the previous `console.warn` only logged\nserver-side is now propagated to the CLI and printed under\n\"Compilation warnings\".\n\n### New `quickback migrations doctor` CLI command\n\nTwo modes:\n\n```bash\nquickback migrations doctor # diagnose\nquickback migrations doctor --rebuild-journal # repair\n```\n\nDiagnose walks `quickback/drizzle/{auth,features,files,webhooks,audit}/`,\nprints a per-dir table (`.sql files`, `journal entries`, `snapshots`),\nand flags every drift kind the compiler precheck enforces. Repair\nrewrites `_journal.json` from on-disk `.sql` filenames in sorted order —\nthis is the recovery recipe users were applying by hand. Snapshot drift\non drizzle-kit dirs (`auth/`, `features/`) can only be repaired by\nrunning `drizzle-kit introspect` against the live DB; the doctor prints\nthe exact command.\n\n### Upgrade path for projects in the broken state\n\nProjects with existing drift will get a clear error message and an\nexplicit fix command on the next compile against v0.34.1:\n\n```\n✖ Drizzle migration state is inconsistent — refusing to compile.\n Causes:\n - quickback/drizzle/features: 7 .sql file(s) have no matching journal entry: ...\n Fixes:\n - Run `quickback migrations doctor` to diagnose, then\n `quickback migrations doctor --rebuild-journal` to repair.\n```\n\nNo action needed for projects whose journals are already in sync.\n\n## v0.34.0 — May 23, 2026\n\nCustomizable email-OTP templates and a dedicated admin-create-user hook\n— closes a longstanding gap where projects on `email.provider: 'aws-ses'`\nhad to live with the generic \"Your password reset code is ...\" copy for\nadmin-bootstrapped accounts.\n\n### Per-type email-OTP template overrides\n\nDrop a `.ts` file at `quickback/email-templates/<name>.ts` that\ndefault-exports `(input) => ({ subject, html, text })`, then reference\nit from the new `plugins.emailOtp.templates` map. Missing keys fall\nthrough to the package defaults from `@quickback-dev/better-auth-aws-ses`\n— this is purely additive; existing `emailOtp: true` projects emit the\nsame code they did before.\n\n```ts title=\"quickback/quickback.config.ts\"\ndefineAuth(\"better-auth\", {\n plugins: {\n emailOtp: {\n templates: {\n 'forget-password': './email-templates/forget-password',\n 'welcome': './email-templates/welcome',\n },\n },\n },\n});\n```\n\n```ts title=\"quickback/email-templates/welcome.ts\"\nexport default function welcome({ otp, name, appName, appUrl }) {\n const greeting = name ? `Hi ${name},` : 'Hi,';\n return {\n subject: `Welcome to ${appName} — set your password`,\n html: `<h1>Welcome to ${appName}</h1><p>${greeting} use this code: <b>${otp}</b></p>`,\n text: `${greeting}\\n\\nYour ${appName} code: ${otp}`,\n };\n}\n```\n\nRecognized keys: `'sign-in' | 'email-verification' | 'forget-password' |\n'welcome'`. The first three map 1:1 to Better Auth's emailOTP `type`\nenum.\n\n### Synthetic `welcome` routing — credential-row lookup\n\n`'welcome'` has no native Better Auth OTP type. When configured, the\ngenerated `sendVerificationOTP` callback queries the `account` table\nfor a `credential`-provider row for the recipient *before* rendering;\nif the user has none (typical of an admin-plugin-created account\nwithout a password), the send is rerouted through the welcome\ntemplate. Without a welcome template, those sends fall through to\n`forget-password` — same behavior as before. DB-error path fails open\nto the normal forget-password flow so a transient failure can't\ndeadlock the password-reset surface.\n\nProvider scope: overrides are only honored on `email.provider:\n'aws-ses'`. The Cloudflare Email path uses the helper's own template\npipeline and ignores the new config.\n\n### New recognized hook: `after-admin-user-create.ts`\n\nA virtual event that wires into the same Better Auth\n`databaseHooks.user.create.after` slot as the generic\n`after-user-create.ts`, but the generator gates the call on\n`_baCtx?.context?.path` matching `/admin/create-user` so it only fires\nwhen the row came from the admin plugin's create-user endpoint. Use it\nfor first-time-user provisioning (welcome email, default org\nassignment, audit-log writes) without inspecting the BA context by\nhand. The generic `after-user-create.ts` still runs for every signup,\nincluding admin-created ones; the two coexist in a single merged\n`after:` handler.\n\n```\nquickback/hooks/\n after-user-create.ts # every signup\n after-admin-user-create.ts # admin-plugin /admin/create-user only\n```\n\n### File transport mirrors existing slots\n\nThe new `quickback/email-templates/` directory follows the same\npattern as `quickback/plugins/`, `quickback/hooks/`, and\n`quickback/lib/`: the CLI walks the folder and uploads each `.ts` file\nin a new `projectEmailTemplates` field on the compile request; the\nbetter-auth provider stages referenced files into\n`src/email-templates/<name>.ts` and emits default imports in\n`src/lib/auth.ts`. Files not referenced by any template entry are\nignored — the CLI uploads the whole directory; the compiler picks only\nwhat's needed. A relative path pointing at a file the CLI never\nshipped fails compile fast with a \"place the file at … and rerun\"\nhint.\n\nSee [AWS SES Plugin → Per-Type Template Overrides](/stack/auth/plugins/aws-ses#per-type-template-overrides)\nand [Account UI → Hooks](/stack/account-ui/hooks#recognized-events).\n\n## v0.33.6 — May 22, 2026\n\nTwo compiler-side fixes for the queue-consumer / embedding surface and one\nschema-emission bug that blocked `generateId: 'cuid'` projects.\n\n### Schema-emitted `createId()` now ships with a polyfill (no missing import)\n\nWhen `providers.database.config.generateId` is set to `'cuid'`, the audit-\nfield injector emits an id column like\n`id: text('id').primaryKey().$defaultFn(() => createId())`. Previously the\nschema source referenced `createId` but no import landed, so `tsc` on the\ngenerated project failed with `Cannot find name 'createId'`. Recurring\nbug — every recompile re-emitted the broken file (the \"do not edit\"\nbanner doesn't protect from regeneration).\n\nFix: the injector now prepends a top-of-file polyfill backed by\n`crypto.randomUUID()` — a Workers / Node 19+ / Bun global — instead of\ntrying to import `@paralleldrive/cuid2`. The package isn't bundled by\nQuickback (per the [hooks doc](/stack/account-ui/hooks)'s \"stick to\nbuilt-ins\" guidance) and the schema-gen sandbox can't resolve project\nnode_modules anyway, so the polyfill is the only path that works\nout-of-the-box.\n\n```ts title=\"Generated schema header (cuid strategy)\"\n\n// Polyfill — Quickback compiler does not ship @paralleldrive/cuid2 in\n// generated projects, and the schema-gen sandbox can't see node_modules.\n// crypto.randomUUID() is a Workers / Node 19+ / Bun global.\nconst createId = () => crypto.randomUUID();\n\nexport const widgets = sqliteTable('widgets', {\n id: text('id').primaryKey().$defaultFn(() => createId()),\n // ...\n});\n```\n\nIf you want real cuid2 strings (collision-resistant, shorter than UUIDs)\nyou can still install `@paralleldrive/cuid2` and add the import yourself —\nthe injector honours an existing import and skips the polyfill.\n\n### queue-consumer.ts header reflects what the file actually does\n\nBefore v0.33.6 the generated `src/queue-consumer.ts` always carried the\npreamble:\n\n```\n* Queue Consumer for Embedding Jobs & Custom Queue Handlers\n*\n* Processes embedding jobs asynchronously using Workers AI and Vectorize.\n* Also supports custom queue handlers defined in services/queues/.\n```\n\n— even on projects with zero embedding features. Users on\ncustom-queue-only deployments would search for `EMBEDDINGS_QUEUE` /\nVectorize bindings that wrangler.toml correctly didn't emit, wasting\ndiagnostic time.\n\nThe preamble now reflects the actual surface:\n\n| `hasEmbeddings` | `hasCustomHandlers` | Header |\n|---|---|---|\n| ✓ | ✓ | \"Queue Consumer for Embedding Jobs & Custom Queue Handlers\" |\n| ✓ | — | \"Queue Consumer for Embedding Jobs\" |\n| — | ✓ | \"Queue Consumer for Custom Queue Handlers\" + explicit \"No embedding bindings (EMBEDDINGS_QUEUE / Vectorize / AI) are referenced\" |\n| — | — | \"Queue Consumer Stub\" (additionalQueues with no handler yet) |\n\n### Symmetric embedding detection prevents silent drift\n\nThe wrangler.toml emit path (`EMBEDDINGS_QUEUE` producer/consumer\ndeclaration) and the queue-consumer.ts emit path (embedding handler code)\npreviously used two different functions to detect \"this project has\nembeddings\": `hasEmbeddingsConfig` checked both `feature.resource.\nembeddings` and `feature.tables[].resource.embeddings`;\n`extractEmbeddingFeatures` only iterated the tables array. A feature\nshape with feature-level embeddings sugar but no populated tables would\nland in the wrangler binding while NOT landing in the consumer file\n— silent drift.\n\n`hasEmbeddingsConfig` is now defined as\n`extractEmbeddingFeatures(...).length > 0`. The two stay in lock-step\nby construction. `extractEmbeddingFeatures` now reads from both shapes\n(tables-level when present, feature-level otherwise).\n\n## v0.33.5 — May 22, 2026\n\nTwo structural fixes that resolve recurring classes of bug for projects with\ninteger primary keys and for projects whose audit columns drift between\nschema and database.\n\n### URL `:id` params coerce to Number when the PK column is integer\n\nPer-id CRUD handlers (`GET /:id`, `PATCH /:id`, `DELETE /:id`, `PUT /:id`)\nextracted the URL param as a string and passed it straight into\n`eq(table.id, id)`. For resources with `integer().primaryKey()` columns —\ntriggered either by `generateId: 'serial'` on the database config or by\nimported legacy schemas — every per-id route raised a downstream tsc\ntype error (integer ≠ string). One production project reported 249 such\nerrors across 30+ generated `*.routes.ts` files.\n\nGenerated handlers for integer-PK resources now emit:\n\n```ts\nconst __idRaw = c.req.param('id');\nconst id = Number(__idRaw);\nif (!Number.isInteger(id)) {\n return c.json(ValidationErrors.invalidInput([{\n path: ['id'],\n message: `Expected integer, got \"${__idRaw}\"`,\n code: 'invalid_type',\n }]), 400);\n}\n```\n\nText-PK resources (the default and the recommended path) are unchanged.\n\nA soft-deprecation warning now fires at compile time when\n`providers.database.config.generateId === 'serial'` is set, nudging new\nprojects toward text-PK strategies (`'cuid'`, `'uuid'`, `'prefixed'`, or\nthe default). Existing serial-PK projects keep working.\n\n### Audit-field injection now runs for every dialect\n\nThe compiler auto-injects `created_at`, `modified_at`, `created_by`, and\n`modified_by` columns into every feature table, and the scoped-db\nruntime auto-fills them on insert. Until v0.33.5, the early injection\nstep in `parseCompilerInput` was gated on `targetDialect ===\n'postgresql'`. SQLite/D1 projects fell back to a later injection inside\n`generateFeature`, which only fired when `feature.tables.length > 0` —\nfeatures arriving without a populated tables array (raw-drizzle shapes,\ncertain legacy migration tables) silently skipped audit injection.\n\nSymptom: schemas claimed the columns existed (so the scoped-db proxy\ntried to fill them on insert), but the database table didn't have them.\nInserts failed with \"column doesn't exist.\" Users reported this for the\n`user_preferences` table and, earlier, for `chat_reads` (the\n`0028_chat_reads_id_column.sql` incident).\n\nThe early injection now runs for all dialects. `injectAuditFields` is\nalready idempotent, so the subsequent per-target injections in\n`compilePureSQLTarget` and `feature-generator.ts` are no-ops when the\ncolumns are already present. Net: every feature's schema source has\naudit columns by the time drizzle-kit reads it, regardless of dialect\nor feature shape.\n\nUpgrade path: recompile against v0.33.5, commit the generated migration\nthat adds the missing audit columns, then `wrangler d1 migrations apply`.\n\n## v0.33.4 — May 21, 2026\n\nPatch fixes covering upgrade-path bugs and OpenAPI spec/route divergence. No\nnew features or breaking changes.\n\n### OpenAPI emits CRUD endpoints only when the route emitter registers them\n\nThe OpenAPI emitter previously advertised `GET /`, `POST /`, `GET /:id`,\n`PATCH /:id`, `DELETE /:id`, and the corresponding `/batch` operations on\nevery resource, regardless of which CRUD verbs were actually declared.\nClients generated from `openapi.json` then issued requests that fell\nthrough to `ROUTE_NOT_FOUND` from the firewall layer — a silent contract\nbreak for anyone whose code path was driven by openapi-typescript or\nsimilar codegen.\n\nEach gate now mirrors the route emitter exactly. A resource that only\ndeclares `read + create + delete` (no `update`) gets no PATCH operations\nin the spec. A write-only sink (`create` only, no `read`) gets no GET\noperations. Same for batch variants — `POST /batch` only when\n`crud.create` is set, `DELETE /batch` only when `crud.delete` is set,\netc.\n\nIf your generated client was calling these spurious endpoints, those\ncalls were already failing at runtime; this just removes them from the\nspec.\n\n### Legacy D1 audit-timestamp migrations rewritten in place\n\nCompilers ≤ v0.33.1 emitted\n`DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))` for audit columns\n(`created_at`, `modified_at`, etc.). Cloudflare D1 rejects this in\n`ALTER TABLE ADD COLUMN` with `SQLITE_ERROR [code: 7500] \"Cannot add a\ncolumn with non-constant default\"`. v0.33.2 stopped emitting the\nnon-constant form, but pending unapplied legacy migration files on\nupgrading projects still poisoned `wrangler d1 migrations apply` and\nleft the deploy stuck.\n\nThe D1 migration safety pass now retrofits these files in place,\nreplacing the strftime expression with the same `'1970-01-01T00:00:00.000Z'`\nconstant v0.33.2+ uses. The compile-time warning lists the affected\ncolumns:\n\n```\n⚠ D1 helper adjusted features migrations for Cloudflare D1 safety:\n 0004_early_dracula.sql [rewrote=applied_at,created_at,modified_at]\n```\n\nUpgrade path: recompile against v0.33.4, commit the rewritten SQL, then\n`wrangler d1 migrations apply` proceeds.\n\n### D1 helper warning is now actionable\n\nThe same migration safety pass auto-prepends `PRAGMA defer_foreign_keys\n= on` to every drizzle table-rebuild migration — required on D1\nbecause it doesn't honour `PRAGMA foreign_keys=OFF/ON` mid-migration the\nway SQLite does. The pass used to surface this insertion as a warning\non every recompile, training users to ignore the warning entirely.\n\nThe PRAGMA is still inserted (it has to be), but no longer fires the\nwarning. Stripped Better Auth cleanup, reordered child-first DROPs, and\nthe new `rewrote=…` annotation above still warn — those are cases where\na human should look.\n\n### Reference: `account.appUrl` / `account.tenantPattern`\n\nv0.33's redesigned dashboard org-card uses two new optional fields on\nthe `account` config to deep-link into the tenant's own app:\n\n```ts\n// quickback.config.ts\naccount: {\n // …existing fields\n appUrl: 'https://app.example.com',\n tenantPattern: '/{slug}',\n}\n```\n\nBoth are typed in the config schema and baked into the Account SPA at\nbuild time as `VITE_QUICKBACK_APP_URL` and `VITE_TENANT_URL_PATTERN`.\nWithout them, the dashboard falls back to a single-target card that\nlinks to the account org-settings page (legacy v0.32 behaviour). Adding\nthem enables the two-zone layout with the external deep-link affordance.\n\n(No code change in v0.33.4 — the fields shipped with v0.33.0 but weren't\ncalled out in the changelog.)\n\n## v0.33.0 — May 21, 2026\n\n### Dedicated hostnames for `/auth/v1/*` and `/api/v1/*` (Shape 1)\n\nTwo new optional overrides let you carve specific backend surfaces onto dedicated hostnames, served by the same Worker:\n\n```ts\n// quickback.config.ts\nauth: { domain: 'auth.example.com' }, // /auth/v1/* lives here too\napi: { domain: 'api.example.com' }, // /api/v1/* lives here too\n```\n\nOn the dedicated hostname, the hostname IS the namespace — `/v1/*` is a shortcut that the Worker-entry rewriter prepends with `/auth` or `/api` before route matching. So `https://api.example.com/v1/users` reaches the same handler as `https://quickback.example.com/api/v1/users`. Both forms work; the long form is also accepted on the dedicated host. Non-matching paths return a JSON 404 (\"Not found on api.domain — this hostname serves /api/v1/* and the /v1/* shortcut only\") — each hostname stays dedicated to its surface. `/health` and `/openapi.json` are explicit exceptions because monitoring/discovery agents expect them everywhere.\n\nBoth new domains:\n- Get a `{ pattern, custom_domain: true }` route in `wrangler.toml`\n- Join `trustedOrigins` (CORS allowlist)\n- Join the cross-subdomain cookie inference (auto-enables `crossSubDomainCookies` when ≥2 same-parent subdomains are configured)\n- Join CSP `connect-src` so SPAs can fetch from them\n\n**Dual-reach:** all routes remain reachable at the unified backend host (see below) regardless of which dedicated hostnames are configured. The dedicated hostnames are aliases, never replacements.\n\n### `quickback.{baseDomain}` codified as the always-present unified backend\n\nThe compiler has always auto-inferred a `quickback.{baseDomain}` hostname when any subdomain is configured. v0.33 promotes this from inferred fallback to **load-bearing contract**:\n\n- The unified backend hostname is GUARANTEED to exist when any custom subdomain (`account.domain`, `cms.domain`, `auth.domain`, `api.domain`, `apps.<n>.domain`) is set.\n- Every compiler-emitted backend route (api, auth, storage, health, openapi, realtime, mcp, bundled SPAs, sysadmin endpoints) is reachable at the unified host, always.\n- Per-surface domain overrides are additive (Shape 1) — they create more hostnames, never remove routes from the unified host.\n\nThis is forward-pointing: the future management layer can rely on a single discovery URL pattern (`https://quickback.{baseDomain}/...`) to find any backend regardless of how the operator split their surfaces onto subdomains.\n\nInference also extends to consider `auth.domain` and `api.domain` as domain sources, so a project configuring only one of them still derives `quickback.{baseDomain}` automatically. Explicit `config.domain` still wins over inference.\n\n### `compiler.routes` config block (scaffold — partial)\n\nOptional path-prefix overrides for compiler-emitted system routes:\n\n```ts\ncompiler: {\n routes: {\n storage: '/files', // default '/storage'\n broadcast: '/realtime', // default '/broadcast/v1'\n mcp: '/agent', // default '/mcp'\n health: '/_health', // default '/health'\n openapi: '/openapi.yaml', // default '/openapi.json'\n },\n}\n```\n\n**Status:** the config is validated and reaches the reserved-prefix registry (so SPA pass-through and compile-time collision detection already honor overrides), but the per-section route emitters still hardcode the defaults. Setting a non-default value today will produce a misconfigured Worker — the registry knows the new path but the actual `app.route('/storage/v1', …)` mount uses the old one. **Don't set these in production yet.** Per-section emit wiring lands in a follow-up.\n\n`/api/v1/` and `/auth/v1/` are NOT configurable here — those are deep contracts touched by feature emitters, OpenAPI generation, generated clients, and BA's own basePath. The Shape 1 hostname overrides above are the supported way to relocate them.\n\n## v0.32.0 — May 21, 2026\n\n### Single-origin path-routed architecture\n\nA modern Quickback project now runs on **one Cloudflare Worker behind one custom domain**, with the bundled Account and CMS SPAs path-mounted at `/account/` and `/cms/`, system routes at `/api/`, `/auth/`, `/storage/`, and the user's own SPAs anywhere else they want. No cross-subdomain cookies, zero CORS preflights, no separate `api.`/`account.`/`cms.` subdomains required:\n\n```ts\n// quickback.config.ts\napps: { www: { domain: 'app.example.com' } }, // user's root SPA\naccount: true, // bundled at /account/\ncms: true, // bundled at /cms/\n// /api/, /auth/, /storage/, /openapi.json, /health all live here too\n```\n\nThe bug that previously broke this shape: when a hostname-mounted root SPA was configured (`apps.www.domain`), its middleware swallowed every path that wasn't in a hardcoded list (`/api/`, `/auth/`, `/admin/`, `/storage/`, `/health`). Requests to `/account/profile` got remapped to `/www/account/profile`, 404'd, then SPA-fallback'd to the wrong SPA. v0.32 introduces a **reserved-prefix registry** (`resolveReservedPrefixes` in `apps/compiler/src/generators/core/reserved-prefixes.ts`) as the single source of truth for what every catchall middleware must pass through:\n\n- **System** (always present): `/api/`, `/auth/`, `/storage/`, `/health`, `/openapi.json`\n- **Conditional** (only when feature is on): `/account/` (when `account: true`), `/cms/` (when `cms: true`), `/broadcast/v1/` (realtime), `/mcp` (MCP server)\n- **User-contributed**: every `apps.<name>.path` for path-mounted apps\n\nPath-mounted apps that collide with a system or bundled-SPA reservation throw a compile-time error naming both owners. `apps.api = { path: '/api' }` errors clearly instead of silently hijacking feature routes at runtime.\n\n### Admin URL namespace migration: `/admin/v1/*` → `/auth/v1/admin/*`\n\nQuickback's legacy admin tier emitted three things under `/admin/v1/*`:\n\n1. A role-admit middleware that admitted both `'admin'` and `'sysadmin'` — contradicting the pseudo-role evaluator's strict-independence model (`ADMIN` admits `'admin'` only; `SYSADMIN` admits `'sysadmin'` only).\n2. `GET /admin/v1/organizations` — a thin proxy to Better Auth's own `/auth/v1/organization/list`.\n3. `GET /admin/v1/sysadmin/organizations` — cross-tenant org listing, sysadmin-only.\n\nIn v0.32, the first two are **removed** and the third **renames** to `GET /auth/v1/admin/list-organizations`. The new path sits under Better Auth's admin URL namespace (sibling of `/auth/v1/admin/list-users`, `/auth/v1/admin/ban-user`, etc.), follows BA's verb-noun convention, and keeps its sysadmin-only gate inside the handler — Quickback-emitted, not BA-mounted.\n\nWhat this enables: `/admin/*` is no longer a reserved system prefix. Projects can mount their own admin SPA via `apps.admin = { path: '/admin' }` without colliding with anything.\n\nWhat changes for callers:\n- The bundled CMS SPA's sysadmin org switcher is updated in lockstep (no migration needed for projects using the SPA as-is).\n- External callers of `/admin/v1/organizations` should migrate to BA's `/auth/v1/organization/list` (same behavior — caller's memberships).\n- External callers of `/admin/v1/sysadmin/organizations` should migrate to `/auth/v1/admin/list-organizations`.\n- Features that previously relied on the \"admit both admin AND sysadmin\" middleware should declare `access: { roles: ['ADMIN', 'SYSADMIN'] }` explicitly on each route.\n\nThe `ADMIN_ROUTE_FEATURES` carve-out in the compiler is also removed — feature routes always mount at `/api/v1/<feature>`, and admin-only behavior is enforced by per-operation `access: { roles: ['ADMIN'] }` at the resource level.\n\n### Two compiler bug fixes\n\n- **Soft-delete index callback parameter bug.** The auto-index injector emitted hardcoded `t.<col>` references regardless of the existing extras callback's parameter name. When a user (or upstream transform) wrote `(table3) => ({ … })`, the appended composite-index entries referenced `t.organizationId, t.deletedAt` — `t` undefined inside the arrow scope, `ReferenceError` at module load. Fixed in `apps/compiler/src/utils/auto-indexes.ts` by capturing and reusing the callback's parameter name.\n- **Reserved-word action filename collision.** Action discovery walks `actions/*.ts` and emits `import <name> from './actions/<name>'`. A user filename of `import.ts`, `delete.ts`, `await.ts`, `export.ts`, etc. produced `import import from './actions/import';` — a SyntaxError on module load. Fixed in `apps/compiler/src/codegen/discovered-actions.ts` by aliasing reserved-word and invalid-identifier filenames to `__action_<sanitized>` bindings while preserving the public action key (route emitters use bracket notation, so reserved-word keys are fine in the lookup map).\n\n## v0.29.0 — May 19, 2026\n\n### Opt-in `id` auto-injection (`compiler.injectId: 'auto'`)\n\nQuickback's generated CRUD routes, FK extractor, relationship resolver, and `/:id` mount points all assume every feature table has an `id` primary key column. Authoring a table without one — common when porting an existing schema, or when a domain genuinely uses a compound or non-`id` PK — produced silent failures: routes that 404, batch operations that targeted the wrong rows, FK lookups that returned empty.\n\nv0.29 adds an opt-in flag that auto-injects an `id` column into every feature table that doesn't already declare one. Same mechanism as the existing `createdAt`/`modifiedAt` injection — early-pass, idempotent, dialect-aware.\n\n```ts\n// quickback.config.ts\ncompiler: {\n injectId: 'auto', // off by default; opt in per project\n}\n```\n\nWhen `'auto'`:\n- Tables with no `.primaryKey()` declared get `id: text(\"id\").primaryKey().$defaultFn(() => createId())` (or the matching shape for `dbConfig.generateId` — `serial`, `uuid`, `prefixed`).\n- Tables that already declare an `id` column (in any shape) are no-op — the injector is idempotent.\n- Tables with a `.primaryKey()` on a non-`id` column raise a clear compile error that names the offending column and points at the v0.30 follow-up which will rewrite custom PKs to unique indexes automatically. v0.29 surfaces the conflict; v0.30 fixes it.\n\nDefault stays `false` so existing projects don't get migration churn. Opt in when you want to lean on every-table-has-id semantics across your schema.\n\n### Why this is opt-in (and what v0.30 changes)\n\nThe \"every table has `id`\" assumption is load-bearing across 68+ sites in the compiler — every CRUD emitter, the FK regex (`.references(() => target.id)`), the relationship resolver hydration block, the `/:id` route mounts. v0.29 only injects the column; v0.30 will close the remaining gaps:\n\n- FK extraction migrates from `.id` regex to schema-aware metadata lookup, so tables with non-`id` PKs participate in FK display + relationship resolution.\n- The PK→unique-index rewrite lands — tables with explicit non-`id` PKs auto-keep their uniqueness as a constraint while gaining the auto-injected `id`.\n- The flag flips to default-on; opting out becomes the rare path.\n\nv0.29 ships the foundation so projects can opt in today without waiting for the full structural pass.\n\n## v0.28.0 — May 19, 2026\n\n### INTERNAL pseudo-role: server-only schemas, unforgeable from HTTP\n\nv0.27 had five pseudo-roles — `PUBLIC`, `AUTHENTICATED`, `USER`, `ADMIN`, `SYSADMIN` — and one structural gap: there was no way to mark a schema as \"the server enumerates this; no user-facing route should ever read across tenants.\" Push subscriptions, personal access tokens, OAuth tokens, broadcast job tables — anywhere the server needs full visibility but users should only see their own row. The workaround was `firewall: { exception: true }` plus an out-of-band convention, which left auth on the schema looking incidental.\n\nv0.28 adds **`INTERNAL`** as the sixth pseudo-role. Schemas with `roles: ['INTERNAL']` are reachable only by `AppContext` values where `ctx.internal === true` — a flag the HTTP auth middleware **never** sets. No session, JWT, header, query parameter, or body field populates it. The flag is reserved for compiler-emitted server-internal entry points (queue consumers, cron workers, server-side helpers that bypass HTTP entirely).\n\n```ts\n// features/comms/push-subscriptions.ts\nexport default defineTable(push_subscriptions, {\n firewall: [{ field: 'ownerId', equals: 'ctx.userId' }],\n // User reads their own subscriptions via the standard CRUD route.\n read: { access: { roles: ['USER'] } },\n // Server enumerates ALL subscriptions for a broadcast — INTERNAL only.\n crud: {\n delete: { access: { roles: ['INTERNAL'] } },\n },\n});\n```\n\nThe split-surface pattern is the recommended shape: a user-facing access node uses `USER` / `AUTHENTICATED` / a real role; a server-only access node uses `INTERNAL`. Mixing INTERNAL with a user-facing pseudo-role on the **same** access node is a compile error — it almost always means the developer is confused about which side of the trust boundary they're on. The error names the cohabiting markers explicitly and points at the fix (split into separate access blocks).\n\nThe runtime stamping (queue consumer ctx, cron worker ctx) lands in a follow-up; v0.28 ships the declarative surface so projects can mark schemas accurately today. Until the stamping ships, server-internal code uses `unsafeDb` to enumerate INTERNAL surfaces — the security guarantee is in place because no HTTP-derived context can ever carry `ctx.internal === true`.\n\n### Reserved-name fix: SYSADMIN and INTERNAL added to ALWAYS_RESERVED\n\n`SYSADMIN` was previously omitted from the `ALWAYS_RESERVED` set in `authz-schema.ts`. The runtime validator rejected `roles: ['SYSADMIN']` when `cms.sysadmin: true` wasn't set, but the **shadow-declaration path** — user code writing `authz.roles.SYSADMIN: { roles: [...] }` to silently change the pseudo-role's meaning — wasn't blocked. v0.28 closes that gap by adding both `SYSADMIN` and `INTERNAL` to the unconditionally-reserved set.\n\n### Per-table OWNER_SCOPE_RULES: explicit owner predicates no longer over-scope\n\nWhen a user declared a non-canonical owner predicate on one table — e.g. `firewall: [{ field: 'linkedUserId', equals: 'ctx.userId' }]` — that column got promoted into the **project-global** `OWNER_SCOPE_RULES` list. Any other table in the project that happened to have a `linkedUserId` column (even as a plain FK reference, not for scoping) had the same `WHERE linkedUserId = ctx.userId` injected on every read, update, and delete. Silent over-scoping that surfaced only when a query returned the wrong rows.\n\nv0.28 narrows the global list to the **canonical owner column** — the one matching `authDefaults.owner.column` (default `ownerId`). Explicit predicates on custom-named columns are honored on their declaring table via that table's own `buildFirewallConditions` helper, but stay per-table. Reads on other tables with the same column name are unaffected.\n\n```ts\n// Before v0.28: linkedUserId on `comments` ALSO got the WHERE\n// because `event_organizers` declared an explicit owner predicate.\nexport default defineTable(event_organizers, {\n firewall: [{ field: 'linkedUserId', equals: 'ctx.userId' }],\n});\nexport default defineTable(comments, {\n // comments.linkedUserId is just an FK reference; we don't want it scoped.\n firewall: [{ field: 'eventId', equals: 'ctx.activeOrgId' }],\n});\n```\n\nIn v0.28, `event_organizers` queries get the per-table `linkedUserId = ctx.userId` predicate as before; `comments` queries are no longer mis-scoped.\n\nIf you genuinely want the same column to scope multiple tables (rare), declare the explicit firewall predicate on each table. The implicit \"every table with this column gets scoped\" behavior was the bug — explicit-per-table is the cure.\n\n## v0.27.0 — May 19, 2026\n\n### Narrow `ctx.<exposeAs>` typing for namespace-scoped actions\n\nSince v0.23 the namespace middleware has hydrated `ctx.<exposeAs>` with the loaded resource row before each action runs. The static type of that field stayed `any` — runtime safety was solid, but autocomplete and typo-catching were missed opportunities.\n\nv0.27 ships the second half: one **per-namespace `defineAction` helper** emitted alongside the standard one. Importing from the narrowed helper retypes `ctx.<exposeAs>` inside `execute({ ctx })` to the loaded row's `$inferSelect` shape. Nothing about discovery, routing, or runtime behavior changes — this is purely TypeScript ergonomics.\n\n```ts title=\"features/feeds/actions/feed-moments.ts\"\n// Before — ctx.event is `any`\n\n// After — ctx.event is `typeof events.$inferSelect`\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, autocomplete works\n ctx.event.startsAt // ✓ Date\n ctx.event.idd // ✗ TS2339 — typo caught at compile time\n },\n});\n```\n\n#### Where the file lives\n\nThe compiler emits one narrowed 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` → `define-action.event-scope.ts`), sibling to the standard `define-action.ts`:\n\n```text\nsrc/features/feeds/.quickback/\n├── define-action.ts # generic — standard fallback\n└── define-action.event-scope.ts # ctx.event narrowed\n```\n\nA feature contributing to multiple namespaces gets one helper per namespace. Each action picks the import that matches its path.\n\n#### Opt-in, no breaking change\n\nActions that keep their existing `import { defineAction } from '../.quickback/define-action'` continue to compile unchanged. The `AppContext` index signature still admits `ctx.event` at type `any`; runtime hydration is unaffected. 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 logs a one-line `[quickback:typing]` 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 family as `[quickback:authz]`.\n\n#### Side fix\n\nRepaired a latent off-by-one in the inlined `AppContext` import path that landed in the v0.26 helper prelude but hadn't been exercised against a recompiled project yet (`\"../../lib/types\"` → `\"../../../lib/types\"`). New compiles produce a helper whose `AppContext` import actually resolves.\n\n#### Out of scope\n\nNon-namespace standalone actions with relationship-based access keep their existing `(ctx.event as typeof events.$inferSelect)` body cast. Same per-relationship helper pattern would apply if the demand surfaces — defer until requested.\n\n## v0.26.0 — May 19, 2026\n\n### Bulk-grant namespace lanes: org admins and team members in one line\n\nv0.25 widened `via:` to accept an array of relationship lanes — attendeeOf OR organizerOf, first match wins. That covers per-row authorization paths. v0.26 adds the missing piece: **bulk-grant lanes** for the \"you work here, so you see everything in your scope\" case. Org admins, team members, and other tenant-scoped staff no longer need a per-event relationship row to be authorized for a namespace.\n\n```ts\nauthz: {\n namespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: [\n 'attendeeOf', // per-event relationship\n 'organizerOf', // per-event relationship\n { roles: ['admin', 'owner'] }, // org-role bulk grant\n { team: true }, // active-team-membership bulk grant\n ],\n },\n },\n}\n```\n\nLanes resolve in declaration order, first match wins. Per-row relationships and bulk-grant guards compose freely.\n\n#### What each bulk-grant lane does\n\n- **`{ roles: [...] }`** — passes when the caller's BA org-role for the namespace's loaded resource includes any listed role. The check is in-memory and short-circuits the relationship loop entirely. The loads-table firewall (scoped by `ctx.activeOrgId`) does the tenant isolation; this lane just adds the role precondition on top.\n- **`{ team: true }`** — passes when `ctx.activeTeamId` is set. The loads-table firewall (which scopes by team for team-scoped tables) does the actual `events.teamId === ctx.activeTeamId` match during hydration. If the firewall returns no row, the request gets a contextual 404 explaining the row isn't visible to the current session — same ambiguous-by-design phrasing the firewall has always used to prevent cross-tenant ID probing.\n\n#### Why this matters\n\nUntil v0.26, the only way to authorize an org admin for a namespace was to write `access.or: [{ via: 'attendeeOf' }, { roles: ['admin', 'owner'] }]` on every individual action under it. That OR-arm shim worked but defeated the purpose of namespaces — the whole point of hoisting the gate was to write the auth rule once. Now you do.\n\n#### Rich deny payloads\n\nThe 403 response when every lane misses lists every path the caller could have taken — relationship names, role names, and `\"team-membership\"` for `{ team: true }` lanes — in the `required` field. A developer hitting an unexpected 403 sees the full set of authorization options they need to satisfy, not a generic \"Insufficient permissions\" wall.\n\nThe 404 from hydration (when the loads-table firewall filters the request out) now includes a hint explaining that the row may exist out of scope, and a `details` field with the resource name and key, so a developer working in their own environment has enough to debug.\n\n#### Compile-time guards\n\n- **Pure bulk-grant namespaces** (no relationship lane at all) are accepted as long as `loads:` + `exposeAs:` are declared directly on the namespace. With at least one relationship lane present, those fields are inherited from the relationship — declare them on the namespace itself only when no relationship lane is available to anchor hydration.\n- **Heterogeneous `loads:` between relationship lanes is rejected** — `ctx.<exposeAs>` must always hydrate the same table regardless of which lane matched.\n- **`namespace.loads` that disagrees with the inherited value is rejected** with a clear \"drop one or align the other\" message.\n\n## v0.25.0 — May 19, 2026\n\n### Multi-lane namespace gates: more than one way to be authorized\n\nv0.24 lets you hoist a namespace gate to the project level via `authz.namespaces.<name>.via: 'attendeeOf'` — one relationship-resolver middleware running once per request for every action under `/event/:eventId/*`. That works when there's exactly one way to be authorized for the resource. It breaks the moment you have **two**: an attendee row and a per-event organizer row, say. The shim today is to OR the second check inside every individual action's `access` block, which puts you back to writing the gate over and over.\n\nv0.25 widens `via:` to accept an array of relationship lanes. The middleware tries each in declaration order, and the first one whose subject row matches authorizes the request and hydrates `ctx.<exposeAs>`.\n\n```ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'linkedUserId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events',\n exposeAs: 'event',\n },\n // Per-event named organizers. The subject can be a user OUTSIDE\n // the event's organization — e.g. a freelance event manager.\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'], // first match wins\n },\n },\n}\n```\n\nThe thing this actually unlocks isn't \"two checks instead of one.\" It's **per-event grants for users outside the owning organization** — external co-organizers, freelance event managers, partner staff. They don't need a `member` row in the event's org; they just need a row in `event_organizers` for that specific event. The horizontal axis (org / team membership) stays for \"staff at this company\"; the new vertical axis (per-event relationships) handles \"specifically connected to this event,\" regardless of payroll.\n\n#### Backward compatible\n\nThe string form keeps working — `via: 'attendeeOf'` is sugar for `via: ['attendeeOf']`. No existing namespaces break; opt into multi-lane by switching to the array form when you actually need it.\n\n#### Compile-time guards\n\nThe validator rejects three things at parse time:\n\n- **Undeclared lane names** — every entry in the array must resolve to an `authz.relationships[*]` declaration.\n- **Lanes that disagree on `loads:` or `exposeAs:`** — if attendeeOf loads `events` as `ctx.event` and organizerOf loads `agendaItems` as `ctx.agendaItem`, downstream handlers can't predict what's in `ctx.<exposeAs>`. Lanes in one namespace must hydrate the same shape.\n- **Empty arrays** — at least one lane is required (otherwise the namespace gate is meaningless).\n\n#### Follow-up: v0.26 bulk-grant lanes (shipped same day — see above)\n\nThe full 4-lane shape adds heterogeneous `via:` arrays accepting `{ roles: ['admin', 'owner'] }` and `{ team: true }` entries, so org admins and team members get the gate without writing relationship rows. v0.25 was the foundation; [v0.26](#v0260--may-19-2026) lifted the existing per-action `access.or: [..., { roles: [...] }]` shim into the namespace and landed same-day.\n\n## v0.24.0 — May 19, 2026\n\n### Cross-feature namespaces: one hoisted gate, many features\n\nv0.23 shipped `defineTable({ namespace: { prefix, via } })` — a hoisted relationship-resolver middleware that gates every standalone action in *one feature's* Hono app. That covers the 95% case where a domain concept (events) and the actions under it all live in the same feature directory.\n\nv0.24 lifts the namespace to the project level so it can span multiple features. A new `authz.namespaces` block on `quickback.config.ts` declares a path-prefix gate that any feature's standalone action can participate in by matching the prefix in its `path:`. One synthetic routes file, one resolver mount, one relationship match per request — regardless of how many feature directories contribute actions.\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 loads: 'events',\n exposeAs: 'event',\n },\n },\n namespaces: {\n eventScope: { prefix: '/event/:eventId', via: 'attendeeOf' },\n },\n}\n\n// features/feeds/actions/feed-moments.ts (cross-feature)\nexport default defineAction({\n path: '/event/:eventId/feed-moments',\n method: 'POST',\n // No gate boilerplate. ctx.event is typed.\n});\n\n// features/rsvp/actions/respond.ts (different feature, same namespace)\nexport default defineAction({\n path: '/event/:eventId/respond',\n method: 'POST',\n});\n```\n\nThe compiler emits one `src/routes/__namespace-event-scope.routes.ts` mounted at `/api/v1/event/:eventId/*`. The file imports each contributing feature's `actions` map under a distinct alias (`feedsActions`, `rsvpActions`), runs the `attendeeOf` resolver once per request at the head of the file, and dispatches to the matching action handler.\n\n#### Discovery is path-prefix-only\n\nNo new `namespace: 'eventScope'` field on `defineAction`. Actions opt in by matching `path:` against a declared namespace prefix — same model the table-level v0.23 form uses, just lifted to the project level. This means actions move in/out of the namespace based on their path strings, which is the simplest discovery story and matches today's convention (filenames and paths are already the discoverable surface).\n\n#### Source-feature stays the action's home for metadata\n\nOpenAPI tags, MCP tool grouping, and CMS form discovery continue to bucket each action under its source feature. Only the *runtime routes file* moves to the synthetic location — the feed-moments action is still tagged \"feeds\" in OpenAPI, the response shape doesn't change, and your generated SDK reads identically. The URL conveys the namespace membership without forcing every layer of the compiler to re-anchor the action.\n\n#### Worker-root mount order\n\nSynthetic namespace routes files register at priority `20` — ahead of per-feature mounts (priority `0`/`10`). `sortRoutesBySpecificity` keeps the order stable, and the namespace prefix's path parameter makes it sort more specific than `/api/v1/<feature>` anyway, so the middleware fires first for every request under its prefix.\n\n#### Compile-time guardrails\n\nThe same v0.23 invariants apply at the project level, with two additions:\n\n- **`via:` must point at a declared `authz.relationships[*]` entry**, and that relationship must declare `loads + exposeAs` — without `loads` there's nothing for the middleware to hydrate, and a namespace that only gates without hydrating is indistinguishable from a per-action access rule.\n- **`prefix:` must contain at least one `:param` segment** — middleware runs before input parsing, so the relationship key comes from `c.req.param()`.\n- **Same-name conflict** between `defineTable({ namespace })` and `authz.namespaces.<sameName>` is rejected. Pick one declaration site.\n- **Ambiguous prefixes** like `/a/:x` and `/a/:y` (same shape, different `:param` names) error at compile time. Strict super/sub-set relationships (e.g. `/event/:e` and `/event/:e/admin`) are fine — the harvester routes each action to the longest matching prefix.\n- **Unused namespace warning** emits `[quickback:authz]` when no standalone action's path matches a declared prefix. Not a hard error — the namespace may be staged ahead of the actions.\n\n#### Picking the right declaration site\n\nThe table-level v0.23 form is now the **single-feature shorthand**. The project-level v0.24 form is **canonical for cross-feature**.\n\n- **Use `defineTable({ namespace })`** when every action under the prefix lives in the same feature directory. The namespace travels with the table that owns it; nothing to add to `quickback.config.ts`.\n- **Use `authz.namespaces`** when the namespace spans features. The declaration sits next to your `authz.relationships` and `authz.roles` — the canonical home for cross-cutting authz config.\n\nThe two forms can't coexist for the same namespace name. If a v0.23 table-level namespace is starting to attract cross-feature actions, lift it to `authz.namespaces` — same shape, just at the project level, and the matching paths in other features will join automatically.\n\n#### Migration\n\nZero breaking changes. Nothing in v0.23 needs to change for v0.24 to land. The new field is opt-in; existing projects pick it up the moment they declare an `authz.namespaces` entry.\n\nThe harvester runs after Zod schema validation but before route generation, so unused or misconfigured namespaces surface immediately as errors or warnings rather than as silently-broken routes.\n\n#### Fixes shipped alongside\n\nThe first two were load-bearing for v0.23 namespaces to actually work — projects upgrading from a pre-fix v0.23 will see crashes/compile errors disappear on the v0.24 recompile.\n\n- **No more dual emission of namespace-claimed standalone routes.** Pre-fix, an action with a cross-feature path like `/event/:eventId/agenda/list-my-agenda` emitted into both `src/index.ts` (without the namespace resolver) and the synthetic file (with it). The plain root copy in `src/index.ts` won every URL match and `ctx.<exposeAs>` was never hydrated — every request 500'd with `Cannot read properties of undefined (reading 'id')`. `extractStandaloneActions` now skips namespace-claimed actions; the synthetic namespace file is the sole emission.\n- **Stripped-path validator no longer rejects namespace-claimed actions.** The synthetic file mounts at `/api/v1${namespace.prefix}` and strips the prefix from each action's local path. The per-action relationship-resolver was validating the *stripped* path for `:eventId`, finding nothing, and rejecting every namespace-mounted action with \"action's surface exposes neither a path parameter ':eventId' nor an input field 'eventId'\". `planRelationshipResolver` now receives the namespace's `via` and skips its surface-key check entirely — the hoisted middleware is the single source of truth.\n- **Broadcaster DO migration tag consistent across `realtime.mode`.** Inline-mode emission was already going through `qb-do-${className}` + `new_sqlite_classes`. Separate-mode was still hardcoded `tag = \"v1\"` + `new_classes`, so flipping `realtime: { mode }` produced different migration tags for the same DO class and tripped CF error 10074 (\"class already depended on\") on cross-mode deploys. Both modes now emit `tag = \"qb-do-Broadcaster\"` + `new_sqlite_classes`.\n- **Batch handler id arrays type-derive from the input parser.** Pre-fix, `validIds`, `recordMap`, and `validEntries` in bulk-delete / bulk-update / bulk-upsert were hardcoded `string[]` / `Map<string, any>` even when the table's PK column was `integer(\"id\")` — 274× TS2769 in projects mixing string and integer PKs. Handlers now declare `type IdT = typeof ids[number]` (or `typeof records[number]['id']`) and use it for the local id types. Strings stay strings, integers stay integers, no emitter knowledge of the PK column type required.\n- **`ctx` in action handlers is now `AppContext`, not `any`.** Both `StandaloneExecuteParams.ctx` and `RecordExecuteParams.ctx` in the generated `<feature>/.quickback/define-action.ts` are typed `AppContext`. AppContext keeps its `[key: string]: any` index signature so hydrated namespace keys (`ctx.event`, `ctx.<exposeAs>`) stay accessible without TS2339; named fields (`userId`, `activeOrgId`, `roles`, `authenticated`, `user`) get autocomplete and type-checking. Cleared ~49× TS2339 in generated projects.\n- **`c.get('ctx') as AppContext` in every emitted route handler.** Pre-fix, `const ctx = c.get('ctx')` returned `any`, so `ctx.roles?.some(r => …)` left the callback parameter implicitly `any` — 16× TS7006. Now `ctx.roles` is `string[] | undefined`, `r` is `string`, no callback annotation needed.\n\n#### Deferred (tracked, not blocking)\n\n- Per-namespace narrow typing of `ctx.<exposeAs>` (so `ctx.event` resolves to `typeof events.$inferSelect` instead of `any`). The compiler emits a typed cast at the `execute()` call site in the routes file today, which type-checks the call but not the handler body. Full narrow typing requires per-namespace helper emission (one `define-action.<namespace>.ts` per namespace, or a generic param threading through the action config). Tracked separately.\n\n---\n\n## v0.23.0 — May 19, 2026\n\n### Authz relationships: compile-time guarantees, less boilerplate, hoisted middleware\n\nThis release closes the gap between what `authz.relationships` *promised* in v0.19 and what it actually enforced. Every documented invariant is now a real compile-time check; every per-action ergonomic friction has a fix. Net effect: relationship-based authorization feels native — declare the relationship once, use the role anywhere, the compiler does the wiring.\n\n#### Compile-time guarantees (the authz `firewall` parity)\n\nThe org/owner/team firewall has always been compile-time-checked: a routed resource without a scope fails the compile, full stop. As of this release, `authz.relationships` carries the same guarantees:\n\n- **Bad `via:` names fail at parse time.** A typo in a firewall predicate (`firewall: [{ field: 'eventId', via: 'guestOff' }]`) used to surface deep inside the firewall generator after most validation had passed. It's now caught alongside the `authz.roles` `via:` validation, same layer, same error format.\n- **Relationship-from tables can't opt out.** The doc at `define/types/authz.ts:73-74` always said a relationship `from:` table with `firewall: { exception: true }` \"refuses to compile\" — that's now enforced. Without this check, every `via:` subquery that pivots through an exception-marked table loses tenant isolation and can return rows from other tenants.\n- **`allowResourceMigration` is now mandatory** when the relationship's `resource.column` is on a writable update endpoint. A guest doing `PATCH /messages/:id { eventId: <other-event-id> }` to migrate a row out of their access scope used to slip past the runtime — it now fails compile with a three-option remediation (set the flag, mark the column immutable, or drop it from the guards.updatable allowlist).\n- **`via: string[]` in firewall predicates.** \"Member of attendees OR speakers\" no longer requires inventing a composite role just to use it once in a firewall — `firewall: [{ field: 'eventId', via: ['attendeeOf', 'speakerOf'] }]` lowers to an OR-combined subquery.\n\n#### Less boilerplate: auto-derivation + realtime resolver\n\n- **`resource.column` auto-derives from FKs.** Omit it and the compiler scans the relationship's `from:` table for foreign-key columns, drops the `subject.column`, and picks the remaining FK. One match → auto; zero or many → error with the candidate list. Pattern mirrors the existing firewall auto-detection.\n- **`realtime.requiredRoles` accepts authz roles.** Previously a relationship-role in `realtime.requiredRoles` fell through with a misleading \"unknown role\" error. The compiler now flattens declared authz roles into their composing Better Auth roles before the realtime ticket-handshake sees them. Relationship-only roles (no static BA fallback) emit a `[quickback:authz]` warning and fail-close at handshake — the row-stream firewall continues to enforce the relationship dimension on the data side.\n\n#### Record-based actions can finally use relationship-roles\n\nThe v0.19 fail-closed hardening had an unintended side effect: a record-based action with `access: { roles: ['attendee'] }` (where `attendee` was a relationship-role) 403'd every caller, including the legitimate ones. The runtime helper couldn't evaluate `relationship:` arms, so it fail-closed correctly — but the inline match expression that *would* evaluate the relationship was never wired up for record-based actions.\n\nThis release routes record-based actions with relationship arms through the same inline access generator the resource CRUD path already uses. `roles: ['attendee']` on `/applications/:id/recap` now actually checks whether the caller is an attendee, with the loaded record in scope. Non-relationship access trees keep the runtime path unchanged.\n\n#### Typed `ctx.<exposeAs>` in action handlers\n\nWhen a relationship declares `loads: 'events', exposeAs: 'event'`, the runtime hydrates `ctx.event` with the loaded row — but the static type was always `any`, so handlers had to write `const event = ctx.event as typeof events.$inferSelect`. As of this release, when an action's access references **exactly one** relationship with `loads + exposeAs`, the compiler emits the cast for you at the execute() call site. Handlers read `ctx.event` with the right shape; no per-handler boilerplate.\n\nMulti-arm OR actions (referencing two relationships with hydration) keep the `any` shape — we can't statically know which arm matched.\n\n#### New: `defineNamespace` — one mount, one resolver, many actions\n\nThe marquee Wave 3 change. Today's pattern for \"five standalone actions under `/event/:eventId/*` all gated by `attendeeOf`\" requires writing the same inline relationship resolver in each action — and pays the resolver cost (one subquery, one row-load) on every request, multiplied by N actions. The new `namespace` field on `defineTable` hoists the resolver into a single Hono middleware mount:\n\n```ts\n// features/events/events.ts\nexport default defineTable(events, {\n firewall: [...],\n crud: { ... },\n namespace: {\n prefix: '/event/:eventId', // absolute URL path the mount covers\n via: 'attendeeOf', // relationship gate\n },\n});\n\n// features/events/actions/post-announcement.ts\nexport default defineAction({\n path: '/event/:eventId/announcements',\n method: 'POST',\n // No relationship-gate boilerplate. ctx.event is typed\n // `typeof events.$inferSelect` inside execute().\n});\n```\n\nThe compiler:\n1. Emits one `app.use('/:eventId/*', async (c, next) => { /* relationship resolver */; await next(); })` at the head of the feature's standalone-routes file (path-prefix stripping handles the feature mount).\n2. Skips the inline relationship resolver in every per-action handler under the prefix — the middleware already ran it.\n3. Hydrates `ctx.event` once per request and threads the typed cast into every namespace action's execute() call.\n\n**Validation guardrails:**\n- `namespace.via` must point at a declared `authz.relationships[*]` entry.\n- The referenced relationship must declare `loads + exposeAs` — without `loads` there's nothing for the middleware to hydrate, and the namespace gate would be indistinguishable from a per-action access rule.\n- `namespace.prefix` must contain at least one `:param` segment — the middleware reads the relationship key from `c.req.param()`, not from request body (body parsing hasn't run at middleware time).\n\n**Scope (v1):**\n- Namespace lives within a single feature's Hono `app`; cross-feature shared namespaces are deferred to v2.\n- One namespace per `defineTable` declaration; multiple namespaces in a feature mount as siblings.\n- For namespace actions whose access references additional relationships beyond the namespace's via, the inline resolver still fires for those — namespace handles only its own.\n\n#### Migration\n\nNothing in v0.20 → v0.23 breaks existing code that compiles cleanly. The new errors fire only against patterns that were already latent bugs:\n\n- A `via:` typo that previously surfaced as a deep codegen error now surfaces at parse time, same message.\n- A `firewall: { exception: true }` on a relationship-from table now errors; this configuration was always documented as unsupported.\n- A relationship's `resource.column` writable on the resource's UPDATE endpoint now errors unless `allowResourceMigration: true` is set; previously this was a runtime escape hatch.\n- Record-based actions with `roles: ['<relationship-role>']` previously 403'd every caller; they now work as the v0.19 docs originally promised.\n\n#### Why this matters\n\nAuthz relationships are how Quickback expresses \"the caller is allowed to touch this resource because of a row in *that* table\" — guest-of-event, member-of-organization, scorer-of-interview. Until now, the feature worked but had sharp edges: typos surfaced late, the documented exception-not-allowed constraint wasn't enforced, and the namespace pattern (which most apps with nested resources end up wanting) required repeating the same gate in every action. This release brings authz to parity with the org/owner/team firewall: declare it once, the compiler enforces it everywhere, the runtime emits exactly one query per request.\n\n---\n\n## v0.22.0 — May 19, 2026\n\n### Quickback Stack is Cloudflare-only: one runtime, two databases, one auth provider\n\nWe've focused the platform on the stack we actually believe in: **Cloudflare Workers + Hono + Better Auth**, with **Cloudflare D1** or **Neon** as the database. Providers and modes that targeted non-Cloudflare backends are gone. The result is a smaller concept set, fewer footguns, and clearer docs.\n\n#### What's been removed\n\n- **Runtimes**: `bun` and `supabase-edge` are no longer supported. The only runtime is `cloudflare`. Local development for compiled projects has always used `wrangler dev` — that's unchanged.\n- **Databases**: `supabase`, `libsql`, `better-sqlite3`, `bun-sqlite` are removed. Use `cloudflare-d1` for SQLite at the edge or `neon` for PostgreSQL via Hyperdrive.\n- **Auth providers**: `supabase-auth` is removed. `better-auth` is the default; `external` (Cloudflare service binding) remains for advanced setups.\n- **Template**: `template: 'nextjs'` is removed from the public config type. It was never fully implemented. The only template is `'hono'`. If you need a Next.js frontend, bring it as a separate deploy and call the Quickback API, or drop a static export into the `apps:` mount.\n- **Quickback for Supabase RLS** product line is retired. The compiler no longer emits Supabase Row Level Security policies. The `/products/quickback-supabase-rls/` and `/for/supabase-users/` pages have been removed from the marketing site, and the `compiler/targets/supabase-rls/` docs section has been deleted.\n\n#### Account UI: one delivery mode\n\nThe standalone `quickback-better-auth-account-ui` npm package has been **deprecated** and the upstream GitHub repo (`Kardoe-com/quickback-better-auth-account-ui`) has been **archived**. Account UI is now exclusively delivered the way 99% of projects already use it: the compiler builds it from source and bundles it into your Worker.\n\n- `account: { domain: 'auth.example.com', ... }` in `quickback.config.ts` — that's the entire integration story.\n- The compiler builds the SPA inside Docker with your branding and feature flags baked in, emits hostname-based routing, and wires cross-subdomain cookies automatically.\n- The three standalone delivery-mode docs (`stack/account-ui/standalone`, `library-usage`, `worker`) are removed; the remaining pages explain the compiler-bundled flow.\n\nIf you previously deployed the standalone Account UI Worker against a Quickback backend, switch to `account: { domain }` in the config — same end result, one less deploy.\n\n#### `VITE_AUTH_ROUTE` hardcoded to Quickback\n\nThe `VITE_AUTH_ROUTE` env var (which used to switch between `quickback` and `better-auth` routing dialects) is gone. The auth-client always uses Quickback's namespaced routes (`/auth/v1`, `/api/v1`, `/storage/v1`). Generic Better Auth backends are no longer a supported target. Removing the var also closes a known footgun where setting the wrong value silently 404'd every auth call.\n\n#### New: every config option is now discoverable\n\nWhen you bootstrap a project, the kitchen-sink marker block in `quickback.config.ts` lists every option Quickback supports — with descriptions and sensible defaults — commented out for you to copy above the marker as needed. Three top-level options were missing from this discovery surface and are now included:\n\n- **`apps`** — mount your own prebuilt SPA on its own hostname (`apps: { www: { domain: 'www.example.com', aliasDomains: ['example.com'] } }`). Drop the build at `quickback/apps/<name>/` and the compiler serves it from your Worker alongside the API. Reserved names: `cms`, `account`, `public`.\n- **`security`** — HTTP security headers (CSP, COOP, COEP, HSTS, Referrer-Policy, Permissions-Policy, X-Frame-Options). Set `security: false` to suppress everything; defaults are sensible for the embedded SPAs.\n- **`authz`** — relationship-based authorization roles. Declare joins between the caller and a resource column, then bind role names to those joins for use in `access: { roles: [...] }`.\n\n#### Migration\n\nProjects that compile cleanly against v0.21 and use any of these providers will hit a clear error at compile time:\n\n```\nUnknown database provider: \"supabase\". Available: cloudflare-d1, neon\n```\n\nTo migrate:\n\n1. **From Supabase**: switch `providers.database` to `cloudflare-d1` or `neon`, and `providers.auth` to `better-auth`. Your `defineTable()` definitions transfer as-is; the security DSL (firewall, access, guards, masking) compiles to Better Auth + Drizzle queries instead of RLS policies.\n2. **From Bun runtime / `bun-sqlite`**: switch `providers.runtime` to `cloudflare` and `providers.database` to `cloudflare-d1`. Local dev becomes `wrangler dev`.\n3. **From libsql / Turso**: switch to `cloudflare-d1` or `neon`. Both run natively from Cloudflare Workers via the right binding.\n4. **From `template: 'nextjs'`**: deploy Next.js separately and call the Quickback API, or drop a static export into `apps:`.\n\n#### Why this matters\n\nThe Quickback Stack is the Supabase alternative for Cloudflare. Every Quickback project ships a Hono API, an Account SPA, a CMS SPA, optional realtime/storage/queues — all built from one config and bundled into one Worker. Keeping that promise focused is more valuable than supporting deployment targets that don't share the runtime.\n\n---\n\n## v0.21.0 — May 19, 2026\n\n### Auto-firewall column swap: `ownerId` is now canonical on feature tables, `userId` warns\n\nThe compiler's default auto-firewall column for feature tables flips from `userId` to `ownerId`. This closes a long-standing footgun where a `userId` column meaning \"a user this row references\" (a member, a contact, an invitee) got silently clobbered with `ctx.userId` on insert, because the wrapper matched purely on column name across every table in the project.\n\n**What changed in the compiler**\n\n- `BETTER_AUTH_DEFAULTS.owner.column`: `'userId'` → `'ownerId'`. Schemas with an `ownerId` column auto-resolve to `firewall: [{ field: 'ownerId', equals: 'ctx.userId' }]` and have `ownerId` auto-stamped on insert.\n- The generated `OWNER_SCOPE_RULES` in `src/lib/scoped-db.ts` is seeded with `ownerId` instead of `userId`. Schemas that don't explicitly name `userId` in a `firewall:` block no longer trigger the global `userId`-stamping rule — the most common collision goes away without renames.\n- A new compile-time warning fires when a feature table carries both an auto-resolved isolation column AND a `userId` column. The warning recommends renaming the column to `linkedUserId` (or similar) if it's informational, or declaring `firewall: [{ field: 'userId', equals: 'ctx.userId' }]` if it really is the access boundary on that table.\n- The targeted compile-time error for \"the only candidate column is `userId`\" now points users at `ownerId` and the explicit-firewall escape hatch. The previous error wording (which assumed `ownerId` was business-logic) is removed.\n\n**What stayed the same**\n\n- Better Auth's own internal tables (`session`, `account`, `member`, `passkey`, `subscriptions`) still use `userId` by convention. They aren't feature tables and don't pass through the auto-firewall.\n- Explicit `firewall: [{ field: 'userId', equals: 'ctx.userId' }]` declarations continue to work and are still recognized as the \"owner\" pattern in the generated comment header.\n- The `USER` pseudo-role validator behaviour is unchanged; only the error-message wording flips to lead with `ownerId` and list `userId` as the explicit fallback.\n- Audit-wrapper (`createdBy` / `modifiedBy`) behavior is untouched.\n\n**Migration**\n\nProjects that auto-firewalled on a `userId` column will see a hard error on next compile telling them which table is affected, with two suggested fixes:\n\n1. **Recommended**: rename the column to `ownerId` in the schema. Cleanest semantics — readers immediately understand the column is access-control.\n2. **Explicit firewall**: keep the `userId` column and add `firewall: [{ field: 'userId', equals: 'ctx.userId' }]` to the resource. The auto-stamping and auto-scoping still happen; you've just opted in by name.\n\nProjects that have a `userId` column meaning \"a user this row references\" no longer need the `linkedUserId` rename workaround — auto-stamping won't touch the column unless you name it in a firewall block. The new warning makes this audit-discoverable.\n\n**Caveat (deferred)**: explicit `firewall: { owner: { column: 'X' } }` declarations still populate the project-global `OWNER_SCOPE_RULES` list, so a hand-named owner column on one resource will still match by name on every other table that happens to have a column called `X`. A future release will make scope-rule resolution per-table rather than project-global. The warning text calls this out so callers know what to expect.\n\n---\n\n## v0.20.0 — May 19, 2026\n\n### CMS + Account SPAs: shadcn base-ui migration, central Tailwind config\n\nBoth first-party SPAs are now on the shadcn **base-ui** variants (`@base-ui/react`) instead of the Radix-based primitives, applied via shadcn preset **`bdvxIkMq`** (style `base-mira`, `baseColor: zinc`, `iconLibrary: remixicon`, Inter Variable font). The migration also collapses the previously duplicated per-SPA theme + `components.json` into a single source at `packages/ui/`.\n\n#### Single source of truth in `packages/ui/`\n\nBoth SPAs were independently declaring the same `@theme` / `:root` / `.dark` token blocks in their own `app.css`, and each had its own `components.json` pointing at non-existent local component directories. That's gone:\n\n- `packages/ui/styles/theme.css` — the only place tokens live. Includes the base-mira palette, sidebar + chart tokens, and the Inter font import.\n- `packages/ui/components.json` — the only shadcn config in the repo. Future `pnpm dlx shadcn@latest add <name>` runs from `packages/ui/`.\n- `packages/cms/app/app.css` and `packages/account/app/app.css` reduce to two imports plus SPA-specific layers (CMS keeps its AG Grid + richtext-display overrides). `packages/{cms,account}/components.json` deleted.\n\n#### Components, icons, deps\n\n- All 22 shadcn primitives regenerated against `@base-ui/react` (`@radix-ui/*` removed everywhere). `Drawer` stays on `vaul` — base-ui has no Drawer primitive.\n- Icons migrated from `lucide-react` to `@remixicon/react` line variants across ~100 source files (`Plus → RiAddLine`, `ChevronDown → RiArrowDownSLine`, `X → RiCloseLine`, etc.). `lucide-react` removed from all `package.json` + `deps-spa-*` files.\n- `pnpm.overrides` pin `@types/react ^19.2.0` workspace-wide to resolve the duplicate-React-types conflict introduced by `@base-ui/react`'s bundled type peer.\n- Per-SPA deps and the Docker build mirrors (`apps/compiler/deps-spa-{cms,account}-package.json`) both gain `@base-ui/react`, `@remixicon/react`, `@fontsource-variable/inter`, and bump `shadcn` to `^4.7.0`.\n\n#### Backwards-compat `asChild` shim\n\nBase-ui replaces Radix's `asChild` boolean with a `render={\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",
@@ -81,17 +81,29 @@ export const DOCS = {
81
81
  "title": "Actions",
82
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 orgId: { equals: \"$ctx.orgId\" }\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- platform admin gate (`ctx.userRole === \"admin\"`)\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, orgId)\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## 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, details?)`.\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
+ "compiler/definitions/arrows": {
85
+ "title": "Arrows",
86
+ "content": "A relationship answers *\"does the caller have a row linking them to this\nresource?\"* An **arrow** answers a different question: *\"the caller has\nauthority over **another** object — does that authority **flow across a\nforeign key** to this one?\"* An event's announcements inherit the authority\nof the event's organization; a folder's documents inherit the authority of\nthe folder; a child section inherits the authority of its ancestors.\n\nAn arrow is a declared **FK hop**: it names a foreign-key column on a `from`\ntable and the `to` table that FK resolves to. Referenced from a permission,\nit resolves the row's FK to its target object and requires a permission\n**there** — SpiceDB's `relation->permission`, lowered to SQL. Two emit\nshapes: a single FK hop lowers to a subquery; a self-referential hop\n(`folder.parentId -> folder`) lowers to a depth-bounded `WITH RECURSIVE` CTE.\n\n## Declaring arrows\n\nArrows live in `quickback.config.ts` under `authz.arrows`, alongside\n`authz.relationships` and `authz.permissions`:\n\n```typescript\n// quickback.config.ts\n\nexport default defineConfig({\n // ...providers...\n authz: {\n arrows: {\n // single FK hop: an event row → the organization that owns it\n eventOrg: { from: 'event', fk: 'organizationId', to: 'organization' },\n // self-referential hierarchy: a folder → its parent folder\n folderTree: { from: 'folder', fk: 'parentId', to: 'folder', recursive: true },\n },\n permissions: {\n 'org:admin': { anyOf: [{ role: 'admin' }, { role: 'owner' }] },\n // org admins of an event's org inherit access to the event\n 'event:view': { anyOf: ['organizerOf', { arrowRef: 'eventOrg', permission: 'org:admin' }] },\n // anyone who can administer an ancestor folder can read this folder\n 'folder:read': { anyOf: [{ arrowRef: 'folderTree', permission: 'org:admin' }] },\n },\n },\n});\n```\n\n| Field | Meaning |\n|---|---|\n| `from` | Source table the FK column lives on. |\n| `fk` | Foreign-key column on `from`. **For a non-recursive arrow this is the tenant column** the claim binds against (see below); for a recursive arrow it is the recursion pointer (`parentId`). |\n| `to` | Target table the FK resolves to. A self-hop has `from === to`. |\n| `recursive?` | Forces the recursive-CTE lowering. When `from === to` the compiler auto-detects recursion even if this is omitted. Default `false`. |\n| `maxDepth?` | Per-arrow recursion bound (positive integer). Ignored for non-recursive arrows. Default is the global bound, `8`. |\n| `tenantColumn?` | The tenant column the seed of a **recursive** arrow binds the org claim against — defaults to `organizationId`. Set it when the hierarchy table spells the column differently (e.g. `organisationId`). Ignored for non-recursive arrows. |\n\n## Referencing an arrow from a permission\n\nAn arrow is never used directly. It is a **leaf** inside a\n[permission](/compiler/definitions/permissions) expression, written as\n`{ arrowRef: '<name>', permission: '<perm-at-target>' }`:\n\n```typescript\n'event:view': { anyOf: ['organizerOf', { arrowRef: 'eventOrg', permission: 'org:admin' }] },\n```\n\nRead it as: *\"`event:view` holds if the caller is an `organizerOf` the\nevent, **or** if — hopping across `eventOrg` to the event's organization —\nthe caller has `org:admin` **there**.\"* The `permission` named on the leaf is\nthe permission required **at the target object**, and it participates in the\npermission composition graph (resolution + cycle detection) exactly like a\n`{ permissionRef }`.\n\n**M2 target restriction.** The target permission must reduce to\n**org-membership roles** (`admin` / `owner` / `member`) — directly or\nthrough a `permissionRef` / `anyOf` / `allOf` of org roles. That's what lets\nthe hop bind to the caller's verified active-org claim (`ctx.activeOrgId`).\nA target permission that references a relation, a scoped role, a pseudo-role,\na `not`, or a nested arrow is a **compile error** in M2 (never a silent\nallow) — those richer targets are a documented fast-follow. So\n`org:admin = anyOf(role('admin'), role('owner'))` is the canonical target.\n\n## Using the permission in a firewall\n\nThe permission that contains the arrow is referenced from a resource's\n[`firewall`](/compiler/definitions/firewall) with a `{ field, permission }`\narm, like any other named permission. `field` is the resource-side column the\nlowered subquery constrains:\n\n```typescript\n// features/event-documents/event-documents.ts\nfirewall: {\n all: [\n { field: 'eventId', permission: 'event:view' },\n { field: 'deletedAt', isNull: true },\n ],\n}\n```\n\nThe arrow arm of `event:view` lowers to an FK-hop subquery on `eventId`; the\nrelationship arms (`organizerOf`) lower to relationship subqueries; the\n`anyOf` OR's them under the null-safe empty-guard (`anyGuarded`) so an absent\nclaim **denies** rather than reading the whole table.\n\n## Emit shape 1 — non-recursive (FK-hop subquery)\n\nFor `eventOrg = { from: 'event', fk: 'organizationId', to: 'organization' }`\nwith target permission `org:admin`, an `{ arrowRef: 'eventOrg' }` arm on a\nresource constrained by `eventId` lowers to:\n\n```sql\nWHERE event_documents.eventId IN (\n SELECT event.id FROM event\n WHERE event.organizationId = ? -- ? = ctx.activeOrgId (signed claim)\n )\n```\n\nIn Drizzle terms:\n\n```typescript\ninArray(event_documents.eventId,\n db.select({ x: event.id }).from(event)\n .where(eq(event.organizationId, ctx.activeOrgId!)))\n```\n\nThe seed of every non-recursive hop binds the **`fk` column** to the active-org\nclaim — so for a non-recursive arrow, **`fk` is the org/tenant column on\n`from`**, not an unrelated FK. (A self-FK hierarchy is the recursive case\nbelow; that's where `fk` is a recursion pointer and the tenant column is\nseparate.)\n\n## Emit shape 2 — recursive (bounded `WITH RECURSIVE` CTE)\n\nA self-referential arrow expresses **inherited authority down a hierarchy**:\na row is visible if the caller controls it directly **or** controls any of\nits ancestors. For `folderTree = { from: 'folder', fk: 'parentId', to: 'folder', recursive: true }`\nthe arrow lowers to a recursive CTE bounded by `maxDepth`:\n\n```sql\nWITH RECURSIVE __arrow_closure(id, depth) AS (\n -- seed: the folders the caller directly controls (tenant-constrained)\n SELECT folder.id, 0 FROM folder\n WHERE folder.organizationId = ? -- ? = ctx.activeOrgId\n UNION ALL\n -- step: walk parent → child, RE-constraining tenancy on every walked row\n SELECT folder.id, c.depth + 1\n FROM folder JOIN __arrow_closure c ON folder.parentId = c.id\n WHERE c.depth < 8 AND folder.organizationId = ?\n)\nSELECT id FROM __arrow_closure\n```\n\nBoth D1 (SQLite) and Neon (Postgres) speak `WITH RECURSIVE`, so the same\narrow is valid on either provider. Drizzle interpolates the column/table\n**objects** (dialect-correct identifiers) and binds the claim as a\n**parameter** — never string-concatenated, so an arrow is never an injection\nsurface (the FK column and tables are compile-time identifiers; the only\nruntime value is the signed org claim).\n\n## Tenant isolation semantics\n\nArrows are tenant-safe by construction. Three guarantees, all enforced at\nthe SQL level:\n\n- **The seed is tenant-constrained.** The CTE root (and the non-recursive\n hop's `WHERE`) binds the tenant column to `ctx.activeOrgId`. A caller only\n ever seeds the closure with rows in their own org.\n- **The recursive arm re-constrains tenancy on *every* walked row** — not\n just the seed. The step is `JOIN __arrow_closure c ON folder.parentId = c.id`\n **`AND folder.organizationId = ctx.activeOrgId`**. A row that was reparented\n under an in-tenant parent but whose **own** org differs is excluded. This is\n defense-in-depth: cross-org inheritance must never happen, and the SQL\n enforces it regardless of what the write path allows. Strict per-row\n tenancy is the correct default for an org-membership arrow.\n- **A missing claim fails closed.** When `ctx.activeOrgId` is null (anonymous\n or cross-tenant caller), the subquery short-circuits to `sql\\`1 = 0\\`` —\n a deny, never an unconstrained read and never an `undefined` bind.\n\n## Bounded recursion\n\nRecursion is **always** finite. The recursive arm's `WHERE c.depth < maxDepth`\ncaps the walk so a deep or cyclic hierarchy can never run away. The bound is\nresolved with this precedence:\n\n1. Per-permission override — `authz.permissionMaxDepth['<perm>']`.\n2. Per-arrow `maxDepth`.\n3. The global default, **8**.\n\n```typescript\nauthz: {\n arrows: {\n sectionTree: { from: 'sections', fk: 'parentId', to: 'sections', recursive: true, maxDepth: 6 },\n },\n permissions: {\n 'section:inTree': { anyOf: [{ arrowRef: 'sectionTree', permission: 'org:admin' }] },\n },\n // optional: raise the bound for one permission without touching the arrow\n permissionMaxDepth: { 'section:inTree': 16 },\n}\n```\n\nAn author who **explicitly opts out** of the bound — `unbounded: true` —\nwith no token-closure path is a **compile error**: there is no safe finite\nSQL for unbounded recursion, so the compiler refuses to emit a\nnon-terminating CTE. The fix is to set a `maxDepth`. Quickback never silently\nallows an unbounded traversal.\n\n## Worked example — q-events\n\nThe `q-events` example ships both shapes.\n\nA **recursive** self-FK on the `sections` feature. `sections.parentId`\npoints back at `sections`; access to an ancestor section confers access to\nall descendants:\n\n```typescript\n// quickback.config.ts\nauthz: {\n arrows: {\n sectionTree: { from: 'sections', fk: 'parentId', to: 'sections', recursive: true, maxDepth: 6 },\n },\n permissions: {\n 'org:admin': { anyOf: [{ role: 'admin' }, { role: 'owner' }] },\n 'section:inTree': { anyOf: [{ arrowRef: 'sectionTree', permission: 'org:admin' }] },\n },\n}\n\n// features/sections/sections.ts — the permission arm rides alongside the org scope\nfirewall: {\n all: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'id', permission: 'section:inTree' }, // emits the tenant-gated WITH RECURSIVE CTE\n { field: 'deletedAt', isNull: true },\n ],\n}\n```\n\nThe org `equals` arm and the recursive arrow's per-row tenant re-constraint\nare belt-and-suspenders — both pin the closure to the caller's org. The arrow\nadds the *ancestor-authority* dimension on top of the flat org scope.\n\n## Reference\n\n```typescript\n// authz.arrows.<name>\ninterface ArrowDefinition {\n from: string; // source table the FK lives on\n fk: string; // FK column (non-recursive: the tenant column; recursive: the parent pointer)\n to: string; // target table the FK resolves to (self-hop: from === to)\n recursive?: boolean; // force the recursive-CTE lowering (auto when from === to)\n maxDepth?: number; // per-arrow recursion bound (default 8)\n tenantColumn?: string; // recursive-seed tenant column override (default 'organizationId')\n}\n\n// referenced from a permission as a leaf:\n{ arrowRef: '<arrowName>', permission: '<permissionAtTarget>' }\n\n// per-permission depth override (overrides per-arrow maxDepth + the global 8):\nauthz.permissionMaxDepth?: Record<string, number>\n```\n\n- Every `{ arrowRef }` in a permission must name a declared `authz.arrows[*]`\n entry, and the arrow's `fk` / `to` are checked against the real schema at\n compile time.\n- The target `permission` must reduce to org-membership roles in M2.\n- See [Permissions](/compiler/definitions/permissions) for the expression DSL\n the arrow leaf lives in, and [Firewall — named permissions](/compiler/definitions/firewall#named-permissions-permission)\n for how the resulting `{ permission }` arm sits inside a firewall. The\n compile-time analyzer reports the subquery / CTE depth of every arrow-bearing\n permission — see [Diagnostics](/compiler/definitions/diagnostics).\n```"
87
+ },
84
88
  "compiler/definitions/concepts": {
85
89
  "title": "Glossary",
86
90
  "content": "Quick reference for terms used across the Quickback documentation.\n\n## Core Concepts\n\n| Term | Definition |\n|------|-----------|\n| **Feature** | A directory in `quickback/features/` containing related tables and actions. Example: a `candidates` feature with `candidates.ts`, `candidate-notes.ts`, and `actions.ts`. |\n| **Resource** | A table with a `defineTable()` default export. Each resource gets its own CRUD API endpoints (`GET`, `POST`, `PATCH`, `DELETE`, plus batch operations). Example: `candidates.ts` with `defineTable()` generates `/api/v1/candidates`. |\n| **Internal Table** | A Drizzle table exported WITHOUT `defineTable()`. Used as supporting data (junction tables, lookup tables) — no API routes generated. |\n| **Definition** | A TypeScript file in `quickback/features/` that defines a table schema and/or security configuration. |\n| **Compilation** | The process of transforming your definitions into production-ready code: routes, middleware, types, and migrations. |\n\n## Security Layers\n\n| Term | Definition |\n|------|-----------|\n| **Firewall** | Row-level data isolation. Automatically adds WHERE clauses (e.g., `WHERE organizationId = ?`) to every query so users only see data they should. |\n| **Access** | CRUD operation permissions. Controls which roles can perform list, get, create, update, and delete operations. |\n| **Guards** | Field-level write protection. Controls which fields can be set on create (`createable`), modified on update (`updatable`), changed only via actions (`protected`), or never changed after creation (`immutable`). |\n| **Masking** | Field-level read protection. Redacts sensitive values (SSN, email, phone) in API responses based on the user's role. |\n| **Views** | Column-level projections. Named subsets of fields (e.g., \"summary\", \"full\") with their own access control. Accessed via `GET /api/v1/{resource}/views/{name}`. |\n\n## Actions\n\n| Term | Definition |\n|------|-----------|\n| **Action** | Custom business logic endpoint beyond CRUD. Defined with `defineActions()` in an `actions.ts` file. |\n| **Record Action** | An action that operates on a specific record (`POST /api/v1/{resource}/:id/{action}`). Receives the record in the handler. Example: `POST /api/v1/applications/:id/advance-stage`. |\n| **Standalone Action** | An action not tied to a specific record (`POST /api/v1/{resource}/{action}`). Used for hiring reports, AI resume screening, bulk candidate imports. |\n| **Scoped DB** | The security-filtered database handle passed to action handlers. Automatically applies firewall, soft-delete, and org isolation. |\n| **Unsafe Mode** | When an action enables `unsafe` (prefer object form), it receives `rawDb` for explicit admin/cross-tenant operations. Cross-tenant mode requires admin role + audit trail. |\n\n## Configuration\n\n| Term | Definition |\n|------|-----------|\n| **`defineTable()`** | The function that combines a Drizzle schema with security configuration. Imported from `@quickback/compiler`. |\n| **`defineActions()`** | The function that defines custom actions for a table. Imported from `@quickback/compiler`. |\n| **`defineConfig()`** | The function that configures your Quickback project (runtime, database, auth providers). Lives in `quickback/quickback.config.ts`. |\n| **Audit Fields** | Auto-injected columns: `createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`, `deletedAt`, `deletedBy`. You don't define these — the compiler adds them. |\n| **Soft Delete** | Default delete behavior. Sets `deletedAt` instead of removing the row. Soft-deleted records are filtered from queries automatically. |\n| **Hard Delete** | Permanent row removal. Configured per-resource with `delete: { mode: \"hard\" }`. |\n\n## Infrastructure\n\n| Term | Definition |\n|------|-----------|\n| **Cloud Compiler** | The remote compilation service at `compiler.quickback.dev`. The CLI sends your definitions and receives generated code back. |\n| **Stack** | The runtime infrastructure (Cloudflare Workers, D1, KV, R2, Better Auth) where your compiled API runs. |\n| **Template** | A pre-configured project starter (`cloudflare`, `bun`, `turso`) created by `quickback create`. |"
87
91
  },
92
+ "compiler/definitions/diagnostics": {
93
+ "title": "Diagnostics",
94
+ "content": "Quickback compiles your authorization model into a single normalized **policy\nIR** — relations, permissions, arrows, scopes, grants, and per-resource\nfirewalls — and then runs a set of static checks over it. The analyzer never\nchanges what's emitted; it reports problems it can prove from the policy\ngraph: a permission that can never be satisfied, a scoped role no grant\nreaches, a resource that hands a scope role more than its profile allows, a\nnegation that can silently pass.\n\n## The console channel\n\nDiagnostics render to the existing `[quickback:authz]` / `[quickback:authn]`\nconsole channel — the same prefix the compiler has always used for security\nwarnings, so any CI grep you already key on keeps working. Each line carries\na stable, greppable **code**:\n\n```\n[quickback:authz] AUTHZ_EMPTY_PERMISSION: permission \"event:locked\" can never be satisfied — it requires organizerOf AND its negation simultaneously.\n at resource=sessions authz.permissions[\"event:locked\"]\n hint: Remove the contradictory arm, or split into separate permissions.\n```\n\nThe first line stays greppable (`[quickback:<channel>] CODE: message`); the\nsource location and fix hint render on continuation lines.\n\n## Warn by default, opt-in strict\n\nThe analyzer is **warn-by-default, compile-continues**. This is deliberate:\nthe analyzer runs on the shared compiler that serves every project, so a new\ncheck must never break an existing build on upgrade. In the default path\nevery diagnostic — *including* the one check authored at `error` severity\n(the capability ceiling) — is rendered as a warning line and the compile\nproceeds.\n\nSet **`QUICKBACK_AUTHZ_STRICT=true`** to promote every `warn` to `error`.\nUnder strict mode the compile **fails** (throws an aggregate error listing the\ncodes) if any diagnostic is — after promotion — an error. `info` lines\n(the pushdown-cost report) stay informational and never fail a build.\n\n```bash\n# warn-only (default): prints diagnostics, compile succeeds\nquickback compile\n\n# strict: any warn or error fails the compile\nQUICKBACK_AUTHZ_STRICT=true quickback compile\n```\n\n> The analyzer is compile-time only — zero runtime blast radius. A defect in\n> the analyzer itself is caught and downgraded to a single warning in the\n> default path, so an analyzer bug can never take down an otherwise-valid\n> compile. (Strict mode re-raises, because there the throw is the intended\n> hard failure.)\n\n## Authz codes\n\nThese read the permission graph projected from the policy IR. All are `warn`\nseverity (so `info` for the pushdown report) **except** the capability ceiling,\nwhich is authored as `error`.\n\n| Code | Severity | What it catches |\n|---|---|---|\n| `AUTHZ_EMPTY_PERMISSION` | warn | A permission that can never be satisfied — e.g. `allOf(a, not(a))`, which requires a fact and its negation at the same AND-level. |\n| `AUTHZ_SHADOWED_ARM` | warn | An `anyOf` arm subsumed by a broader arm: a leaf `X` and an `allOf(X, …)` in the same union — the narrower arm can never widen the result. |\n| `AUTHZ_UNREACHABLE_ROLE` | warn | A scoped role declared under `authz.scopes` with **no grant profile** — it can authorize no read, action, or channel, so it's dead config. |\n| `AUTHZ_UNREACHABLE_VIEW` | warn | A grant's `read` names a `resource:view` whose resource has no firewall — no role can reach that view. |\n| `AUTHZ_PUSHDOWN_COST` | info | Per-permission report: how many SQL subqueries the permission lowers to, plus the max recursive-CTE depth (from recursive arrows). Advisory, never fails a build. |\n| `AUTHZ_CAPABILITY_CEILING` | **error** | A resource's firewall grants a `scope:<kind>:<role>` role read access **beyond its capability profile** — either the role has no profile at all, or the profile doesn't list this resource. |\n| `AUTHZ_NOT_OVER_RESOURCE` | warn | A `not` whose operand resolves to a **resource (SQL) site** — `NOT EXISTS` over a nullable join can silently pass (the null-trap). The analyzer resolves the operand's site from its leaves, so it fires even when the lowering left the site unset. |\n\nA few codes are reserved in the diagnostic enum for the milestones that emit\nthem and don't fire on a shipped config today: `AUTHZ_UNBOUNDED_RECURSION`\n(an unbounded recursive arrow with no claim path — currently a hard compile\nerror raised at config validation, before the analyzer runs),\n`AUTHZ_UNENFORCEABLE_FACT`, and `AUTHZ_CAVEAT_SITE_MISMATCH` (M3 caveats).\n\n### The capability ceiling\n\nThe one `error`-severity authz check. It is the M0.2 deliverable that backs\n[scope grant profiles](/compiler/definitions/scopes): a scoped role is\ndeny-by-default and may touch only what its `grants` profile lists. The\nanalyzer walks every resource firewall, follows each `{ permission }` arm\ninto the permission graph to find the scope roles it references, and fails the\nbuild (in strict mode) if a resource grants a scope role access the profile\ndoesn't cover. In the default path it warns loudly. This is what makes the\ngrant profile the single auditable manifest of what an external principal can\nsee.\n\n## Authn codes\n\nFour **structural authentication** checks — proving properties over the\ngenerated route + credential surface rather than the authz policy:\n\n| Code | Severity | What it catches |\n|---|---|---|\n| `AUTHN_ROUTE_COVERAGE` | warn | A route that reaches data with an **unclassified** auth gate and isn't declared `PUBLIC` — the signup / flag-gap bug class (data delivered to an unauthenticated ctx). |\n| `AUTHN_SECRET_CONSISTENCY` | error | A credential's mint site and verify site don't share key / issuer / audience — every minted token would fail verification (the ws-ticket \"401 on every upgrade\" trap). |\n| `AUTHN_CREDENTIAL_DELIVERY` | error | A fire-and-forget credential send (the OTP-email shape) not anchored to `waitUntil` / `await` — the Worker may drop the promise and never deliver (the OTP-500 bug class). |\n| `AUTHN_CLAIM_PROVENANCE` | error | An identity `ctx` field written from **request input** rather than a credential verifier — client-asserted identity, which is forbidden. |\n| `AUTHN_SURFACE_INVARIANT` | warn / error | A surface contract breach: an `/mcp` or agent route not gated bearer-only (warn), or an `INTERNAL`-gated route mounted on an HTTP-reachable surface (error). |\n\nThese check definitions are **wired and fully unit-tested**, but their inputs\n— the per-route and per-credential metadata (`RouteNode` / `MintSite` /\n`VerifySite` / `ClaimWrite`) — are not yet emitted by the route, middleware,\nand credential generators. Until those generators emit that metadata the\nanalyzer runs the authn checks against **empty** route/credential graphs, so\nthey are effectively no-ops on a real compile. The check logic needs no change\nwhen the metadata lands — the route/credential coverage activates the moment\nthe generators emit it. The authz / permission-graph checks above run\nunconditionally today, because the policy IR is always present.\n\n## Reading the pushdown-cost report\n\n`AUTHZ_PUSHDOWN_COST` is an `info` line per permission that pushes down to\nSQL — it never fails a build, but it surfaces the query cost of an\nauthorization rule before you ship it:\n\n```\n[quickback:authz] AUTHZ_PUSHDOWN_COST: permission \"section:inTree\" lowers to 1 SQL subquery, recursive CTE depth 6 (sites: resource).\n```\n\nA high subquery count or a deep recursive CTE (from a recursive\n[arrow](/compiler/definitions/arrows)) is a signal to reconsider the rule —\nnot an error, but worth a look.\n\n## See also\n\n- [Permissions](/compiler/definitions/permissions) — the `anyOf` / `allOf` /\n `not` DSL the empty / shadowed / not-over-resource checks analyze.\n- [Arrows](/compiler/definitions/arrows) — recursive-CTE depth feeds the\n pushdown-cost report; the unbounded-recursion guard is a hard error.\n- [Scopes & capability grants](/compiler/definitions/scopes) — the grant\n profiles the capability-ceiling check enforces.\n- [Firewall](/compiler/definitions/firewall) — the `{ permission }` arms the\n ceiling check follows into the permission graph.\n```"
95
+ },
88
96
  "compiler/definitions/feature": {
89
97
  "title": "feature() — single-export sugar",
90
98
  "content": "The `q.table()` + `defineTable()` pair has been co-equal with Drizzle since day one. It works, but it means two exports and two concepts for something most feature files treat as one unit: a table with a security contract.\n\n`feature()` collapses both into a single default export.\n\n## Before\n\n```ts title=\"quickback/features/contacts.ts\"\n\nexport const contacts = q.table(\"contacts\", {\n id: q.id(),\n organizationId: q.text().required().index(),\n address: q.text().required().index(),\n name: q.text().optional(),\n});\n\nexport default defineTable(contacts, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: { access: { roles: [\"member+\"] } },\n create: { access: { roles: [\"member+\"] } },\n update: { access: { roles: [\"member+\"] } },\n delete: { access: { roles: [\"admin+\"] }, mode: \"soft\" },\n guards: { createable: [\"address\", \"name\"] },\n});\n\nexport type Contact = typeof contacts.$infer;\n```\n\n## After\n\n```ts title=\"quickback/features/contacts.ts\"\n\nexport default feature(\"contacts\", {\n columns: {\n id: q.id(),\n organizationId: q.text().required().index(),\n address: q.text().required().index(),\n name: q.text().optional(),\n },\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: { access: { roles: [\"member+\"] } },\n create: { access: { roles: [\"member+\"] } },\n update: { access: { roles: [\"member+\"] } },\n delete: { access: { roles: [\"admin+\"] }, mode: \"soft\" },\n guards: { createable: [\"address\", \"name\"] },\n});\n```\n\nType inference still works — `typeof import(\"./contacts\").default.$infer` gives you the `Contact` row type.\n\n## How it works\n\n`feature(name, config)` is a **compile-time sugar**, not a runtime abstraction. When the compiler sees `export default feature(...)`, it rewrites the source to the canonical two-export form before any parsing runs. Every downstream layer — dialect pass, audit injection, security contracts, generated routes, OpenAPI, MCP tools, RLS emission — runs on the same Drizzle source it always did. Zero runtime cost; zero semantic difference from `q.table()` + `defineTable()`.\n\nThat means:\n\n- **Both forms remain supported indefinitely.** Mix them freely — some files `feature(...)`, some files `q.table() + defineTable()`, some files Drizzle `sqliteTable() + defineTable()`. The compiler dispatches per file.\n- **Action files reference the table by default import.** `import contacts from \"./contacts\"` gives you the same typed handle `q.table(\"contacts\", ...)` would have returned, so `defineActions(contacts, { … })` still works.\n- **Diagnostics are identical.** Missing firewall → same warning. Protected-field wiring → same check. Nothing about `feature()` weakens the secure-by-default posture.\n\n## Aliases\n\n`q` is canonical (matches Zod's `z.`, Superstruct's `s.`). `qb` is exported as an alias if you'd rather self-document the namespace:\n\n```ts\n\nexport default feature(\"contacts\", {\n columns: { id: qb.id(), name: qb.text().required() },\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n // …\n});\n```\n\nSame object, two names — pick one.\n\n## When to use which\n\n| Pattern | When |\n|---|---|\n| `feature(name, {...})` | Default. One table, one security contract, one file. |\n| `q.table()` + `defineTable()` | Multiple tables per file (rare), or you want to reference the table identifier before the default export. |\n| `sqliteTable()` / `pgTable()` + `defineTable()` | Interop with existing Drizzle code / migrations. |\n| `q.table(...)` alone (no `defineTable`) | Internal join/lookup/pivot tables with no public API. Compiler warns so you confirm the opt-out is intentional. |\n\n## Feature directory layout\n\nA feature directory holds tables, optional shared schemas, and the handler files that back any actions:\n\n```\nfeatures/podcast/\n├── episodes.ts ← defineTable + (optional) defineActions(episodes, {…})\n├── shows.ts ← defineTable + (optional) defineActions(shows, {…})\n├── episode-tags.ts ← defineTable only (junction)\n├── _feature.ts ← non-table-bound actions + shared zod schemas\n├── handlers/\n│ ├── episodes/{publish,revertToDraft}.ts\n│ └── shows/…\n└── lib/\n └── shared.ts ← feature-local helpers, copied verbatim\n```\n\nThree things to know:\n\n- **`handlers/` walks recursively**, keyed by relative path (`handlers/episodes/publish.ts`). The canonical layout is per-table subdirectories so action handlers stay grouped with the table they act on.\n- **`lib/` rides along** — feature-local helper modules get copied verbatim into the generated output. Use this for shared utilities that both handlers and inline `execute:` bodies reference.\n- **`_feature.ts` is the universal slot** for non-table-bound actions and shared schemas. Top-level decls in `_feature.ts` get prepended once to the merged actions module, so a `const sharedSchema = z.object({…})` in `_feature.ts` is referenceable from any sibling action's `input:` without re-declaring it.\n\nFor everything action-related — three modes, conflict rules, the `_feature.ts` shape — see [Actions](/compiler/definitions/actions).\n\n## Handlers — one `q` namespace for everything\n\nCustom action handlers need to run queries against the database. Quickback's compiled projects expose the Drizzle query-builder helpers on the same `q` namespace you use for schema authoring, so handler code stays inside one DSL:\n\n```ts title=\"quickback/features/mail/handlers/inbound.ts\"\n\nexport const execute = async ({ unsafeDb, input }) => {\n // Find the mailbox this email was addressed to\n const mailbox = await unsafeDb.query.mailboxes.findFirst({\n where: q.eq(mailboxes.address, input.mailboxAddress),\n });\n if (!mailbox) return { error: \"unknown mailbox\" };\n\n // Look up the thread by in-reply-to + organization scope\n const thread = input.parsed.inReplyTo\n ? await unsafeDb.query.threads.findFirst({\n where: q.and(\n q.eq(threads.organizationId, mailbox.organizationId),\n q.eq(threads.lastMessageId, input.parsed.inReplyTo),\n ),\n })\n : null;\n\n // Insert the new message\n await unsafeDb.insert(messages).values({\n id: crypto.randomUUID(),\n threadId: thread?.id,\n organizationId: mailbox.organizationId,\n subject: input.parsed.subject,\n createdAt: new Date().toISOString(),\n });\n\n return { ok: true };\n};\n```\n\nThe `q` in handlers is a runtime re-export of Drizzle's query builder — `q.eq`, `q.and`, `q.or`, `q.not`, `q.ne`, `q.gt`, `q.gte`, `q.lt`, `q.lte`, `q.like`, `q.ilike`, `q.inArray`, `q.notInArray`, `q.isNull`, `q.isNotNull`, `q.between`, `q.desc`, `q.asc`, `q.sql`. Pure re-export, zero wrapper cost.\n\n**The compiler generates `src/lib/q.ts`** in every project so the runtime `q` is always available. You never need to `import { eq } from \"drizzle-orm\"` in a handler — though you can if you want (Quickback doesn't hide drizzle, it just offers a consistent surface that matches the schema DSL).\n\n## Why one namespace\n\nQuickback is an opinionated wrapper with opinionated security. One DSL for schema (`q.table`, `q.text`, `q.id`), one DSL for queries (`q.eq`, `q.and`, `q.gte`), one opt-in for routes (`feature()` / `defineTable`). You never need to learn the names of the underlying tools to write a feature — the same way Next.js users don't need to know they're using webpack, or Astro users don't need to know they're using Vite."
91
99
  },
100
+ "compiler/definitions/fga": {
101
+ "title": "FGA - Relationship-Based Access (Zanzibar)",
102
+ "content": "The **FGA pillar** brings [OpenFGA](https://openfga.dev) / Google Zanzibar\n**Relationship-Based Access Control (ReBAC)** to Quickback. You declare an\nauthorization model in the OpenFGA modeling DSL, store relationship tuples in a\ncompiler-owned table, and resolve graph-shaped permission checks at request\ntime — no external authorization service, all inside your Worker.\n\nIt is **opt-in** and sits alongside the role-based [Access](/compiler/definitions/access)\npillar and the lightweight [`authz.relationships`](/compiler/definitions/access#relationship-roles)\njoin-roles. Use whichever fits:\n\n| Need | Use |\n| --- | --- |\n| \"Admins can edit, members can read\" | [Access](/compiler/definitions/access) roles |\n| \"The caller has a row linking them to this record\" | [`authz.relationships`](/compiler/definitions/access) |\n| \"A recruiter is automatically a viewer; a folder's viewer can view its docs; share publicly\" | **FGA** |\n\n## When you need a permission *graph*\n\nRoles and one-hop relationship joins can't express:\n\n- **Derived** permissions — an `editor` is automatically a `viewer`.\n- **Hierarchical** permissions — a document inherits viewers from its folder.\n- **Group** permissions — every member of `team:eng` is a viewer.\n- **Per-record grants** — assign one person to one record without a global role.\n- **Public sharing** — make one object viewable by everyone, with a share link.\n\nThese are exactly what Zanzibar's *userset rewrites* and *tuple-to-userset*\nrelations solve, and what the FGA pillar gives you.\n\n## The model\n\nDeclare it with `authz.fga.model` in `quickback.config.ts`, using the OpenFGA\nmodeling DSL verbatim (the same text the OpenFGA CLI and VS Code extension\nuse):\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n // ...\n authz: {\n fga: {\n model: `\n model\n schema 1.1\n\n type user\n\n type organization\n relations\n define member: [user]\n\n type job\n relations\n define org: [organization]\n define hiring_manager: [user]\n define recruiter: [user] or hiring_manager\n define viewer: [user, user:*] or recruiter or member from org\n define can_manage: recruiter\n\n type application\n relations\n define job: [job]\n define viewer: viewer from job\n define editor: can_manage from job\n `,\n },\n },\n});\n```\n\nThe compiler **parses and validates** the model at compile time — every type,\nrelation, and `from` reference must resolve, or the compile fails loud.\n\n### DSL reference\n\n| Syntax | Meaning |\n| --- | --- |\n| `define viewer: [user]` | Direct assignment — a stored tuple grants `viewer`. |\n| `define viewer: [user, user:*]` | `user:*` = **type-bound public access** (everyone). |\n| `define viewer: [team#member]` | A **userset** — every `member` of a `team` is a `viewer`. |\n| `define viewer: [user] or editor` | **Union** — `editor`s are also `viewer`s (derived). |\n| `define viewer: editor and member` | **Intersection** — must be both. |\n| `define viewer: editor but not blocked` | **Exclusion**. |\n| `define viewer: viewer from parent` | **Tuple-to-userset** — inherit `viewer` from the `parent` object. |\n\n## Tuples\n\nA **relationship tuple** is `(user, relation, object)` — e.g.\n`(user:anne, recruiter, job:123)`. Tuples live in a compiler-owned,\n**organization-scoped** `fga_tuples` table that the compiler emits and migrates\nfor you (a Check never reads another tenant's tuples).\n\nWrite them three ways:\n\n```typescript\n// 1. In an action / handler via ctx.fga\nawait ctx.fga.write([\n { user: 'user:' + input.userId, relation: 'recruiter', object: 'job:' + record.id },\n]);\n\n// 2. Over the REST API (admin / write-role gated)\n// POST /api/v1/fga/v1/write\n// { \"writes\": [{ \"user\": \"user:anne\", \"relation\": \"recruiter\", \"object\": \"job:123\" }] }\n\n// 3. A public share link (see Public sharing below)\n```\n\n## Checking access\n\n### `ctx.fga` in handlers and actions\n\nEvery authenticated request gets an org-scoped `ctx.fga` client:\n\n```typescript\nconst allowed = await ctx.fga.check('user:' + ctx.userId, 'can_manage', 'job:' + jobId);\nconst myJobs = await ctx.fga.listObjects('user:' + ctx.userId, 'viewer', 'job'); // ['job:1', ...]\nconst tree = await ctx.fga.expand('job:123', 'viewer'); // debug the userset tree\n```\n\n### The `access: { fga }` arm — secure by construction\n\nEnforce a Check declaratively on a resource operation. The compiler fetches the\nrecord and emits an inline `ctx.fga.check(...)` gate:\n\n```typescript\nexport default feature('jobs', {\n // ...\n // Org owners/admins can edit any job, OR anyone with the FGA `can_manage`\n // relation on THIS specific job — without an org-wide admin role.\n update: {\n access: {\n or: [\n { roles: ['owner', 'admin'] },\n { fga: { relation: 'can_manage', object: 'job:{id}' } },\n ],\n },\n },\n});\n```\n\n`object` is a template — `{field}` tokens interpolate the fetched record's\ncolumns (`job:{id}` → `job:${record.id}`). On per-record operations\n(`GET /:id`, `update`, `delete`, and record-based actions) the compiler emits\nthe inline check. It is **fail-closed**: if the check can't run, access is\ndenied.\n\n### Filtering a collection by an FGA relation\n\nOn `read.access` (and named views) the `fga` arm does more than gate the\nper-record `GET /:id` — it **filters the collection `GET /`** too. The compiler\nresolves the caller's authorized object ids via the engine's `ListObjects` and\ninjects an `inArray(id, …)` into the list query *before* it runs, so the row\npage, `total`, and `hasMore` all stay correct (no fetch-then-drop that would\nbreak pagination):\n\n```typescript\nexport default feature('jobs', {\n // ...\n read: {\n // Collection GET / returns only jobs the caller is a `viewer` of;\n // GET /:id enforces the same relation per record.\n access: { fga: { relation: 'viewer', object: 'job:{id}' } },\n },\n});\n```\n\nThree access shapes are supported on a collection-filtering arm:\n\n| Access shape | Collection behavior |\n| --- | --- |\n| `{ fga }` | Always filter to the FGA-authorized ids. |\n| `{ or: [{ roles }, { fga }] }` | If the role arm passes, return all firewall-scoped rows (no FGA filter); otherwise filter to the authorized ids. |\n| `{ and: [{ roles }, { fga }] }` | If the role arm fails, return an empty page; otherwise filter to the authorized ids. |\n\nDeeper nesting (an `fga` arm under multi-level `and`/`or`, or multiple\nconflicting `fga` arms) is a **compile error** that points you at\n`POST /fga/v1/list-objects` to filter manually.\n\n**The cap.** The authorized id set is bounded by `authz.fga.listObjects.maxIds`\n(default **1000**). If a caller's authorized set exceeds the cap, the collection\nrequest fails with a hard **422 `FGA_LIST_TOO_LARGE`** whose hint points to\n`POST /fga/v1/list-objects` for paginated enumeration — never a silent partial\npage. Raise the cap or paginate via the API for collections that legitimately\nauthorize more than `maxIds` rows per caller.\n\n## Public sharing\n\nThe FGA pillar is also Quickback's public-sharing mechanism — two\ncomplementary tools.\n\n### Type-bound public access (`user:*`)\n\nA model relation that lists `user:*` (e.g. `define viewer: [user, user:*] …`)\ncan be granted to *everyone* by writing one tuple:\n\n```typescript\nawait ctx.fga.write([{ user: 'user:*', relation: 'viewer', object: 'job:' + id }]);\n```\n\nNow every Check for `viewer` on that object passes.\n\n### Share links\n\nEnable signed, unauthenticated share links:\n\n```typescript\nauthz: {\n fga: {\n model: `...`,\n sharing: {\n enabled: true,\n // The dedicated public route (always mounted): GET /share/v1/:token\n route: '/share',\n // Optional vanity base URL (also add it to your runtime `routes`).\n baseUrl: 'https://share.acme.dev',\n // Tokens never expire by default; set a TTL in seconds to expire them.\n ttlSeconds: 0,\n // Public projection: what a `job:<id>` share link may reveal, no login.\n resources: {\n job: { table: 'jobs', fields: ['id', 'title', 'department', 'status'] },\n },\n },\n },\n}\n```\n\n- **Mint** a link: `POST /api/v1/fga/v1/share` `{ \"object\": \"job:123\", \"relation\": \"viewer\" }`\n (write-role gated) → `{ token, url }`. Minting **writes the `(user:*, relation,\n object)` tuple** (making the object publicly viewable per the model) and then\n signs the link. If the relation has no `user:*` arm in the model, minting\n fails with a 400 rather than handing back a dead link.\n- **Resolve** a link: `GET /share/v1/:token` — **no authentication**. The route\n verifies the HMAC, then **checks the stored grant** (no contextual shortcut):\n the object must still have the granted `user:*` relation right now. Only then\n does it return the configured public projection. Nothing else leaks — the\n token is scoped to exactly that object and relation.\n- **Revoke** a link: delete the `(user:*, relation, object)` tuple (via\n `POST /fga/v1/write` `deletes`, or your own action). The next `GET` Check\n fails and the link stops returning content — revocation is real, not just\n token expiry.\n\n### The share URL: route, base URL, or both\n\nYou get **both** by default:\n\n- A **dedicated route** on the API origin — `…/share/v1/:token` — always\n available when sharing is enabled.\n- An optional **vanity base URL** (`share.<your-domain>`). Set\n `sharing.baseUrl` and add the host to your runtime `routes`:\n\n ```typescript\n providers: {\n runtime: defineRuntime('cloudflare', {\n routes: [\n { pattern: 'api.acme.dev', custom_domain: true },\n { pattern: 'share.acme.dev', custom_domain: true }, // share base URL\n ],\n }),\n },\n ```\n\n Minted links then use `https://share.acme.dev/v1/:token`; otherwise they use\n the API origin + the dedicated route.\n\n## REST API\n\nWhen `authz.fga` is set, the compiler mounts an OpenFGA-compatible surface at\n`/api/v1/fga/v1`, all tenant-scoped to `ctx.activeOrgId`:\n\n| Endpoint | Body | Returns |\n| --- | --- | --- |\n| `POST /check` | `{ user, relation, object, contextual_tuples? }` | `{ allowed }` |\n| `POST /list-objects` | `{ user, relation, type }` | `{ objects }` |\n| `POST /expand` | `{ relation, object }` | `{ tree }` |\n| `POST /read` | `{ object?, relation?, user? }` | `{ tuples }` |\n| `POST /write` | `{ writes?, deletes? }` | `{ ok }` (write-role) |\n| `POST /share` | `{ object, relation, ttlSeconds? }` | `{ token, url }` (write-role) |\n\n`writeRoles` (default `['admin']`) controls who can write tuples and mint share\nlinks. Pseudo-roles and `+` hierarchy suffixes are honored.\n\n## How it resolves\n\nThe embedded engine resolves a Check by walking the model: direct tuples,\ntype-bound public access (`user:*`), userset subjects (`team:eng#member`),\ncomputed usersets (union / intersection / exclusion), and tuple-to-userset\n(`viewer from parent`), plus request-scoped **contextual tuples**. It has cycle\ndetection and a configurable resolution-depth cap (`authz.fga.maxDepth`,\ndefault 25).\n\nThe engine **enforces the model's direct type restrictions at check time**: a\nstored tuple whose subject shape isn't allowed for the relation is inert. So a\n`user:*` tuple on a relation declared `[user]` (no wildcard) can never grant\naccess, even if it was written out-of-band — the model is the ceiling.\n\n## Limitations (v0.35)\n\n- `access: { fga }` covers **per-record** operations (`GET /:id`, `update`,\n `delete`, record-based actions) and **collection filtering** on\n `read.access` / views (see\n [Filtering a collection](#filtering-a-collection-by-an-fga-relation)). It is\n **not valid on `create`** (no record yet — rejected at compile) or\n **standalone actions** (use `ctx.fga.check` in `execute`).\n- **Collection filtering is bounded** by `authz.fga.listObjects.maxIds`\n (default 1000). A caller authorized for more rows than the cap gets a hard\n **422 `FGA_LIST_TOO_LARGE`**, not a partial page — paginate via\n `POST /fga/v1/list-objects` for those cases. Only the bare/`or`/`and`-with-roles\n shapes are filtered; deeper nesting is a compile error.\n- **Conditional tuples** (CEL conditions / ABAC) — the schema reserves the\n columns, but condition evaluation is not yet wired.\n- `ListObjects` enumerates candidate objects from tuples and Checks each — a\n reverse-index optimization is a planned follow-up."
103
+ },
92
104
  "compiler/definitions/firewall": {
93
105
  "title": "Firewall - Data Isolation",
94
- "content": "The firewall generates WHERE clauses automatically to isolate data by user, organization, or team.\n\n## Basic Usage\n\nThe cleanest pattern is `q.scope()` — declare the tenant column once and the firewall is auto-derived:\n\n```typescript\n// features/candidates/candidates.ts\n\nexport default feature('candidates', {\n columns: {\n id: q.id(),\n name: q.text().required(),\n email: q.text().required(),\n organizationId: q.scope('organization'), // Auto-derives the firewall\n },\n // No firewall: block needed — auto-derived as\n // [{ field: 'organizationId', equals: 'ctx.activeOrgId' },\n // { field: 'deletedAt', isNull: true }]\n // ... guards, crud, read\n});\n```\n\nIf you need to declare the firewall explicitly, two forms are accepted — pick whichever reads better:\n\n**Named-scope** (compact, default for simple overrides):\n\n```typescript\nfirewall: { organization: { column: 'tenant_id' } }\nfirewall: { owner: { column: 'account_user_id' } }\nfirewall: { exception: true } // opt out of tenant scoping entirely\n```\n\n**Predicate array** (explicit, required for `in`-lists or custom non-scope predicates):\n\n```typescript\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n]\n```\n\nBoth shapes compile to the same canonical predicate array internally — the named-scope object is coerced at parse time. Pick by readability.\n\n## Auto-detected column synonyms\n\nWhen you omit the `firewall:` block entirely, the compiler scans the schema for one of these isolation columns and auto-derives the predicates:\n\n| Scope | Accepted column names |\n|---|---|\n| Organization | `organizationId`, `organisationId`, `orgId`, `organization`, `organisation`, `org` |\n| User | `userId` |\n| Team | `teamId` |\n\n`ownerId` is **not** auto-detected — it's reserved for business-logic ownership (who owns this record), not access control. A table that has only `ownerId` and no isolation column raises a targeted error explaining the distinction; either rename to `userId` if the column controls access, add an isolation column, or specify `firewall:` explicitly.\n\n## Predicate Shape\n\n```typescript\ntype FirewallPredicate =\n | { field: string; equals: string } // column = ctx.* (or literal)\n | { field: string; isNull: true } // column IS NULL\n | { field: string; in: string[] | string }// column IN (...)\n | { field: string; via: string } // column IN (relationship subquery)\n | { exception: true }; // opt out of tenant scoping\n\ntype FirewallConfig = ReadonlyArray<FirewallPredicate>;\n\n// Resource top-level (sibling to `firewall:`)\nfirewallErrorMode?: 'reveal' | 'hide';\n```\n\nPredicates are AND'd together. `firewallErrorMode` lives at the resource top level — it's a presentation-layer choice (403 vs 404), not a query-shape one.\n\n## Relationship-based scoping (`via:`)\n\nFor relationship authorization — \"this user can see rows X if they have a confirmed `event_guests` row pointing at X\" — declare the relationship under `authz.relationships` in `quickback.config.ts`, then reference it from `firewall:` with a `via:` predicate:\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests', // table name\n subject: { column: 'userId', equals: 'ctx.userId' }, // caller side\n resource: { column: 'eventId' }, // resource side\n where: { status: 'confirmed' }, // optional row filter\n },\n },\n}\n\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' },\n]\n```\n\nCompiles to:\n\n```sql\nWHERE sessions.organizationId = ?\n AND sessions.eventId IN (\n SELECT eventId FROM event_guests\n WHERE userId = ?\n AND status = 'confirmed'\n AND <event_guests' own firewall — tenant scope + soft-delete>\n )\n```\n\nKey properties:\n\n- **Firewall stays the outermost AND.** A guest of an event in another tenant is still blocked by your tenant predicate. Relationship-based scoping never bypasses tenant isolation.\n- **The relationship table's own firewall is AND'd into the subquery.** Soft-deleting a `event_guests` row revokes access immediately; cross-tenant relationship rows can't grant access.\n- **Anonymous callers fail closed.** `ctx.userId` is null-guarded; the subquery short-circuits to `WHERE 1 = 0` for unauthenticated requests.\n- **The relationship table must be tenant-scoped** (`firewall: { exception: true }` is rejected at compile time on relationship tables).\n\nSee [Access — relationships](/compiler/definitions/access#authz-relationships) for the full `authz.relationships` shape and role-binding patterns.\n\n## Context Sources\n\nWhen `equals` references the request context, use these standard sources:\n\n| Source | Description |\n|--------|-------------|\n| `ctx.userId` | Current authenticated user's ID |\n| `ctx.activeOrgId` | User's active organization ID |\n| `ctx.activeTeamId` | User's active team ID |\n\nThese values are populated by the auth middleware from the user's session. Any predicate where `equals` starts with `ctx.` is treated as server-derived: the column lands in `GUARDS_CONFIG.systemManaged` (clients cannot submit it) and is auto-populated on create / upsert from the context.\n\n## Auto-Derivation\n\nWhen the `firewall:` block is omitted, the compiler scans the schema for known scope columns and synthesises the predicate array:\n\n| Column found | Predicate emitted |\n|--------------|-------------------|\n| `organizationId` / `organisationId` / `orgId` / `organization` / `organisation` / `org` | `{ field: '...', equals: 'ctx.activeOrgId' }` |\n| `userId` | `{ field: 'userId', equals: 'ctx.userId' }` |\n| `teamId` | `{ field: 'teamId', equals: 'ctx.activeTeamId' }` |\n| `deletedAt` (always present via audit injection) | `{ field: 'deletedAt', isNull: true }` — appended automatically whenever the schema carries the column, regardless of which firewall shape you wrote |\n\n`q.scope(kind)` is the canonical way to declare the column — auto-derivation works the same way for plain `q.text().required()` or Drizzle `text(...).notNull()` columns named to match the convention.\n\n**Rules:**\n- Exactly one isolation column → auto-derived.\n- Zero columns AND no PUBLIC route → compile-time error (\"missing isolation column\").\n- Two or more (e.g. `organizationId` + `ownerId`) → compile-time error; declare `firewall:` explicitly.\n\n## What `{ exception: true }` Actually Does\n\n`{ exception: true }` disables **tenant scoping only** — the generated `buildFirewallConditions()` emits no tenant `WHERE` clauses. It does **not** affect:\n\n- **Audit field injection.** `createdAt`, `modifiedAt`, `createdBy`, `modifiedBy`, `deletedAt`, `deletedBy` are always added to every table unless you disable them globally with `compiler.features.auditFields: false`.\n- **Soft-delete filtering.** If the table has a `deletedAt` column (which it does by default, thanks to audit injection), the firewall still emits `isNull(<table>.deletedAt)` so soft-deleted records stay hidden. To opt out of soft-delete filtering on an exception resource, either set `compiler.features.auditFields: false` globally or hand-author a schema without `deletedAt`.\n\nSo `firewall: [{ exception: true }]` on the default configuration returns `isNull(<table>.deletedAt)` from `buildFirewallConditions()` — no tenant filter, soft-delete filter still applied.\n\n## Sysadmin Escape Hatch\n\nWhen `cms: { sysadmin: true }` is set on the project (introduced in v0.15.0), every `buildFirewallConditions()` emits a runtime branch that drops tenant scopes for `ctx.userRole === 'sysadmin'` callers while keeping the soft-delete predicate:\n\n```typescript\n// Generated for an org-scoped table when cms.sysadmin: true\nexport function buildFirewallConditions(ctx: AppContext): SQL | undefined {\n if (ctx.userRole === 'sysadmin') {\n return isNull(invoices.deletedAt); // tenant predicate dropped, soft-delete kept\n }\n return and(\n eq(invoices.organizationId, ctx.activeOrgId!),\n isNull(invoices.deletedAt),\n );\n}\n```\n\nThe escape branch is **only** emitted when:\n\n- `cms.sysadmin: true` is set on the project config\n- The table has at least one tenant-scope predicate (org / owner / team / `via:` relationship). Tables with no tenant scopes already return what a sysadmin would see, so the runtime check would be dead code.\n- The firewall does not declare `{ exception: true }` (no tenant scopes to drop).\n\n**Sysadmin is distinct from admin.** `userRole === 'admin'` callers still go through the firewall normally — only `userRole === 'sysadmin'` triggers the bypass. Admins keep their existing universal-bypass at the *access* layer (cross-org reads on per-record routes via `?organizationId=`), but the firewall's row predicate remains in force. Sysadmin is opt-in, configured per-project, and intended for the cross-tenant CMS DB-admin tier — see [CMS Configuration](/compiler/config#cms-configuration).\n\nIf your project doesn't set `cms.sysadmin: true`, the escape branch is never emitted and the role value is functionally inert.\n\n## Common Patterns\n\n```typescript\n// Public/system table - no tenant filtering (soft-delete still applied)\nfirewall: [{ exception: true }]\n\n// Organization-scoped (auto-derived when organizationId is present — block can be omitted)\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n]\n\n// User-owned personal data\nfirewall: [\n { field: 'ownerId', equals: 'ctx.userId' },\n { field: 'deletedAt', isNull: true },\n]\n\n// Multi-tenant + per-team scoping\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'teamId', equals: 'ctx.activeTeamId' },\n { field: 'deletedAt', isNull: true },\n]\n\n// Custom ctx field\nfirewall: [\n { field: 'workspaceId', equals: 'ctx.activeWorkspaceId' },\n]\n\n// Status-gated (literal value, not ctx-derived — does NOT add to systemManaged)\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'status', in: ['active', 'pending'] },\n]\n```\n\n## Error Responses\n\nWhen a record isn't found behind the firewall (wrong org, soft-deleted, or genuinely doesn't exist), the error response depends on `firewallErrorMode`:\n\n### Reveal Mode (Default)\n\nReturns **403** with a structured error:\n\n```json\n{\n \"error\": \"Record not found or not accessible\",\n \"layer\": \"firewall\",\n \"code\": \"FIREWALL_NOT_FOUND\",\n \"hint\": \"Check the record ID and your organization membership\"\n}\n```\n\nThis is developer-friendly and helps debug access issues during development.\n\n### Hide Mode\n\nReturns **404** with a generic error:\n\n```json\n{\n \"error\": \"Not found\",\n \"code\": \"NOT_FOUND\"\n}\n```\n\nUse `firewallErrorMode: 'hide'` for security-hardened deployments where you don't want attackers to distinguish between \"record exists but you can't access it\" and \"record doesn't exist\":\n\n```typescript\nexport default defineTable(records, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n firewallErrorMode: 'hide', // Opaque 404s prevent record enumeration\n});\n```\n\n### Foreign-Key Referential Checks\n\nGenerated `POST /` and `POST /batch` handlers validate every foreign-key column against the **target table's** firewall before inserting. If a record references a row that the caller can't see (wrong org, soft-deleted, or non-existent), the request fails with:\n\n```json\n{\n \"error\": \"Referenced jobs row not found\",\n \"code\": \"FK_NOT_FOUND\",\n \"layer\": \"validation\",\n \"field\": \"jobId\"\n}\n```\n\nThis closes a cross-tenant injection vector: even if an attacker knows a foreign tenant's row ID, they cannot attach a child record to it, and they cannot trigger a cross-tenant cascade delete. The check uses the target table's `buildXFirewallConditions(ctx)` helper, so it honors whatever firewall predicates the target declared (organization, owner, team, custom). FKs to tables with `{ exception: true }` get a plain existence check (still verifies the row exists, doesn't tenant-scope it).\n\nThe check runs after guards but before the insert, so it appears as `layer: \"validation\"` in error responses. Status code is `400`, not `404` — returning `404` would leak existence of out-of-scope rows.\n\n### Pre-Record ID-Probe Defense\n\nIndependent of `firewallErrorMode`, generated `/:id` handlers run a\n**role-only access check before** the firewall query (see\n[Access ordering](/compiler/definitions/access#evaluation-order)). A caller\nwithout the right role gets 403 before the database is touched, so they\ncan't distinguish \"row exists out-of-scope\" from \"row doesn't exist\" via\nresponse timing or status differences.\n\n`firewallErrorMode` controls what happens **after** the role check passes\nbut the firewall hides the row — i.e., when an authorized caller asks for\na record in another tenant. Use `'hide'` to make that case indistinguishable\nfrom a non-existent ID.\n\n## Rules\n\n- Every resource MUST have at least one tenant predicate OR `{ exception: true }` OR a PUBLIC route\n- `{ exception: true }` cannot be combined with tenant predicates in the same array\n\n## Why Can't You Mix `{ exception: true }` with Tenant Predicates?\n\nThey represent opposite intentions:\n- `{ exception: true }` = \"Don't generate tenant `WHERE` clauses, data is public/global\"\n- Tenant predicates = \"Generate tenant `WHERE` clauses to isolate data\"\n\nCombining them would be contradictory — you can't both isolate and not isolate. (Note: soft-delete filtering is independent of this decision, see above.)\n\n## Handling \"Some Public, Some Private\" Data\n\nIf you need records that are sometimes public and sometimes scoped, you have two options:\n\n### Option 1: Two Separate Tables\n\nSplit into two tables - one public, one scoped:\n\n```typescript\n// features/job-templates/template-library.ts - Public job templates\nexport default defineTable(templateLibrary, {\n firewall: [{ exception: true }],\n // ...\n});\n\n// features/job-templates/custom-templates.ts - Org's custom job templates\nexport default defineTable(customTemplates, {\n firewall: [{ field: 'ownerId', equals: 'ctx.userId' }],\n // ...\n});\n```\n\n### Option 2: Use Access Control Instead\n\nKeep tenant scope but make access permissive, then control visibility via `access`:\n\n```typescript\n// features/jobs/jobs.ts\nexport default defineTable(jobs, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: {\n // Anyone in the org can list — visibility differences are handled\n // via record-level access conditions on /:id\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n // Use record conditions to allow public jobs OR owned jobs on GET /:id\n // (single-record GET inherits read.access, with optional record-level overrides)\n // ...\n});\n```\n\n### Which to Choose?\n\n| Scenario | Recommendation |\n|----------|----------------|\n| Truly global data (app config, public job templates) | `exception: true` in separate resource |\n| \"Public within org\" but still org-isolated | Ownership scope + permissive access rules |\n| Recruiter can toggle job postings public/private | Ownership scope + `visibility` field + access conditions |"
106
+ "content": "The firewall generates WHERE clauses automatically to isolate data by user, organization, or team.\n\n## Basic Usage\n\nThe cleanest pattern is `q.scope()` — declare the tenant column once and the firewall is auto-derived:\n\n```typescript\n// features/candidates/candidates.ts\n\nexport default feature('candidates', {\n columns: {\n id: q.id(),\n name: q.text().required(),\n email: q.text().required(),\n organizationId: q.scope('organization'), // Auto-derives the firewall\n },\n // No firewall: block needed — auto-derived as\n // [{ field: 'organizationId', equals: 'ctx.activeOrgId' },\n // { field: 'deletedAt', isNull: true }]\n // ... guards, crud, read\n});\n```\n\nIf you need to declare the firewall explicitly, two forms are accepted — pick whichever reads better:\n\n**Named-scope** (compact, default for simple overrides):\n\n```typescript\nfirewall: { organization: { column: 'tenant_id' } }\nfirewall: { owner: { column: 'account_user_id' } }\nfirewall: { exception: true } // opt out of tenant scoping entirely\n```\n\n**Predicate array** (explicit, required for `in`-lists or custom non-scope predicates):\n\n```typescript\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n]\n```\n\nBoth shapes compile to the same canonical predicate array internally — the named-scope object is coerced at parse time. Pick by readability.\n\n## Auto-detected column synonyms\n\nWhen you omit the `firewall:` block entirely, the compiler scans the schema for one of these isolation columns and auto-derives the predicates:\n\n| Scope | Accepted column names |\n|---|---|\n| Organization | `organizationId`, `organisationId`, `orgId`, `organization`, `organisation`, `org` |\n| User | `userId` |\n| Team | `teamId` |\n\n`ownerId` is **not** auto-detected — it's reserved for business-logic ownership (who owns this record), not access control. A table that has only `ownerId` and no isolation column raises a targeted error explaining the distinction; either rename to `userId` if the column controls access, add an isolation column, or specify `firewall:` explicitly.\n\n## Predicate Shape\n\n```typescript\ntype FirewallPredicate =\n | { field: string; equals: string; optional?: boolean } // column = ctx.* (or literal)\n | { field: string; isNull: true } // column IS NULL\n | { field: string; in: string[] | string; optional?: boolean } // column IN (...)\n | { field: string; via: string } // column IN (relationship subquery)\n | { field?: string; permission: string } // named authz.permissions reference (v0.35+)\n | { all: FirewallPredicate[] } // AND group (v0.35+)\n | { any: FirewallPredicate[] } // OR group (v0.35+)\n | { exception: true }; // opt out of tenant scoping\n\ntype FirewallConfig = ReadonlyArray<FirewallPredicate>;\n\n// Resource top-level (sibling to `firewall:`)\nfirewallErrorMode?: 'reveal' | 'hide';\n```\n\nThe top-level array is AND'd together. `firewallErrorMode` lives at the resource top level — it's a presentation-layer choice (403 vs 404), not a query-shape one.\n\n## Boolean groups: `all` / `any` (v0.35+)\n\nA flat array can only express AND. To grant access through **either** of two independent paths — \"an org member **OR** an event attendee\" — nest an `any` group. The top-level array stays sugar for `all`, so every existing firewall is byte-identical.\n\n```typescript\nfirewall: {\n any: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' }, // org-member grant\n { field: 'eventId', equals: 'ctx.scope.event' }, // attendee grant (token-verified)\n ],\n}\n```\n\nNull-safe scope semantics make this safe (these apply **inside `all`/`any` groups**, opt-in via the new syntax):\n\n- A **scope** arm (`ctx.activeOrgId`, `ctx.activeTeamId`, `ctx.scope.*`) whose claim is **absent never binds `undefined`** (the classic 500 / \"match every row\" trap). In an `any` group an absent arm **drops**; if **every** arm drops, the group denies with `sql\\`1 = 0\\`` (the empty-guard) — never a full-table read. In an `all` group an absent required scope **denies** the group.\n- Mark an arm `{ optional: true }` to **drop-instead-of-deny** when absent inside an `all` group (the teamless rest-of-org slice — `ctx.activeTeamId` is implicitly optional).\n- **Owner** (`ctx.userId`) and **soft-delete** (`isNull deletedAt`) are always present / always AND'd — never relaxed.\n\n```typescript\n// (org OR event) AND owner AND not-deleted\nfirewall: {\n all: [\n { any: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', equals: 'ctx.scope.event' },\n ] },\n { field: 'ownerId', equals: 'ctx.userId' },\n ],\n}\n```\n\nThe `ctx.scope.*` arms are how **relationship-derived scopes** (attendees, shuttle drivers, vendors) reach event-scoped rows without org membership — see [Scopes & capability grants](/compiler/definitions/scopes).\n\n## Relationship-based scoping (`via:`)\n\nFor relationship authorization — \"this user can see rows X if they have a confirmed `event_guests` row pointing at X\" — declare the relationship under `authz.relationships` in `quickback.config.ts`, then reference it from `firewall:` with a `via:` predicate:\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests', // table name\n subject: { column: 'userId', equals: 'ctx.userId' }, // caller side\n resource: { column: 'eventId' }, // resource side\n where: { status: 'confirmed' }, // optional row filter\n },\n },\n}\n\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' },\n]\n```\n\nCompiles to:\n\n```sql\nWHERE sessions.organizationId = ?\n AND sessions.eventId IN (\n SELECT eventId FROM event_guests\n WHERE userId = ?\n AND status = 'confirmed'\n AND <event_guests' own firewall — tenant scope + soft-delete>\n )\n```\n\nKey properties:\n\n- **Firewall stays the outermost AND.** A guest of an event in another tenant is still blocked by your tenant predicate. Relationship-based scoping never bypasses tenant isolation.\n- **The relationship table's own firewall is AND'd into the subquery.** Soft-deleting a `event_guests` row revokes access immediately; cross-tenant relationship rows can't grant access.\n- **Anonymous callers fail closed.** `ctx.userId` is null-guarded; the subquery short-circuits to `WHERE 1 = 0` for unauthenticated requests.\n- **The relationship table must be tenant-scoped** (`firewall: { exception: true }` is rejected at compile time on relationship tables).\n\nSee [Access — relationships](/compiler/definitions/access#authz-relationships) for the full `authz.relationships` shape and role-binding patterns.\n\n## Named permissions (`{ permission }`)\n\nA `via:` arm references **one** relationship. When the same grant rule —\n\"organizer **or** confirmed attendee\" — recurs across several resources,\nname it **once** under `authz.permissions` and reference it from any\nfirewall with a `{ permission }` arm. See [Permissions](/compiler/definitions/permissions)\nfor the full DSL.\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: { organizerOf: { /* … */ }, attendeeOf: { /* … */ } },\n permissions: {\n 'event:view': { anyOf: ['organizerOf', 'attendeeOf'] },\n },\n}\n\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', permission: 'event:view' },\n]\n```\n\nThe compiler lowers `{ permission }` to the same `all` / `any` relationship\nsubqueries the expression names — `anyOf` becomes an OR of subqueries,\n`allOf` an AND. `field` is the resource-side column those subqueries\nconstrain (the same column you'd put on a `via:` arm).\n\nA permission referenced from a firewall can also resolve an\n[**arrow**](/compiler/definitions/arrows) — an `{ arrowRef, permission }`\nleaf that traverses a foreign key to inherit authority from a parent object\n(\"org admins of the event's org can see its announcements\", \"anyone who\nadministers an ancestor folder can read this one\"). An arrow leaf lowers to\nan FK-hop subquery (non-recursive) or a bounded `WITH RECURSIVE` CTE\n(self-FK hierarchy), tenant-constrained at every row.\n\n**M1 limit — firewall arms must be SQL-pushable.** A firewall runs as a\nWHERE clause, so a permission referenced from one may only resolve to\nrelationship subqueries. A permission whose expression contains a\n**claim-site leaf** (`{ role }`, `{ scopeRole }`, `{ pseudoRole }`) or a\n`not` is rejected at compile time when referenced from a firewall — those\nshapes are valid in the DSL but reserved for future claim/runtime\nenforcement sites. Use a role gate on `read.access` / `crud.*.access` for\nmembership checks.\n\nThe compile-time analyzer additionally flags a referenced permission that can\nnever be satisfied, an arm shadowed by a broader one, and the SQL / CTE cost\nof each permission — see [Diagnostics](/compiler/definitions/diagnostics).\n\n## Context Sources\n\nWhen `equals` references the request context, use these standard sources:\n\n| Source | Description |\n|--------|-------------|\n| `ctx.userId` | Current authenticated user's ID |\n| `ctx.activeOrgId` | User's active organization ID |\n| `ctx.activeTeamId` | User's active team ID |\n\nThese values are populated by the auth middleware from the user's session. Any predicate where `equals` starts with `ctx.` is treated as server-derived: the column lands in `GUARDS_CONFIG.systemManaged` (clients cannot submit it) and is auto-populated on create / upsert from the context.\n\n## Auto-Derivation\n\nWhen the `firewall:` block is omitted, the compiler scans the schema for known scope columns and synthesises the predicate array:\n\n| Column found | Predicate emitted |\n|--------------|-------------------|\n| `organizationId` / `organisationId` / `orgId` / `organization` / `organisation` / `org` | `{ field: '...', equals: 'ctx.activeOrgId' }` |\n| `userId` | `{ field: 'userId', equals: 'ctx.userId' }` |\n| `teamId` | `{ field: 'teamId', equals: 'ctx.activeTeamId' }` |\n| `deletedAt` (always present via audit injection) | `{ field: 'deletedAt', isNull: true }` — appended automatically whenever the schema carries the column, regardless of which firewall shape you wrote |\n\n`q.scope(kind)` is the canonical way to declare the column — auto-derivation works the same way for plain `q.text().required()` or Drizzle `text(...).notNull()` columns named to match the convention.\n\n**Rules:**\n- Exactly one isolation column → auto-derived.\n- Zero columns AND no PUBLIC route → compile-time error (\"missing isolation column\").\n- Two or more (e.g. `organizationId` + `ownerId`) → compile-time error; declare `firewall:` explicitly.\n\n## What `{ exception: true }` Actually Does\n\n`{ exception: true }` disables **tenant scoping only** — the generated `buildFirewallConditions()` emits no tenant `WHERE` clauses. It does **not** affect:\n\n- **Audit field injection.** `createdAt`, `modifiedAt`, `createdBy`, `modifiedBy`, `deletedAt`, `deletedBy` are always added to every table unless you disable them globally with `compiler.features.auditFields: false`.\n- **Soft-delete filtering.** If the table has a `deletedAt` column (which it does by default, thanks to audit injection), the firewall still emits `isNull(<table>.deletedAt)` so soft-deleted records stay hidden. To opt out of soft-delete filtering on an exception resource, either set `compiler.features.auditFields: false` globally or hand-author a schema without `deletedAt`.\n\nSo `firewall: [{ exception: true }]` on the default configuration returns `isNull(<table>.deletedAt)` from `buildFirewallConditions()` — no tenant filter, soft-delete filter still applied.\n\n## Sysadmin Escape Hatch\n\nWhen `cms: { sysadmin: true }` is set on the project (introduced in v0.15.0), every `buildFirewallConditions()` emits a runtime branch that drops tenant scopes for `ctx.userRole === 'sysadmin'` callers while keeping the soft-delete predicate:\n\n```typescript\n// Generated for an org-scoped table when cms.sysadmin: true\nexport function buildFirewallConditions(ctx: AppContext): SQL | undefined {\n if (ctx.userRole === 'sysadmin') {\n return isNull(invoices.deletedAt); // tenant predicate dropped, soft-delete kept\n }\n return and(\n eq(invoices.organizationId, ctx.activeOrgId!),\n isNull(invoices.deletedAt),\n );\n}\n```\n\nThe escape branch is **only** emitted when:\n\n- `cms.sysadmin: true` is set on the project config\n- The table has at least one tenant-scope predicate (org / owner / team / `via:` relationship). Tables with no tenant scopes already return what a sysadmin would see, so the runtime check would be dead code.\n- The firewall does not declare `{ exception: true }` (no tenant scopes to drop).\n\n**Sysadmin is distinct from admin.** `userRole === 'admin'` callers still go through the firewall normally — only `userRole === 'sysadmin'` triggers the bypass. Admins keep their existing universal-bypass at the *access* layer (cross-org reads on per-record routes via `?organizationId=`), but the firewall's row predicate remains in force. Sysadmin is opt-in, configured per-project, and intended for the cross-tenant CMS DB-admin tier — see [CMS Configuration](/compiler/config#cms-configuration).\n\nIf your project doesn't set `cms.sysadmin: true`, the escape branch is never emitted and the role value is functionally inert.\n\n## Common Patterns\n\n```typescript\n// Public/system table - no tenant filtering (soft-delete still applied)\nfirewall: [{ exception: true }]\n\n// Organization-scoped (auto-derived when organizationId is present — block can be omitted)\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n]\n\n// User-owned personal data\nfirewall: [\n { field: 'ownerId', equals: 'ctx.userId' },\n { field: 'deletedAt', isNull: true },\n]\n\n// Multi-tenant + per-team scoping\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'teamId', equals: 'ctx.activeTeamId' },\n { field: 'deletedAt', isNull: true },\n]\n\n// Custom ctx field\nfirewall: [\n { field: 'workspaceId', equals: 'ctx.activeWorkspaceId' },\n]\n\n// Status-gated (literal value, not ctx-derived — does NOT add to systemManaged)\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'status', in: ['active', 'pending'] },\n]\n```\n\n## Error Responses\n\nWhen a record isn't found behind the firewall (wrong org, soft-deleted, or genuinely doesn't exist), the error response depends on `firewallErrorMode`:\n\n### Reveal Mode (Default)\n\nReturns **403** with a structured error:\n\n```json\n{\n \"error\": \"Record not found or not accessible\",\n \"layer\": \"firewall\",\n \"code\": \"FIREWALL_NOT_FOUND\",\n \"hint\": \"Check the record ID and your organization membership\"\n}\n```\n\nThis is developer-friendly and helps debug access issues during development.\n\n### Hide Mode\n\nReturns **404** with a generic error:\n\n```json\n{\n \"error\": \"Not found\",\n \"code\": \"NOT_FOUND\"\n}\n```\n\nUse `firewallErrorMode: 'hide'` for security-hardened deployments where you don't want attackers to distinguish between \"record exists but you can't access it\" and \"record doesn't exist\":\n\n```typescript\nexport default defineTable(records, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n firewallErrorMode: 'hide', // Opaque 404s prevent record enumeration\n});\n```\n\n### Foreign-Key Referential Checks\n\nGenerated `POST /` and `POST /batch` handlers validate every foreign-key column against the **target table's** firewall before inserting. If a record references a row that the caller can't see (wrong org, soft-deleted, or non-existent), the request fails with:\n\n```json\n{\n \"error\": \"Referenced jobs row not found\",\n \"code\": \"FK_NOT_FOUND\",\n \"layer\": \"validation\",\n \"field\": \"jobId\"\n}\n```\n\nThis closes a cross-tenant injection vector: even if an attacker knows a foreign tenant's row ID, they cannot attach a child record to it, and they cannot trigger a cross-tenant cascade delete. The check uses the target table's `buildXFirewallConditions(ctx)` helper, so it honors whatever firewall predicates the target declared (organization, owner, team, custom). FKs to tables with `{ exception: true }` get a plain existence check (still verifies the row exists, doesn't tenant-scope it).\n\nThe check runs after guards but before the insert, so it appears as `layer: \"validation\"` in error responses. Status code is `400`, not `404` — returning `404` would leak existence of out-of-scope rows.\n\n### Pre-Record ID-Probe Defense\n\nIndependent of `firewallErrorMode`, generated `/:id` handlers run a\n**role-only access check before** the firewall query (see\n[Access ordering](/compiler/definitions/access#evaluation-order)). A caller\nwithout the right role gets 403 before the database is touched, so they\ncan't distinguish \"row exists out-of-scope\" from \"row doesn't exist\" via\nresponse timing or status differences.\n\n`firewallErrorMode` controls what happens **after** the role check passes\nbut the firewall hides the row — i.e., when an authorized caller asks for\na record in another tenant. Use `'hide'` to make that case indistinguishable\nfrom a non-existent ID.\n\n## Rules\n\n- Every resource MUST have at least one tenant predicate OR `{ exception: true }` OR a PUBLIC route\n- `{ exception: true }` cannot be combined with tenant predicates in the same array\n\n## Why Can't You Mix `{ exception: true }` with Tenant Predicates?\n\nThey represent opposite intentions:\n- `{ exception: true }` = \"Don't generate tenant `WHERE` clauses, data is public/global\"\n- Tenant predicates = \"Generate tenant `WHERE` clauses to isolate data\"\n\nCombining them would be contradictory — you can't both isolate and not isolate. (Note: soft-delete filtering is independent of this decision, see above.)\n\n## Handling \"Some Public, Some Private\" Data\n\nIf you need records that are sometimes public and sometimes scoped, you have two options:\n\n### Option 1: Two Separate Tables\n\nSplit into two tables - one public, one scoped:\n\n```typescript\n// features/job-templates/template-library.ts - Public job templates\nexport default defineTable(templateLibrary, {\n firewall: [{ exception: true }],\n // ...\n});\n\n// features/job-templates/custom-templates.ts - Org's custom job templates\nexport default defineTable(customTemplates, {\n firewall: [{ field: 'ownerId', equals: 'ctx.userId' }],\n // ...\n});\n```\n\n### Option 2: Use Access Control Instead\n\nKeep tenant scope but make access permissive, then control visibility via `access`:\n\n```typescript\n// features/jobs/jobs.ts\nexport default defineTable(jobs, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: {\n // Anyone in the org can list — visibility differences are handled\n // via record-level access conditions on /:id\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n // Use record conditions to allow public jobs OR owned jobs on GET /:id\n // (single-record GET inherits read.access, with optional record-level overrides)\n // ...\n});\n```\n\n### Which to Choose?\n\n| Scenario | Recommendation |\n|----------|----------------|\n| Truly global data (app config, public job templates) | `exception: true` in separate resource |\n| \"Public within org\" but still org-isolated | Ownership scope + permissive access rules |\n| Recruiter can toggle job postings public/private | Ownership scope + `visibility` field + access conditions |"
95
107
  },
96
108
  "compiler/definitions/guards": {
97
109
  "title": "Guards - Field Modification Rules",
@@ -105,6 +117,10 @@ export const DOCS = {
105
117
  "title": "Masking - Field Redaction",
106
118
  "content": "Hide sensitive data from unauthorized users while showing it to those with permission.\n\n## Automatic Masking (Secure by Default)\n\nQuickback automatically applies masking to columns that match sensitive naming patterns. This ensures a high security posture even if you don't explicitly configure masking.\n\n### Sensitive Keywords & Default Masks\n\n| Pattern | Default Mask | Description |\n| :--- | :--- | :--- |\n| `email` | `email` | p***@e******.com |\n| `phone`, `mobile`, `fax` | `phone` | ******4567 |\n| `ssn`, `socialsecurity`, `nationalid` | `ssn` | *****6789 |\n| `creditcard`, `cc`, `cardnumber`, `cvv` | `creditCard` | ************1234 |\n| `iban` | `redact` | [REDACTED] |\n| `password`, `secret`, `token`, `apikey`, `privatekey` | `redact` | [REDACTED] |\n| `accesstoken`, `refreshtoken`, `clientsecret`, `signingsecret`, `bearer` | `redact` | [REDACTED] |\n| `stripe`, `webhook` | `redact` | [REDACTED] |\n\n### Build-Time Alerts\n\nIf the compiler auto-detects a sensitive column that you haven't explicitly configured, it will emit a warning:\n\n```bash\n[Warning] Auto-masking enabled for sensitive column \"users.email\". Explicitly configure masking to silence this warning.\n```\n\nTo silence this warning or change the behavior, simply define the field explicitly in your `masking` configuration. Explicit configurations always take precedence over auto-detected defaults.\n\n#### Tables without an owner column\n\nThe default auto-mask predicate is `show: { or: 'owner', roles: ['admin'] }` — admins always see the value, the row's owner sees their own. If the table has no owner column at all (no `userId` / `ownerId` and no `q.scope('owner')`), the compiler drops the `owner` clause and emits a second warning so the rule is still safe but transparent:\n\n```bash\n[Warning] Auto-masking on \"people.email\" requested owner OR-show, but \"people\"\n has no \"ownerId\" column. Falling back to roles-only (roles: [\"admin\"]).\n Declare `masking: { email: { show: { roles: [...] } } }` explicitly to\n silence this and pick a real predicate.\n```\n\nThis is a real behavioral signal, not boilerplate — the auto-detector can't tell whether the table is \"ownerless on purpose\" (e.g. a shared lookup table) or \"should have an owner column but was authored without one.\" Declare the predicate explicitly to silence the warning and lock in the intent.\n\n### Overriding Defaults\n\nIf you want to show a sensitive field to everyone (disable masking) or use a different rule, define it explicitly in the `resource.masking` block:\n\n```typescript\nexport default defineTable(candidates, {\n masking: {\n // Show email to everyone (overrides auto-masking)\n email: { type: 'email', show: { roles: ['everyone'] } },\n\n // Silence warning but keep secure (recruiter and above only)\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } }\n }\n});\n```\n\n## Basic Usage\n\n```typescript\n// features/candidates/candidates.ts\n\nexport default feature('candidates', {\n columns: {\n id: q.id(),\n name: q.text().required(),\n email: q.text().required(),\n phone: q.text().optional(),\n resumeUrl: q.text().optional(),\n organizationId: q.scope('organization'),\n },\n guards: { createable: [\"name\", \"email\", \"phone\", \"resumeUrl\"], updatable: [\"name\", \"phone\"] },\n masking: {\n email: { type: 'email', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n },\n read: { access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] } },\n create: { /* ... */ },\n update: { /* ... */ },\n delete: { /* ... */ },\n});\n```\n\n## Built-in Mask Types\n\n| Type | Example Input | Masked Output |\n|------|---------------|---------------|\n| `'email'` | `john@yourdomain.com` | `j***@y*********.com` |\n| `'phone'` | `555-123-4567` | `******4567` |\n| `'ssn'` | `123-45-6789` | `*****6789` |\n| `'creditCard'` | `4111111111111111` | `************1111` |\n| `'name'` | `John Smith` | `J*** S****` |\n| `'redact'` | `anything` | `[REDACTED]` |\n| `'custom'` | (your logic) | (your output) |\n\n## Configuration\n\n```typescript\nmasking: {\n // Basic masking - everyone sees masked value\n phone: { type: 'phone' },\n\n // Show unmasked to specific roles\n email: {\n type: 'email',\n show: { roles: ['hiring-manager', 'recruiter'] }\n },\n\n // Show unmasked to owner (createdBy === ctx.userId)\n resumeUrl: {\n type: 'redact',\n show: { or: 'owner' }\n },\n\n // Custom mask function\n externalProfileUrl: {\n type: 'custom',\n mask: (value) => value.slice(0, 4) + '...' + value.slice(-4),\n show: { roles: ['recruiter'] }\n },\n}\n```\n\n## Show Conditions\n\n```typescript\nshow: {\n roles?: string[]; // Unmasked if user has any of these roles\n or?: 'owner'; // Unmasked if user is the record owner\n}\n```\n\nThe `'owner'` condition compares against the owner column declared via `q.scope('owner')` (or auto-detected from a `userId` / `ownerId` column). If no owner scope is present, it falls back to `createdBy`.\n\n### Relationship-roles in masking (v1 limitation)\n\nRelationship-roles declared under `authz.roles` (e.g. `guest: { via: 'guestOf' }`) are **not yet supported in `show:` clauses**. The compiler refuses to build with a clear error message because async, db-aware mask functions plus a batched relationship matcher (to avoid N+1 on list responses) are required to ship safely — that pipeline has not yet landed. The runtime evaluator fails closed on unrecognized arms, so silent grants are impossible.\n\n**Workarounds**, depending on intent:\n\n- **Gate on BA roles only**: keep masking simple and put the relationship check at the access layer instead — `read.views.<v>.access: { roles: ['guest'] }` returns a curated field projection that excludes the sensitive column entirely for non-staff callers, without involving masking.\n- **Move the field into a view that's gated by the relationship-role at access**: same pattern — column-level security via field projection rather than per-row masking.\n\nA future async-mask pipeline with batched lookups will lift this limitation; the schema slot is reserved so the v2 add will be non-breaking.\n\n## Query Gate (filter / sort / search)\n\nMasking has a second concern beyond hiding values in the response: a non-admin caller could enumerate masked PII via the query string — e.g. `?filter=email:like:%@target.com` — and infer presence even when the response payload is redacted. The `query` allowlist closes this:\n\n```typescript\nmasking: {\n email: {\n type: 'email',\n show: { roles: ['admin'] },\n // Optional — defaults to show.roles when omitted\n query: { roles: ['admin'] },\n },\n}\n```\n\n`query` is a single role gate that covers `?filter`, `?sort`, and `?search` uniformly. When omitted, it inherits from `show.roles` — \"if you can see it, you can query it\" — which is the right shape for almost all PII.\n\nA view can opt back in for a higher-privileged role pair by listing the column in its own `query.{filterable,searchable,sortable}` allowlist. The compiler validates at build time that the view's access roles intersect the masking `query.roles` (or `show.roles` when `query` is omitted), so the opt-in can never reach a caller who'd see the value masked.\n\n```typescript\nmasking: {\n email: { type: 'email', show: { roles: ['admin'] } },\n // query: defaults to show.roles → ['admin']\n},\nread: {\n views: {\n pipeline: {\n fields: ['id', 'name'],\n access: { roles: ['member', 'admin'] },\n query: {\n searchable: ['name'], // email NOT listed → not searchable on this view\n },\n },\n full: {\n fields: ['id', 'name', 'email'],\n access: { roles: ['admin'] },\n query: {\n filterable: ['email'], // ✓ admin satisfies email's query gate\n searchable: ['name', 'email'],\n },\n },\n },\n},\n```\n\n`query` replaces the legacy per-capability flags (`filterable`, `searchable`, `sortable`). Setting any of those is rejected at compile time with a migration hint.\n\n## Complete Example\n\n```typescript\n// features/candidates/candidates.ts\n\nexport default feature('candidates', {\n columns: {\n id: q.id(),\n name: q.text().required().filterable('like').searchable(),\n email: q.text().required().filterable('eq').searchable(),\n phone: q.text().optional().filterable('eq'),\n resumeUrl: q.text().optional(),\n organizationId: q.scope('organization'),\n },\n guards: {\n createable: ['name', 'email', 'phone', 'resumeUrl'],\n updatable: ['name', 'phone'],\n },\n masking: {\n email: { type: 'email', show: { roles: ['admin+'] } },\n phone: { type: 'phone', show: { roles: ['admin+'] } },\n resumeUrl: {\n type: 'custom',\n mask: () => '[RESUME LINK HIDDEN]',\n show: { roles: ['admin+'] },\n },\n },\n read: {\n access: { roles: ['member+'] },\n views: {\n pipeline: {\n fields: ['id', 'name'],\n access: { roles: ['member+'] },\n query: { searchable: ['name'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'phone', 'resumeUrl'],\n access: { roles: ['admin+'] },\n query: {\n filterable: ['email', 'phone'],\n searchable: ['name', 'email'],\n },\n },\n },\n },\n create: { access: { roles: ['admin+'] } },\n update: { access: { roles: ['admin+'] } },\n delete: { access: { roles: ['owner'] }, mode: 'soft' },\n});\n```"
107
119
  },
120
+ "compiler/definitions/permissions": {
121
+ "title": "Permissions",
122
+ "content": "A `via:` arm references **one** relationship. A `roles: [...]` array ORs a\nflat list of role names. When the *same* grant rule recurs across several\nresources — \"organizer **or** confirmed attendee\", \"admin **and not**\nsuspended\" — name it once under `authz.permissions` and reference it\neverywhere by name. A permission is a **named boolean expression** over the\nauthorization primitives you've already declared.\n\n## Declaring permissions\n\nPermissions live in `quickback.config.ts` alongside `authz.relationships`:\n\n```typescript\n// quickback.config.ts\n\nexport default defineConfig({\n // ...providers...\n authz: {\n relationships: {\n organizerOf: { from: 'event_staff', subject: { column: 'userId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { role: 'organizer' } },\n attendeeOf: { from: 'event_guests', subject: { column: 'userId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { status: 'confirmed' } },\n },\n permissions: {\n 'event:view': { anyOf: ['organizerOf', 'attendeeOf'] },\n 'event:manage': { allOf: ['organizerOf', { not: 'suspendedFromEvent' }] },\n 'org:admin': { anyOf: [{ role: 'admin' }, { role: 'owner' }] },\n },\n },\n});\n```\n\n## The expression DSL\n\nA permission is a tree of three combinators over **leaves**:\n\n| Combinator | Meaning |\n|---|---|\n| `{ anyOf: [...] }` | union — satisfied if **any** arm holds |\n| `{ allOf: [...] }` | intersection — satisfied only if **all** arms hold |\n| `{ not: <expr> }` | exclusion — satisfied if the operand does **not** hold |\n\nA bare leaf (no combinator) is a one-arm permission — the replacement for a\nsingle `via:`.\n\n### Leaves\n\nA leaf names one authorization primitive. The common case is a bare string;\nobject forms are the unambiguous escape hatch.\n\n| Leaf | Resolves to |\n|---|---|\n| `'organizerOf'` (bare string, no prefix) | a declared **relationship** |\n| `{ relationRef: 'organizerOf' }` | a declared relationship (explicit) |\n| `{ permissionRef: 'event:view' }` | **another permission** (composition) |\n| `{ role: 'admin' }` | an org-membership role (`ctx.roles`) |\n| `{ scopeRole: { kind: 'event', role: 'organizer' } }` | a [scoped role](/compiler/definitions/scopes) |\n| `{ pseudoRole: 'AUTHENTICATED' }` | `PUBLIC` / `AUTHENTICATED` / `INTERNAL` / … |\n| `{ arrowRef: 'eventOrg', permission: 'org:admin' }` | an [FK-traversal arrow](/compiler/definitions/arrows) — resolve the row's FK to its target object and require a permission there |\n\nString sugar for the prefixed forms is also accepted inside an expression:\n`'permission:event:view'`, `'scope:event:organizer'`, `'role:admin'`. A bare\nstring with no recognized prefix is always a relationship reference.\n\n## Referencing a permission\n\nA resource references a permission from its `firewall` with a\n`{ permission }` arm. `field` is the resource-side column the lowered\nsubqueries constrain — the same column a `via:` arm would carry:\n\n```typescript\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', permission: 'event:view' },\n]\n```\n\nThe compiler **lowers** the permission to the equivalent firewall arms:\n`anyOf` becomes an OR of relationship subqueries (`any`), `allOf` becomes an\nAND (`all`), and `{ permissionRef }` inlines the referenced permission's\narms. The result is byte-identical to writing those `via:` arms by hand — the\npermission is just the named, reusable spelling.\n\nSee [Firewall — named permissions](/compiler/definitions/firewall#named-permissions-permission)\nfor how the arm sits inside a firewall.\n\n## M1 limits\n\nPermissions are richer than what a firewall can enforce today. The DSL\naccepts the full shape so configs are forward-compatible, but a firewall\nruns as a SQL `WHERE` clause, so a permission referenced from a firewall\nmust be **SQL-pushable**. Two cases are rejected at compile time when\nreferenced from a firewall:\n\n- **Claim-site leaves.** `{ role }`, `{ scopeRole }`, and `{ pseudoRole }`\n are decided from the request's verified claims, not from a row subquery.\n A permission containing one of these can't lower to a `WHERE` clause, so\n referencing it from a firewall is a compile error. Gate membership on\n `read.access` / `crud.*.access` instead, where role checks belong.\n- **`not`.** A `not` whose operand resolves to a SQL (relationship) site is\n rejected — `NOT IN (subquery)` over a nullable set is the classic\n null-trap (a `NULL` row silently passes). It's representable in the DSL for\n future claim/runtime sites but errors in a firewall in M1.\n\nThese shapes (`{ role }`, `not`, typed caveats) remain in the DSL because\nthey're the enforcement surfaces of later milestones (claim-site and runtime\nchecks). M1 ships the SQL-pushable subset: relationship and `{ permissionRef }`\nleaves under `anyOf` / `allOf`. FK-traversal arrows (`{ arrowRef, permission }`)\nare now shipped and **are** firewall-pushable — see\n[Arrows](/compiler/definitions/arrows).\n\nThe compile-time analyzer flags permissions that can never be satisfied,\narms shadowed by a broader arm, a `not` over a SQL site (the null-trap), and\nthe subquery / CTE cost of each rule — see\n[Diagnostics](/compiler/definitions/diagnostics).\n\n## Reference\n\n```typescript\n// authz.permissions.<name>\ntype PermissionExpr =\n | PermissionLeaf\n | { anyOf: PermissionExpr[] }\n | { allOf: PermissionExpr[] }\n | { not: PermissionExpr };\n\ntype PermissionLeaf =\n | string // relationship name (bare) or prefixed sugar\n | { relationRef: string }\n | { permissionRef: string }\n | { role: string } // claim-site — not firewall-pushable (M1)\n | { scopeRole: { kind: string; role: string } } // claim-site — not firewall-pushable (M1)\n | { pseudoRole: string } // claim-site — not firewall-pushable (M1)\n | { arrowRef: string; permission: string }; // FK-traversal arrow — see Arrows\n```\n\n- Referenced from a firewall as `{ field, permission: '<name>' }`.\n- Relationship leaves carry every property of the underlying relationship —\n the `from` table's own firewall (tenant scope + soft-delete) is AND'd into\n each subquery, exactly as with a `via:` arm.\n- See [Scopes & capability grants](/compiler/definitions/scopes) for scoped\n roles and [Access — relationships](/compiler/definitions/access#authz-relationships)\n for the relationship shape."
123
+ },
108
124
  "compiler/definitions/read": {
109
125
  "title": "Read - Unified Read Pipeline",
110
126
  "content": "The `read` block owns the read side of every resource: the collection-level\n`GET /` endpoint, single-record `GET /:id`, and named view projections. It\nreplaces the legacy `crud.list` and `crud.get` shapes — those are rejected\nat compile time in DSL v2.\n\n## Basic Usage\n\n```typescript\n// features/customers/customers.ts\n\nexport const customers = sqliteTable('customers', {\n id: text('id').primaryKey(),\n name: text('name').notNull(),\n email: text('email').notNull(),\n ssn: text('ssn'),\n status: text('status').notNull(),\n organizationId: text('organization_id').notNull(),\n});\n\nexport default defineTable(customers, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n masking: {\n ssn: { type: 'ssn', show: { roles: ['admin'] } },\n },\n read: {\n access: { roles: ['member', 'admin'] },\n views: {\n summary: {\n fields: ['id', 'name', 'status'],\n access: { roles: ['member', 'admin'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'ssn', 'status'],\n access: { roles: ['admin'] },\n },\n },\n },\n create: { access: { roles: ['admin'] } },\n update: { access: { roles: ['admin'] } },\n delete: { access: { roles: ['admin'] }, mode: 'soft' },\n});\n```\n\n## What `read` Owns\n\n| Endpoint | Gate |\n|----------|------|\n| `GET /api/v1/{resource}` | `read.access` |\n| `GET /api/v1/{resource}/:id` | `read.access` |\n| `GET /api/v1/{resource}/views/{name}` | `read.views[name].access` (falls back to `read.access`) |\n\nSingle-record `GET /:id` inherits `read.access` automatically — there's no\nseparate `read.get` block. If you need different access for single records,\nuse record-level conditions on `read.access`:\n\n```typescript\nread: {\n access: {\n or: [\n { roles: ['admin'] },\n { roles: ['member'], record: { ownerId: { equals: '$ctx.userId' } } },\n ],\n },\n}\n```\n\n## Configuration Options\n\n```typescript\ninterface ReadConfig {\n // Role/condition gate for collection reads, single-record reads, and the\n // default view fallback.\n access?: Access;\n\n // Optional read-side firewall override. If omitted, the resource-level\n // `firewall` block is used (the common case).\n firewall?: FirewallConfig;\n\n // Pagination defaults for collection reads.\n pageSize?: number; // Default page size (default: 50)\n maxPageSize?: number; // Hard cap (default: 100)\n\n // Named field projections. Each view has its own access and field list.\n views?: {\n [viewName: string]: ViewConfig;\n };\n}\n\ninterface ViewConfig {\n fields: string[]; // Columns returned by this view\n access?: Access; // Per-view access (falls back to read.access)\n pageSize?: number;\n maxPageSize?: number;\n}\n```\n\n## Access Ordering on `/:id`\n\nSingle-record `GET /:id` evaluates checks in this order to close the\n404-vs-403 ID-probe channel:\n\n1. **Auth gate** — 401 if unauthenticated\n2. **Pre-record access** — role-only check (skips `access.record` predicates)\n3. **Firewall query** — `WHERE` clause filters by ownership\n4. **Post-record access** — full check including record-level predicates\n5. **Masking** — applied to the response\n\nAn unauthorized caller without a matching role gets 403 from step 2 before\nthe database is touched, so they can't distinguish \"row exists in another\ntenant\" from \"row doesn't exist.\" A caller with the right role but the wrong\ntenant gets the firewall's configured response (403 by default; see\n[`firewallErrorMode: 'hide'`](/compiler/definitions/firewall) for an opaque\n404 instead).\n\nFunction-form access is opaque to the pre-check (it always passes there) and\nis fully evaluated post-record, so `access: async (ctx, record) => ...`\nstill works as before.\n\n## Views Under `read.views`\n\nViews are named field projections — Column Level Security. They live under\n`read.views` (not at the resource top level). See\n[Views](/compiler/definitions/views) for the full feature reference.\n\n```typescript\nread: {\n access: { roles: ['member', 'admin'] },\n views: {\n public: {\n fields: ['id', 'title', 'status'],\n access: { roles: ['PUBLIC'] },\n },\n internal: {\n fields: ['id', 'title', 'status', 'salaryMin', 'salaryMax'],\n access: { roles: ['admin'] },\n },\n },\n}\n```\n\nNamed views are emitted at dedicated path routes:\n\n- `GET /api/v1/jobs/views/internal`\n- If `read.defaultView` is set, bare `GET /api/v1/jobs` resolves to that view.\n\n## Migrating from `crud.list` / `crud.get`\n\nDSL v2 rejects both at compile time. The migration is mechanical:\n\n| Before (DSL v1) | After (DSL v2) |\n|---|---|\n| `crud.list.access` | `read.access` |\n| `crud.list.pageSize` | `read.pageSize` |\n| `crud.list.maxPageSize` | `read.maxPageSize` |\n| `crud.list.fields: [...]` | Move to a named view under `read.views` |\n| `crud.get.access` | `read.access` (or record-level conditions) |\n| `crud.get.fields: [...]` | Move to a named view; clients call `/views/{name}` |\n| Top-level `views: {...}` | `read.views: {...}` |\n\nExample before/after:\n\n```typescript\n// Before — DSL v1\ncrud: {\n list: {\n access: { roles: ['member'] },\n pageSize: 25,\n },\n get: {\n access: { roles: ['member'] },\n fields: ['id', 'name', 'status'], // per-field projection\n },\n create: { access: { roles: ['admin'] } },\n}\n\n// After — DSL v2\nread: {\n access: { roles: ['member'] },\n pageSize: 25,\n views: {\n summary: {\n fields: ['id', 'name', 'status'],\n access: { roles: ['member'] },\n },\n },\n}\ncreate: { access: { roles: ['admin'] } }\n```\n\nClients that previously hit `GET /:id` to retrieve only summary fields now\nmove that projection to a named collection view such as\n`GET /api/v1/jobs/views/summary`. Single-record `GET /:id` always returns the\nfull masked record.\n\n## Read-Only Resources\n\nA resource that exposes only reads is valid with no write-operation blocks at all:\n\n```typescript\nexport default defineTable(balanceSnapshots, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: { access: { roles: ['member', 'admin'] } },\n // no create/update/delete/upsert — no writes\n});\n```\n\n## See Also\n\n- [Views](/compiler/definitions/views) — Full reference for named projections\n- [Access](/compiler/definitions/access) — Roles, record conditions, and combinators\n- [Firewall](/compiler/definitions/firewall) — Tenant scoping and `firewallErrorMode`\n- [Views API](/compiler/targets/hono-api/using-the-api/views-api) — Calling views from clients"
@@ -113,13 +129,17 @@ export const DOCS = {
113
129
  "title": "Database Schema",
114
130
  "content": "Quickback supports three co-equal authoring patterns. All compile to the same generated runtime — the compiler dispatches per file, so every feature in a project may choose independently.\n\n- **`feature()`** — single-export sugar for the `q` DSL. One import, one export, everything about the table and its security contract in one call. **Recommended default.** See [feature() — single-export sugar](/compiler/definitions/feature).\n- **`q.table()` + `defineTable()`** — the two-export form. Same DSL, more explicit. Use when you want to reference the table identifier before the default export (e.g. from an action file).\n- **Drizzle `sqliteTable()` / `pgTable()` + `defineTable()`** — interop with existing Drizzle code. Use when you're bringing an existing schema forward or want dialect-specific column options.\n\n## feature() — the one-call form (default)\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport default feature('jobs', {\n columns: {\n id: q.id(),\n title: q.text().required(),\n department: q.text().required(),\n status: q.text().default('draft').required(), // \"draft\" | \"open\" | \"closed\"\n salaryMin: q.int().optional(),\n salaryMax: q.int().optional(),\n organizationId: q.scope('organization'),\n },\n // firewall block omitted — q.scope('organization') triggers auto-derivation\n // of [{ field: 'organizationId', equals: 'ctx.activeOrgId' }, { field: 'deletedAt', isNull: true }].\n guards: {\n createable: [\"title\", \"department\", \"status\", \"salaryMin\", \"salaryMax\"],\n updatable: [\"title\", \"department\", \"status\"],\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n});\n```\n\nType inference still works — `typeof import('./jobs').default.$infer` gives you the row type. In action files, `import jobs from './jobs'` gives you the same typed handle you'd get from `q.table()`, so `defineActions(jobs, { … })` accepts it unchanged.\n\n## q.table() + defineTable() — the two-export form\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport const jobs = q.table('jobs', {\n id: q.id(),\n title: q.text().required(),\n department: q.text().required(),\n status: q.text().default('draft').required(),\n salaryMin: q.int().optional(),\n salaryMax: q.int().optional(),\n organizationId: q.scope('organization'),\n});\n\nexport default defineTable(jobs, {\n guards: { /* ... */ },\n read: { /* ... */ },\n create: { /* ... */ },\n update: { /* ... */ },\n delete: { /* ... */ },\n});\n\nexport type Job = typeof jobs.$infer;\n```\n\nProduces byte-identical output to the `feature()` form above — the compiler expands `feature()` to exactly this shape internally. Use whichever reads better for the file you're writing.\n\nA few mechanics to know:\n\n- **Column names** default to snake_case of the JS key — `organizationId` ↔ `organization_id`, `salaryMin` ↔ `salary_min`. Pass a positional argument to override: `q.text('custom_name')`.\n- **`q.id()`** emits `text('id').primaryKey()` with a cuid2 app-layer default.\n- **`.required()` / `.optional()`** control NOT NULL. Chain before or after `.default(x)`.\n- **References:** `q.text().required().references(() => other.id, { onDelete: 'cascade' })`.\n- **Indexes:** column-level `.index()` or table-level `indexes` / `unique` as a third arg to `q.table(name, cols, { indexes, unique })`. With `feature()`, pass `indexes` and `unique` as top-level keys alongside `columns` — the sugar forwards them into the same `q.table` opts.\n\n### Column Types\n\n| Builder | Drizzle equivalent | Zod type |\n|---------|---------------------|----------|\n| `q.text()` | `text(...)` | `z.string()` |\n| `q.url()` | `text(...)` | `z.string().url()` |\n| `q.int()` | `integer(...)` | `z.number().int()` |\n| `q.bool()` | `boolean(...)` | `z.boolean()` |\n| `q.uuid()` | `uuid(...)` | `z.string().uuid()` |\n| `q.timestamp()` | `timestamp(...)` (converted to SQLite `text` on sqlite targets) | `z.coerce.date()` |\n| `q.json()` | `jsonb(...)` | `z.unknown()` (or the type you pass in) |\n| `q.enum(['a','b'])` | `text(..., { enum: [...] })` | `z.enum([...])` |\n| `q.id()` | `text('id').primaryKey()` | `z.string()` |\n| `q.scope(kind)` | `text(...).notNull()` | `z.string()` |\n\n`q.text()` and `q.url()` accept either a SQL-name string or an options object — `q.text({ sqlName: 'org_id', maxLength: 80 })`. `maxLength` adds `z.string().max(n)` at the validation edge; the SQL column stays `text` (D1 ignores `VARCHAR(n)` length anyway).\n\n`q.url()` is `q.text()` plus `z.string().url()` at the validation edge, so `javascript:` / `data:` URIs and free-form strings are rejected before they ever land in storage or get rendered in the CMS.\n\n`q.id()` emits a plain text primary key. Actual ID assignment at insert time is driven by the provider's `generateId` setting — prefixed UUIDs for D1, `crypto.randomUUID()` for Neon, etc. This keeps q's output decoupled from any specific ID library.\n\n### q.scope() — tenant scope columns\n\n`q.scope(kind)` is the canonical way to declare a column that holds a tenant-scope value (org / owner / team). It compiles to `text(...).notNull()` like a regular required text column, plus metadata that the compiler reads to:\n\n1. **Auto-derive the firewall predicate** — `q.scope('organization')` produces `[{ field: 'organizationId', equals: 'ctx.activeOrgId' }]` so you can omit the explicit `firewall:` block. (If `deletedAt` is present — and it is whenever the resource uses soft delete, which is the default — the `isNull(deletedAt)` predicate is appended automatically.)\n2. **Reject the column from client input** — scope fields land in `GUARDS_CONFIG.systemManaged` alongside the audit fields, so `POST { organizationId: 'org_other' }` returns 400 even if guards aren't otherwise configured.\n3. **Auto-populate on create / upsert** — the value is taken from the request context, not the request body.\n\n```typescript\ncolumns: {\n organizationId: q.scope('organization'), // → ctx.activeOrgId\n ownerId: q.scope('owner'), // → ctx.userId\n teamId: q.scope('team'), // → ctx.activeTeamId\n}\n```\n\nOverride the context source for non-default sources:\n\n```typescript\nownerId: q.scope('owner', { source: 'ctx.userId' }),\n```\n\n`q.scope()` is preferred over `q.text().required()` for tenant columns. Auto-detection on column names (`organizationId`, `userId`, etc.) still works as a fallback for projects bringing forward Drizzle schemas, but the explicit `q.scope()` form locks in the semantics in the source.\n\n### Naming Convention\n\nBy default, `q` picks the SQL column name from the JS key using the target database's conventional casing. Both `cloudflare-d1` and `neon` default to **`snake_case`** (`organizationId` → `organization_id`).\n\nYou can override for any project by setting `namingConvention` on the database provider config:\n\n```ts\n// quickback/quickback.config.ts\nexport default {\n providers: {\n database: {\n name: 'cloudflare-d1',\n config: {\n namingConvention: 'camelCase', // keep JS-style names in the SQL\n },\n },\n },\n};\n```\n\nFor one-off overrides on a specific column, pass an explicit name as the positional argument:\n\n```ts\norganizationId: q.scope('organization', { sqlName: 'org_id' }), // SQL name: 'org_id'\n```\n\n## Defining Tables with Drizzle\n\nIf you prefer Drizzle — or have an existing schema you're bringing forward — use `pgTable` / `sqliteTable` / `mysqlTable` directly:\n\n| Target Database | Import From | Table Function |\n|-----------------|-------------|----------------|\n| Cloudflare D1, Turso, SQLite | `drizzle-orm/sqlite-core` | `sqliteTable` |\n| Supabase, Neon, PostgreSQL | `drizzle-orm/pg-core` | `pgTable` |\n| PlanetScale, MySQL | `drizzle-orm/mysql-core` | `mysqlTable` |\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport const jobs = sqliteTable('jobs', {\n id: text('id').primaryKey(),\n organizationId: text('organization_id').notNull(),\n title: text('title').notNull(),\n department: text('department').notNull(),\n status: text('status').notNull(),\n salaryMin: integer('salary_min'),\n salaryMax: integer('salary_max'),\n});\n\nexport default defineTable(jobs, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"title\", \"department\", \"status\", \"salaryMin\", \"salaryMax\"],\n updatable: [\"title\", \"department\", \"status\"],\n },\n create: { /* ... */ },\n update: { /* ... */ },\n delete: { /* ... */ },\n});\n\nexport type Job = typeof jobs.$inferSelect;\n```\n\nWhen using Drizzle (rather than `q.scope()`), declare the firewall as a predicate array. Auto-detection still works on column names (`organizationId`, `ownerId`, `teamId`) so you can omit `firewall:` entirely if exactly one isolation column is present.\n\n### Choosing Between `q` and Drizzle\n\n| Pick `q` when | Pick Drizzle when |\n|---|---|\n| Starting a new feature from scratch | You already have Drizzle schemas to bring forward |\n| You want the same Zod across actions, forms, and routes | You need Drizzle-specific column options not yet in `q` (e.g., `decimal`, `varchar` with length, dialect-specific types) |\n| You prefer concise, Zod-native syntax | You prefer the explicit Drizzle dialect import per target |\n\nFeatures in the same project may mix freely — Quickback dispatches per feature.\n\n### Drizzle Column Types\n\nDrizzle supports all standard SQL column types:\n\n| Type | Drizzle Function | Example |\n|------|------------------|---------|\n| String | `text()`, `varchar()` | `text('name')` |\n| Integer | `integer()`, `bigint()` | `integer('count')` |\n| Boolean | `boolean()` | `boolean('is_active')` |\n| Timestamp | `timestamp()` | `timestamp('created_at')` |\n| JSON | `json()`, `jsonb()` | `jsonb('metadata')` |\n| UUID | `uuid()` | `uuid('id')` |\n| Decimal | `decimal()`, `numeric()` | `decimal('price', { precision: 10, scale: 2 })` |\n\n### Drizzle Column Modifiers\n\n```typescript\n// Required field\nname: text('name').notNull()\n\n// Default value\nisActive: boolean('is_active').default(true)\n\n// Primary key\nid: text('id').primaryKey()\n\n// Unique constraint\nemail: text('email').unique()\n\n// Default to current timestamp\ncreatedAt: timestamp('created_at').defaultNow()\n```\n\n## File Organization\n\nOrganize your tables by feature. Each feature directory contains table files:\n\n```\nquickback/\n├── quickback.config.ts\n└── features/\n ├── jobs/\n │ ├── jobs.ts # Main table + config\n │ ├── applications.ts # Related table + config\n │ └── actions.ts # Custom actions\n ├── candidates/\n │ ├── candidates.ts # Table + config\n │ └── candidate-notes.ts # Related table\n └── organizations/\n └── organizations.ts\n```\n\n**Key points:**\n- Tables with `export default defineTable(...)` get resource routes generated\n- Tables without a default export are internal (no routes, used for joins/relations)\n- Route paths are derived from filenames: `applications.ts` → `/api/v1/applications`\n\n### defineTable vs defineResource\n\n- **`defineTable`** — The standard function for defining tables with generated API routes\n- **`defineResource`** — Deprecated. Still works but emits a warning during compilation. Use `defineTable` instead.\n\n```typescript\n// Preferred:\nexport default defineTable(jobs, { /* config */ });\n```\n\n## 1 Resource = 1 Security Boundary\n\nEach `defineTable()` call defines a complete, self-contained security boundary. The security config you write — firewall, access, guards, and masking — is compiled into a single resource file that wraps all generated routes for that table.\n\nThis is a deliberate design choice. Mixing two resources with different security rules in one configuration would create ambiguity about which firewall, access, or masking rules apply to which table. By keeping it 1:1, there's never any question.\n\n| Scenario | What to do |\n|----------|------------|\n| Table needs its own API routes + security | Own file with `defineTable()` |\n| Table is internal/supporting (no direct API) | Extra `.ts` file in the parent feature directory, no `defineTable()` |\n\nA supporting table without `defineTable()` is useful when it's accessed internally — by action handlers, joins, or background jobs — but should never be directly exposed as its own API endpoint.\n\n## Internal Tables (No Routes)\n\nFor junction tables or internal data structures that shouldn't have API routes, simply omit the `defineTable` export. Add a `// @quickback-internal` marker so the compiler skips the \"no defineTable found\" warning:\n\n```typescript\n// quickback/features/jobs/interview-scores.ts\n\n// @quickback-internal — child table, no routes intentionally.\n\nexport const interviewScores = sqliteTable('interview_scores', {\n applicationId: text('application_id').notNull(),\n interviewerId: text('interviewer_id').notNull(),\n score: integer('score'),\n organizationId: text('organization_id').notNull(), // Scope junction tables for cascade soft-deletes\n});\n\n// No default export = no routes generated\n```\n\nThese internal tables still participate in the database schema and migrations — they just don't get API routes or security configuration. Without the `@quickback-internal` marker the compiler emits a warning per table, since the missing `defineTable` is more often a bug than a deliberate choice.\n\nThe compiler automatically injects the four **[audit fields](#audit-fields)** (`createdAt`/`createdBy`/`modifiedAt`/`modifiedBy`), the soft-delete pair (`deletedAt`/`deletedBy`, when soft delete is enabled), and **`organizationId`** into child/junction tables when the parent feature is org-scoped. This ensures cascade soft deletes and scoped queries work correctly without manual column definitions.\n\n## Audit Fields\n\nQuickback adds four audit columns to **every table** (including child/junction tables without `defineTable`) — never declare them in your schemas:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `createdAt` | timestamp | Set on insert |\n| `createdBy` | text | Actor that performed the insert (`ctx.userId`) |\n| `modifiedAt` | timestamp | Set on every insert and update |\n| `modifiedBy` | text | Actor that performed the latest insert/update (`ctx.userId`) |\n\nAudit fields are a separate concept from soft-delete (`deletedAt`/`deletedBy`) — they're always present, regardless of delete mode. See [Soft-Delete Fields](#soft-delete-fields) below.\n\nOpt out of audit injection entirely with `compiler.features.auditFields: false` in `quickback.config.ts`. (You almost never want to.)\n\n### How auto-injection works (two layers)\n\n\"Auto-injection\" covers two distinct steps. Conflating them is the most common source of confusion:\n\n1. **Schema injection (compile-time)** — the compiler adds the four columns to every Drizzle table. Idempotent: if you've authored a column with the same name yourself, the compiler leaves yours alone.\n2. **Runtime injection (per-write)** — a Proxy around the request-context `db` (`createAuditDb`, generated to `src/lib/audit-wrapper.ts`) intercepts `.insert(...).values(...)` and `.update(...).set(...)` and writes the audit columns from `ctx.userId` and the actual write moment.\n\nThe runtime layer **hard-stamps** every audit field on every write. Caller-supplied values for `createdAt`/`createdBy`/`modifiedAt`/`modifiedBy` are silently overwritten. This is intentional: the audit log can never be forged by a crafted request body or by a client echoing a row back into a PATCH.\n\n```ts\n// In a custom action handler — caller cannot fake audit attribution\nawait db.insert(records).values({\n id: createId(),\n status: 'active',\n createdBy: 'admin', // ← ignored; wrapper writes ctx.userId\n modifiedAt: '1999-01-01', // ← ignored; wrapper writes \"now\"\n});\n```\n\nWhat the caller is responsible for: `id` (the framework doesn't mint ids for you) and the domain fields.\n\nWhat the caller does *not* need to set: any of the four audit fields, ever.\n\n### Actors: who shows up in `createdBy` / `modifiedBy`\n\nThe wrapper writes whatever string is in `ctx.userId`. For user-driven requests this is the authenticated user's id — set by auth middleware before the handler runs. For non-user-driven entry points (inbound webhooks, cron, queue workers), you mint a synthetic actor id at the boundary so the audit log preserves provenance.\n\n**Inherit before you mint.** If a real user's request triggers cascades, hooks, or enqueues background jobs, every downstream write should carry that user's id — not a synthetic one. The cascade is part of the user's action. Only mint when there is genuinely no upstream user.\n\nWhen you do mint, use a single namespace and a stable convention:\n\n| Boundary | Actor id |\n|----------|----------|\n| Inbound webhook | `system:webhook-<provider>` (e.g. `system:webhook-stripe`) |\n| Scheduled / cron | `system:cron-<job>` (e.g. `system:cron-cleanup-stale`) |\n| Queue worker | `system:queue-<queue>` (e.g. `system:queue-embeddings-retry`) |\n| Quickback platform-internal write with no user upstream | `system:quickback` |\n| Out-of-band operator script | `system:script-<name>` |\n\nThe `system:` prefix marks \"not a real user\" — readable by anyone joining the audit columns to `users`, and cheap to filter on. Don't use `tenant:admin` or `quickback:admin`: those imply a human role nobody is actually playing. The tenant context is already on the row (in `organizationId`); the actor id is purely about *source*.\n\n### Failure mode: missing `ctx.userId`\n\nIf a write reaches the wrapper without a `ctx.userId`, the wrapper throws:\n\n```\naudit-wrapper: insert reached without ctx.userId.\nIf this is an intentional system-side write, use the unwrapped db directly.\n```\n\nTwo paths to fix it, depending on intent:\n\n- **Mint a synthetic actor** (preferred — preserves attribution) — populate `ctx.userId` with one of the conventions above before calling into your handler.\n- **Bypass the wrapper entirely** — use the unwrapped `createDb` instead of the request-context `db`. Use this only for migrations, schema repair, or backfill scripts where you genuinely don't want any audit attribution. The audit columns will fall back to DB defaults (`createdAt`/`modifiedAt` populate from `defaultNow()`; `createdBy`/`modifiedBy` end up `NULL`).\n\n### Disabling Audit Fields\n\nTo disable automatic audit fields for your project:\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n // ...\n compiler: {\n features: {\n auditFields: false, // Disable for entire project\n }\n }\n});\n```\n\nThis turns off both layers — schema injection and the runtime wrapper.\n\n## Soft-Delete Fields\n\n`deletedAt` and `deletedBy` are **not** audit fields. They're a separate, per-table mechanism for soft delete:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `deletedAt` | timestamp | Set when the record is soft-deleted |\n| `deletedBy` | text | Actor that performed the soft delete (`ctx.userId`) |\n\nThe compiler injects them only when the resource uses soft delete — i.e. when neither `delete.mode` nor `delete.batch.mode` is explicitly `'hard'`. Soft is the default, so most tables get the columns. Tables with both delete paths set to `'hard'` skip them entirely, which also drops the `isNull(deletedAt)` predicate from the firewall WHERE clause.\n\n```typescript\n// soft delete (default) — table gets deletedAt + deletedBy\ndelete: {}\n\n// hard delete — no deletedAt/deletedBy columns, no soft-delete predicate\ndelete: { mode: 'hard', batch: { mode: 'hard' } }\n```\n\n### Caller contract\n\nIn custom-action handlers, **passing `deletedAt` in `.set({})` is the signal** that this update is a soft delete. Any value works — the wrapper detects the field and overwrites both `deletedAt` and `deletedBy` with `now` and `ctx.userId`:\n\n```ts\nawait db.update(records)\n .set({ deletedAt: new Date() }) // signal — value is overwritten\n .where(eq(records.id, id));\n```\n\nYou don't set `deletedBy` yourself; the wrapper pairs it with the `deletedAt` signal.\n\n### Protected system fields\n\nThe audit and soft-delete columns are always protected from client input, even with `guards: false`:\n\n- `id` (when `generateId` is not `false`)\n- `createdAt`, `createdBy` *(audit — always present)*\n- `modifiedAt`, `modifiedBy` *(audit — always present)*\n- `deletedAt`, `deletedBy` *(soft-delete — present when delete mode allows soft)*\n\nProtection is enforced by the runtime wrapper — even if a request body passes one of these, it gets overwritten before the SQL is built.\n\n## Auto-Indexes\n\nThe compiler injects performance-critical indexes you'd otherwise have to author by hand. The pass runs after audit-field injection (so `deletedAt` is present) and is idempotent — if you already declared a matching index it's left alone.\n\n| Trigger | Index | Why |\n|---------|-------|-----|\n| Tenant column (`organizationId` / `organisationId` / `userId`) + `deletedAt` | Composite `(<isolation_col>, deletedAt)` | Every list query filters by isolation AND `deletedAt IS NULL` — a composite index lets D1/SQLite prune both predicates in one btree walk. |\n| Any FK column (`.references(() => other.id)`) | Single-column `(<fk_col>)` | SQLite/D1 don't auto-index FK columns, and the generated FK existence checks read by id on the parent. |\n| Any column that appears in a view's `read.query.sortable` allowlist (or `defaultSort`) | Single-column `(<col>)` | Sort scans go through an index instead of a full-table scan. |\n\nIndexes are emitted into the table's Drizzle extras callback (`(t) => ({ ... })`) and named `<table>_<col>_idx` (or `<table>_<col1>_<col2>_idx` for the composite). The `index` import is added to your schema's `drizzle-orm/<dialect>-core` import line if it isn't already there.\n\nYou can opt out of any auto-injected index by declaring your own with the same name or column set — the injector treats both as already-present and skips.\n\n## Ownership Fields\n\nFor the firewall to work, declare a tenant-scope column. With `q.scope()` (recommended), the compiler auto-derives the firewall predicate, marks the column as system-managed, and auto-populates it on create:\n\n```typescript\n// q DSL (recommended)\norganizationId: q.scope('organization') // → ctx.activeOrgId\nownerId: q.scope('owner') // → ctx.userId\nteamId: q.scope('team') // → ctx.activeTeamId\n```\n\nWhen using Drizzle directly, declare a regular column. Auto-detection picks it up by name; `q.scope()` semantics (systemManaged, auto-populate) still apply because they're keyed off the firewall predicate, not the column DSL:\n\n```typescript\n// Drizzle interop\norganizationId: text('organization_id').notNull()\nownerId: text('owner_id').notNull()\nteamId: text('team_id').notNull()\n```\n\n## Display Column\n\nWhen a table has foreign key columns (e.g., `departmentId` referencing `departments`), Quickback can automatically resolve the human-readable label in GET and LIST responses. This eliminates the need for frontend lookup calls.\n\n### Auto-Detection\n\nQuickback auto-detects the display column by checking for common column names in this order:\n\n`name` → `title` → `label` → `headline` → `subject` → `code` → `displayName` → `fullName` → `description`\n\nIf your `departments` table has a `name` column, it's automatically used as the display column. No config needed.\n\n### Explicit Override\n\nOverride the auto-detected column with `displayColumn`:\n\n```typescript\nexport default defineTable(interviewStages, {\n displayColumn: 'label', // Use 'label' instead of auto-detected 'name'\n read: { access: { roles: [\"hiring-manager\", \"recruiter\"] } },\n});\n```\n\n### Default Sort\n\nSet a default sort order for the CMS table list view with `defaultSort`:\n\n```typescript\nexport default defineTable(podcastEpisodes, {\n defaultSort: { field: \"createdAt\", order: \"desc\" },\n firewall: [{ exception: true }],\n read: { access: { roles: [\"PUBLIC\"] } },\n});\n```\n\nThe CMS applies this sort when the table first loads. Users can still click column headers to change the sort order.\n\n### How Labels Appear in Responses\n\nFor any FK column ending in `Id`, the API adds a `_label` field with the resolved display value:\n\n```json\n{\n \"id\": \"job_abc\",\n \"title\": \"Senior Engineer\",\n \"departmentId\": \"dept_xyz\",\n \"department_label\": \"Engineering\",\n \"locationId\": \"loc_123\",\n \"location_label\": \"San Francisco\"\n}\n```\n\nThe pattern is `{columnWithoutId}_label`. The frontend can find all labels with:\n\n```typescript\nObject.keys(record).filter(k => k.endsWith('_label'))\n```\n\nLabel resolution works within the same feature (tables in the same feature directory). System columns (`organizationId`, `createdBy`, `modifiedBy`) are never resolved.\n\nFor LIST endpoints, labels are batch-resolved efficiently — one query per FK column, not per record.\n\n## References\n\nWhen your FK columns don't match the target table name by convention (e.g., `vendorId` actually points to the `contact` table), declare explicit references so the CMS and schema registry know the correct target:\n\n```typescript\nexport default defineTable(applications, {\n references: {\n candidateId: \"candidate\",\n jobId: \"job\",\n referredById: \"candidate\",\n },\n // ... firewall, guards, crud\n});\n```\n\nEach key is a column name ending in `Id`, and the value is the camelCase table name it references. These mappings flow into the schema registry as `fkTarget` on each column, enabling the CMS to render typeahead/lookup inputs that search the correct table.\n\nConvention-based matching (strip `Id` suffix, look for a matching table) still works for simple cases like `projectId` → `project`. Use `references` only for columns where the convention doesn't match.\n\n## Input Hints\n\nControl how the CMS renders form inputs for specific columns. By default the CMS infers input types from the column's SQL type — `inputHints` lets you override that:\n\n```typescript\nexport default defineTable(jobs, {\n inputHints: {\n status: \"select\",\n department: \"select\",\n salaryMin: \"currency\",\n salaryMax: \"currency\",\n description: \"richtext\",\n },\n // ... firewall, guards, crud\n});\n```\n\n### Available Hint Values\n\n| Hint | Renders As |\n|------|-----------|\n| `richtext` | Rich text editor (tiptap) — bold, italic, headings, lists, links. Stores HTML. Lazy-loaded in edit mode, rendered as formatted HTML in view mode. |\n| `select` | Dropdown select (single value) |\n| `multi-select` | Multi-value select |\n| `radio` | Radio button group |\n| `checkbox` | Checkbox toggle |\n| `textarea` | Multi-line text input |\n| `lookup` | FK typeahead search |\n| `hidden` | Hidden from forms |\n| `color` | Color picker |\n| `date` | Date picker |\n| `datetime` | Date + time picker |\n| `time` | Time picker |\n| `currency` | Currency input with formatting |\n\nInput hints are emitted in the schema registry as `inputHints` on the table metadata, and the CMS reads them to render the appropriate form controls.\n\n### Rich Text Example\n\nFor fields that contain HTML content (e.g., blog posts, descriptions from RSS feeds), use `\"richtext\"`:\n\n```typescript\nexport default defineTable(podcastEpisodes, {\n inputHints: { description: \"richtext\" },\n // ...\n});\n```\n\nThe CMS will:\n- **View mode**: Render the HTML with proper formatting (headings, lists, links, etc.)\n- **Edit mode**: Load a tiptap rich text editor with a toolbar (bold, italic, H2, H3, bullet/ordered lists, links, code, undo/redo)\n- **Storage**: HTML strings — no format conversion needed, compatible with external HTML content\n\n## Relations (Optional)\n\nDrizzle supports defining relations for type-safe joins:\n\n```typescript\n\nexport const jobsRelations = relations(jobs, ({ one, many }) => ({\n organization: one(organizations, {\n fields: [jobs.organizationId],\n references: [organizations.id],\n }),\n applications: many(applications),\n}));\n```\n\n## Database Configuration\n\nConfigure database options in your Quickback config:\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n name: 'my-app',\n providers: {\n database: defineDatabase('cloudflare-d1', {\n generateId: 'prefixed', // 'uuid' | 'cuid' | 'nanoid' | 'short' | 'prefixed' | 'serial' | false\n namingConvention: 'snake_case', // 'camelCase' | 'snake_case'\n usePlurals: false, // Auth table names: 'users' vs 'user'\n }),\n },\n compiler: {\n features: {\n auditFields: true, // Auto-manage audit timestamps\n }\n }\n});\n```\n\n## Choosing Your Dialect\n\nUse the Drizzle dialect that matches your database provider:\n\n### SQLite (Cloudflare D1)\n\n```typescript\n\nexport const jobs = sqliteTable('jobs', {\n id: text('id').primaryKey(),\n title: text('title').notNull(),\n metadata: text('metadata', { mode: 'json' }), // JSON stored as text\n isOpen: integer('is_open', { mode: 'boolean' }).default(false),\n organizationId: text('organization_id').notNull(),\n});\n```\n\n### PostgreSQL (Neon)\n\n```typescript\n\nexport const jobs = pgTable('jobs', {\n id: serial('id').primaryKey(),\n title: text('title').notNull(),\n metadata: jsonb('metadata'), // Native JSONB\n isOpen: boolean('is_open').default(false),\n organizationId: text('organization_id').notNull(),\n});\n```\n\n### Key Differences\n\n| Feature | SQLite | PostgreSQL |\n|---------|--------|------------|\n| Boolean | `integer({ mode: 'boolean' })` | `boolean()` |\n| JSON | `text({ mode: 'json' })` | `jsonb()` or `json()` |\n| Auto-increment | `integer().primaryKey()` | `serial()` |\n| UUID | `text()` | `uuid()` |\n\n## Next Steps\n\n- [Configure the firewall](/compiler/definitions/firewall) for data isolation\n- [Set up access control](/compiler/definitions/access) for read and write operations\n- [Define guards](/compiler/definitions/guards) for field modification rules\n- [Add custom actions](/compiler/definitions/actions) for business logic"
115
131
  },
132
+ "compiler/definitions/scopes": {
133
+ "title": "Scopes & Capability Grants",
134
+ "content": "Org membership answers *\"which tenant is this caller in?\"* Scopes answer a different question: *\"this caller isn't an org member, but they're a **confirmed attendee of event E** — let them see exactly E's rows, as exactly the role they hold, and nothing else.\"*\n\nA **scope** is a tenant axis whose value is established by a **relationship you prove once** (at `POST /scope/v1/enter`) and then carry in a signed JWT claim — verified cryptographically on every later request with **no database round-trip**. It's the REST/JWT twin of the realtime ws-ticket.\n\n## When to use it\n\nReach for a scope when a principal must touch a bounded slice of an instance **without being an org member**:\n\n- **Event attendee** — reads their event's announcements / sessions, not the org.\n- **Shuttle driver** — sees only the passengers on *their* bus (a row slice), can DM them.\n- **F&B vendor** — reads dietary *counts*, zero attendee rows.\n- **Visiting nurse / carrier / contractor** — one patient's meds, one carrier's shipments.\n\nEach is *event-scoped* but a **distinct least-privilege role**. Org members are unaffected — they keep their normal tenant access.\n\n## The model\n\n### 1. Declare relationships + scopes\n\nA scope **kind** (`event`) declares named **roles**, each conferred by a relationship whose `from` row carries the role (and optionally a **sub-key** for row slicing):\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: { from: 'guests', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { status: 'confirmed' } },\n organizerOf: { from: 'staff', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { role: 'organizer' } },\n shuttleDriverOf: { from: 'staff', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { role: 'shuttleDriver' } },\n },\n scopes: {\n event: {\n requestField: 'eventId', // the body field the client sends to /enter\n roles: {\n attendee: { via: 'attendeeOf' },\n organizer: { via: 'organizerOf' },\n shuttleDriver: { via: 'shuttleDriverOf', subKeys: ['shuttleId'] }, // row-slice sub-key\n },\n },\n },\n}\n```\n\n### 2. Enter the scope\n\n```http\nPOST /scope/v1/enter (session OR existing JWT auth)\n{ \"eventId\": \"evt_123\" }\n```\n\nThe server probes **every declared role** for the proposed instance (one DB touch), and mints the proven roles + sub-keys into a signed JWT `scope` claim, returned via the `set-auth-token` header and the body:\n\n```jsonc\n// a shuttle driver who is also a confirmed guest\n\"scope\": { \"event\": { \"id\": \"evt_123\", \"roles\": [\"attendee\", \"shuttleDriver\"], \"shuttleId\": \"shA\" } }\n```\n\nThe client sends that JWT as `Authorization: Bearer …` on subsequent requests. The auth middleware verifies the signature and sets `ctx.scope` — **no DB**. The claim is carried forward on every authed call (rolling refresh) until you `enter` a different instance.\n\n> **Invariant:** the client only *proposes* the instance id (from the URL). The server proves membership before signing. No client-asserted scope is ever trusted.\n\n### 3. Gate the pillars\n\nScoped roles are referenced everywhere a pillar takes a role as the namespaced identifier **`scope:<kind>:<role>`**:\n\n```typescript\n// features/guests/guests.ts — the manifest, row-sliced + PII-masked\nexport default feature('guests', {\n columns: { /* … eventId, shuttleId, email, … */ },\n // org staff see the whole event; a shuttle driver sees only their bus\n firewall: {\n any: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { all: [\n { field: 'eventId', equals: 'ctx.scope.event' },\n { field: 'shuttleId', equals: 'ctx.scope.event.shuttleId' }, // sub-key row slice\n ] },\n ],\n },\n masking: {\n email: { type: 'email', show: { roles: ['admin', 'scope:event:organizer'] } }, // hidden from the driver\n },\n read: {\n views: {\n manifest: {\n fields: ['id', 'nameAtInvite', 'shuttleId', 'pickupLocation'],\n access: { roles: ['admin', 'scope:event:organizer', 'scope:event:shuttleDriver'] },\n },\n },\n },\n});\n```\n\n| Pillar | How it reads the scoped role |\n|--------|------------------------------|\n| **Firewall** (rows) | `all`/`any` arms keyed on `ctx.scope.<kind>` (+ sub-keys) — see [Firewall](/compiler/definitions/firewall) |\n| **Access** (verbs/views) | `access.roles: ['scope:event:shuttleDriver']` on CRUD, actions, and views |\n| **Masking** (fields) | `masking.<col>.show.roles` includes / excludes `scope:event:<role>` |\n\n## The org / scope split (security)\n\n**Scoped roles never merge into `ctx.roles`.** A `scope:*` identifier matches **only** the verified scope claim (`ctx.scope.<kind>.roles`); a bare org role (`admin`, `member`) matches **only** `ctx.roles`. The compiler enforces the split so an externally-provisioned `shuttleDriver` can **never** satisfy an `admin` gate by string coincidence, and a tampered scope claim can't impersonate an org role. This is the precondition for admitting limited outside users at all.\n\n## Sub-keys (row slicing)\n\nA role's `subKeys` name columns on the relationship's `from` row that are projected into the claim. A firewall arm then slices on them:\n\n```typescript\n{ field: 'shuttleId', equals: 'ctx.scope.event.shuttleId' }\n```\n\nBecause sub-key arms compose with `all`, an **absent** sub-key denies (`sql\\`1 = 0\\``) rather than widening — a driver can never see *all* shuttles by simply lacking the claim. The scope accessor is always emitted null-safe (`ctx.scope?.event?.shuttleId`), so an org caller who never entered the scope hits a clean deny, not a 500.\n\n### Set-valued sub-keys\n\nA driver may cover **more than one** bus. Append a `[]` marker to the\nsub-key name to project **every** matched `from` row's value into the claim\nas a `string[]`:\n\n```typescript\nroles: {\n shuttleDriver: { via: 'shuttleDriverOf', subKeys: ['shuttleId[]'] }, // set-valued\n}\n```\n\nThe `[]` is a marker only — it's stripped from the column name (the\nrelationship's `from` row still reads `shuttleId`). At `/scope/v1/enter` the\nproven rows union their values, so the claim carries an array:\n\n```jsonc\n\"scope\": { \"event\": { \"id\": \"evt_123\", \"roles\": [\"shuttleDriver\"], \"shuttleId\": [\"shA\", \"shC\"] } }\n```\n\nThe matching firewall arm — written exactly as for the scalar case\n(`{ field: 'shuttleId', equals: 'ctx.scope.event.shuttleId' }`) — is\n**rewritten by the compiler** to an `inArray` row-slice:\n\n```sql\nWHERE shuttle_id IN (ctx.scope?.event?.shuttleId ?? [])\n```\n\nThe `?? []` default makes an absent claim lower to `inArray(col, [])` — a\nclean DENY, never a malformed SQL fragment or a 500. A scalar sub-key (no\n`[]` marker) is untouched and keeps lowering to `eq`. You write the same\n`equals` arm either way; declaring `shuttleId[]` vs `shuttleId` in the scope\nrole is the only switch.\n\n## Auto-stamping the scope column on insert (`q.scope`)\n\n`q.scope('organization')` auto-stamps the tenant column on write, the same\nway `q.scope('owner')` stamps `ownerId`. A relationship-derived kind works\nidentically: `q.scope('event')` auto-stamps the column from the **verified\nscope claim** (`ctx.scope.event.id`) on insert — no need to pass `eventId`\nin the request body:\n\n```typescript\nexport const eventNotes = q.table('event_notes', {\n id: q.id(),\n eventId: q.scope('event'), // INSERT autofill from ctx.scope.event.id\n body: q.text().required(),\n organizationId: q.scope('organization'), // INSERT autofill from ctx.activeOrgId\n});\n```\n\nThe stamp is **insert-only** and null-safe — the generated CREATE handler\nwrites `eventId: ctx.scope?.event?.id`, so it never binds `undefined`. It\ndoes **not** add a read-time `WHERE` filter (that's the firewall's job; a\nread scoped to `eventId = ctx.scope.event.id` would be wrong here). Infra\nkinds map to their session fields (`organization` → `ctx.activeOrgId`,\n`owner` → `ctx.userId`, `team` → `ctx.activeTeamId`); any other kind maps to\n`ctx.scope.<kind>.id`.\n\n## Namespace scope-claim refresh\n\nA scope is normally minted at `POST /scope/v1/enter`. When you also mount a\n[namespace](/compiler/definitions/access#namespace-mounts-hoisted-relationship-middleware)\nthat gates `/event/:eventId/*` on the **same** relationship, the namespace\nresolver can refresh `ctx.scope.<kind>` in memory for the duration of that\nrequest — so an attendee hitting `/event/evt_123/announce` gets\n`ctx.scope.event = { id: 'evt_123', roles: ['attendee'] }` without a separate\n`enter` round-trip. The refresh runs **after** the gate (the gate proves the\nrelationship; the refresh stamps the proven role from the path param).\n\nThis is a strictly-guarded convenience, and it stamps **per matched lane**. The\nresolver records which `via:` lane opened the gate (first-match-wins) and stamps\n**only that lane's** scope role — an attendee who matched `attendeeOf` gets\n`roles: ['attendee']`; an organizer who matched `organizerOf` gets\n`roles: ['organizer']`. A caller can never receive a role they didn't prove this\nrequest.\n\n- **Relationship lanes** each confer their own scope role, stamped only when that exact lane matched — so a **multi-lane `via:`** (e.g. `via: ['attendeeOf', 'organizerOf']`) refreshes the matched lane's role, not an ambiguous union.\n- A **bulk-grant lane** (`{ roles: [...] }` or `{ team: true }`) confers **no** scope role — it opens the gate via the caller's org role *without* proving any relationship, so there is nothing to stamp (stamping one would forge it). The gate still passes; the caller is simply authorized by their org role.\n\nThe refresh described so far is in-memory and single-request. To also hand the\ncaller a **persisted** scope token, opt the namespace into `mintScope` — see\nbelow.\n\n### Gotcha: a namespace only emits its resolver when it claims a standalone action\n\nThis is the single most common surprise (it has tripped up a customer): **a\nnamespace emits its resolver — and therefore the scope refresh and the\n[`mintScope`](#mintscope-mint-the-scope-token-from-the-namespace-resolver)\nmint — only when at least one STANDALONE action's `path:` falls under the\nnamespace prefix.**\n\nA standalone action declares its own `path:` (e.g.\n`path: '/event/:eventId/home'`), so the compiler can match it against the\nnamespace prefix and hoist it into the synthetic namespace routes file.\n**Record-based actions are different** — they mount under their resource's CRUD\nroutes (`/api/v1/guests/:id/checkin`), which live *outside* the\n`/event/:eventId` prefix. They never match the prefix, so they never get\nclaimed.\n\nA namespace that contains **only** record-based actions is therefore **inert**:\nnothing matches the prefix, no synthetic routes file is emitted, and so there\nis **no resolver, no scope refresh, and no mint** — even though the namespace\nis declared and validates cleanly. The middleware you expected to gate\n`/event/:eventId/*` simply isn't there.\n\nThe fix is to give the namespace at least one standalone action under the\nprefix. In `q-events`, `eventHome` exists precisely for this — a standalone\n`GET /event/:eventId/home` that pulls the resolver (and the §5.3 mint) into\nexistence:\n\n```typescript\n// features/events/actions/eventHome.ts\nexport default defineAction({\n path: '/event/:eventId/home', // ← standalone path UNDER the namespace prefix\n method: 'GET',\n input: z.object({}),\n access: { roles: ['scope:event:attendee', 'scope:event:organizer', 'manager+'] },\n async execute({ db, ctx, c }) { /* … */ },\n});\n```\n\nWith that action present, the `eventScope` resolver is emitted, runs the\n`attendeeOf` probe once per `/event/:eventId/*` request, stamps\n`ctx.scope.event`, and (because the namespace sets `mintScope: true`) mints the\nscope token. Without a standalone action under the prefix, none of that fires.\n\n## `mintScope` — mint the scope token from the namespace resolver\n\nA scope is normally minted by an explicit `POST /scope/v1/enter` round-trip.\nSetting **`mintScope: true`** on a namespace folds that mint into the\nnamespace resolver: on a successful relationship probe the resolver MINTS a\npersisted scope JWT and returns it via the `set-auth-token` header — so a\nnative client hitting `/event/:eventId/*` gets a scope token **without ever\ncalling `/scope/v1/enter`**.\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'linkedUserId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'guests',\n exposeAs: 'guest',\n },\n },\n namespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: ['attendeeOf'], // one or more lanes — mints the matched lane's role\n mintScope: true, // ← fold the scope-token mint into the resolver\n },\n },\n}\n```\n\nA confirmed attendee then hits the standalone action under the prefix:\n\n```http\nGET /api/v1/event/evt_123/home\nAuthorization: Bearer <existing-jwt>\n\n200 OK\nset-auth-token: <new-scoped-jwt> ← carries scope.event.roles = [\"attendee\"]\n```\n\nThe client stores the `set-auth-token` value and sends it as the bearer on\nevery subsequent `/event/:eventId/*` request. The JWT carries\n`scope.event = { id: 'evt_123', roles: ['attendee'] }`, so the scoped-role\naccess checks (`scope:event:attendee`) pass with no DB touch and no second\n`enter` call.\n\n`mintScope` is **opt-in per namespace** and defaults to `false`. With it off,\nthe resolver does the in-memory `ctx.scope.<kind>` refresh only (the section\nabove); subsequent requests must still call `/scope/v1/enter` for a persisted\ntoken.\n\n### Per-matched-lane minting (forging safety)\n\nThe mint stamps the scope role of **whichever lane matched**, gated on the\nfirst-match-wins probe — the *same* per-lane discipline as the in-memory stamp,\napplied here with higher stakes: a minted token **persists for its whole TTL**,\nso it can only ever carry the role the caller actually proved this request.\n\n- A **multi-lane `via:`** (e.g. `via: ['attendeeOf', 'organizerOf']`) mints the matched lane's role — `attendeeOf` → `scope.event.roles = ['attendee']`, `organizerOf` → `['organizer']`. The resolver records which lane opened the gate, so there is no ambiguity.\n- A **bulk-grant lane** (`{ roles: [...] }` or `{ team: true }`) mints **no** scope role — it opens the gate via the caller's org role without proving a relationship. The gate passes; the caller carries their org role, not a minted scope role.\n\n> The realtime [ws-ticket](/stack/realtime/durable-objects#namespace-backed-tickets-per-matched-lane) can authorize through this same namespace `via:`, issuing a per-matched-lane WebSocket ticket — so the socket gate and the REST gate stay identical.\n\nIn every suppressed case the gate still authorizes the request; only the mint\n(and the in-memory refresh) are skipped, and those callers obtain a scope\ntoken through `/scope/v1/enter` as usual. Flipping `mintScope: true` can never\nforge a scope role — the guard, not the flag, is the gate.\n\n### TTL and best-effort semantics\n\n- **TTL is the scope-token TTL** — `auth.jwt.expiresIn` (default 180s), **clamped to a hard ≤180s ceiling** at the mint site. A longer-lived scope token would widen the post-revocation replay window past the spec bound, so the clamp is non-negotiable.\n- **The mint is gated by the same proven-relationship guard as the in-memory stamp.** It runs *after* the gate has granted access, reading the instance id from the proven path param (`:eventId`) — never from request input — so the minted `scope:<kind>:<role>` is backed by exactly the proof `/scope/v1/enter` requires. The token is **byte-identical** to one `/scope/v1/enter` would produce: same shared mint helper, same carry-forward of any *other* verified scope kinds already on the incoming token (the freshly-proven kind takes precedence; siblings survive the re-mint).\n- **The mint is best-effort.** A mint failure (e.g. a missing signing secret) **never fails the request** — the in-memory stamp already authorized it; the caller simply doesn't receive a refreshed token on that response and can fall back to `/scope/v1/enter`.\n\n## Revocation & TTL\n\nThe scope claim is trusted for the JWT TTL (default 180s, `auth.jwt.expiresIn`) — identical to how `orgId` / `role` claims already behave. Removing a guest/staff row takes effect within one TTL (the next `enter` won't re-mint the role). Immediate revocation (`auth.jwt.revocationCheck: 'kv'`) is on the roadmap.\n\n## Reference\n\n```typescript\n// AppContext (generated lib/types.ts)\nctx.scope?: Record<string, { id: string; roles?: string[]; [subKey: string]: string | string[] | undefined }>;\n\n// authz.scopes.<kind>\n{\n requestField: string; // body field carrying the instance id\n roles: Record<string, { via: string; subKeys?: string[] }>; // 'col' → eq, 'col[]' → inArray\n}\n```\n\n- `requestField` must equal every role-relationship's `resource.column`.\n- Each relationship's `from` table must exist and ship a generated firewall (it can't be `exception`).\n- A `subKeys` entry ending in `[]` is **set-valued** (lowers to `inArray`, minted as `string[]`); without the marker it's scalar (`eq`, minted as `string`).\n- `q.scope('<kind>')` auto-stamps the column from `ctx.scope.<kind>.id` on insert.\n- Generated route: `POST /scope/v1/enter` (mounted only when `authz.scopes` is declared)."
135
+ },
116
136
  "compiler/definitions/validation": {
117
137
  "title": "Validation",
118
138
  "content": "## Action Input Validation\n\nYou can validate input data in custom actions using Zod schemas. The input is validated before the action handler executes:\n\n```typescript\n// quickback/features/applications/actions.ts\n\nexport default defineActions(applications, {\n 'advance-stage': {\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().min(1).max(500).optional(),\n }),\n access: { roles: [\"owner\", \"hiring-manager\"] },\n execute: async ({ db, record, ctx, input }) => {\n // input is validated against the Zod schema before execution\n return record;\n },\n },\n});\n```\n\nIf validation fails, the API returns a `400 Bad Request` with details about which fields failed.\n\nSee [Actions](/compiler/definitions/actions) for the full action definition reference."
119
139
  },
120
140
  "compiler/definitions/views": {
121
141
  "title": "Views - Column Level Security",
122
- "content": "Views implement **Column Level Security (CLS)** - controlling which columns users can access. This complements **Row Level Security (RLS)** provided by the [Firewall](/compiler/definitions/firewall), which controls which rows users can access.\n\n> **Migration note**: views were previously declared at the resource top\n> level (`views: {...}`). In DSL v2 they live under\n> [`read.views`](/compiler/definitions/read#views-under-read-views) so the\n> read pipeline owns its own configuration. The top-level form is rejected\n> at compile time.\n\n| Security Layer | Controls | Quickback Feature |\n|----------------|----------|-------------------|\n| Row Level Security | Which records | Firewall |\n| Column Level Security | Which fields | Views |\n\nViews provide named field projections with role-based access control. Use views to return different sets of columns to different users without duplicating CRUD endpoints.\n\n## When to Use Views\n\n| Concept | Purpose | Example |\n|---------|---------|---------|\n| CRUD list | Full records | Returns all columns |\n| Masking | Hide values | Email `j***@c******.com` |\n| Views | Exclude columns | Only `id`, `name`, `source` |\n\n- **CRUD list** returns all fields to authorized users\n- **Masking** transforms sensitive values but still includes the column\n- **Views** completely exclude columns from the response\n\n## Basic Usage\n\n```typescript\n// features/candidates/candidates.ts\n\nexport const candidates = sqliteTable('candidates', {\n id: text('id').primaryKey(),\n name: text('name').notNull(),\n email: text('email').notNull(),\n phone: text('phone'),\n source: text('source'),\n resumeUrl: text('resume_url'),\n internalNotes: text('internal_notes'),\n organizationId: text('organization_id').notNull(),\n});\n\nexport default defineTable(candidates, {\n masking: {\n email: { type: 'email', show: { roles: ['hiring-manager', 'recruiter'] } },\n phone: { type: 'phone', show: { roles: ['hiring-manager', 'recruiter'] } },\n },\n\n read: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n\n // Named field projections\n views: {\n pipeline: {\n fields: ['id', 'name', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'phone', 'source', 'resumeUrl', 'internalNotes'],\n access: { roles: ['hiring-manager', 'recruiter'] },\n },\n report: {\n fields: ['id', 'name', 'source', 'createdAt'],\n access: { roles: ['owner', 'hiring-manager'] },\n },\n },\n },\n});\n```\n\n## Generated Endpoints\n\nEach named view generates a dedicated GET endpoint:\n\n```\nGET /api/v1/candidates # Full read - read.access fields\nGET /api/v1/candidates/views/pipeline # interviewer/recruiter/etc.\nGET /api/v1/candidates/views/full # hiring-manager/recruiter only\nGET /api/v1/candidates/views/report # report fields\n```\n\nIf `read.defaultView` is set, bare `GET /api/v1/candidates` can also resolve\nto that named view. Without `defaultView`, bare `GET /api/v1/candidates`\nreturns `VIEW_REQUIRED` once views are declared.\n\n## Query Parameters\n\nViews support the same query parameters as the list endpoint:\n\n### Pagination\n\n| Parameter | Description | Default | Max |\n|-----------|-------------|---------|-----|\n| `limit` | Number of records to return | 50 | 100 |\n| `offset` | Number of records to skip | 0 | - |\n\n```bash\n# Get first 10 records\nGET /api/v1/candidates/views/pipeline?limit=10\n\n# Get records 11-20\nGET /api/v1/candidates/views/pipeline?limit=10&offset=10\n```\n\n### Filtering\n\n```bash\n# Filter by exact value\nGET /api/v1/candidates/views/pipeline?source=linkedin\n\n# Filter with operators\nGET /api/v1/candidates/views/pipeline?createdAt.gt=2024-01-01\n\n# Multiple filters (AND logic)\nGET /api/v1/candidates/views/pipeline?source=linkedin&name.like=Smith\n```\n\n### Sorting\n\n| Parameter | Description | Default |\n|-----------|-------------|---------|\n| `sort` | Field to sort by | `createdAt` |\n| `order` | Sort direction (`asc` or `desc`) | `desc` |\n\n```bash\nGET /api/v1/candidates/views/pipeline?sort=name&order=asc\n```\n\n## Security\n\nAll four security pillars apply to views:\n\n| Pillar | Behavior |\n|--------|----------|\n| **Firewall** | WHERE clause applied (same as list) |\n| **Access** | Per-view access control |\n| **Guards** | N/A (read-only) |\n| **Masking** | Applied to returned fields |\n\n### Firewall\n\nViews automatically apply the same firewall conditions as the list endpoint. Users only see records within their organization scope.\n\n### Access Control\n\nEach view has its own access configuration:\n\n```typescript\nread: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n // Pipeline view - available to all roles\n pipeline: {\n fields: ['id', 'name', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n // Full view - recruiter and above\n full: {\n fields: ['id', 'name', 'source', 'email', 'phone', 'internalNotes'],\n access: { roles: ['hiring-manager', 'recruiter'] },\n },\n },\n}\n```\n\n### Masking\n\nMasking rules are applied to the returned fields. If a view includes a masked field like `email`, the masking rules still apply:\n\n```typescript\nmasking: {\n email: { type: 'email', show: { roles: ['hiring-manager', 'recruiter'] } },\n},\n\nread: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n // Even if an interviewer accesses the 'full' view, email will be masked\n // because masking rules take precedence\n full: {\n fields: ['id', 'name', 'email'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n },\n}\n```\n\n### How Views and Masking Work Together\n\nViews and masking are orthogonal concerns:\n- **Views** control field selection (which columns appear)\n- **Masking** controls field transformation (how values appear based on role)\n\nExample configuration:\n\n```typescript\nmasking: {\n email: { type: 'email', show: { roles: ['hiring-manager', 'recruiter'] } },\n},\n\nread: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n pipeline: {\n fields: ['id', 'name'], // email NOT included\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n full: {\n fields: ['id', 'name', 'email'], // email included\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n },\n}\n```\n\n| Endpoint | Role | `email` in response? | `email` value |\n|----------|------|---------------------|---------------|\n| `/views/pipeline` | interviewer | No | N/A |\n| `/views/pipeline` | recruiter | No | N/A |\n| `/views/full` | interviewer | Yes | `j***@c******.com` |\n| `/views/full` | recruiter | Yes | `jane@company.com` |\n\n## Aggregations\n\nViews can declare pre-computed aggregations that run alongside the row\nquery and surface as `aggregations: { ... }` on the response. This avoids a\ncustom standalone action for every \"count of X grouped by Y\" dashboard\ntile — the firewall and view filters already in place drive the metric.\n\n```typescript\nread: {\n access: { roles: ['owner', 'admin', 'member'] },\n views: {\n pipeline: {\n fields: ['id', 'jobId', 'candidateId', 'status', 'appliedAt'],\n aggregations: {\n totalApplications: { fn: 'count' },\n byStatus: { fn: 'groupBy', field: 'status' },\n },\n },\n },\n}\n```\n\nResponse now carries the aggregations alongside `data`:\n\n```json\n{\n \"data\": [/* paginated rows */],\n \"view\": \"pipeline\",\n \"pagination\": { \"count\": 50, \"page\": 1, \"pageSize\": 50, \"hasMore\": true },\n \"aggregations\": {\n \"totalApplications\": 173,\n \"byStatus\": {\n \"applied\": 102,\n \"screening\": 41,\n \"interview\": 18,\n \"offer\": 7,\n \"rejected\": 5\n }\n }\n}\n```\n\n### Supported aggregation functions\n\n| `fn` | `field` | Returns | Example |\n|---|---|---|---|\n| `sum` | required, numeric | scalar number | `{ fn: 'sum', field: 'guestCount' }` |\n| `avg` | required, numeric | scalar number | `{ fn: 'avg', field: 'salary' }` |\n| `min` | required | scalar number | `{ fn: 'min', field: 'price' }` |\n| `max` | required | scalar number | `{ fn: 'max', field: 'price' }` |\n| `count` | optional | `COUNT(*)` if omitted, `COUNT(field)` (non-null) if given | `{ fn: 'count' }` |\n| `count_distinct` | required | scalar number | `{ fn: 'count_distinct', field: 'sourceId' }` |\n| `groupBy` | required | `{ value: count }` map | `{ fn: 'groupBy', field: 'status' }` |\n\n`groupBy` always returns a count map keyed by the distinct values of `field`.\n`NULL` values bucket under the literal string `\"(none)\"`. Other rollup\nfunctions (`groupBy` + `sum` of another column) are deferred to a future\nrelease.\n\n### Filter and firewall inheritance\n\nAggregations always run over the **same** filtered, firewalled set as the\nrow query. Pagination is intentionally ignored — you get the value over\nevery matching record, not just the current page.\n\nIn practice: a request like\n`GET /applications/views/pipeline?status=applied&jobId=job_123&limit=10`\nreturns the first 10 applied rows for that job, AND `byStatus` reflects\nonly that filtered set (which will be `{ applied: <total> }` since the\nfilter pinned the status). This is the only consistent default — divorcing\nthe metric from the user's filters would surprise.\n\n### Constraints (compile-time)\n\n- `field` must reference a real column on the table.\n- `sum`/`avg` require numeric column types (`int`, `real`, `decimal`,\n `numeric`, `bigint`). Non-numeric columns are rejected at compile time.\n- The same masking opt-out gate that governs `query.{filterable, sortable,\n searchable}` applies to aggregations: the view's roles must satisfy the\n masking rule, otherwise the aggregation is rejected. (A `sum(salary)`\n leaks structure across the masked set even when the row payload is\n redacted.)\n- Aggregation names cannot collide with the reserved response fields\n `data`, `pagination`, `view`.\n- No raw SQL `expr:` form. Column references only — declare a generated\n column or write a custom action if you need arithmetic.\n\n## Response Format\n\nView responses include metadata about the view:\n\n```json\n{\n \"data\": [\n { \"id\": \"cnd_123\", \"name\": \"Jane Doe\", \"source\": \"linkedin\" },\n { \"id\": \"cnd_456\", \"name\": \"John Smith\", \"source\": \"referral\" }\n ],\n \"view\": \"pipeline\",\n \"pagination\": {\n \"count\": 2,\n \"page\": 1,\n \"pageSize\": 50,\n \"hasMore\": false\n }\n}\n```\n\nWhen the view declares `aggregations`, the response also includes an\n`aggregations: { ... }` field. See [Aggregations](#aggregations).\n\n## Complete Example\n\n```typescript\n// features/jobs/jobs.ts\nexport default defineTable(jobs, {\n guards: {\n createable: ['title', 'department', 'status', 'salaryMin', 'salaryMax'],\n updatable: ['title', 'department', 'status'],\n },\n\n masking: {\n salaryMin: { type: 'redact', show: { roles: ['owner', 'hiring-manager'] } },\n salaryMax: { type: 'redact', show: { roles: ['owner', 'hiring-manager'] } },\n },\n\n read: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n // Public job board view\n board: {\n fields: ['id', 'title', 'department', 'status'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n // Internal view with salary info\n internal: {\n fields: ['id', 'title', 'department', 'status', 'salaryMin', 'salaryMax'],\n access: { roles: ['owner', 'hiring-manager'] },\n },\n // Compensation report\n compensation: {\n fields: ['id', 'title', 'department', 'salaryMin', 'salaryMax'],\n access: { roles: ['owner', 'hiring-manager'] },\n },\n },\n },\n\n create: { access: { roles: ['owner', 'hiring-manager'] } },\n update: { access: { roles: ['owner', 'hiring-manager'] } },\n delete: { access: { roles: ['owner', 'hiring-manager'] } },\n});\n```"
142
+ "content": "Views implement **Column Level Security (CLS)** - controlling which columns users can access. This complements **Row Level Security (RLS)** provided by the [Firewall](/compiler/definitions/firewall), which controls which rows users can access.\n\n> **Migration note**: views were previously declared at the resource top\n> level (`views: {...}`). In DSL v2 they live under\n> [`read.views`](/compiler/definitions/read#views-under-read-views) so the\n> read pipeline owns its own configuration. The top-level form is rejected\n> at compile time.\n\n| Security Layer | Controls | Quickback Feature |\n|----------------|----------|-------------------|\n| Row Level Security | Which records | Firewall |\n| Column Level Security | Which fields | Views |\n\nViews provide named field projections with role-based access control. Use views to return different sets of columns to different users without duplicating CRUD endpoints.\n\n## When to Use Views\n\n| Concept | Purpose | Example |\n|---------|---------|---------|\n| CRUD list | Full records | Returns all columns |\n| Masking | Hide values | Email `j***@c******.com` |\n| Views | Exclude columns | Only `id`, `name`, `source` |\n\n- **CRUD list** returns all fields to authorized users\n- **Masking** transforms sensitive values but still includes the column\n- **Views** completely exclude columns from the response\n\n## Basic Usage\n\n```typescript\n// features/candidates/candidates.ts\n\nexport const candidates = sqliteTable('candidates', {\n id: text('id').primaryKey(),\n name: text('name').notNull(),\n email: text('email').notNull(),\n phone: text('phone'),\n source: text('source'),\n resumeUrl: text('resume_url'),\n internalNotes: text('internal_notes'),\n organizationId: text('organization_id').notNull(),\n});\n\nexport default defineTable(candidates, {\n masking: {\n email: { type: 'email', show: { roles: ['hiring-manager', 'recruiter'] } },\n phone: { type: 'phone', show: { roles: ['hiring-manager', 'recruiter'] } },\n },\n\n read: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n\n // Named field projections\n views: {\n pipeline: {\n fields: ['id', 'name', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'phone', 'source', 'resumeUrl', 'internalNotes'],\n access: { roles: ['hiring-manager', 'recruiter'] },\n },\n report: {\n fields: ['id', 'name', 'source', 'createdAt'],\n access: { roles: ['owner', 'hiring-manager'] },\n },\n },\n },\n});\n```\n\n## Generated Endpoints\n\nEach named view generates a dedicated GET endpoint:\n\n```\nGET /api/v1/candidates # Full read - read.access fields\nGET /api/v1/candidates/views/pipeline # interviewer/recruiter/etc.\nGET /api/v1/candidates/views/full # hiring-manager/recruiter only\nGET /api/v1/candidates/views/report # report fields\n```\n\nIf `read.defaultView` is set, bare `GET /api/v1/candidates` can also resolve\nto that named view. Without `defaultView`, bare `GET /api/v1/candidates`\nreturns `VIEW_REQUIRED` once views are declared.\n\n## Query Parameters\n\nViews support the same query parameters as the list endpoint:\n\n### Pagination\n\n| Parameter | Description | Default | Max |\n|-----------|-------------|---------|-----|\n| `limit` | Number of records to return | 50 | 100 |\n| `offset` | Number of records to skip | 0 | - |\n\n```bash\n# Get first 10 records\nGET /api/v1/candidates/views/pipeline?limit=10\n\n# Get records 11-20\nGET /api/v1/candidates/views/pipeline?limit=10&offset=10\n```\n\n### Filtering\n\n```bash\n# Filter by exact value\nGET /api/v1/candidates/views/pipeline?source=linkedin\n\n# Filter with operators\nGET /api/v1/candidates/views/pipeline?createdAt.gt=2024-01-01\n\n# Multiple filters (AND logic)\nGET /api/v1/candidates/views/pipeline?source=linkedin&name.like=Smith\n```\n\n### Sorting\n\n| Parameter | Description | Default |\n|-----------|-------------|---------|\n| `sort` | Field to sort by | `createdAt` |\n| `order` | Sort direction (`asc` or `desc`) | `desc` |\n\n```bash\nGET /api/v1/candidates/views/pipeline?sort=name&order=asc\n```\n\n## Security\n\nAll four security pillars apply to views:\n\n| Pillar | Behavior |\n|--------|----------|\n| **Firewall** | WHERE clause applied (same as list) |\n| **Access** | Per-view access control |\n| **Guards** | N/A (read-only) |\n| **Masking** | Applied to returned fields |\n\n### Firewall\n\nViews automatically apply the same firewall conditions as the list endpoint. Users only see records within their organization scope.\n\n### Access Control\n\nEach view has its own access configuration:\n\n```typescript\nread: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n // Pipeline view - available to all roles\n pipeline: {\n fields: ['id', 'name', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n // Full view - recruiter and above\n full: {\n fields: ['id', 'name', 'source', 'email', 'phone', 'internalNotes'],\n access: { roles: ['hiring-manager', 'recruiter'] },\n },\n },\n}\n```\n\n### Masking\n\nMasking rules are applied to the returned fields. If a view includes a masked field like `email`, the masking rules still apply:\n\n```typescript\nmasking: {\n email: { type: 'email', show: { roles: ['hiring-manager', 'recruiter'] } },\n},\n\nread: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n // Even if an interviewer accesses the 'full' view, email will be masked\n // because masking rules take precedence\n full: {\n fields: ['id', 'name', 'email'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n },\n}\n```\n\n### How Views and Masking Work Together\n\nViews and masking are orthogonal concerns:\n- **Views** control field selection (which columns appear)\n- **Masking** controls field transformation (how values appear based on role)\n\nExample configuration:\n\n```typescript\nmasking: {\n email: { type: 'email', show: { roles: ['hiring-manager', 'recruiter'] } },\n},\n\nread: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n pipeline: {\n fields: ['id', 'name'], // email NOT included\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n full: {\n fields: ['id', 'name', 'email'], // email included\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n },\n}\n```\n\n| Endpoint | Role | `email` in response? | `email` value |\n|----------|------|---------------------|---------------|\n| `/views/pipeline` | interviewer | No | N/A |\n| `/views/pipeline` | recruiter | No | N/A |\n| `/views/full` | interviewer | Yes | `j***@c******.com` |\n| `/views/full` | recruiter | Yes | `jane@company.com` |\n\n## Aggregations\n\nViews can declare pre-computed aggregations that run alongside the row\nquery and surface as `aggregations: { ... }` on the response. This avoids a\ncustom standalone action for every \"count of X grouped by Y\" dashboard\ntile — the firewall and view filters already in place drive the metric.\n\n```typescript\nread: {\n access: { roles: ['owner', 'admin', 'member'] },\n views: {\n pipeline: {\n fields: ['id', 'jobId', 'candidateId', 'status', 'appliedAt'],\n aggregations: {\n totalApplications: { fn: 'count' },\n byStatus: { fn: 'groupBy', field: 'status' },\n },\n },\n },\n}\n```\n\nResponse now carries the aggregations alongside `data`:\n\n```json\n{\n \"data\": [/* paginated rows */],\n \"view\": \"pipeline\",\n \"pagination\": { \"count\": 50, \"page\": 1, \"pageSize\": 50, \"hasMore\": true },\n \"aggregations\": {\n \"totalApplications\": 173,\n \"byStatus\": {\n \"applied\": 102,\n \"screening\": 41,\n \"interview\": 18,\n \"offer\": 7,\n \"rejected\": 5\n }\n }\n}\n```\n\n### Supported aggregation functions\n\n| `fn` | `field` | Returns | Example |\n|---|---|---|---|\n| `sum` | required, numeric | scalar number | `{ fn: 'sum', field: 'guestCount' }` |\n| `avg` | required, numeric | scalar number | `{ fn: 'avg', field: 'salary' }` |\n| `min` | required | scalar number | `{ fn: 'min', field: 'price' }` |\n| `max` | required | scalar number | `{ fn: 'max', field: 'price' }` |\n| `count` | optional | `COUNT(*)` if omitted, `COUNT(field)` (non-null) if given | `{ fn: 'count' }` |\n| `count_distinct` | required | scalar number | `{ fn: 'count_distinct', field: 'sourceId' }` |\n| `groupBy` | required | `{ value: count }` map | `{ fn: 'groupBy', field: 'status' }` |\n\n`groupBy` always returns a count map keyed by the distinct values of `field`.\n`NULL` values bucket under the literal string `\"(none)\"`. Other rollup\nfunctions (`groupBy` + `sum` of another column) are deferred to a future\nrelease.\n\n### Filter and firewall inheritance\n\nAggregations always run over the **same** filtered, firewalled set as the\nrow query. Pagination is intentionally ignored — you get the value over\nevery matching record, not just the current page.\n\nIn practice: a request like\n`GET /applications/views/pipeline?status=applied&jobId=job_123&limit=10`\nreturns the first 10 applied rows for that job, AND `byStatus` reflects\nonly that filtered set (which will be `{ applied: <total> }` since the\nfilter pinned the status). This is the only consistent default — divorcing\nthe metric from the user's filters would surprise.\n\n### Constraints (compile-time)\n\n- `field` must reference a real column on the table.\n- `sum`/`avg` require numeric column types (`int`, `real`, `decimal`,\n `numeric`, `bigint`). Non-numeric columns are rejected at compile time.\n- The same masking opt-out gate that governs `query.{filterable, sortable,\n searchable}` applies to aggregations: the view's roles must satisfy the\n masking rule, otherwise the aggregation is rejected. (A `sum(salary)`\n leaks structure across the masked set even when the row payload is\n redacted.)\n- Aggregation names cannot collide with the reserved response fields\n `data`, `pagination`, `view`.\n- No raw SQL `expr:` form. Column references only — declare a generated\n column or write a custom action if you need arithmetic.\n\n## Aggregate-only views\n\nA normal view returns rows *and* (optionally) aggregations. An\n**aggregate-only** view returns the rollup and **nothing else** — no\n`data[]`, no field selection. Set `aggregateOnly: true`:\n\n```typescript\nread: {\n views: {\n 'dietary-rollup': {\n aggregateOnly: true,\n fields: [], // must be empty/absent\n kMin: 5, // k-anonymity bucket size\n access: { roles: ['scope:event:fnb', 'admin'] },\n aggregations: {\n dietaryRollup: { fn: 'groupBy', field: 'dietaryNotes' },\n totalGuests: { fn: 'sum', field: 'guestCount' },\n headcount: { fn: 'count' },\n },\n },\n },\n}\n```\n\nThe response carries only `aggregations`:\n\n```json\n{\n \"view\": \"dietary-rollup\",\n \"aggregations\": {\n \"dietaryRollup\": { \"vegan\": 18, \"gluten-free\": 12, \"(none)\": 143 },\n \"totalGuests\": 184,\n \"headcount\": 173\n }\n}\n```\n\nThis lets a vendor see *\"12 guests need a gluten-free meal\"* without ever\nreading the roster. The endpoint is gated **independently** of the base\ncollection and the per-row views — reading the rollup grants zero row or\nfield access.\n\n**Constraints (compile-time):**\n\n- Requires a non-empty `aggregations` map.\n- `fields` must be empty or absent — field selection is disabled, and\n `?fields=` cannot coax row-level data out.\n- Only the view's `query.filterable` allowlist is honored. `query.searchable`\n and `query.sortable` are rejected (no `?search=`, no `?sort=`, no\n free-form `?<col>=` outside the allowlist).\n\n### `kMin` — k-anonymity suppression\n\n`kMin` (default `5`) protects against re-identification through small\nbuckets (\"1 guest, allergy = shellfish\"):\n\n- `groupBy` buckets with fewer than `kMin` rows collapse into a single\n `\"(other)\"` bucket carrying their summed count.\n- A scalar `count` / `sum` / `avg` / `min` / `max` / `count_distinct`\n computed over a filtered set smaller than `kMin` rows returns the literal\n string `\"(suppressed)\"` instead of a number.\n\n`kMin` is only meaningful on `aggregateOnly: true` views. It's ignored on\nrow-returning views, where the aggregations ride alongside the rows and the\nrow firewall already governs disclosure.\n\n## Response Format\n\nView responses include metadata about the view:\n\n```json\n{\n \"data\": [\n { \"id\": \"cnd_123\", \"name\": \"Jane Doe\", \"source\": \"linkedin\" },\n { \"id\": \"cnd_456\", \"name\": \"John Smith\", \"source\": \"referral\" }\n ],\n \"view\": \"pipeline\",\n \"pagination\": {\n \"count\": 2,\n \"page\": 1,\n \"pageSize\": 50,\n \"hasMore\": false\n }\n}\n```\n\nWhen the view declares `aggregations`, the response also includes an\n`aggregations: { ... }` field. See [Aggregations](#aggregations).\n\n## Complete Example\n\n```typescript\n// features/jobs/jobs.ts\nexport default defineTable(jobs, {\n guards: {\n createable: ['title', 'department', 'status', 'salaryMin', 'salaryMax'],\n updatable: ['title', 'department', 'status'],\n },\n\n masking: {\n salaryMin: { type: 'redact', show: { roles: ['owner', 'hiring-manager'] } },\n salaryMax: { type: 'redact', show: { roles: ['owner', 'hiring-manager'] } },\n },\n\n read: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n // Public job board view\n board: {\n fields: ['id', 'title', 'department', 'status'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n // Internal view with salary info\n internal: {\n fields: ['id', 'title', 'department', 'status', 'salaryMin', 'salaryMax'],\n access: { roles: ['owner', 'hiring-manager'] },\n },\n // Compensation report\n compensation: {\n fields: ['id', 'title', 'department', 'salaryMin', 'salaryMax'],\n access: { roles: ['owner', 'hiring-manager'] },\n },\n },\n },\n\n create: { access: { roles: ['owner', 'hiring-manager'] } },\n update: { access: { roles: ['owner', 'hiring-manager'] } },\n delete: { access: { roles: ['owner', 'hiring-manager'] } },\n});\n```"
123
143
  },
124
144
  "compiler/getting-started/claude-code": {
125
145
  "title": "AI Tools",
@@ -403,15 +423,19 @@ export const DOCS = {
403
423
  },
404
424
  "stack/realtime/durable-objects": {
405
425
  "title": "Realtime",
406
- "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## 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 via the `createRealtime(env)` helper described below.\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\nThe `createRealtime()` factory provides convenient methods for both Postgres Changes (CRUD events) and custom broadcasts:\n\n```typescript\n\nexport const execute: ActionExecutor = async ({ db, ctx, input }) => {\n const realtime = createRealtime(ctx.env);\n\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\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) |"
426
+ "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 via the `createRealtime(env)` helper described below.\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\nThe `createRealtime()` factory provides convenient methods for both Postgres Changes (CRUD events) and custom broadcasts:\n\n```typescript\n\nexport const execute: ActionExecutor = async ({ db, ctx, input }) => {\n const realtime = createRealtime(ctx.env);\n\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\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) |"
407
427
  },
408
428
  "stack/realtime": {
409
429
  "title": "Realtime",
410
430
  "content": "Quickback ships **two parallel realtime primitives**, both backed by Cloudflare Durable Objects:\n\n- **`/broadcast/v1/*` — server fan-out.** One DO instance per subscription scope. Postgres-changes events from CRUD routes plus custom broadcast events flow out to every subscriber, with role filtering and per-role field masking applied. Best for \"tell every client in this shared scope that something changed.\" The scope can be an organization, a specific user, or a compiler-resolved resource key like `events:evt_123`. Documented on this page.\n- **`/realtime/<binding>/<room-id>` — bidirectional rooms.** One DO instance per room (per document, per interview, per game). Client↔client messages, presence, and CRDT-friendly state. Use these for collaborative editing. See [PartyServer rooms](/stack/realtime/partyserver-rooms).\n\nBoth share the same auth model and ride on the same compiled worker; they solve different problems.\n\n## Architecture\n\n```\n┌──────────────────────────────────────────┐\n│ Quickback Worker │\n│ │\n│ ┌──────────┐ DO binding ┌────────────────────┐\n│ │ Hono API │ ──────────────► │ Broadcaster (DO) │\n│ │ │ │ WebSocket manager │\n│ └──────────┘ └─────────┬──────────┘\n│ │\n└─────────────────────────────────────────┼┘\n │ WebSocket\n │\n ┌────────▼─────────┐\n │ Browser Clients │\n │ (CMS, Account, │\n │ Admin, Custom) │\n └──────────────────┘\n```\n\nThe Broadcaster Durable Object runs **inline** in your main Quickback worker — no separate worker deployment needed. The API calls the DO directly via its binding (in-process, no network hop).\n\n1. **Quickback Worker** — Your compiled API with the Broadcaster DO class exported from the same worker.\n2. **Broadcaster (Durable Object)** — Manages WebSocket connections per subscription scope. One instance per `scopeKey`, organization, or user lane.\n3. **Browser Clients** — CMS, Account, Admin, and custom frontends connect via WebSocket on the same origin.\n\n## Key Features\n\n| Feature | Description |\n|---------|-------------|\n| Scope-aware fan-out | Routes by `scopeKey`, `organizationId`, or `userId` |\n| Role-based filtering | Only send events to users with matching roles |\n| Per-role masking | Different users see different field values based on their role |\n| User-specific targeting | Send events to a specific user within an org |\n| Resource-scoped tickets | Reuse authz relationship roles to mint scope-bound ws tickets |\n| Custom broadcasts | Arbitrary events beyond CRUD |\n| Custom namespaces | `defineRealtime()` for type-safe event helpers |\n| Ticket-based auth | HMAC-signed tickets verified at WebSocket upgrade — no HTTP round-trip |\n\n## Enabling Realtime\n\nAdd `realtime` to individual table definitions:\n\n```typescript\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n realtime: {\n enabled: true,\n onInsert: true,\n onUpdate: true,\n onDelete: true,\n requiredRoles: [\"recruiter\", \"hiring-manager\"],\n fields: [\"id\", \"candidateId\", \"stage\"],\n },\n});\n```\n\nAnd enable the realtime binding in your database config. The compiler generates the Durable Object class, helper functions, and wrangler bindings — all within your main worker.\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\nWith that config, `/broadcast/v1/ws-ticket` can authenticate the caller, verify the declared authz relationship role against `body.eventId`, and mint a short-lived ticket scoped to the resolved `events:<id>` channel.\n\n## Pages\n\n- **[Durable Objects Setup](/stack/realtime/durable-objects)** — Broadcaster configuration, wrangler bindings, event formats, masking, and custom namespaces\n- **[Using Realtime](/stack/realtime/using-realtime)** — Subscribing to `/broadcast/v1/*`: WebSocket connection, ticket auth, client-side handling\n- **[PartyServer Rooms](/stack/realtime/partyserver-rooms)** — Per-room collab via `/realtime/<binding>/<room-id>`: presence, live notes, room IDs"
411
431
  },
432
+ "stack/realtime/live-views": {
433
+ "title": "Live Views",
434
+ "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."
435
+ },
412
436
  "stack/realtime/partyserver-rooms": {
413
437
  "title": "PartyServer Rooms",
414
- "content": "When you need **client↔client** state — presence, live cursors, shared notes, concurrent editing — Quickback exposes [PartyServer](https://github.com/cloudflare/partykit) rooms at `/realtime/<binding>/<room-id>`. Each room is its own Durable Object instance, so isolation between rooms is automatic and the runtime hibernates idle rooms for free.\n\nThis is **separate from `/broadcast/v1/*`** (the org-wide server fan-out documented in [Using Realtime](/stack/realtime/using-realtime)). They share the worker and the auth model but solve different problems:\n\n| Concern | `/broadcast/v1/*` | `/realtime/<binding>/<room-id>` |\n|---|---|---|\n| Direction | Server → clients | Client ↔ clients |\n| Sharding | One DO per org | One DO per room |\n| Use case | Postgres-changes, app-wide events | Live cursors, shared edits, presence |\n| Catchup | Ephemeral | Per-room state survives reconnects |\n\n## When to use rooms vs broadcast\n\nReach for rooms when **the messages flow between users in the same context** (interview, document, game match). Reach for broadcast when **the server is publishing facts** that any client in the org may want to react to (a record was updated, a webhook fired, a role changed).\n\nYou can use both in the same project. Cost is the same.\n\n## Define a room class\n\nThe PartyServer `Server` class extends `DurableObject`, so any in-worker DO you wire up via `bindings.durableObjects` qualifies. The lifecycle hooks below are what PartyServer adds on top:\n\n```ts\n// quickback/features/interviews/lib/InterviewRoom.ts\n\nexport class InterviewRoom extends Server {\n static options = { hibernate: true };\n\n presence = new Map<string, { userId?: string; name?: string }>();\n\n onConnect(connection: Connection) {\n this.presence.set(connection.id, {});\n this.broadcastPresence();\n }\n\n onMessage(connection: Connection, message: WSMessage) {\n if (typeof message !== 'string') return;\n const parsed = JSON.parse(message);\n if (parsed.type === 'note') {\n this.broadcast(JSON.stringify({ type: 'note', from: connection.id, body: parsed.body }), [connection.id]);\n }\n }\n\n onClose(connection: Connection) {\n this.presence.delete(connection.id);\n this.broadcastPresence();\n }\n\n private broadcastPresence() {\n const peers = Array.from(this.presence.entries()).map(([id, meta]) => ({ id, ...meta }));\n this.broadcast(JSON.stringify({ type: 'presence', peers }));\n }\n}\n```\n\n## Wire it into your config\n\nOne entry under `bindings.durableObjects` is everything the compiler needs. The Server class lives under a `lib/` directory inside the feature (the same path the compiler uses for any in-worker shared code) — author it at `quickback/features/interviews/lib/InterviewRoom.ts`. The `from` value is the corresponding module path, no extension.\n\n```ts\n// quickback/quickback.config.ts\nexport default defineConfig({\n // ...\n bindings: {\n durableObjects: [\n {\n name: 'INTERVIEW_ROOM',\n className: 'InterviewRoom',\n from: 'features/interviews/lib/InterviewRoom',\n },\n ],\n },\n build: {\n dependencies: {\n partyserver: '^0.5.5',\n partysocket: '^1.1.18',\n },\n },\n});\n```\n\nThe compiler emits the `[[durable_objects.bindings]]` block, the `[[migrations]]` entry (SQLite-backed by default), and the class re-export from `src/index.ts`. **It also auto-mounts the `hono-party` middleware at `/realtime/*`** the moment any in-worker DO is declared, so URL routing follows PartyServer's own convention.\n\n## Connect from the client\n\nThe `partysocket` package handles reconnection, buffering, and resilience. The `party` field is the kebab-cased binding name (`INTERVIEW_ROOM` → `interview-room`); the `room` field is any opaque ID.\n\n```ts\n\nconst socket = new PartySocket({\n host: window.location.host,\n party: 'interview-room',\n room: 'interview-abc123',\n prefix: 'realtime',\n});\n\nsocket.addEventListener('message', (e) => {\n const msg = JSON.parse(e.data);\n if (msg.type === 'presence') updatePresence(msg.peers);\n if (msg.type === 'note') appendNote(msg.from, msg.body);\n});\n\nsocket.send(JSON.stringify({ type: 'note', body: 'asked about tenure' }));\n```\n\n## Authentication\n\nThe auto-mounted middleware is **secure by default** — anonymous WebSocket upgrades are rejected with `401 Unauthorized` before `partyserverMiddleware` sees the request. The four auth mechanisms the rest of the worker honors all unlock connections:\n\n- session cookie\n- `Authorization: Bearer <jwt>`\n- `x-api-key` header\n- `?api_key=` / `?key=` query parameter\n\n(For the hand-written mount form below, you can also accept signed `?ws_ticket=` query params using the same issuer the Broadcaster exposes at `/broadcast/v1/ws-ticket`.)\n\nThe default gate only checks **whether** the caller is authenticated, not whether they're allowed in *this* room. For per-room authorization, the `access` field on the binding lets the compiler emit a path-scoped gate that runs your existing resource firewall + `read.access` pipeline before the WebSocket upgrade — no hand-written code, same status semantics as `GET /api/v1/<resource>/:id`.\n\n### Per-room authorization via `access` (v0.12+)\n\n```ts\n// quickback/quickback.config.ts\nbindings: {\n durableObjects: [\n // Single-resource: roomId IS the row id of `chats`.\n // Auto-emits a gate at /realtime/chat/* that runs `chats`'s firewall.\n {\n name: 'Chat', className: 'Chat', from: 'lib/Chat',\n access: { resource: 'chats' },\n },\n\n // Multi-resource: roomId pattern dispatches kind → resource.\n // Auto-emits a gate at /realtime/notepad/* that parses\n // `day-note:<rowId>` | `interaction:<rowId>` | `record:<rowId>`\n // and runs the matched resource's firewall on the rowId.\n {\n name: 'Notepad', className: 'Notepad', from: 'lib/Notepad',\n access: {\n roomId: { pattern: '^(day-note|interaction|record):([A-Za-z0-9_-]+)$', kindGroup: 1, idGroup: 2 },\n resources: {\n 'day-note': { resource: 'day-notes' },\n 'interaction': { resource: 'interactions' },\n 'record': { resource: 'records' },\n },\n },\n },\n\n // Multi-table feature: pin the gate to a specific table so the\n // firewall + id query is unambiguous (v0.16.1+).\n {\n name: 'NotepadInteractions', className: 'NotepadInteractions', from: 'lib/NotepadInteractions',\n access: { resource: { feature: 'interactions', table: 'interactions' } },\n },\n\n // Genuinely public room (no auth, no row lookup) — opt out explicitly.\n { name: 'PublicLobby', className: 'PublicLobby', from: 'lib/PublicLobby',\n access: 'public' },\n ],\n}\n```\n\nWhat the compiler emits:\n\n- **`access: { resource: 'chats' }`** — `app.use('/realtime/chat/*', …)` that 401s anonymous, parses the URL segment as a row id, queries `chats` with the resource's `buildFirewallConditions(ctx)` and `eq(chats.id, rowId)`, and 403s when the row is invisible to the caller (out-of-org, soft-deleted, etc.). The DO's `onLoad` / `onConnect` then runs only for rows the user can already read.\n- **`access: { resource: { feature, table } }`** — same gate, but the schema import + firewall alias are keyed off the pinned `table` instead of the feature name. Required when a feature owns more than one resourceful table; the access gate emit can't pick which table's firewall to query otherwise.\n- **Multi-resource form** — same gate but with a regex parser dispatching to per-kind firewall lookups. Unknown kinds 400 at the gate. Each `resources[kind].resource` accepts either form (string shorthand or `{ feature, table }`).\n- **`access: 'public'`** — `app.use('/realtime/<kebab>/*', …)` that just passes through. Use for anonymous game lobbies / public collab pads where the room itself is the unit of access.\n- **No `access` declared** — falls through to the catchall `/realtime/*` gate that just checks `ctx.authenticated`. (v0.11.1 behavior.)\n\nCompile-time validation: every `resource` / `resources[].resource` value is checked against the project's feature names so typos surface as build errors, not as runtime 400s on the first WS upgrade. The string shorthand requires the feature to have exactly one resourceful table; multi-table features must use the long form `{ feature, table }` to pin a specific table.\n\n### Hand-written mount with `onBeforeConnect`\n\nPartyServer also accepts an `onBeforeConnect` hook that runs before the WebSocket upgrade. Reject the upgrade by returning a `Response`; otherwise return `undefined` (or a modified `Request`) and the connection proceeds. Use this when you want a different auth shape than the default — for example, requiring `?ws_ticket=` exclusively (and rejecting raw header / query api-keys), or running per-room checks at the gate instead of in `onConnect`:\n\n```ts\n\napp.use('/realtime/*', partyserverMiddleware({\n options: {\n prefix: 'realtime',\n onBeforeConnect: async (req) => {\n const token = new URL(req.url).searchParams.get('ws_ticket');\n if (!token || !await verifyTicket(token)) {\n return new Response('Unauthorized', { status: 401 });\n }\n },\n },\n}));\n```\n\nThe matching `ws_ticket` issuer is the same one the Broadcaster already uses at `/broadcast/v1/ws-ticket` — generate a ticket from your authenticated UI, pass it as a query param on the WebSocket URL, and verify it inside `onBeforeConnect`. To use this hand-written form, declare a custom route at `/realtime/*` *before* the auto-mount runs (Hono dispatches the first matching middleware) — that lets you opt out of the default auth gate or layer per-room access checks at the upgrade step.\n\n## CRDT-grade document collab (Yjs)\n\nDrop in [`Y-PartyServer`](https://github.com/cloudflare/partykit) when you need true concurrent text/document editing. It's a `Server` subclass that wraps Yjs's sync protocol; everything else above stays the same.\n\n```ts\n\nexport class DocumentRoom extends YServer {\n // Yjs doc lives on `this.doc`; sync protocol is automatic.\n // Override `onLoad()` / `onSave()` to persist to R2 / KV / your DB.\n}\n```\n\n## Why this and not the Broadcaster\n\nThe Broadcaster is a one-DO-per-org fan-out. It can't shard by document, and it doesn't model client→client messages. PartyServer's per-room model is the right primitive for collab; the Broadcaster's per-org model is the right primitive for \"tell everyone in this org that X happened.\" Run both."
438
+ "content": "When you need **client↔client** state — presence, live cursors, shared notes, concurrent editing — Quickback exposes [PartyServer](https://github.com/cloudflare/partykit) rooms at `/realtime/<binding>/<room-id>`. Each room is its own Durable Object instance, so isolation between rooms is automatic and the runtime hibernates idle rooms for free.\n\nThis is **separate from `/broadcast/v1/*`** (the org-wide server fan-out documented in [Using Realtime](/stack/realtime/using-realtime)). They share the worker and the auth model but solve different problems:\n\n| Concern | `/broadcast/v1/*` | `/realtime/<binding>/<room-id>` |\n|---|---|---|\n| Direction | Server → clients | Client ↔ clients |\n| Sharding | One DO per org | One DO per room |\n| Use case | Postgres-changes, app-wide events | Live cursors, shared edits, presence |\n| Catchup | Ephemeral | Per-room state survives reconnects |\n\n## When to use rooms vs broadcast\n\nReach for rooms when **the messages flow between users in the same context** (interview, document, game match). Reach for broadcast when **the server is publishing facts** that any client in the org may want to react to (a record was updated, a webhook fired, a role changed).\n\nYou can use both in the same project. Cost is the same.\n\n## Define a room class\n\nThe PartyServer `Server` class extends `DurableObject`, so any in-worker DO you wire up via `bindings.durableObjects` qualifies. The lifecycle hooks below are what PartyServer adds on top:\n\n```ts\n// quickback/features/interviews/lib/InterviewRoom.ts\n\nexport class InterviewRoom extends Server {\n static options = { hibernate: true };\n\n presence = new Map<string, { userId?: string; name?: string }>();\n\n onConnect(connection: Connection) {\n this.presence.set(connection.id, {});\n this.broadcastPresence();\n }\n\n onMessage(connection: Connection, message: WSMessage) {\n if (typeof message !== 'string') return;\n const parsed = JSON.parse(message);\n if (parsed.type === 'note') {\n this.broadcast(JSON.stringify({ type: 'note', from: connection.id, body: parsed.body }), [connection.id]);\n }\n }\n\n onClose(connection: Connection) {\n this.presence.delete(connection.id);\n this.broadcastPresence();\n }\n\n private broadcastPresence() {\n const peers = Array.from(this.presence.entries()).map(([id, meta]) => ({ id, ...meta }));\n this.broadcast(JSON.stringify({ type: 'presence', peers }));\n }\n}\n```\n\n## Wire it into your config\n\nOne entry under `bindings.durableObjects` is everything the compiler needs. The Server class lives under a `lib/` directory inside the feature (the same path the compiler uses for any in-worker shared code) — author it at `quickback/features/interviews/lib/InterviewRoom.ts`. The `from` value is the corresponding module path, no extension.\n\n```ts\n// quickback/quickback.config.ts\nexport default defineConfig({\n // ...\n bindings: {\n durableObjects: [\n {\n name: 'INTERVIEW_ROOM',\n className: 'InterviewRoom',\n from: 'features/interviews/lib/InterviewRoom',\n },\n ],\n },\n build: {\n dependencies: {\n partyserver: '^0.5.5',\n partysocket: '^1.1.18',\n },\n },\n});\n```\n\nThe compiler emits the `[[durable_objects.bindings]]` block, the `[[migrations]]` entry (SQLite-backed by default), and the class re-export from `src/index.ts`. **It also auto-mounts the `hono-party` middleware at `/realtime/*`** the moment any in-worker DO is declared, so URL routing follows PartyServer's own convention.\n\n## Connect from the client\n\nThe `partysocket` package handles reconnection, buffering, and resilience. The `party` field is the kebab-cased binding name (`INTERVIEW_ROOM` → `interview-room`); the `room` field is any opaque ID.\n\n```ts\n\nconst socket = new PartySocket({\n host: window.location.host,\n party: 'interview-room',\n room: 'interview-abc123',\n prefix: 'realtime',\n});\n\nsocket.addEventListener('message', (e) => {\n const msg = JSON.parse(e.data);\n if (msg.type === 'presence') updatePresence(msg.peers);\n if (msg.type === 'note') appendNote(msg.from, msg.body);\n});\n\nsocket.send(JSON.stringify({ type: 'note', body: 'asked about tenure' }));\n```\n\n## Authentication\n\nThe auto-mounted middleware is **secure by default** — anonymous WebSocket upgrades are rejected with `401 Unauthorized` before `partyserverMiddleware` sees the request. The four auth mechanisms the rest of the worker honors all unlock connections:\n\n- session cookie\n- `Authorization: Bearer <jwt>`\n- `x-api-key` header\n- `?api_key=` / `?key=` query parameter\n\n(For the hand-written mount form below, you can also accept signed `?ws_ticket=` query params using the same issuer the Broadcaster exposes at `/broadcast/v1/ws-ticket`.)\n\nThe default gate only checks **whether** the caller is authenticated, not whether they're allowed in *this* room. For per-room authorization, the `access` field on the binding lets the compiler emit a path-scoped gate that runs your existing resource firewall + `read.access` pipeline before the WebSocket upgrade — no hand-written code, same status semantics as `GET /api/v1/<resource>/:id`.\n\n### Per-room authorization via `access` (v0.12+)\n\n```ts\n// quickback/quickback.config.ts\nbindings: {\n durableObjects: [\n // Single-resource: roomId IS the row id of `chats`.\n // Auto-emits a gate at /realtime/chat/* that runs `chats`'s firewall.\n {\n name: 'Chat', className: 'Chat', from: 'lib/Chat',\n access: { resource: 'chats' },\n },\n\n // Multi-resource: roomId pattern dispatches kind → resource.\n // Auto-emits a gate at /realtime/notepad/* that parses\n // `day-note:<rowId>` | `interaction:<rowId>` | `record:<rowId>`\n // and runs the matched resource's firewall on the rowId.\n {\n name: 'Notepad', className: 'Notepad', from: 'lib/Notepad',\n access: {\n roomId: { pattern: '^(day-note|interaction|record):([A-Za-z0-9_-]+)$', kindGroup: 1, idGroup: 2 },\n resources: {\n 'day-note': { resource: 'day-notes' },\n 'interaction': { resource: 'interactions' },\n 'record': { resource: 'records' },\n },\n },\n },\n\n // Multi-table feature: pin the gate to a specific table so the\n // firewall + id query is unambiguous (v0.16.1+).\n {\n name: 'NotepadInteractions', className: 'NotepadInteractions', from: 'lib/NotepadInteractions',\n access: { resource: { feature: 'interactions', table: 'interactions' } },\n },\n\n // Room keyed by a unique non-PK column (v0.36+). A Yjs page editor is\n // addressed by `event_pages.yjsRoomId`, not the row id — `key` tells the\n // gate which column the roomId matches.\n {\n name: 'PageRoom', className: 'PageRoom', from: 'lib/PageRoom',\n access: { resource: { feature: 'event-pages', table: 'eventPages', key: 'yjsRoomId' } },\n },\n\n // Genuinely public room (no auth, no row lookup) — opt out explicitly.\n { name: 'PublicLobby', className: 'PublicLobby', from: 'lib/PublicLobby',\n access: 'public' },\n ],\n}\n```\n\nWhat the compiler emits:\n\n- **`access: { resource: 'chats' }`** — `app.use('/realtime/chat/*', …)` that 401s anonymous, parses the URL segment as a row id, queries `chats` with the resource's `buildFirewallConditions(ctx)` and `eq(chats.id, rowId)`, and 403s when the row is invisible to the caller (out-of-org, soft-deleted, etc.). The DO's `onLoad` / `onConnect` then runs only for rows the user can already read.\n- **`access: { resource: { feature, table } }`** — same gate, but the schema import + firewall alias are keyed off the pinned `table` instead of the feature name. Required when a feature owns more than one resourceful table; the access gate emit can't pick which table's firewall to query otherwise.\n- **`access: { resource: { feature, table, key } }`** — same gate, but it matches the roomId against `table.<key>` instead of `table.id`. Use it when the room is addressed by a unique non-PK column — e.g. a Yjs editor keyed by `event_pages.yjsRoomId` (`ns.idFromName(row.yjsRoomId)`). `key` defaults to `'id'`, so existing pins are unchanged. The compiler validates the column exists at compile time. `key` also works inside each multi-resource branch.\n- **Multi-resource form** — same gate but with a regex parser dispatching to per-kind firewall lookups. Unknown kinds 400 at the gate. Each `resources[kind].resource` accepts either form (string shorthand or `{ feature, table, key? }`).\n- **`access: 'public'`** — `app.use('/realtime/<kebab>/*', …)` that just passes through. Use for anonymous game lobbies / public collab pads where the room itself is the unit of access.\n- **No `access` declared** — falls through to the catchall `/realtime/*` gate that just checks `ctx.authenticated`. (v0.11.1 behavior.)\n\nCompile-time validation: every `resource` / `resources[].resource` value is checked against the project's feature names so typos surface as build errors, not as runtime 400s on the first WS upgrade. The string shorthand requires the feature to have exactly one resourceful table; multi-table features must use the long form `{ feature, table }` to pin a specific table. When `key` is set, the column is checked against the pinned table's schema.\n\n### Migrating a hand-rolled `onConnect` room to a declarative gate\n\nIf a room currently enforces access by hand inside `onConnect` / `onBeforeConnect` — typically because the room sits on a multi-table feature and an earlier compiler refused the ambiguous string shorthand — you can almost always replace it with a declarative `access` block. The decision is just \"what is the roomId?\":\n\n1. **roomId is a table's row id** → `access: { resource: { feature, table } }`.\n2. **roomId is a unique non-PK column** (a slug, a `yjsRoomId`) → add `key`: `access: { resource: { feature, table, key: 'yjsRoomId' } }`.\n3. **one DO class serves several room kinds** (e.g. `conv-<id>` / `ticket-<id>`) → the multi-resource form with a `pattern` that captures the kind and id.\n4. **access depends on membership, not just tenant** (e.g. \"is this user an attendee of the event that owns this page\") → you do **not** need hand-written code. Declare the pinned table's firewall with a `via:` relationship; the gate runs the table's *full* `buildFirewallConditions`, relationship subqueries included.\n\nThe declarative gate runs the exact firewall the CRUD `GET /:id` handler enforces, with the same 401/403 semantics, *before* the WebSocket upgrade — so by the time `onConnect` fires the caller is already authorized. Dropping the hand-rolled check also closes a common gap: a room with no `access` block is reachable by **any** authenticated user who can guess a room id, regardless of tenant.\n\n### Hand-written mount with `onBeforeConnect`\n\nPartyServer also accepts an `onBeforeConnect` hook that runs before the WebSocket upgrade. Reject the upgrade by returning a `Response`; otherwise return `undefined` (or a modified `Request`) and the connection proceeds. Use this when you want a different auth shape than the default — for example, requiring `?ws_ticket=` exclusively (and rejecting raw header / query api-keys), or running per-room checks at the gate instead of in `onConnect`:\n\n```ts\n\napp.use('/realtime/*', partyserverMiddleware({\n options: {\n prefix: 'realtime',\n onBeforeConnect: async (req) => {\n const token = new URL(req.url).searchParams.get('ws_ticket');\n if (!token || !await verifyTicket(token)) {\n return new Response('Unauthorized', { status: 401 });\n }\n },\n },\n}));\n```\n\nThe matching `ws_ticket` issuer is the same one the Broadcaster already uses at `/broadcast/v1/ws-ticket` — generate a ticket from your authenticated UI, pass it as a query param on the WebSocket URL, and verify it inside `onBeforeConnect`. To use this hand-written form, declare a custom route at `/realtime/*` *before* the auto-mount runs (Hono dispatches the first matching middleware) — that lets you opt out of the default auth gate or layer per-room access checks at the upgrade step.\n\n## CRDT-grade document collab (Yjs)\n\nDrop in [`Y-PartyServer`](https://github.com/cloudflare/partykit) when you need true concurrent text/document editing. It's a `Server` subclass that wraps Yjs's sync protocol; everything else above stays the same.\n\n```ts\n\nexport class DocumentRoom extends YServer {\n // Yjs doc lives on `this.doc`; sync protocol is automatic.\n // Override `onLoad()` / `onSave()` to persist to R2 / KV / your DB.\n}\n```\n\n## Why this and not the Broadcaster\n\nThe Broadcaster is a one-DO-per-org fan-out. It can't shard by document, and it doesn't model client→client messages. PartyServer's per-room model is the right primitive for collab; the Broadcaster's per-org model is the right primitive for \"tell everyone in this org that X happened.\" Run both."
415
439
  },
416
440
  "stack/realtime/using-realtime": {
417
441
  "title": "Using Realtime",
@@ -483,14 +507,19 @@ export const TOPIC_LIST = [
483
507
  "compiler/config/variables",
484
508
  "compiler/definitions/access",
485
509
  "compiler/definitions/actions",
510
+ "compiler/definitions/arrows",
486
511
  "compiler/definitions/concepts",
512
+ "compiler/definitions/diagnostics",
487
513
  "compiler/definitions/feature",
514
+ "compiler/definitions/fga",
488
515
  "compiler/definitions/firewall",
489
516
  "compiler/definitions/guards",
490
517
  "compiler/definitions",
491
518
  "compiler/definitions/masking",
519
+ "compiler/definitions/permissions",
492
520
  "compiler/definitions/read",
493
521
  "compiler/definitions/schema",
522
+ "compiler/definitions/scopes",
494
523
  "compiler/definitions/validation",
495
524
  "compiler/definitions/views",
496
525
  "compiler/getting-started/claude-code",
@@ -565,6 +594,7 @@ export const TOPIC_LIST = [
565
594
  "stack/queues/using-queues",
566
595
  "stack/realtime/durable-objects",
567
596
  "stack/realtime",
597
+ "stack/realtime/live-views",
568
598
  "stack/realtime/partyserver-rooms",
569
599
  "stack/realtime/using-realtime",
570
600
  "stack/storage",