@quickback-dev/cli 0.34.3 → 0.39.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/dist/commands/compile.d.ts.map +1 -1
  2. package/dist/commands/compile.js +36 -2
  3. package/dist/commands/compile.js.map +1 -1
  4. package/dist/commands/compile.test.d.ts +2 -0
  5. package/dist/commands/compile.test.d.ts.map +1 -0
  6. package/dist/commands/compile.test.js +83 -0
  7. package/dist/commands/compile.test.js.map +1 -0
  8. package/dist/commands/create.js +15 -11
  9. package/dist/commands/create.js.map +1 -1
  10. package/dist/commands/migrations.d.ts +33 -0
  11. package/dist/commands/migrations.d.ts.map +1 -1
  12. package/dist/commands/migrations.js +41 -2
  13. package/dist/commands/migrations.js.map +1 -1
  14. package/dist/commands/migrations.test.d.ts +2 -0
  15. package/dist/commands/migrations.test.d.ts.map +1 -0
  16. package/dist/commands/migrations.test.js +67 -0
  17. package/dist/commands/migrations.test.js.map +1 -0
  18. package/dist/docs/content.d.ts.map +1 -1
  19. package/dist/docs/content.js +56 -26
  20. package/dist/docs/content.js.map +1 -1
  21. package/dist/examples/recruitment.tar.gz +0 -0
  22. package/dist/index.js +1 -1
  23. package/dist/lib/action-harvest.d.ts +48 -0
  24. package/dist/lib/action-harvest.d.ts.map +1 -0
  25. package/dist/lib/action-harvest.js +292 -0
  26. package/dist/lib/action-harvest.js.map +1 -0
  27. package/dist/lib/action-harvest.test.d.ts +2 -0
  28. package/dist/lib/action-harvest.test.d.ts.map +1 -0
  29. package/dist/lib/action-harvest.test.js +112 -0
  30. package/dist/lib/action-harvest.test.js.map +1 -0
  31. package/dist/lib/api-client.d.ts +10 -0
  32. package/dist/lib/api-client.d.ts.map +1 -1
  33. package/dist/lib/api-client.js +17 -1
  34. package/dist/lib/api-client.js.map +1 -1
  35. package/dist/lib/api-client.test.js +19 -0
  36. package/dist/lib/api-client.test.js.map +1 -1
  37. package/dist/lib/artifact-routing.d.ts +1 -0
  38. package/dist/lib/artifact-routing.d.ts.map +1 -1
  39. package/dist/lib/artifact-routing.js +15 -3
  40. package/dist/lib/artifact-routing.js.map +1 -1
  41. package/dist/lib/artifact-routing.test.js +12 -1
  42. package/dist/lib/artifact-routing.test.js.map +1 -1
  43. package/dist/lib/file-loader.d.ts +1 -0
  44. package/dist/lib/file-loader.d.ts.map +1 -1
  45. package/dist/lib/file-loader.js +34 -1
  46. package/dist/lib/file-loader.js.map +1 -1
  47. package/dist/lib/file-loader.test.js +28 -4
  48. package/dist/lib/file-loader.test.js.map +1 -1
  49. package/dist/lib/prepare-state-output.d.ts +8 -0
  50. package/dist/lib/prepare-state-output.d.ts.map +1 -0
  51. package/dist/lib/prepare-state-output.js +17 -0
  52. package/dist/lib/prepare-state-output.js.map +1 -0
  53. package/dist/lib/prepare-state-output.test.d.ts +2 -0
  54. package/dist/lib/prepare-state-output.test.d.ts.map +1 -0
  55. package/dist/lib/prepare-state-output.test.js +31 -0
  56. package/dist/lib/prepare-state-output.test.js.map +1 -0
  57. package/dist/skill/SKILL.md +4 -4
  58. package/dist/skill/agents/quickback-specialist/AGENT.md +3 -3
  59. package/dist/skill/docs/changelog.md +643 -0
  60. package/dist/skill/docs/compiler/config/agents.md +1 -1
  61. package/dist/skill/docs/compiler/config/auth.md +1 -1
  62. package/dist/skill/docs/compiler/config/index.md +8 -9
  63. package/dist/skill/docs/compiler/config/providers.md +3 -0
  64. package/dist/skill/docs/compiler/config/single-tenant.md +65 -73
  65. package/dist/skill/docs/compiler/definitions/access.md +40 -33
  66. package/dist/skill/docs/compiler/definitions/actions.md +1 -1
  67. package/dist/skill/docs/compiler/definitions/arrows.md +269 -0
  68. package/dist/skill/docs/compiler/definitions/diagnostics.md +136 -0
  69. package/dist/skill/docs/compiler/definitions/feature.md +3 -3
  70. package/dist/skill/docs/compiler/definitions/fga.md +314 -0
  71. package/dist/skill/docs/compiler/definitions/firewall.md +94 -7
  72. package/dist/skill/docs/compiler/definitions/permissions.md +145 -0
  73. package/dist/skill/docs/compiler/definitions/schema.md +8 -2
  74. package/dist/skill/docs/compiler/definitions/scopes.md +339 -0
  75. package/dist/skill/docs/compiler/definitions/views.md +66 -0
  76. package/dist/skill/docs/compiler/getting-started/template-blog.md +7 -7
  77. package/dist/skill/docs/compiler/getting-started/template-empty.md +1 -4
  78. package/dist/skill/docs/compiler/getting-started/templates.md +6 -6
  79. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/actions-api.md +2 -2
  80. package/dist/skill/docs/stack/account-ui/features/admin.md +1 -1
  81. package/dist/skill/docs/stack/account-ui/features/index.md +2 -2
  82. package/dist/skill/docs/stack/cms/connecting.md +17 -16
  83. package/dist/skill/docs/stack/cms/index.md +7 -7
  84. package/dist/skill/docs/stack/cms/schema-format.md +0 -2
  85. package/dist/skill/docs/stack/cms/schema-registry.md +0 -6
  86. package/dist/skill/docs/stack/cms/security.md +6 -6
  87. package/dist/skill/docs/stack/realtime/durable-objects.md +48 -7
  88. package/dist/skill/docs/stack/realtime/live-views.md +168 -0
  89. package/dist/skill/docs/stack/realtime/partyserver-rooms.md +22 -2
  90. package/dist/skill/docs/stack/storage/r2.md +112 -3
  91. package/dist/skill/docs/stack/storage/using-r2.md +30 -10
  92. package/dist/templates/registry.js +2 -2
  93. package/dist/templates/registry.js.map +1 -1
  94. package/package.json +1 -1
  95. package/src/examples/recruitment.tar.gz +0 -0
  96. package/src/skill/SKILL.md +4 -4
  97. package/src/skill/agents/quickback-specialist/AGENT.md +3 -3
  98. package/src/skill/docs/changelog.md +643 -0
  99. package/src/skill/docs/compiler/config/agents.md +1 -1
  100. package/src/skill/docs/compiler/config/auth.md +1 -1
  101. package/src/skill/docs/compiler/config/index.md +8 -9
  102. package/src/skill/docs/compiler/config/providers.md +3 -0
  103. package/src/skill/docs/compiler/config/single-tenant.md +65 -73
  104. package/src/skill/docs/compiler/definitions/access.md +40 -33
  105. package/src/skill/docs/compiler/definitions/actions.md +1 -1
  106. package/src/skill/docs/compiler/definitions/arrows.md +269 -0
  107. package/src/skill/docs/compiler/definitions/diagnostics.md +136 -0
  108. package/src/skill/docs/compiler/definitions/feature.md +3 -3
  109. package/src/skill/docs/compiler/definitions/fga.md +314 -0
  110. package/src/skill/docs/compiler/definitions/firewall.md +94 -7
  111. package/src/skill/docs/compiler/definitions/permissions.md +145 -0
  112. package/src/skill/docs/compiler/definitions/schema.md +8 -2
  113. package/src/skill/docs/compiler/definitions/scopes.md +339 -0
  114. package/src/skill/docs/compiler/definitions/views.md +66 -0
  115. package/src/skill/docs/compiler/getting-started/template-blog.md +7 -7
  116. package/src/skill/docs/compiler/getting-started/template-empty.md +1 -4
  117. package/src/skill/docs/compiler/getting-started/templates.md +6 -6
  118. package/src/skill/docs/compiler/targets/hono-api/using-the-api/actions-api.md +2 -2
  119. package/src/skill/docs/stack/account-ui/features/admin.md +1 -1
  120. package/src/skill/docs/stack/account-ui/features/index.md +2 -2
  121. package/src/skill/docs/stack/cms/connecting.md +17 -16
  122. package/src/skill/docs/stack/cms/index.md +7 -7
  123. package/src/skill/docs/stack/cms/schema-format.md +0 -2
  124. package/src/skill/docs/stack/cms/schema-registry.md +0 -6
  125. package/src/skill/docs/stack/cms/security.md +6 -6
  126. package/src/skill/docs/stack/realtime/durable-objects.md +48 -7
  127. package/src/skill/docs/stack/realtime/live-views.md +168 -0
  128. package/src/skill/docs/stack/realtime/partyserver-rooms.md +22 -2
  129. package/src/skill/docs/stack/storage/r2.md +112 -3
  130. package/src/skill/docs/stack/storage/using-r2.md +30 -10
@@ -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.39.0 — June 2, 2026\n\nMedia and large-binary uploads are now first-class. Instead of streaming file\nbytes through your Worker — which hits the request-body cap and burns Worker\nCPU/duration — an action mints a short-lived **presigned URL** and the client\nuploads the bytes **directly to R2**. The Worker only signs; it never sits in\nthe data path. This is the supported way to author image/video/document upload\nendpoints, and it survives every `quickback compile` with no generated-file\npatching.\n\nRequires R2 file storage (`defineFileStorage(\"cloudflare-r2\", …)`).\n\n### `ctx.storage` — sign uploads from any action\n\nWhen R2 file storage is configured, every `defineAction` execute receives a\ntyped `storage` signer. Your action runs all the usual security layers (auth,\nroles, org/relationship scope), computes a tenant-scoped key, hands the client\nan upload URL, and stores the key in **your own table** — no separate metadata\nsystem required:\n\n```ts\nexport default defineAction({\n path: \"/event/:eventId/media/upload-file-binary\",\n method: \"POST\",\n input: z.object({ filename: z.string(), contentType: z.string() }),\n access: { roles: [\"admin\", \"member\", \"scope:event:attendee\"] },\n async execute({ input, ctx, c, db, storage }) {\n const eventId = c.req.param(\"eventId\");\n const key = `org/${ctx.activeOrgId}/event/${eventId}/${crypto.randomUUID()}-${input.filename}`;\n const upload = await storage.signPutUrl(key, { contentType: input.contentType, expiresIn: 600 });\n await db.insert(images).values({ key, eventId });\n return { uploadUrl: upload.url, key, headers: upload.headers, expiresAt: upload.expiresAt };\n },\n});\n```\n\n`storage` exposes `signPutUrl(key, { contentType?, expiresIn? })` (returns\n`{ url, method, headers, key, expiresAt }`) and\n`signGetUrl(key, { expiresIn?, downloadFilename? })` (returns a presigned GET\nURL). Construction is zero-cost — actions that never touch `storage` pay\nnothing.\n\n### Managed presign + confirm endpoints\n\nFor the zero-config path, the built-in storage API now exposes a presigned\nupload alongside the existing through-Worker upload:\n\n- `POST /storage/v1/presign/:bucket/*path` — runs the bucket's auth/role/scope\n checks, validates the declared `contentType` + `size` against bucket limits,\n records a pending object row, and returns `{ id, key, uploadUrl, method,\n headers, expiresAt }`\n- `POST /storage/v1/confirm/:bucket/*path` — reconciles the recorded size and\n etag against what actually landed in R2 (`HEAD`)\n\n### Setup: R2 API token\n\nPresigning uses R2's S3 API, which needs an **R2 API token** — the Workers R2\nbinding cannot presign on its own. Set three secrets:\n\n```bash\nwrangler secret put R2_ACCOUNT_ID\nwrangler secret put R2_ACCESS_KEY_ID\nwrangler secret put R2_SECRET_ACCESS_KEY\n```\n\n`aws4fetch` is added to the generated `package.json` automatically, and the R2\npresign secrets are added to the generated `Env` type. If you pass `contentType`\nto `signPutUrl`, the client must replay exactly that `Content-Type` header on\nthe `PUT`.\n\n### No raw-body action flag\n\nStreaming a raw binary request body through an action is intentionally **not**\nsupported. Presigning delivers the same result — large files, no body cap —\nwithout poking a hole in the body-parsing layer, so JSON actions and the ~1 MiB\nJSON cap stay intact for every other route.\n\n### Storage routes hardened\n\nEnabling R2 file storage previously exposed several latent type errors in the\ngenerated `/storage/v1/*` routes (dead references from an old multipart\nrefactor, JSON-string role columns treated as arrays, a few undefined\nvariables). The full storage surface now type-checks cleanly when file storage\nis configured.\n\n## v0.38.1 — May 26, 2026\n\nCustom action handlers get the same typed ergonomics as generated CRUD paths:\ntyped Cloudflare bindings on `env`, a first-class typed `realtime` helper when\nrealtime is enabled, and no more `createRealtime(...)` boilerplate inside every\naction just to emit an explicit broadcast.\n\n### Neon compile output and local recompile state are now stable\n\nThe Neon + Cloudflare path now emits a correct runtime/output surface instead\nof leaking SQLite-era state.\n\n- `wrangler.toml` no longer emits a stray `[[d1_databases]]` block for Neon\n projects\n- repeated local Neon compiles now upload and sync the root PostgreSQL Drizzle\n state correctly, so `drizzle-kit` can report \"No schema changes\" instead of\n regenerating duplicate `0000_*.sql` files\n- stale root Drizzle migrations from earlier bad compiles are pruned during the\n compile/sync path\n\n### Shared-target namespace hydration now works for bulk-grant lanes\n\nBulk-grant namespace callers (`{ roles: [...] }`, `{ team: true }`) now inherit\nthe namespace's shared hydration target when every relationship lane points at\nthe same resource load shape.\n\nThat fixes the case where a namespace like:\n\n```ts\nvia: ['attendeeOf', 'organizerOf', { roles: ['admin', 'owner'] }]\n```\n\nwould authorize an org admin through the bulk lane but leave `ctx.event`\nundefined, even though the sibling relationship lanes all hydrated the same\n`events` row.\n\nRuntime behavior is now split cleanly:\n\n- **Shared target** — if all hydrating lanes share the same `loads`,\n `exposeAs`, and resource key, hydration runs unconditionally after the gate\n passes, so bulk callers get the same `ctx.<exposeAs>` as relationship callers\n- **Distinct targets** — if lanes hydrate different tables / keys / ctx slots,\n hydration stays per-matched-lane to avoid cross-table false 404s\n\nStandalone action typing now matches that runtime behavior too: shared-target\nhydration remains non-optional, while distinct-target multi-lane hydration stays\noptional.\n\n### Platform role split: `appmanager` for control-plane, `sysadmin` for cross-tenant\n\nQuickback no longer treats `user.role === \"admin\"` as the platform-wide role.\nThe control-plane role is now `user.role === \"appmanager\"` (CMS shell, Better\nAuth admin endpoints, support tooling), while `user.role === \"sysadmin\"`\nremains the only true cross-tenant data-plane tier.\n\nThis also retires the `ADMIN` pseudo-role. Any `roles: [\"ADMIN\"]` usage now\nfails the compile with migration guidance:\n\n- `userRole: [\"appmanager\"]` for platform control-plane access\n- `roles: [\"admin\"]` for org-membership admin access\n- `roles: [\"SYSADMIN\"]` for true cross-tenant access\n\nRuntime behavior now matches that split end-to-end:\n\n- Better Auth's admin plugin is generated with `adminRoles: [\"appmanager\", \"sysadmin\"]`\n- CMS / OpenAPI / auth-admin surfaces gate on `appmanager` (and admit\n `sysadmin` where appropriate)\n- unsafe cross-tenant actions and tenant-bypass helpers require `sysadmin` only\n\n### Typed `env` + injected `realtime` in action handlers\n\nThe generated `<feature>/.quickback/define-action.ts` helper now types action\n`env` from the project's runtime bindings surface instead of `any`, so custom\nbindings like R2 buckets, queues, Durable Objects, auth env vars, and split DB\nbindings no longer need `(env as any)` casts inside action handlers.\n\nWhen realtime is enabled in config, action handlers also receive a typed\n`realtime` helper directly in `execute(...)`. It exposes the same\n`insert/update/delete/broadcast` methods as `createRealtime(env)`, but without\nthe extra import or hand-rolled factory call in every custom action.\n\nThis is a DX-only change. The auto-broadcast boundary is unchanged: generated\nCRUD routes still broadcast automatically, while custom action writes still\nbroadcast explicitly.\n\n### `generateId: \"cuid\"` docs now reflect the split runtime/schema behavior\n\nQuickback's `cuid` strategy is now documented as the split path it actually is:\ncompiler-managed schema auto-injection keeps the `createId()` call site but may\nback it with a file-local `crypto.randomUUID()` polyfill, while import-capable\nruntime paths still emit real `createId()` usage.\n\nThat matters most for `compiler.injectId` and other schema-emission paths that\nrun in sandboxes where project `node_modules` are not visible. The generated\nschema can safely keep:\n\n```ts\nid: text(\"id\").primaryKey().$defaultFn(() => createId())\n```\n\nwhile satisfying the reference via:\n\n```ts\nconst createId = () => crypto.randomUUID();\n```\n\ninstead of importing `@paralleldrive/cuid2` inside the schema-generation\nenvironment.\n\n**Important nuance:** this is not a guarantee that every generated id is a true\ncuid2 string. Auto-injected schema paths may produce UUID-shaped strings\nthrough the polyfill, while runtime paths that can import helpers may still use\nreal `createId()`. If you need strict cuid2 shape everywhere, explicitly import\n`createId` from `@paralleldrive/cuid2` in the authored schema file; the\ncompiler preserves that import and skips the polyfill.\n\n## 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",
@@ -35,11 +35,11 @@ export const DOCS = {
35
35
  },
36
36
  "compiler/config/agents": {
37
37
  "title": "AI Agent Readiness",
38
- "content": "Every compiled Quickback Worker advertises itself to AI agents and MCP clients — no user wiring required. One config flag controls the whole discovery surface.\n\n## What the compiler generates\n\nWhen `agents` is enabled (the default), the Worker serves:\n\n| Route | What it is |\n|-------|-----------|\n| `GET /robots.txt` | AI-bot policy with the [Cloudflare Content Signals](https://developers.cloudflare.com/bots/concepts/content-signals/) preamble and explicit `Allow:` rules for GPTBot, ClaudeBot, PerplexityBot, Google-Extended, CCBot, Applebot-Extended, Bytespider, MistralAI, Cohere, DuckAssist. |\n| `GET /llms.txt` | Agent-facing summary of the API — project name, authentication, resource list, endpoint conventions — derived from your own config. |\n| `GET /.well-known/oauth-protected-resource` | [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) metadata declaring this Worker as a protected resource. |\n| `GET /.well-known/oauth-authorization-server` | [RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414) metadata pointing at the sign-in and token endpoints. |\n| `GET /.well-known/api-catalog` | [RFC 9727](https://datatracker.ietf.org/doc/html/rfc9727) catalog linking at `/openapi.json`. |\n| `GET /.well-known/mcp.json` | MCP Server Card — discoverable metadata for the MCP server below. |\n| `POST /mcp` | Auto-generated MCP-over-HTTP server. One tool per OpenAPI operation, JWT auth forwarded through the same middleware as the REST API. |\n\n## Default behavior\n\n```ts title=\"quickback.config.ts\"\n\nexport default defineConfig({\n name: 'my-api',\n // …\n // agents: true is the default — no need to write it.\n});\n```\n\nRun `quickback compile` and every endpoint above ships in the Worker.\n\n## Opting out\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // …\n agents: false, // disables everything\n});\n```\n\n## Fine-grained control\n\nPass an object to toggle individual surfaces:\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // …\n agents: {\n robotsTxt: true, // default\n llmsTxt: true, // default\n mcp: true, // default\n oauthDiscovery: true, // default\n apiCatalog: true, // default\n allowAiCrawlers: true, // default — flip to false to Disallow in robots.txt\n },\n});\n```\n\n## The MCP server\n\n### Tools\n\nEvery operation in your generated OpenAPI spec becomes one MCP tool. The tool name is the operation's `operationId` (e.g. `listCustomers`, `createInvoice`, `sendInvoice`). Each tool's `inputSchema` is a flat JSON Schema combining path params, query params, and the request body.\n\n`tools/call` re-enters the same Hono app via `app.request(...)` — so **every existing middleware runs exactly as it would for a direct REST call**: authentication, firewall, access control, guards, masking. No bypass.\n\n### Access-filtered `tools/list`\n\n`tools/list` only returns tools the calling identity could actually invoke. Each generated tool entry carries the operation's access metadata (`roles`, `userRole`, `or` / `and` combinators) and `tools/list` filters against `ctx` before responding:\n\n- **Unauthenticated callers** see only tools whose access declares the `PUBLIC` pseudo-role, or operations that have no security requirement at all (e.g. sign-in / sign-up).\n- **Authenticated callers** see tools whose role gate intersects their `ctx.roles` or `ctx.userRole`. Admin-only endpoints don't appear for non-admins.\n- **Function-form access** (escape hatch) is opaque at list time — surfaced to any authenticated caller, then evaluated for real on `tools/call`.\n- **Record predicates** are dropped from the list-time check (no record yet) and applied normally on the actual call.\n\nThis is recon-mitigation, not a security boundary. Hiding a tool from the list never weakens the underlying gate — `tools/call` still runs the full middleware chain and rejects unauthorized invocations the same way a direct REST call would.\n\nThe unauthenticated `GET /mcp` discovery payload returns server info only; it does **not** enumerate tool names. Inventory is exclusively available via the access-filtered `tools/list`.\n\n### Authentication\n\nMCP clients pass their credentials through the standard `Authorization: Bearer <jwt>` header. The generated MCP handler forwards the header verbatim into the internal request, and the same JWT middleware that guards `/api/v1/*` validates it.\n\nMint a JWT from an authenticated session:\n\n```bash\ncurl -X POST https://my-api.example.com/api/v1/token \\\n -H \"Cookie: better-auth.session_token=...\" \\\n -H \"Content-Type: application/json\"\n```\n\n### Connecting clients\n\n**Claude Desktop** — add to `~/Library/Application Support/Claude/claude_desktop_config.json`:\n\n```json\n{\n \"mcpServers\": {\n \"my-api\": {\n \"url\": \"https://my-api.example.com/mcp\",\n \"headers\": {\n \"Authorization\": \"Bearer <jwt>\"\n }\n }\n }\n}\n```\n\n**Cursor** — use the same config shape under `.cursor/mcp.json`.\n\n**Quick sanity check with curl:**\n\n```bash\n# List available tools\ncurl -X POST https://my-api.example.com/mcp \\\n -H \"Authorization: Bearer $JWT\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}'\n\n# Call a tool\ncurl -X POST https://my-api.example.com/mcp \\\n -H \"Authorization: Bearer $JWT\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{\"name\":\"listCustomers\",\"arguments\":{\"limit\":10}}}'\n```\n\n### Transport\n\nThe server speaks the **Streamable HTTP** MCP transport — JSON-RPC 2.0 over `POST`. A plain `GET /mcp` returns the server info document for sanity checks.\n\nThe MCP route does **not** emit its own CORS headers. The Worker's existing `cors()` middleware applies uniformly, so browser-origin access is governed by the same allowlist as the rest of the API (`auth.trustedOrigins` + the deploy origin). Server-to-server clients (Claude Desktop, Cursor, MCP Inspector) connect with a Bearer token and don't need browser CORS at all. If you want a browser-based MCP client (ChatGPT, Claude.ai) to connect cross-origin, add its origin to `auth.trustedOrigins` like any other web client.\n\n## Verification\n\nAfter you deploy, scan both the REST and MCP surfaces:\n\n```bash\n# Agent-readiness scan (external)\nopen https://isitagentready.com/?url=https://my-api.example.com\n\n# MCP Inspector (official tool)\nnpx @modelcontextprotocol/inspector https://my-api.example.com/mcp\n```"
38
+ "content": "Every compiled Quickback Worker advertises itself to AI agents and MCP clients — no user wiring required. One config flag controls the whole discovery surface.\n\n## What the compiler generates\n\nWhen `agents` is enabled (the default), the Worker serves:\n\n| Route | What it is |\n|-------|-----------|\n| `GET /robots.txt` | AI-bot policy with the [Cloudflare Content Signals](https://developers.cloudflare.com/bots/concepts/content-signals/) preamble and explicit `Allow:` rules for GPTBot, ClaudeBot, PerplexityBot, Google-Extended, CCBot, Applebot-Extended, Bytespider, MistralAI, Cohere, DuckAssist. |\n| `GET /llms.txt` | Agent-facing summary of the API — project name, authentication, resource list, endpoint conventions — derived from your own config. |\n| `GET /.well-known/oauth-protected-resource` | [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) metadata declaring this Worker as a protected resource. |\n| `GET /.well-known/oauth-authorization-server` | [RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414) metadata pointing at the sign-in and token endpoints. |\n| `GET /.well-known/api-catalog` | [RFC 9727](https://datatracker.ietf.org/doc/html/rfc9727) catalog linking at `/openapi.json`. |\n| `GET /.well-known/mcp.json` | MCP Server Card — discoverable metadata for the MCP server below. |\n| `POST /mcp` | Auto-generated MCP-over-HTTP server. One tool per OpenAPI operation, JWT auth forwarded through the same middleware as the REST API. |\n\n## Default behavior\n\n```ts title=\"quickback.config.ts\"\n\nexport default defineConfig({\n name: 'my-api',\n // …\n // agents: true is the default — no need to write it.\n});\n```\n\nRun `quickback compile` and every endpoint above ships in the Worker.\n\n## Opting out\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // …\n agents: false, // disables everything\n});\n```\n\n## Fine-grained control\n\nPass an object to toggle individual surfaces:\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // …\n agents: {\n robotsTxt: true, // default\n llmsTxt: true, // default\n mcp: true, // default\n oauthDiscovery: true, // default\n apiCatalog: true, // default\n allowAiCrawlers: true, // default — flip to false to Disallow in robots.txt\n },\n});\n```\n\n## The MCP server\n\n### Tools\n\nEvery operation in your generated OpenAPI spec becomes one MCP tool. The tool name is the operation's `operationId` (e.g. `listCustomers`, `createInvoice`, `sendInvoice`). Each tool's `inputSchema` is a flat JSON Schema combining path params, query params, and the request body.\n\n`tools/call` re-enters the same Hono app via `app.request(...)` — so **every existing middleware runs exactly as it would for a direct REST call**: authentication, firewall, access control, guards, masking. No bypass.\n\n### Access-filtered `tools/list`\n\n`tools/list` only returns tools the calling identity could actually invoke. Each generated tool entry carries the operation's access metadata (`roles`, `userRole`, `or` / `and` combinators) and `tools/list` filters against `ctx` before responding:\n\n- **Unauthenticated callers** see only tools whose access declares the `PUBLIC` pseudo-role, or operations that have no security requirement at all (e.g. sign-in / sign-up).\n- **Authenticated callers** see tools whose role gate intersects their `ctx.roles` or `ctx.userRole`. Platform-operator endpoints don't appear for callers outside the required user roles.\n- **Function-form access** (escape hatch) is opaque at list time — surfaced to any authenticated caller, then evaluated for real on `tools/call`.\n- **Record predicates** are dropped from the list-time check (no record yet) and applied normally on the actual call.\n\nThis is recon-mitigation, not a security boundary. Hiding a tool from the list never weakens the underlying gate — `tools/call` still runs the full middleware chain and rejects unauthorized invocations the same way a direct REST call would.\n\nThe unauthenticated `GET /mcp` discovery payload returns server info only; it does **not** enumerate tool names. Inventory is exclusively available via the access-filtered `tools/list`.\n\n### Authentication\n\nMCP clients pass their credentials through the standard `Authorization: Bearer <jwt>` header. The generated MCP handler forwards the header verbatim into the internal request, and the same JWT middleware that guards `/api/v1/*` validates it.\n\nMint a JWT from an authenticated session:\n\n```bash\ncurl -X POST https://my-api.example.com/api/v1/token \\\n -H \"Cookie: better-auth.session_token=...\" \\\n -H \"Content-Type: application/json\"\n```\n\n### Connecting clients\n\n**Claude Desktop** — add to `~/Library/Application Support/Claude/claude_desktop_config.json`:\n\n```json\n{\n \"mcpServers\": {\n \"my-api\": {\n \"url\": \"https://my-api.example.com/mcp\",\n \"headers\": {\n \"Authorization\": \"Bearer <jwt>\"\n }\n }\n }\n}\n```\n\n**Cursor** — use the same config shape under `.cursor/mcp.json`.\n\n**Quick sanity check with curl:**\n\n```bash\n# List available tools\ncurl -X POST https://my-api.example.com/mcp \\\n -H \"Authorization: Bearer $JWT\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}'\n\n# Call a tool\ncurl -X POST https://my-api.example.com/mcp \\\n -H \"Authorization: Bearer $JWT\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{\"name\":\"listCustomers\",\"arguments\":{\"limit\":10}}}'\n```\n\n### Transport\n\nThe server speaks the **Streamable HTTP** MCP transport — JSON-RPC 2.0 over `POST`. A plain `GET /mcp` returns the server info document for sanity checks.\n\nThe MCP route does **not** emit its own CORS headers. The Worker's existing `cors()` middleware applies uniformly, so browser-origin access is governed by the same allowlist as the rest of the API (`auth.trustedOrigins` + the deploy origin). Server-to-server clients (Claude Desktop, Cursor, MCP Inspector) connect with a Bearer token and don't need browser CORS at all. If you want a browser-based MCP client (ChatGPT, Claude.ai) to connect cross-origin, add its origin to `auth.trustedOrigins` like any other web client.\n\n## Verification\n\nAfter you deploy, scan both the REST and MCP surfaces:\n\n```bash\n# Agent-readiness scan (external)\nopen https://isitagentready.com/?url=https://my-api.example.com\n\n# MCP Inspector (official tool)\nnpx @modelcontextprotocol/inspector https://my-api.example.com/mcp\n```"
39
39
  },
40
40
  "compiler/config/auth": {
41
41
  "title": "Auth & JWT",
42
- "content": "The top-level `auth` config block holds provider-agnostic auth knobs that affect how Quickback emits the auth middleware, JWT helpers, and access-rule expansion.\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // ...\n auth: {\n roleHierarchy: ['member', 'admin', 'owner'],\n jwt: {\n expiresIn: 60,\n issuer: 'my-api',\n // audience, secretEnv, algorithm, revocationCheck...\n },\n },\n});\n```\n\n## `auth.roleHierarchy`\n\nLowest-to-highest privilege list. Lets access rules use `'role+'` shorthand to mean \"this role and above\". Documented in detail under [Access — Role hierarchy](/compiler/definitions/access#role-hierarchy).\n\n## `auth.jwt` — JWT bearer-token fast-path\n\nQuickback ships its own custom HMAC-SHA256 JWT (not Better Auth's JWT plugin) so it can embed `orgId` and `role` claims the fast-path needs to reconstruct `AppContext` without a database round-trip. The signing secret is shared with Better Auth (`BETTER_AUTH_SECRET`) by default — users only manage one secret.\n\n### Behavior recap\n\n1. The browser SPA gets a JWT via the `set-auth-token` response header on every authenticated call.\n2. On subsequent requests the SPA sends `Authorization: Bearer <jwt>`.\n3. The auth middleware's **fast-path** verifies the signature only — no DB query, no session lookup. `AppContext` is reconstructed from JWT claims.\n4. If verification fails (or no JWT is present), the middleware falls back to session auth.\n5. After successful session auth, a fresh JWT is minted and returned via `set-auth-token`. The cycle continues.\n\nThe fast-path is intentionally stateless: it trusts the claims for the full TTL. **Stolen or pre-revocation tokens are valid until they expire.** That's the trade-off the fast-path makes — and the reason `expiresIn` is the most-tuned knob below.\n\n### `expiresIn?: number` — TTL in seconds\n\nDefault `180` (3 minutes).\n\nLowering this shrinks the worst-case window where a stolen / pre-revocation token still works. Browser SPAs auto-refresh via `set-auth-token` on every authed call, so a low TTL is invisible to logged-in users; only stale server-to-server bearer tokens feel it.\n\n```ts\nauth: { jwt: { expiresIn: 30 } } // 30s — tight post-revocation window\nauth: { jwt: { expiresIn: 3600 } } // 1h — longer-lived tokens for CLI / CI\n```\n\n### `issuer?: string` — `iss` claim\n\nDefault omitted.\n\nSet this when other services need to distinguish JWTs minted by this Worker from other issuers. The compiler bakes the issuer into both the mint side (added to claims) and the verify side (rejects tokens with mismatched `iss`).\n\n### `audience?: string` — `aud` claim\n\nDefault omitted.\n\nSet this when this Worker's JWTs are consumed by a sibling service that should reject tokens minted for a different audience. Same mint-and-verify treatment as `issuer`.\n\n### `secretEnv?: string` — signing secret env var\n\nDefault `'BETTER_AUTH_SECRET'`.\n\nOverride this if you want JWT signing isolated from the Better Auth secret (e.g. rotating one without invalidating the other).\n\n```ts\nauth: { jwt: { secretEnv: 'CUSTOM_JWT_SECRET' } }\n```\n\nThe compiler emits `c.env.CUSTOM_JWT_SECRET` (or `process.env.CUSTOM_JWT_SECRET` on Bun/Node) in the auth middleware's verify and mint sites and the `/api/v1/token` endpoint.\n\n> **Note:** the files-worker (separate Worker for R2 access) still reads `BETTER_AUTH_SECRET` directly. If you override `secretEnv`, set both env vars to the same value or the files worker's JWT verification will fall back to DB session lookup. Threading `secretEnv` through the files worker is on the roadmap.\n\n### `algorithm?: 'HS256'`\n\nOnly `HS256` is supported in 0.10.14. `RS256` (asymmetric, public-key verify / private-key sign) is on the roadmap.\n\n### `revocationCheck?: 'none' | 'kv'` — token revocation strategy\n\nDefault `'none'`.\n\n| Value | Behavior | Cost per verify |\n|---|---|---|\n| `'none'` | No revocation check. Stolen tokens valid until TTL expires. Use a low `expiresIn` to bound the replay window. | 0 |\n| `'kv'` | Fast-path consults a denylist KV namespace before accepting the token. Banning a user / revoking sessions writes the user's `sub` to the denylist. | 1 KV read (~5-15ms, edge-cached) |\n\nThe `'kv'` path keeps the fast-path stateless against the auth DB (still 0 D1 queries) — KV reads on Workers are an order of magnitude cheaper than a D1 round trip *and* give sub-second revocation.\n\n> **`'kv'` is deferred to 0.10.15.** Setting `'kv'` in 0.10.14 errors at compile time so the migration path is explicit; the schema accepts it now so users can author their final config today.\n\n## Defaults preserve 0.10.13 behavior\n\nAdding the `auth.jwt` block without setting any field is a no-op vs. the 0.10.13 baseline. Each missing field falls back to its hardcoded value:\n\n| Field | Default |\n|---|---|\n| `expiresIn` | 180 |\n| `issuer` | omitted |\n| `audience` | omitted |\n| `secretEnv` | `'BETTER_AUTH_SECRET'` |\n| `algorithm` | `'HS256'` |\n| `revocationCheck` | `'none'` |\n\n## Tuning recommendations\n\n- **B2C SaaS, mostly browser traffic:** keep defaults. The 180s TTL + auto-refresh model just works.\n- **Pentest engagement / enterprise compliance:** set `expiresIn: 30`. Tokens stay invisible to logged-in users (auto-refreshed every authed call) but stolen-token windows shrink to 30s.\n- **CLI-heavy / long-running CI tokens:** `expiresIn: 3600` for one-hour bearer tokens. Pair with `issuer` / `audience` if multiple services consume the same JWT.\n- **Need immediate revocation:** wait for 0.10.15's `revocationCheck: 'kv'`. Or, today, drop TTL to ~30s — same effect with bounded delay.\n\n## `auth.loginUrl` / `auth.profileUrl` — external sign-in for consumer Workers\n\nWhen a Quickback Worker doesn't host its own Account SPA — e.g. an internal-app mesh where one Worker on the parent domain owns identity (`auth.example.com`) and other Workers share cookies — the compiler-emitted CMS access gates need to redirect unauthenticated visitors to the central sign-in surface, not the local `/account/login` (which doesn't exist there).\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // ...\n auth: {\n loginUrl: 'https://auth.example.com/login',\n profileUrl: 'https://auth.example.com/profile',\n },\n});\n```\n\nBoth fields override compiler-emitted browser redirects in the CMS shell:\n\n- **Unauthenticated visitor hits a CMS route** → `302 → <loginUrl>?redirect=<original-url>`\n- **Authenticated user fails the `cms.access: 'admin'` role check** → `302 → <profileUrl>`\n\nThe `?redirect=…` query param is preserved unchanged so the central sign-in surface can bounce the user back after authentication.\n\n### Resolution precedence\n\nMost-specific wins:\n\n1. Explicit `auth.loginUrl` / `auth.profileUrl` — the cookie-trusting consumer-Worker case (this section).\n2. `https://<account.domain>/login` — inferred when this project hosts its own Account SPA on a custom domain.\n3. `/account/login` — built-in fallback, when neither knob is set.\n\n### Independent from `account.domain`\n\n`account.domain` does *two* things: redirect targets *and* hostname-based asset routing for an Account SPA hosted by this project. Consumer Workers don't host Account at all — they only need the URL. `auth.loginUrl` is a redirect-target string with no routing side effects, which is why it's a separate knob.\n\n### When both are set\n\nSetting `auth.loginUrl` *and* `account.domain` is legal — the explicit override beats the inferred URL at the redirect site, while `account.domain` still drives the local Account SPA's hostname routing as usual. Useful when you want to host Account on one custom domain (`account.foo.com`) but redirect *somewhere else* for sign-in (e.g. an SSO surface at `auth.foo.com`)."
42
+ "content": "The top-level `auth` config block holds provider-agnostic auth knobs that affect how Quickback emits the auth middleware, JWT helpers, and access-rule expansion.\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // ...\n auth: {\n roleHierarchy: ['member', 'admin', 'owner'],\n jwt: {\n expiresIn: 60,\n issuer: 'my-api',\n // audience, secretEnv, algorithm, revocationCheck...\n },\n },\n});\n```\n\n## `auth.roleHierarchy`\n\nLowest-to-highest privilege list. Lets access rules use `'role+'` shorthand to mean \"this role and above\". Documented in detail under [Access — Role hierarchy](/compiler/definitions/access#role-hierarchy).\n\n## `auth.jwt` — JWT bearer-token fast-path\n\nQuickback ships its own custom HMAC-SHA256 JWT (not Better Auth's JWT plugin) so it can embed `orgId` and `role` claims the fast-path needs to reconstruct `AppContext` without a database round-trip. The signing secret is shared with Better Auth (`BETTER_AUTH_SECRET`) by default — users only manage one secret.\n\n### Behavior recap\n\n1. The browser SPA gets a JWT via the `set-auth-token` response header on every authenticated call.\n2. On subsequent requests the SPA sends `Authorization: Bearer <jwt>`.\n3. The auth middleware's **fast-path** verifies the signature only — no DB query, no session lookup. `AppContext` is reconstructed from JWT claims.\n4. If verification fails (or no JWT is present), the middleware falls back to session auth.\n5. After successful session auth, a fresh JWT is minted and returned via `set-auth-token`. The cycle continues.\n\nThe fast-path is intentionally stateless: it trusts the claims for the full TTL. **Stolen or pre-revocation tokens are valid until they expire.** That's the trade-off the fast-path makes — and the reason `expiresIn` is the most-tuned knob below.\n\n### `expiresIn?: number` — TTL in seconds\n\nDefault `180` (3 minutes).\n\nLowering this shrinks the worst-case window where a stolen / pre-revocation token still works. Browser SPAs auto-refresh via `set-auth-token` on every authed call, so a low TTL is invisible to logged-in users; only stale server-to-server bearer tokens feel it.\n\n```ts\nauth: { jwt: { expiresIn: 30 } } // 30s — tight post-revocation window\nauth: { jwt: { expiresIn: 3600 } } // 1h — longer-lived tokens for CLI / CI\n```\n\n### `issuer?: string` — `iss` claim\n\nDefault omitted.\n\nSet this when other services need to distinguish JWTs minted by this Worker from other issuers. The compiler bakes the issuer into both the mint side (added to claims) and the verify side (rejects tokens with mismatched `iss`).\n\n### `audience?: string` — `aud` claim\n\nDefault omitted.\n\nSet this when this Worker's JWTs are consumed by a sibling service that should reject tokens minted for a different audience. Same mint-and-verify treatment as `issuer`.\n\n### `secretEnv?: string` — signing secret env var\n\nDefault `'BETTER_AUTH_SECRET'`.\n\nOverride this if you want JWT signing isolated from the Better Auth secret (e.g. rotating one without invalidating the other).\n\n```ts\nauth: { jwt: { secretEnv: 'CUSTOM_JWT_SECRET' } }\n```\n\nThe compiler emits `c.env.CUSTOM_JWT_SECRET` (or `process.env.CUSTOM_JWT_SECRET` on Bun/Node) in the auth middleware's verify and mint sites and the `/api/v1/token` endpoint.\n\n> **Note:** the files-worker (separate Worker for R2 access) still reads `BETTER_AUTH_SECRET` directly. If you override `secretEnv`, set both env vars to the same value or the files worker's JWT verification will fall back to DB session lookup. Threading `secretEnv` through the files worker is on the roadmap.\n\n### `algorithm?: 'HS256'`\n\nOnly `HS256` is supported in 0.10.14. `RS256` (asymmetric, public-key verify / private-key sign) is on the roadmap.\n\n### `revocationCheck?: 'none' | 'kv'` — token revocation strategy\n\nDefault `'none'`.\n\n| Value | Behavior | Cost per verify |\n|---|---|---|\n| `'none'` | No revocation check. Stolen tokens valid until TTL expires. Use a low `expiresIn` to bound the replay window. | 0 |\n| `'kv'` | Fast-path consults a denylist KV namespace before accepting the token. Banning a user / revoking sessions writes the user's `sub` to the denylist. | 1 KV read (~5-15ms, edge-cached) |\n\nThe `'kv'` path keeps the fast-path stateless against the auth DB (still 0 D1 queries) — KV reads on Workers are an order of magnitude cheaper than a D1 round trip *and* give sub-second revocation.\n\n> **`'kv'` is deferred to 0.10.15.** Setting `'kv'` in 0.10.14 errors at compile time so the migration path is explicit; the schema accepts it now so users can author their final config today.\n\n## Defaults preserve 0.10.13 behavior\n\nAdding the `auth.jwt` block without setting any field is a no-op vs. the 0.10.13 baseline. Each missing field falls back to its hardcoded value:\n\n| Field | Default |\n|---|---|\n| `expiresIn` | 180 |\n| `issuer` | omitted |\n| `audience` | omitted |\n| `secretEnv` | `'BETTER_AUTH_SECRET'` |\n| `algorithm` | `'HS256'` |\n| `revocationCheck` | `'none'` |\n\n## Tuning recommendations\n\n- **B2C SaaS, mostly browser traffic:** keep defaults. The 180s TTL + auto-refresh model just works.\n- **Pentest engagement / enterprise compliance:** set `expiresIn: 30`. Tokens stay invisible to logged-in users (auto-refreshed every authed call) but stolen-token windows shrink to 30s.\n- **CLI-heavy / long-running CI tokens:** `expiresIn: 3600` for one-hour bearer tokens. Pair with `issuer` / `audience` if multiple services consume the same JWT.\n- **Need immediate revocation:** wait for 0.10.15's `revocationCheck: 'kv'`. Or, today, drop TTL to ~30s — same effect with bounded delay.\n\n## `auth.loginUrl` / `auth.profileUrl` — external sign-in for consumer Workers\n\nWhen a Quickback Worker doesn't host its own Account SPA — e.g. an internal-app mesh where one Worker on the parent domain owns identity (`auth.example.com`) and other Workers share cookies — the compiler-emitted CMS access gates need to redirect unauthenticated visitors to the central sign-in surface, not the local `/account/login` (which doesn't exist there).\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // ...\n auth: {\n loginUrl: 'https://auth.example.com/login',\n profileUrl: 'https://auth.example.com/profile',\n },\n});\n```\n\nBoth fields override compiler-emitted browser redirects in the CMS shell:\n\n- **Unauthenticated visitor hits a CMS route** → `302 → <loginUrl>?redirect=<original-url>`\n- **Authenticated user fails the `cms.access: 'admin'` platform-role check** → `302 → <profileUrl>`\n\nThe `?redirect=…` query param is preserved unchanged so the central sign-in surface can bounce the user back after authentication.\n\n### Resolution precedence\n\nMost-specific wins:\n\n1. Explicit `auth.loginUrl` / `auth.profileUrl` — the cookie-trusting consumer-Worker case (this section).\n2. `https://<account.domain>/login` — inferred when this project hosts its own Account SPA on a custom domain.\n3. `/account/login` — built-in fallback, when neither knob is set.\n\n### Independent from `account.domain`\n\n`account.domain` does *two* things: redirect targets *and* hostname-based asset routing for an Account SPA hosted by this project. Consumer Workers don't host Account at all — they only need the URL. `auth.loginUrl` is a redirect-target string with no routing side effects, which is why it's a separate knob.\n\n### When both are set\n\nSetting `auth.loginUrl` *and* `account.domain` is legal — the explicit override beats the inferred URL at the redirect site, while `account.domain` still drives the local Account SPA's hostname routing as usual. Useful when you want to host Account on one custom domain (`account.foo.com`) but redirect *somewhere else* for sign-in (e.g. an SSO surface at `auth.foo.com`)."
43
43
  },
44
44
  "compiler/config/bindings": {
45
45
  "title": "Custom Bindings",
@@ -51,7 +51,7 @@ export const DOCS = {
51
51
  },
52
52
  "compiler/config": {
53
53
  "title": "Configuration",
54
- "content": "The `quickback.config.ts` file configures your Quickback project. It defines which providers to use, which features to enable, and how the compiler generates code.\n\n```typescript\n\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n features: { organizations: true },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## Discoverable options block\n\nAfter your first `quickback compile`, the file gets a managed block bracketed by sentinel comments:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: cloudflare({}),\n\n // [quickback:options-start]\n // ── Project ──\n //\n // Primary custom domain (auto-inferred from cms/account/api domains if unset).\n // domain: \"example.com\",\n //\n // ── Embedded UIs (CMS / Account) ──\n //\n // Login/signup/profile/orgs SPA. Set `true` for default, or object to customize.\n // account: {\n // fileUploads: false, // show the avatar upload UI on the profile page\n // auth: { passkey: false, emailOTP: false, ... },\n // ...\n // },\n //\n // ... every other option Quickback supports\n // [quickback:options-end]\n});\n```\n\nThis block is **regenerated on every compile** — the compiler is the source of truth, so newly added options surface automatically when you upgrade Quickback (no CLI bump needed).\n\n**To enable an option**, copy the line you care about *above* the `[quickback:options-start]` sentinel and uncomment it:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: cloudflare({}),\n\n account: {\n fileUploads: true, // ← lifted out of the managed block\n },\n\n // [quickback:options-start]\n // ... account is now omitted from this block on next compile\n // [quickback:options-end]\n});\n```\n\nQuickback notices that `account` is set above the marker and drops it from the managed block on the next compile to avoid duplicate definitions. Anything outside the marker block is yours and never touched.\n\nIf you ever want to opt out of the auto-managed block, run:\n\n```bash\nquickback compile --no-sync-config\n```\n\n## Required Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `name` | `string` | Project name |\n| `template` | `\"hono\"` | Application template (`\"nextjs\"` is experimental) |\n| `providers` | `object` | Runtime, database, and auth provider configuration |\n\n## Optional Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `features` | `object` | Feature flags — see [Single-Tenant Mode](/compiler/config/single-tenant) |\n| `build` | `object` | Build options (`outputDir`, `packageManager`, `dependencies`) |\n| `compiler` | `object` | Compiler options — `features.auditFields: false` disables audit field injection project-wide; `migrations.renames` provides rename hints for headless CI; `securityContracts` tunes the route/SQL invariants checker |\n| `openapi` | `object` | OpenAPI spec generation (`generate`, `publish`, `docs: 'scalar' \\| 'swagger'` for an in-browser API reference) — see [OpenAPI](/compiler/targets/hono-api/using-the-api/openapi) |\n| `schemaRegistry` | `object` | Schema registry generation for the CMS (enabled by default, `{ generate: false }` to disable) — see [Schema Registry](/stack/cms/schema-registry) |\n| `etag` | `object` | ETag caching for GET responses (enabled by default, `{ enabled: false }` to disable) — see [Caching & ETags](/compiler/targets/hono-api/using-the-api/caching) |\n| `cms` | `boolean \\| object` | Embed CMS in compiled Worker — see [CMS](/stack/cms) |\n| `account` | `boolean \\| object` | Embed Account UI in compiled Worker — see [Account UI](/stack/account-ui) |\n| `trustedOrigins` | `string[]` | CORS trusted origins for cross-domain auth |\n| `domain` | `string` | Primary API domain (auto-inferred from custom domains if not set) |\n| `dev` | `object` | Local development settings (`port`) |\n| `auth` | `object` | App-level auth settings (`roleHierarchy`) — see [Access](/compiler/definitions/access#role-hierarchy) |\n| `email` | `object` | Email delivery config (`provider`, `from`, `fromName`) |\n\n## Custom Dependencies\n\nAdd third-party npm packages to the generated `package.json` using `build.dependencies`. This is useful when your action handlers import external libraries.\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n build: {\n dependencies: {\n \"fast-xml-parser\": \"^4.5.0\",\n \"lodash-es\": \"^4.17.21\",\n },\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\nThese are merged into the generated `package.json` alongside Quickback's own dependencies. Run `npm install` after compiling to install them.\n\n## Headless Migration Rename Hints\n\nWhen `drizzle-kit generate` detects a potential rename, it normally prompts for confirmation. Cloud/CI compiles are non-interactive, so you must provide explicit rename hints.\n\nAdd hints in `compiler.migrations.renames`:\n\n```typescript\nexport default defineConfig({\n // ...\n compiler: {\n migrations: {\n renames: {\n // Keys are NEW names, values are OLD names\n tables: {\n events_v2: \"events\",\n },\n columns: {\n events: {\n summary_text: \"summary\",\n },\n },\n },\n },\n },\n});\n```\n\nRules:\n- `tables`: `new_table_name -> old_table_name`\n- `columns.<table>`: `new_column_name -> old_column_name`\n- Keys must match the names in your current schema (the new names)\n- Validation fails fast for malformed rename config, unsupported keys, or conflicting legacy/new rename paths.\n\n## Disable Audit Field Injection\n\nBy default, Quickback auto-injects four **audit fields** (`createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`) into every feature table, plus two **soft-delete fields** (`deletedAt`, `deletedBy`) into tables that use soft delete (the default delete mode). The audit fields drive record-provenance queries and the CMS audit panel; the soft-delete pair drives soft-delete filtering.\n\nTo opt out project-wide:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n compiler: {\n features: {\n auditFields: false, // skip audit-field injection globally\n },\n },\n providers: { /* ... */ },\n});\n```\n\nWhen disabled, you're responsible for supplying these columns yourself if you want soft delete, audit trails, or modifiedAt-based optimistic concurrency. See the [Schema → Audit Fields](/compiler/definitions/schema#audit-fields) section for the full list and what each field drives.\n\n## Security Contract Reports and Signing\n\nAfter generation, Quickback verifies machine-checkable security contracts for Hono routes and RLS SQL.\n\nIt also emits a report artifact and signature artifact by default:\n\n- `reports/security-contracts.report.json`\n- `reports/security-contracts.report.sig.json`\n\nYou can configure output paths and signing behavior:\n\n```typescript\nexport default defineConfig({\n // ...\n compiler: {\n securityContracts: {\n failMode: \"error\", // or \"warn\"\n report: {\n path: \"reports/security-contracts.report.json\",\n signature: {\n enabled: true,\n required: true,\n keyEnv: \"QUICKBACK_SECURITY_REPORT_SIGNING_KEY\",\n keyId: \"prod-k1\",\n path: \"reports/security-contracts.report.sig.json\",\n },\n },\n },\n },\n});\n```\n\nIf `signature.required: true` and no key is available, compilation fails with a clear error message (or warning in `failMode: \"warn\"`).\n\n## Hostname architecture (v0.33+)\n\nA modern Quickback project runs on **one Cloudflare Worker** that serves multiple URL surfaces. By default, everything lives under a single unified backend hostname (auto-inferred as `quickback.{baseDomain}` from your other configured subdomains, or overridable via `config.domain`). For larger deployments, you can opt-in to **dedicated hostnames** for specific surfaces — they're additive aliases, never replacements.\n\n### The unified backend contract\n\nWhen any subdomain is configured (`account.domain`, `cms.domain`, `auth.domain`, `api.domain`, `apps.<n>.domain`), the compiler always emits a unified backend host where **every compiler-emitted backend route** is reachable:\n\n- `/api/v1/*` — feature routes\n- `/auth/v1/*` — Better Auth\n- `/storage/*` — R2 file storage\n- `/health`, `/openapi.json` — monitoring/discovery\n- `/account/*`, `/cms/*` — bundled SPAs (when enabled)\n- `/broadcast/v1/*` (realtime), `/mcp` (MCP), etc.\n\nThe unified hostname is `quickback.{baseDomain}` by default (where baseDomain is extracted from your first configured subdomain). Override with `config.domain` if you prefer a different name.\n\nThis contract is forward-pointing: it gives a stable URL pattern for future management tooling — `https://quickback.{baseDomain}/...` will always reach a Quickback backend regardless of how the operator splits their surfaces.\n\n### Dedicated hostnames (optional, additive)\n\nFor branding or operational separation, you can opt specific surfaces onto their own hostnames:\n\n```ts\n{\n // Bundled SPAs on their own hosts (already-shipped pattern):\n cms: { domain: 'cms.example.com' },\n account: { domain: 'account.example.com' },\n\n // v0.33+ — backend surfaces on their own hosts:\n auth: { domain: 'auth.example.com' },\n api: { domain: 'api.example.com' },\n\n // User SPAs (existing pattern):\n apps: {\n www: { domain: 'app.example.com' },\n },\n}\n```\n\nOn a dedicated hostname, **the hostname IS the namespace** — the path drops the prefix that matches the hostname:\n\n| URL on dedicated host | Internally rewritten to | Notes |\n|---|---|---|\n| `https://api.example.com/v1/users` | `/api/v1/users` | Worker-entry rewriter prepends `/api` |\n| `https://auth.example.com/v1/sign-in/email` | `/auth/v1/sign-in/email` | Same shape with `/auth` |\n| `https://api.example.com/api/v1/users` | (unchanged) | Long form also accepted |\n| `https://api.example.com/auth/v1/sign-in` | **404** | Auth doesn't live on the API hostname |\n| `https://api.example.com/health` | (unchanged) | Explicit exception — monitoring agents expect `/health` everywhere |\n\nDual-reach is preserved on the unified host:\n\n| URL on unified host | Handler | Notes |\n|---|---|---|\n| `https://quickback.example.com/api/v1/users` | feature route | Works whether `api.domain` is set or not |\n| `https://quickback.example.com/auth/v1/sign-in/email` | Better Auth | Works whether `auth.domain` is set or not |\n| `https://quickback.example.com/v1/users` | **404** | Shortcut only applies on dedicated hostnames |\n\nEach dedicated hostname also:\n\n- Gets a `{ pattern, custom_domain: true }` route in `wrangler.toml` automatically\n- Joins `trustedOrigins` for CORS\n- Joins the cross-subdomain cookie inference (auto-enables `crossSubDomainCookies` when ≥2 same-parent subdomains are configured, so `auth.example.com` and `app.example.com` can share session cookies)\n- Joins CSP `connect-src` so SPAs can fetch from it\n\n### Why two URL shapes (Shape 1 vs Shape 2)\n\nIf you only want Better Auth to **advertise** itself on a different URL (e.g. so verification emails link to `auth.example.com` instead of the unified host), set the `BETTER_AUTH_URL` env var on the Worker — no code change required. BA generates outgoing URLs against that value. This is sufficient when the goal is branding email/OAuth callback URLs without changing where requests actually land.\n\n`auth.domain` (Shape 1, above) is the heavier option: it binds an actual hostname to the Worker, configures CORS/cookies/CSP for it, and adds the path-shortcut rewriter. Use it when you want the dedicated hostname as a real ingress, not just a label.\n\n## CMS Configuration\n\nEmbed the [Quickback CMS](/stack/cms) in your compiled Worker. The CMS reads your schema registry and renders a complete admin interface — zero UI code per table.\n\n```typescript\n// Simple — embed CMS at root\ncms: true,\n\n// With custom domain\ncms: { domain: \"cms.example.com\" },\n\n// With access control (only admins can access CMS)\ncms: { domain: \"cms.example.com\", access: \"admin\" },\n\n// Cross-tenant DB-admin tier — sysadmins see every tenant's data\ncms: { domain: \"cms.example.com\", sysadmin: true },\n```\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `domain` | `string` | — | Custom domain for CMS. Adds a `custom_domain` route to `wrangler.toml`. |\n| `access` | `\"user\" \\| \"admin\"` | `\"user\"` | Controls who can access the CMS. When `\"admin\"`, only users with `user.role === \"admin\"` can enter — enforced at the Worker level (SPA shell, `/api/v1/schema`, and `custom_view` CRUD all return 403 to non-admins) and in the SPA. Also hides the CMS link in Account UI. See [CMS Connecting](/stack/cms/connecting) for the full enforcement model. |\n| `sysadmin` | `boolean` | `false` | Cross-tenant DB-admin tier. When `true`, opts into the `SYSADMIN` pseudo-role (`user.role === \"sysadmin\"`), the firewall escape hatch (sysadmins bypass tenant scopes, soft-delete still enforced), the cross-tenant `/auth/v1/admin/list-organizations` endpoint (sibling of Better Auth's `/auth/v1/admin/list-users`, gated to sysadmin only), and the SPA's \"All organizations\" sentinel. The CMS HTML gate admits `userRole === \"sysadmin\"` alongside `\"admin\"`. Off by default. See [`SYSADMIN` pseudo-role](/compiler/definitions/access#sysadmin--cross-tenant-db-admin-tier). |\n\n### Sysadmin tier (`cms.sysadmin: true`)\n\nQuickback's default model assumes every CMS user belongs to at least one organization (`member` row in the auth DB). For platforms that need a Supabase-style cross-tenant DB-admin tool — debugging a tenant's data, running cross-tenant queries, supporting a customer — that's a poor fit: a sysadmin without `member` rows would dead-end, and auto-filling their active org from \"first membership\" silently scopes them to a tenant they have no relationship with.\n\n`cms: { sysadmin: true }` introduces a separate role tier:\n\n- **Role**: `user.role === \"sysadmin\"` (set on the Better Auth user table). Distinct from `\"admin\"` — admins keep org-scoped CMS access via the membership switcher; sysadmins get cross-tenant. The two roles are independent at the pseudo-role evaluator level: `ADMIN` admits `'admin'` only, `SYSADMIN` admits `'sysadmin'` only. Routes that need both write `access: { roles: ['ADMIN', 'SYSADMIN'] }` explicitly.\n- **Firewall**: every `buildFirewallConditions()` emits an `if (ctx.userRole === \"sysadmin\") return undefined` (or just the soft-delete predicate when present) at the top, so sysadmins see every tenant's rows. See [Firewall escape hatch](/compiler/definitions/firewall#sysadmin-escape-hatch).\n- **Org listing**: a `GET /auth/v1/admin/list-organizations` endpoint selects directly from the auth-schema `organization` table — every row, every tenant. Sits under Better Auth's admin URL namespace (sibling of `/auth/v1/admin/list-users`) so the URL shape matches BA convention; the handler is Quickback-emitted and gated to `user.role === \"sysadmin\"` only. For the membership-bound caller's-orgs listing, use BA's own `/auth/v1/organization/list`.\n- **CMS SPA**: when the user is a sysadmin, the header switcher loads from the cross-tenant endpoint, defaults to \"All organizations\" (which omits `?organizationId=` and reaches the firewall escape), and pins selected tenants via `?organizationId=` on every API call. Org admins keep the existing membership-based switcher.\n- **CMS HTML gate**: admits `userRole === \"sysadmin\"` alongside `\"admin\"`. Org admins are not locked out — both roles can enter the CMS in `cms.access: \"admin\"` mode.\n\nOff by default. Projects that don't enable it get zero behavior change; setting `cms.sysadmin: true` and granting a user `user.role = \"sysadmin\"` is the only way to unlock the cross-tenant view.\n\n## Account UI Configuration\n\nEmbed the [Account UI](/stack/account-ui) in your compiled Worker. Provides login, signup, profile management, organization management, and admin — all built from your config at compile time.\n\nFor post-signup logic — auto-provisioning a workspace, gating signup, setting an active organization — drop a file in `quickback/hooks/`. See [Auth Hooks](/stack/account-ui/hooks).\n\n```typescript\n// Simple — embed Account UI with defaults\naccount: true,\n\n// Full configuration\naccount: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n companyName: \"My Company\",\n auth: {\n password: true,\n emailOTP: false,\n passkey: true,\n organizations: true,\n admin: true,\n },\n},\n```\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `domain` | `string` | Custom domain for Account UI (e.g., `auth.example.com`) |\n| `adminDomain` | `string` | Custom domain for admin-only access (e.g., `admin.example.com`). Serves the same Account SPA — the client-side router handles admin routing. |\n| `appUrl` | `string` | URL of the tenant's main application — where users are redirected after login. Baked into the Account SPA as `VITE_QUICKBACK_APP_URL`. Independent from `domain`. |\n| `name` | `string` | App display name shown on login, profile, and email templates |\n| `companyName` | `string` | Company name for branding |\n| `tagline` | `string` | App tagline shown on login page |\n| `description` | `string` | App description |\n\n### Auth Feature Flags\n\nControl which authentication features are exposed. Disabled features are excluded from the Account UI bundle at compile time (routes removed before the Vite build, keeping bundle sizes minimal) **and** enforced on the server side via the Better Auth config — so \"signup off\" actually closes `POST /auth/v1/sign-up/email`, not just the SPA's signup screen.\n\n`account.auth.*` is a shorthand for `providers.auth.config` — the compiler maps each flag onto the Better Auth server config before any code is generated. You can write either side directly; setting both incompatibly (e.g. `account.auth.signup: false` and `emailAndPassword.disableSignUp: false`) fails the compile with a precise error rather than picking a silent winner.\n\n| Flag | Type | Default | Maps to (server) | Description |\n|------|------|---------|------------------|-------------|\n| `auth.password` | `boolean` | `true` | `emailAndPassword.enabled` | Email/password authentication — both server endpoint and UI |\n| `auth.emailOTP` | `boolean` | `false` | adds `emailOtp` plugin | Email one-time password login — adds plugin server-side, surfaces UI |\n| `auth.passkey` | `boolean` | `false` | adds `passkey` plugin | WebAuthn/FIDO2 passkey authentication — adds plugin server-side, surfaces UI |\n| `auth.signup` | `boolean` | `true` | `emailAndPassword.disableSignUp` (inverted) | Self-service account registration — false hides the UI **and** rejects the server endpoint with 403 |\n| `auth.organizations` | `boolean` | `false` | UI surface only — server gating lives under `features.organizations` | Multi-tenant organization management UI (dashboard, invitations, roles). The BA `organization` plugin is auto-added by `features.organizations` for server-side reasons (org tables) independent of this UI flag |\n| `auth.admin` | `boolean` | `false` | UI surface only — BA `admin` plugin is auto-added when `features.organizations` is on | Admin panel for user management in the Account SPA |\n| `auth.emailVerification` | `boolean` | `false` | `emailAndPassword.requireEmailVerification` | Require email verification before sessions are issued. False = sessions usable immediately after signup |\n\n## Trusted Origins\n\nList of origins allowed to make cross-origin requests to your API. Required when your CMS, Account UI, or frontend app run on different domains.\n\n```typescript\ntrustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n \"https://cms.example.com\",\n \"https://app.example.com\",\n],\n```\n\n## Local Development\n\nConfigure local development URLs. These are automatically added to the trusted origins list for CORS and Better Auth, so authentication works out of the box during local development.\n\n```typescript\ndev: {\n port: 8787, // wrangler dev port (default: 8787)\n api: \"http://localhost:8787\", // API backend URL\n cms: \"http://localhost:8787/cms\", // CMS URL (path on same worker)\n account: \"http://localhost:8787/account\", // Account URL (path on same worker)\n},\n```\n\nIf you run a SPA standalone on its own Vite dev server, set its URL here so CORS allows it:\n\n```typescript\ndev: {\n port: 8787,\n api: \"http://localhost:8787\",\n account: \"http://localhost:5173\", // standalone Account dev server\n},\n```\n\n| Field | Type | Default | Description |\n|-------|------|---------|-------------|\n| `port` | `number` | `8787` | Local dev server port (sets `[dev].port` in wrangler.toml) |\n| `api` | `string` | `http://localhost:{port}` | API backend URL |\n| `cms` | `string` | — | CMS dev URL (added to trusted origins if set) |\n| `account` | `string` | — | Account dev URL (added to trusted origins if set) |\n\n## Email Configuration\n\nConfigure email delivery for authentication emails (verification, password reset, invitations).\n\n> **Cloudflare Email Sending is now in public beta** and is Quickback's default transport for Cloudflare deploys. The Workers `send_email` binding is zero-config — no API keys, no third-party accounts. AWS SES remains supported as an explicit opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes or existing SES setups.\n\n```typescript\n// Cloudflare Email Service (default) — uses send_email binding, no API keys needed\nemail: {\n from: \"noreply@example.com\",\n fromName: \"My App\",\n},\n\n// AWS SES — requires AWS credentials set as Wrangler secrets\nemail: {\n provider: \"aws-ses\",\n region: \"us-east-2\",\n from: \"noreply@example.com\",\n fromName: \"My App\",\n},\n```\n\n| Field | Type | Default | Description |\n|-------|------|---------|-------------|\n| `provider` | `\"cloudflare\" \\| \"aws-ses\"` | `\"cloudflare\"` | Email transport |\n| `from` | `string` | `\"noreply@example.com\"` | Sender email address |\n| `fromName` | `string` | `\"{name} \\| Account Services\"` | Sender display name |\n| `region` | `string` | `\"us-east-2\"` | AWS SES region (aws-ses only) |\n\n### Auto-wiring\n\nFor the Cloudflare provider (the default), the compiler automatically:\n- Emits `[[send_email]] EMAIL` into `wrangler.toml`\n- Generates `src/lib/cloudflare-email.ts`\n- Wires `sendResetPassword`, `sendVerificationEmail`, `sendInvitationEmail`, etc. into Better Auth\n\n…whenever any auth surface needs to send mail — `emailAndPassword.enabled`, the `emailOtp` / `magicLink` / `organization` plugins — or you set the top-level `email: {…}` config. You don't need to add `bindings.sendEmail` by hand for the standard cases.\n\n> **Cloudflare Email Routing setup is required.** The binding alone does not deliver mail. Enable Email Routing on the sending zone and add at least one verified destination address ([Cloudflare docs](https://developers.cloudflare.com/email-routing/get-started/)). Otherwise sends fail at runtime even with the binding present and the `/auth/v1/ses/status` check passing locally.\n\n## Multi-Domain Example\n\nA complete config with CMS, Account UI, and Admin on separate subdomains:\n\n```typescript\nexport default {\n name: \"my-app\",\n template: \"hono\",\n cms: { domain: \"cms.example.com\", access: \"admin\" },\n account: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n companyName: \"Example Inc.\",\n auth: {\n password: true,\n emailOTP: false,\n passkey: true,\n organizations: false,\n admin: true,\n },\n },\n email: {\n from: \"noreply@example.com\",\n fromName: \"My App\",\n },\n trustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n \"https://cms.example.com\",\n \"https://example.com\",\n ],\n providers: {\n runtime: { name: \"cloudflare\", config: {\n routes: [{ pattern: \"api.example.com\", custom_domain: true }],\n }},\n database: { name: \"cloudflare-d1\", config: { binding: \"DB\" } },\n auth: { name: \"better-auth\", config: { plugins: [\"admin\"] } },\n },\n};\n```\n\nThis produces a single Cloudflare Worker serving five domains. See [Multi-Domain Architecture](/compiler/config/domains) for details on hostname routing, cross-subdomain cookies, and the unified fallback domain.\n\n---\n\nSee the sub-pages for detailed reference on each section:\n- [Providers](/compiler/config/providers) — Runtime, database, and auth options\n- [Variables](/compiler/config/variables) — Environment variables and flags\n- [Output](/compiler/config/output) — Generated file structure\n- [Single-Tenant Mode](/compiler/config/single-tenant) — Admin-only and public-facing apps without organizations\n- [Multi-Domain Architecture](/compiler/config/domains) — Custom domains, hostname routing, and cross-subdomain auth"
54
+ "content": "The `quickback.config.ts` file configures your Quickback project. It defines which providers to use, which features to enable, and how the compiler generates code.\n\n```typescript\n\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## Discoverable options block\n\nAfter your first `quickback compile`, the file gets a managed block bracketed by sentinel comments:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: cloudflare({}),\n\n // [quickback:options-start]\n // ── Project ──\n //\n // Primary custom domain (auto-inferred from cms/account/api domains if unset).\n // domain: \"example.com\",\n //\n // ── Embedded UIs (CMS / Account) ──\n //\n // Login/signup/profile/orgs SPA. Set `true` for default, or object to customize.\n // account: {\n // fileUploads: false, // show the avatar upload UI on the profile page\n // auth: { passkey: false, emailOTP: false, ... },\n // ...\n // },\n //\n // ... every other option Quickback supports\n // [quickback:options-end]\n});\n```\n\nThis block is **regenerated on every compile** — the compiler is the source of truth, so newly added options surface automatically when you upgrade Quickback (no CLI bump needed).\n\n**To enable an option**, copy the line you care about *above* the `[quickback:options-start]` sentinel and uncomment it:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: cloudflare({}),\n\n account: {\n fileUploads: true, // ← lifted out of the managed block\n },\n\n // [quickback:options-start]\n // ... account is now omitted from this block on next compile\n // [quickback:options-end]\n});\n```\n\nQuickback notices that `account` is set above the marker and drops it from the managed block on the next compile to avoid duplicate definitions. Anything outside the marker block is yours and never touched.\n\nIf you ever want to opt out of the auto-managed block, run:\n\n```bash\nquickback compile --no-sync-config\n```\n\n## Required Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `name` | `string` | Project name |\n| `template` | `\"hono\"` | Application template (`\"nextjs\"` is experimental) |\n| `providers` | `object` | Runtime, database, and auth provider configuration |\n\n## Optional Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `features` | `object` | Feature flags such as `pinnedOrganizationId` — see [Pinned Organization Mode](/compiler/config/single-tenant) |\n| `build` | `object` | Build options (`outputDir`, `packageManager`, `dependencies`) |\n| `compiler` | `object` | Compiler options — `features.auditFields: false` disables audit field injection project-wide; `migrations.renames` provides rename hints for headless CI; `securityContracts` tunes the route/SQL invariants checker |\n| `openapi` | `object` | OpenAPI spec generation (`generate`, `publish`, `docs: 'scalar' \\| 'swagger'` for an in-browser API reference) — see [OpenAPI](/compiler/targets/hono-api/using-the-api/openapi) |\n| `schemaRegistry` | `object` | Schema registry generation for the CMS (enabled by default, `{ generate: false }` to disable) — see [Schema Registry](/stack/cms/schema-registry) |\n| `etag` | `object` | ETag caching for GET responses (enabled by default, `{ enabled: false }` to disable) — see [Caching & ETags](/compiler/targets/hono-api/using-the-api/caching) |\n| `cms` | `boolean \\| object` | Embed CMS in compiled Worker — see [CMS](/stack/cms) |\n| `account` | `boolean \\| object` | Embed Account UI in compiled Worker — see [Account UI](/stack/account-ui) |\n| `trustedOrigins` | `string[]` | CORS trusted origins for cross-domain auth |\n| `domain` | `string` | Primary API domain (auto-inferred from custom domains if not set) |\n| `dev` | `object` | Local development settings (`port`) |\n| `auth` | `object` | App-level auth settings (`roleHierarchy`) — see [Access](/compiler/definitions/access#role-hierarchy) |\n| `email` | `object` | Email delivery config (`provider`, `from`, `fromName`) |\n\n## Custom Dependencies\n\nAdd third-party npm packages to the generated `package.json` using `build.dependencies`. This is useful when your action handlers import external libraries.\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n build: {\n dependencies: {\n \"fast-xml-parser\": \"^4.5.0\",\n \"lodash-es\": \"^4.17.21\",\n },\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\nThese are merged into the generated `package.json` alongside Quickback's own dependencies. Run `npm install` after compiling to install them.\n\n## Headless Migration Rename Hints\n\nWhen `drizzle-kit generate` detects a potential rename, it normally prompts for confirmation. Cloud/CI compiles are non-interactive, so you must provide explicit rename hints.\n\nAdd hints in `compiler.migrations.renames`:\n\n```typescript\nexport default defineConfig({\n // ...\n compiler: {\n migrations: {\n renames: {\n // Keys are NEW names, values are OLD names\n tables: {\n events_v2: \"events\",\n },\n columns: {\n events: {\n summary_text: \"summary\",\n },\n },\n },\n },\n },\n});\n```\n\nRules:\n- `tables`: `new_table_name -> old_table_name`\n- `columns.<table>`: `new_column_name -> old_column_name`\n- Keys must match the names in your current schema (the new names)\n- Validation fails fast for malformed rename config, unsupported keys, or conflicting legacy/new rename paths.\n\n## Disable Audit Field Injection\n\nBy default, Quickback auto-injects four **audit fields** (`createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`) into every feature table, plus two **soft-delete fields** (`deletedAt`, `deletedBy`) into tables that use soft delete (the default delete mode). The audit fields drive record-provenance queries and the CMS audit panel; the soft-delete pair drives soft-delete filtering.\n\nTo opt out project-wide:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n compiler: {\n features: {\n auditFields: false, // skip audit-field injection globally\n },\n },\n providers: { /* ... */ },\n});\n```\n\nWhen disabled, you're responsible for supplying these columns yourself if you want soft delete, audit trails, or modifiedAt-based optimistic concurrency. See the [Schema → Audit Fields](/compiler/definitions/schema#audit-fields) section for the full list and what each field drives.\n\n## Security Contract Reports and Signing\n\nAfter generation, Quickback verifies machine-checkable security contracts for Hono routes and RLS SQL.\n\nIt also emits a report artifact and signature artifact by default:\n\n- `reports/security-contracts.report.json`\n- `reports/security-contracts.report.sig.json`\n\nYou can configure output paths and signing behavior:\n\n```typescript\nexport default defineConfig({\n // ...\n compiler: {\n securityContracts: {\n failMode: \"error\", // or \"warn\"\n report: {\n path: \"reports/security-contracts.report.json\",\n signature: {\n enabled: true,\n required: true,\n keyEnv: \"QUICKBACK_SECURITY_REPORT_SIGNING_KEY\",\n keyId: \"prod-k1\",\n path: \"reports/security-contracts.report.sig.json\",\n },\n },\n },\n },\n});\n```\n\nIf `signature.required: true` and no key is available, compilation fails with a clear error message (or warning in `failMode: \"warn\"`).\n\n## Hostname architecture (v0.33+)\n\nA modern Quickback project runs on **one Cloudflare Worker** that serves multiple URL surfaces. By default, everything lives under a single unified backend hostname (auto-inferred as `quickback.{baseDomain}` from your other configured subdomains, or overridable via `config.domain`). For larger deployments, you can opt-in to **dedicated hostnames** for specific surfaces — they're additive aliases, never replacements.\n\n### The unified backend contract\n\nWhen any subdomain is configured (`account.domain`, `cms.domain`, `auth.domain`, `api.domain`, `apps.<n>.domain`), the compiler always emits a unified backend host where **every compiler-emitted backend route** is reachable:\n\n- `/api/v1/*` — feature routes\n- `/auth/v1/*` — Better Auth\n- `/storage/*` — R2 file storage\n- `/health`, `/openapi.json` — monitoring/discovery\n- `/account/*`, `/cms/*` — bundled SPAs (when enabled)\n- `/broadcast/v1/*` (realtime), `/mcp` (MCP), etc.\n\nThe unified hostname is `quickback.{baseDomain}` by default (where baseDomain is extracted from your first configured subdomain). Override with `config.domain` if you prefer a different name.\n\nThis contract is forward-pointing: it gives a stable URL pattern for future management tooling — `https://quickback.{baseDomain}/...` will always reach a Quickback backend regardless of how the operator splits their surfaces.\n\n### Dedicated hostnames (optional, additive)\n\nFor branding or operational separation, you can opt specific surfaces onto their own hostnames:\n\n```ts\n{\n // Bundled SPAs on their own hosts (already-shipped pattern):\n cms: { domain: 'cms.example.com' },\n account: { domain: 'account.example.com' },\n\n // v0.33+ — backend surfaces on their own hosts:\n auth: { domain: 'auth.example.com' },\n api: { domain: 'api.example.com' },\n\n // User SPAs (existing pattern):\n apps: {\n www: { domain: 'app.example.com' },\n },\n}\n```\n\nOn a dedicated hostname, **the hostname IS the namespace** — the path drops the prefix that matches the hostname:\n\n| URL on dedicated host | Internally rewritten to | Notes |\n|---|---|---|\n| `https://api.example.com/v1/users` | `/api/v1/users` | Worker-entry rewriter prepends `/api` |\n| `https://auth.example.com/v1/sign-in/email` | `/auth/v1/sign-in/email` | Same shape with `/auth` |\n| `https://api.example.com/api/v1/users` | (unchanged) | Long form also accepted |\n| `https://api.example.com/auth/v1/sign-in` | **404** | Auth doesn't live on the API hostname |\n| `https://api.example.com/health` | (unchanged) | Explicit exception — monitoring agents expect `/health` everywhere |\n\nDual-reach is preserved on the unified host:\n\n| URL on unified host | Handler | Notes |\n|---|---|---|\n| `https://quickback.example.com/api/v1/users` | feature route | Works whether `api.domain` is set or not |\n| `https://quickback.example.com/auth/v1/sign-in/email` | Better Auth | Works whether `auth.domain` is set or not |\n| `https://quickback.example.com/v1/users` | **404** | Shortcut only applies on dedicated hostnames |\n\nEach dedicated hostname also:\n\n- Gets a `{ pattern, custom_domain: true }` route in `wrangler.toml` automatically\n- Joins `trustedOrigins` for CORS\n- Joins the cross-subdomain cookie inference (auto-enables `crossSubDomainCookies` when ≥2 same-parent subdomains are configured, so `auth.example.com` and `app.example.com` can share session cookies)\n- Joins CSP `connect-src` so SPAs can fetch from it\n\n### Why two URL shapes (Shape 1 vs Shape 2)\n\nIf you only want Better Auth to **advertise** itself on a different URL (e.g. so verification emails link to `auth.example.com` instead of the unified host), set the `BETTER_AUTH_URL` env var on the Worker — no code change required. BA generates outgoing URLs against that value. This is sufficient when the goal is branding email/OAuth callback URLs without changing where requests actually land.\n\n`auth.domain` (Shape 1, above) is the heavier option: it binds an actual hostname to the Worker, configures CORS/cookies/CSP for it, and adds the path-shortcut rewriter. Use it when you want the dedicated hostname as a real ingress, not just a label.\n\n## CMS Configuration\n\nEmbed the [Quickback CMS](/stack/cms) in your compiled Worker. The CMS reads your schema registry and renders a complete admin interface — zero UI code per table.\n\n```typescript\n// Simple — embed CMS at root\ncms: true,\n\n// With custom domain\ncms: { domain: \"cms.example.com\" },\n\n// With access control (only admins can access CMS)\ncms: { domain: \"cms.example.com\", access: \"admin\" },\n\n// Cross-tenant DB-admin tier — sysadmins see every tenant's data\ncms: { domain: \"cms.example.com\", sysadmin: true },\n```\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `domain` | `string` | — | Custom domain for CMS. Adds a `custom_domain` route to `wrangler.toml`. |\n| `access` | `\"user\" \\| \"admin\"` | `\"admin\"` | Controls who can access the CMS. When `\"admin\"`, platform control-plane users (`user.role === \"appmanager\"`) can enter; when `sysadmin` mode is also on, `user.role === \"sysadmin\"` is admitted too. The gate is enforced at the Worker level (SPA shell, `/api/v1/schema`, and `custom_view` CRUD all return 403 to callers outside those roles) and in the SPA. Also hides the CMS link in Account UI. See [CMS Connecting](/stack/cms/connecting) for the full enforcement model. |\n| `sysadmin` | `boolean` | `false` | Cross-tenant DB-admin tier. When `true`, opts into the `SYSADMIN` pseudo-role (`user.role === \"sysadmin\"`), the firewall escape hatch (sysadmins bypass tenant scopes, soft-delete still enforced), the cross-tenant `/auth/v1/admin/list-organizations` endpoint (sibling of Better Auth's `/auth/v1/admin/list-users`, gated to sysadmin only), and the SPA's \"All organizations\" sentinel. The CMS HTML gate admits `userRole === \"sysadmin\"` alongside `\"appmanager\"`. Off by default. See [`SYSADMIN` pseudo-role](/compiler/definitions/access#sysadmin--cross-tenant-db-admin-tier). |\n\n### Sysadmin tier (`cms.sysadmin: true`)\n\nQuickback's default model assumes every CMS user belongs to at least one organization (`member` row in the auth DB). For platforms that need a Supabase-style cross-tenant DB-admin tool — debugging a tenant's data, running cross-tenant queries, supporting a customer — that's a poor fit: a sysadmin without `member` rows would dead-end, and auto-filling their active org from \"first membership\" silently scopes them to a tenant they have no relationship with.\n\n`cms: { sysadmin: true }` introduces a separate role tier:\n\n- **Role**: `user.role === \"sysadmin\"` (set on the Better Auth user table). Distinct from `\"appmanager\"` — appmanagers keep platform control-plane access (CMS shell, Better Auth admin surfaces, support tooling), while sysadmins get true cross-tenant data access. `ADMIN` is now a rejected legacy pseudo-role; use `userRole: [\"appmanager\"]` for control-plane gates and `roles: [\"SYSADMIN\"]` for cross-tenant access.\n- **Firewall**: every `buildFirewallConditions()` emits an `if (ctx.userRole === \"sysadmin\") return undefined` (or just the soft-delete predicate when present) at the top, so sysadmins see every tenant's rows. See [Firewall escape hatch](/compiler/definitions/firewall#sysadmin-escape-hatch).\n- **Org listing**: a `GET /auth/v1/admin/list-organizations` endpoint selects directly from the auth-schema `organization` table — every row, every tenant. Sits under Better Auth's admin URL namespace (sibling of `/auth/v1/admin/list-users`) so the URL shape matches BA convention; the handler is Quickback-emitted and gated to `user.role === \"sysadmin\"` only. For the membership-bound caller's-orgs listing, use BA's own `/auth/v1/organization/list`.\n- **CMS SPA**: when the user is a sysadmin, the header switcher loads from the cross-tenant endpoint, defaults to \"All organizations\" (which omits `?organizationId=` and reaches the firewall escape), and pins selected tenants via `?organizationId=` on every API call. Org admins keep the existing membership-based switcher.\n- **CMS HTML gate**: admits `userRole === \"sysadmin\"` alongside `\"appmanager\"`. Org admins are not locked out when you set `cms.access: \"user\"`; `cms.access: \"admin\"` is specifically the platform control-plane gate.\n\nOff by default. Projects that don't enable it get zero behavior change; setting `cms.sysadmin: true` and granting a user `user.role = \"sysadmin\"` is the only way to unlock the cross-tenant view.\n\n## Account UI Configuration\n\nEmbed the [Account UI](/stack/account-ui) in your compiled Worker. Provides login, signup, profile management, organization management, and admin — all built from your config at compile time.\n\nFor post-signup logic — auto-provisioning a workspace, gating signup, setting an active organization — drop a file in `quickback/hooks/`. See [Auth Hooks](/stack/account-ui/hooks).\n\n```typescript\n// Simple — embed Account UI with defaults\naccount: true,\n\n// Full configuration\naccount: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n companyName: \"My Company\",\n auth: {\n password: true,\n emailOTP: false,\n passkey: true,\n organizations: true,\n admin: true,\n },\n},\n```\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `domain` | `string` | Custom domain for Account UI (e.g., `auth.example.com`) |\n| `adminDomain` | `string` | Custom domain for admin-only access (e.g., `admin.example.com`). Serves the same Account SPA — the client-side router handles admin routing. |\n| `appUrl` | `string` | URL of the tenant's main application — where users are redirected after login. Baked into the Account SPA as `VITE_QUICKBACK_APP_URL`. Independent from `domain`. |\n| `name` | `string` | App display name shown on login, profile, and email templates |\n| `companyName` | `string` | Company name for branding |\n| `tagline` | `string` | App tagline shown on login page |\n| `description` | `string` | App description |\n\n### Auth Feature Flags\n\nControl which authentication features are exposed. Disabled features are excluded from the Account UI bundle at compile time (routes removed before the Vite build, keeping bundle sizes minimal) **and** enforced on the server side via the Better Auth config — so \"signup off\" actually closes `POST /auth/v1/sign-up/email`, not just the SPA's signup screen.\n\n`account.auth.*` is a shorthand for `providers.auth.config` — the compiler maps each flag onto the Better Auth server config before any code is generated. You can write either side directly; setting both incompatibly (e.g. `account.auth.signup: false` and `emailAndPassword.disableSignUp: false`) fails the compile with a precise error rather than picking a silent winner.\n\n| Flag | Type | Default | Maps to (server) | Description |\n|------|------|---------|------------------|-------------|\n| `auth.password` | `boolean` | `true` | `emailAndPassword.enabled` | Email/password authentication — both server endpoint and UI |\n| `auth.emailOTP` | `boolean` | `false` | adds `emailOtp` plugin | Email one-time password login — adds plugin server-side, surfaces UI |\n| `auth.passkey` | `boolean` | `false` | adds `passkey` plugin | WebAuthn/FIDO2 passkey authentication — adds plugin server-side, surfaces UI |\n| `auth.signup` | `boolean` | `true` | `emailAndPassword.disableSignUp` (inverted) | Self-service account registration — false hides the UI **and** rejects the server endpoint with 403 |\n| `auth.organizations` | `boolean` | `true` | UI surface only | Organization management UI (dashboard, invitations, roles). Server-side organization support stays on regardless; set `features.pinnedOrganizationId` when you want one fixed org with no switching UI |\n| `auth.admin` | `boolean` | `false` | UI surface only | Admin panel for user management in the Account SPA. The Better Auth admin plugin is compiler-managed separately from this UI toggle |\n| `auth.emailVerification` | `boolean` | `false` | `emailAndPassword.requireEmailVerification` | Require email verification before sessions are issued. False = sessions usable immediately after signup |\n\n## Trusted Origins\n\nList of origins allowed to make cross-origin requests to your API. Required when your CMS, Account UI, or frontend app run on different domains.\n\n```typescript\ntrustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n \"https://cms.example.com\",\n \"https://app.example.com\",\n],\n```\n\n## Local Development\n\nConfigure local development URLs. These are automatically added to the trusted origins list for CORS and Better Auth, so authentication works out of the box during local development.\n\n```typescript\ndev: {\n port: 8787, // wrangler dev port (default: 8787)\n api: \"http://localhost:8787\", // API backend URL\n cms: \"http://localhost:8787/cms\", // CMS URL (path on same worker)\n account: \"http://localhost:8787/account\", // Account URL (path on same worker)\n},\n```\n\nIf you run a SPA standalone on its own Vite dev server, set its URL here so CORS allows it:\n\n```typescript\ndev: {\n port: 8787,\n api: \"http://localhost:8787\",\n account: \"http://localhost:5173\", // standalone Account dev server\n},\n```\n\n| Field | Type | Default | Description |\n|-------|------|---------|-------------|\n| `port` | `number` | `8787` | Local dev server port (sets `[dev].port` in wrangler.toml) |\n| `api` | `string` | `http://localhost:{port}` | API backend URL |\n| `cms` | `string` | — | CMS dev URL (added to trusted origins if set) |\n| `account` | `string` | — | Account dev URL (added to trusted origins if set) |\n\n## Email Configuration\n\nConfigure email delivery for authentication emails (verification, password reset, invitations).\n\n> **Cloudflare Email Sending is now in public beta** and is Quickback's default transport for Cloudflare deploys. The Workers `send_email` binding is zero-config — no API keys, no third-party accounts. AWS SES remains supported as an explicit opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes or existing SES setups.\n\n```typescript\n// Cloudflare Email Service (default) — uses send_email binding, no API keys needed\nemail: {\n from: \"noreply@example.com\",\n fromName: \"My App\",\n},\n\n// AWS SES — requires AWS credentials set as Wrangler secrets\nemail: {\n provider: \"aws-ses\",\n region: \"us-east-2\",\n from: \"noreply@example.com\",\n fromName: \"My App\",\n},\n```\n\n| Field | Type | Default | Description |\n|-------|------|---------|-------------|\n| `provider` | `\"cloudflare\" \\| \"aws-ses\"` | `\"cloudflare\"` | Email transport |\n| `from` | `string` | `\"noreply@example.com\"` | Sender email address |\n| `fromName` | `string` | `\"{name} \\| Account Services\"` | Sender display name |\n| `region` | `string` | `\"us-east-2\"` | AWS SES region (aws-ses only) |\n\n### Auto-wiring\n\nFor the Cloudflare provider (the default), the compiler automatically:\n- Emits `[[send_email]] EMAIL` into `wrangler.toml`\n- Generates `src/lib/cloudflare-email.ts`\n- Wires `sendResetPassword`, `sendVerificationEmail`, `sendInvitationEmail`, etc. into Better Auth\n\n…whenever any auth surface needs to send mail — `emailAndPassword.enabled`, the `emailOtp` / `magicLink` / `organization` plugins — or you set the top-level `email: {…}` config. You don't need to add `bindings.sendEmail` by hand for the standard cases.\n\n> **Cloudflare Email Routing setup is required.** The binding alone does not deliver mail. Enable Email Routing on the sending zone and add at least one verified destination address ([Cloudflare docs](https://developers.cloudflare.com/email-routing/get-started/)). Otherwise sends fail at runtime even with the binding present and the `/auth/v1/ses/status` check passing locally.\n\n## Multi-Domain Example\n\nA complete config with CMS, Account UI, and Admin on separate subdomains:\n\n```typescript\nexport default {\n name: \"my-app\",\n template: \"hono\",\n cms: { domain: \"cms.example.com\", access: \"admin\" },\n account: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n companyName: \"Example Inc.\",\n auth: {\n password: true,\n emailOTP: false,\n passkey: true,\n organizations: false,\n admin: true,\n },\n },\n email: {\n from: \"noreply@example.com\",\n fromName: \"My App\",\n },\n trustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n \"https://cms.example.com\",\n \"https://example.com\",\n ],\n providers: {\n runtime: { name: \"cloudflare\", config: {\n routes: [{ pattern: \"api.example.com\", custom_domain: true }],\n }},\n database: { name: \"cloudflare-d1\", config: { binding: \"DB\" } },\n auth: { name: \"better-auth\", config: { plugins: [\"admin\"] } },\n },\n};\n```\n\nThis produces a single Cloudflare Worker serving five domains. See [Multi-Domain Architecture](/compiler/config/domains) for details on hostname routing, cross-subdomain cookies, and the unified fallback domain.\n\n---\n\nSee the sub-pages for detailed reference on each section:\n- [Providers](/compiler/config/providers) — Runtime, database, and auth options\n- [Variables](/compiler/config/variables) — Environment variables and flags\n- [Output](/compiler/config/output) — Generated file structure\n- [Pinned Organization Mode](/compiler/config/single-tenant) — Fixed-org deployments without org switching UI\n- [Multi-Domain Architecture](/compiler/config/domains) — Custom domains, hostname routing, and cross-subdomain auth"
55
55
  },
56
56
  "compiler/config/output": {
57
57
  "title": "Output Structure",
@@ -66,8 +66,8 @@ export const DOCS = {
66
66
  "content": "Every compiled Quickback Worker sets a baseline of security response-headers on every response: HSTS, `X-Content-Type-Options: nosniff`, a clickjacking CSP (`frame-ancestors 'self' …TRUSTED_ORIGINS`), `X-Frame-Options: SAMEORIGIN`, `Referrer-Policy`, and `Permissions-Policy`. Adding the `security` block lets you override individual headers, ship a fuller Content-Security-Policy, or suppress them all if an upstream gateway handles headers.\n\n## Default behavior\n\nOmit `security` entirely → the baseline above. No config change needed for clickjacking + HSTS protection.\n\n```ts title=\"quickback.config.ts\"\n\nexport default defineConfig({\n name: 'my-api',\n // ...\n // security defaults are applied automatically.\n});\n```\n\n## Suppress every security header\n\nFor Workers fronted by a gateway that owns headers:\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // ...\n security: false,\n});\n```\n\nThe compiler emits a no-op middleware comment so the route table still lines up with the rest of the generated code, but no `c.header(...)` calls fire.\n\n## Per-header overrides\n\nEach field on the `security` block accepts either a typed value or `false` to suppress that specific header. Defaults still apply for fields you don't set.\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // ...\n security: {\n // Suppress just CSP — keeps HSTS, referrer, permissions, etc.\n csp: false,\n\n // Or override individual fields:\n coop: 'same-origin',\n coep: 'credentialless',\n referrerPolicy: 'no-referrer',\n permissionsPolicy: { geolocation: [], microphone: [], camera: [], payment: [] },\n hsts: { maxAge: 63072000, includeSubDomains: true, preload: true },\n },\n});\n```\n\n## Content Security Policy\n\n`security.csp` accepts a typed object. Each `*Src` field is an array of source expressions. The compiler accepts both the `@`-prefixed sentinels (idiomatic, type-safe) and CSP wire-form keywords (`\"'self'\"`, `\"'unsafe-inline'\"`); both normalize to the same output.\n\n### Sentinels\n\n| Sentinel | Wire form | Notes |\n|---|---|---|\n| `@self` | `'self'` | Same-origin. |\n| `@none` | `'none'` | Empty-set keyword. |\n| `@unsafe-inline` | `'unsafe-inline'` | Allows inline scripts/styles — defeats most XSS mitigation when used in `script-src`. |\n| `@unsafe-eval` | `'unsafe-eval'` | Allows `eval()` and friends. |\n| `@trustedOrigins` | The `…TRUSTED_ORIGINS` constant at runtime | Resolves to `auth.trustedOrigins` as configured in `quickback.config.ts`. |\n| `@nonce` | `'nonce-…'` per request | Reserved for the per-request nonce middleware shipping in 0.10.15. Using this in 0.10.14 is a compile-time error. |\n\nUnknown `@…` tokens are rejected at compile rather than silently stringified into the wire CSP.\n\n### Example: paste-in CSP for a Quickback SPA project\n\nThe bundled CMS and Account SPAs load Google Fonts cross-origin, so the strict `'self'`-only CSP would white-screen them on load. This config is a known-working starting point for Quickback projects with the bundled SPAs:\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // ...\n security: {\n csp: {\n defaultSrc: ['@self'],\n // Tailwind dynamic styles + bundled Google Fonts CSS need\n // unsafe-inline + the gstatic / googleapis hosts. Tightening\n // styles to nonces ships in 0.10.15.\n styleSrc: ['@self', '@unsafe-inline', 'https://fonts.googleapis.com'],\n scriptSrc: ['@self'],\n fontSrc: ['@self', 'data:', 'https://fonts.gstatic.com'],\n imgSrc: ['@self', 'data:', 'blob:', 'https:'],\n connectSrc: ['@self', '@trustedOrigins'],\n frameAncestors: ['@self', '@trustedOrigins'],\n formAction: ['@self'],\n baseUri: ['@self'],\n objectSrc: ['@none'],\n upgradeInsecureRequests: true,\n },\n },\n});\n```\n\n### Troubleshooting CSP violations\n\nIf the browser console shows CSP errors after enabling `security.csp`, match the directive named in the error against this table — it maps the failure mode back to the directive that needs widening.\n\n| Console error | Directive | Why it happens | Fix |\n|---|---|---|---|\n| `Loading the stylesheet 'https://fonts.googleapis.com/...' violates 'style-src ...'` | `styleSrc` | Bundled CMS/Account SPAs `<link>` to Google Fonts CSS. | Add `'https://fonts.googleapis.com'` to `styleSrc`. |\n| `Refused to load the font 'https://fonts.gstatic.com/...' because it violates 'font-src ...'` | `fontSrc` | The CSS file from googleapis loads `.woff2` files from gstatic. | Add `'https://fonts.gstatic.com'` to `fontSrc`. |\n| `Connecting to 'https://api.your-domain/...' violates 'connect-src 'self''` | `connectSrc` | API on a sibling subdomain (e.g. SPA on `app.example.com`, API on `api.example.com`) — `'self'` only covers exact origin. | Use `connectSrc: ['@self', '@trustedOrigins']` so the same allowlist `cors()` enforces gets reused. |\n| `Refused to apply inline style because it violates 'style-src ...'` | `styleSrc` | TanStack Router / Tailwind's `style=\"...\"` attributes are inline. | Add `'@unsafe-inline'` to `styleSrc` until 0.10.15 ships per-request nonces. |\n| `Refused to load the image '...' because it violates 'img-src ...'` | `imgSrc` | User-uploaded avatars / R2-hosted assets / `data:` URIs from blob previews. | Widen `imgSrc` to `['@self', 'data:', 'blob:', 'https:']` (or list specific hosts). |\n| `Refused to connect to 'wss://...' because it violates 'connect-src ...'` | `connectSrc` | Realtime / Durable Object WebSockets. | The `@trustedOrigins` sentinel covers HTTPS only — add the explicit `wss://` origin if your DO lives elsewhere. |\n\nThe general rule: `'self'` means *exact origin* (scheme + host + port). Anything cross-origin needs an explicit host or the `@trustedOrigins` sentinel. The [paste-in recipe above](#example-paste-in-csp-for-a-quickback-spa-project) is a known-good baseline for a stock Quickback project — start there and tighten, rather than starting from `'self'`-only and chasing console errors.\n\n### Auto-derivations\n\nThe compiler applies these so config stays minimal:\n\n- **`csp.frameAncestors` defaults to `['@self', '@trustedOrigins']`** when `csp` is set but `frameAncestors` is omitted. Same allowlist as CORS.\n- **`X-Frame-Options` derives from `csp.frameAncestors`** (`['@none']` → `DENY`, contains `@self` → `SAMEORIGIN`, otherwise omitted — XFO can't represent arbitrary origins so CSP becomes the truth there). Override with `security.frameOptions`.\n- **`corp: 'same-origin'` is auto-emitted when `coep` is set.** `require-corp` without CORP breaks the ASSETS binding fetches on Cloudflare; the compiler couples them so users don't have to remember.\n\n### CSP auto-config (0.10.15+)\n\nWhen you opt into a `csp` object, the compiler additively widens directives based on which Quickback features your project has enabled. **Additive** means anything you already wrote stays; we only push values that aren't already present.\n\n| Trigger | Auto-added | To directive | Why |\n|---|---|---|---|\n| `cms: true` OR `account: true` | `'unsafe-inline'` | `styleSrc` | Tailwind / TanStack Router emit inline `style=` attributes |\n| `cms: true` OR `account: true` | `https://fonts.googleapis.com` | `styleSrc` | Bundled SPAs `<link>` to Google Fonts CSS |\n| `cms: true` OR `account: true` | `https://fonts.gstatic.com` | `fontSrc` | The googleapis CSS loads `.woff2` from gstatic |\n| `csp` set (always) | `@trustedOrigins` | `connectSrc` | XHR/fetch must reach the same allowlist `cors()` permits — covers cross-subdomain APIs without re-listing them |\n| `cms: true` OR `account: true` | `https://${domain}` for each `cms.domain` / `account.domain` / `domain` / inferred unified domain | `connectSrc` | The Vite bundle hardcodes `VITE_QUICKBACK_API_URL` at compile time, so the SPA fetches that exact URL even when the page is served from a different origin (e.g. localhost dev hitting prod-baked SPA). Emitted with the host's first letter capitalised (`https://Api.example.com`) so `wrangler dev`'s response-header rewrite can't mangle it — see [the `wrangler dev` note below](#why-the-spa-baked-origin-shows-up-capitalised-in-csp). |\n\n**Scaffold rule:** if you set `defaultSrc` but omit the target directive (e.g. you wrote `defaultSrc: ['@self']` and nothing for `connectSrc`), auto-config creates the new directive seeded with your `defaultSrc` values plus the addition. `defaultSrc` itself stays clean. So `defaultSrc: ['@self']` + auto-config produces:\n\n```\ndefault-src 'self'\nstyle-src 'self' 'unsafe-inline' https://fonts.googleapis.com\nfont-src 'self' https://fonts.gstatic.com\nconnect-src 'self' @trustedOrigins https://api.your-app.com\n```\n\nEach directive is scoped to exactly what it needs. `defaultSrc` is *not* widened with style-only or connect-only hosts — that would let those hosts also reach `script-src` / `img-src` / `media-src` via fall-back, which is wider than the bundled SPA actually needs. (This rule changed in 0.10.17 — earlier versions incorrectly pushed additions into defaultSrc.)\n\n**Visibility:** every applied addition prints to stderr at compile time — one line per addition with the directive, value, and reason. No silent magic. Loop's compile output now looks like:\n\n```\n[security] auto-added 'unsafe-inline' to csp.styleSrc — account: true → bundled Account SPA → inline style attributes from Tailwind / TanStack Router\n[security] auto-added https://fonts.googleapis.com to csp.styleSrc — account: true → bundled Account SPA → loads Google Fonts CSS cross-origin\n[security] auto-added https://fonts.gstatic.com to csp.fontSrc — account: true → bundled Account SPA → woff2 font files served from gstatic.com\n[security] auto-added @trustedOrigins to csp.connectSrc — CORS-trusted origins must be reachable from XHR/fetch (matches cors() allowlist)\n```\n\n**Opt-out:** `security: { cspAutoConfig: false, csp: { ... } }` for projects fronted by a CDN that injects its own CSP, or teams that want strict from-scratch control. With auto-config off, every value above must be authored by hand.\n\n#### Why the SPA-baked origin shows up capitalised in CSP\n\nProjects with `domain: \"...\"` + bundled CMS / Account SPAs will see `connect-src 'self' https://Api.example.com …` in their served CSP — note the capital `A`. That's deliberate (added in 0.10.19) and works around a `wrangler dev` quirk, not a typo on our end.\n\n`wrangler dev` rewrites the configured `custom_domain` host string in **every** response header value (Location, Content-Security-Policy, X-…) to the local hostname, with a case-sensitive substring matcher. Without the case-shift, the served CSP becomes `connect-src 'self' https://localhost:8787 …` and the bundled SPA's hardcoded `VITE_QUICKBACK_API_URL` fetches get blocked because the prod URL no longer appears in the allowlist.\n\nCSP host-source matching is ASCII case-insensitive per CSP3 (`Matching Source Expressions`), so browsers treat `https://Api.example.com` as identical to `https://api.example.com` for the purpose of CSP checks. Wrangler's matcher is case-sensitive, so the capitalised form slips past the rewrite and survives into the served header. End result: the SPA's lowercase fetch target matches the capitalised CSP entry, auth round-trips work in dev, and prod CSP behaviour is unchanged (browsers don't care).\n\nIf wrangler ever fixes the response-header rewrite, the capitalised form remains a valid CSP entry — no follow-up needed.\n\nWith auto-config on, the [paste-in recipe above](#example-paste-in-csp-for-a-quickback-spa-project) becomes much shorter — most users only need:\n\n```ts\nsecurity: {\n csp: {\n defaultSrc: ['@self'],\n scriptSrc: ['@self'],\n imgSrc: ['@self', 'data:', 'blob:', 'https:'],\n objectSrc: ['@none'],\n upgradeInsecureRequests: true,\n },\n}\n```\n\nThe compiler fills in the SPA-specific font hosts, inline-style allowance, and trusted-origin connect rules from the project's own feature flags.\n\n## Cross-origin window/embedder isolation\n\n```ts title=\"quickback.config.ts\"\nsecurity: {\n coop: 'same-origin', // Defends against window.opener back-references from popups.\n coep: 'credentialless', // Required for SharedArrayBuffer / cross-origin isolation.\n // corp auto-emits as 'same-origin' here.\n}\n```\n\n## HSTS\n\nDefault: `max-age=31536000; includeSubDomains; preload` (HSTS preload-list eligible).\n\n```ts title=\"quickback.config.ts\"\nsecurity: {\n hsts: { maxAge: 63072000, includeSubDomains: true, preload: true },\n}\n```\n\nThe generated middleware automatically suppresses HSTS on `localhost`, `127.0.0.1`, and `*.localhost` regardless of this config. Without that gate, `wrangler dev` would pin the developer's browser to HTTPS for `maxAge` seconds, which is observable across every project on that machine.\n\nTo submit to the [HSTS preload list](https://hstspreload.org), you need:\n\n- `maxAge` ≥ 31536000 (one year)\n- `includeSubDomains: true`\n- `preload: true`\n\nThe compiler warns at compile time if `preload: true` without the other two — the preload list rejects either anyway.\n\n## Permissions Policy\n\nMap of feature name → list of allowed origins.\n\n```ts title=\"quickback.config.ts\"\nsecurity: {\n permissionsPolicy: {\n geolocation: [], // disabled for everyone\n microphone: ['self'], // allowed only on own origin\n camera: ['self', 'https://meet.example.com'],\n payment: [],\n },\n}\n```\n\nThe compiler encodes the wire syntax (which differs from CSP — values use `()`, not space-separated tokens, with bareword `self` and quoted URLs).\n\n## Compile-time lint rules\n\nThe compiler walks the resolved config and emits warnings (or errors) for known footguns. Errors block compile; warnings print to stderr.\n\n| Code | Severity | Trigger |\n|---|---|---|\n| `csp/nonce-not-yet-supported` | error | `@nonce` sentinel used in 0.10.14. Per-request nonce middleware ships in 0.10.15. |\n| `csp/unsafe-inline-with-nonce` | error | `@unsafe-inline` and `@nonce` in the same directive (CSP3 silently ignores `unsafe-inline` when nonce is present). |\n| `csp/empty-resolved-directive` | error | `*Src` array contains only `@trustedOrigins` and `auth.trustedOrigins` is empty — would emit a directive Chrome reads as `'none'`. |\n| `csp/unsafe-inline-script` | warn | `@unsafe-inline` in `scriptSrc` defeats most XSS mitigations. |\n| `csp/open-source` | warn | Wildcard `*` or scheme-only `https:` / `http:` in any `*-src`. |\n| `csp/unsafe-eval-with-data` | warn | `@unsafe-eval` combined with any `data:` source — trivial bypass. |\n| `csp/missing-default-src` | warn | Other `*-src` set without `defaultSrc`. |\n| `csp/upgrade-with-http` | warn | `upgradeInsecureRequests: true` plus an `http://` source elsewhere. |\n| `csp/report-uri-only` | warn | `reportUri` set without `reportTo` (deprecated CSP2 path). |\n| `hsts/preload-needs-long-max-age` | warn | `preload: true` with `maxAge < 31536000`. |\n| `hsts/preload-needs-include-subdomains` | warn | `preload: true` without `includeSubDomains`. |\n\n## Verification\n\nSpin up the deployed Worker (or `wrangler dev`) and check the response headers:\n\n```bash\ncurl -sI https://my-api.example.com/health \\\n | grep -E '^(content-security-policy|x-frame-options|strict-transport-security|cross-origin-opener-policy|cross-origin-embedder-policy|cross-origin-resource-policy|referrer-policy|permissions-policy):'\n```\n\nUse [securityheaders.com](https://securityheaders.com) for an external grade — Quickback's defaults are A on the baseline and A+ once a fuller `csp` is configured."
67
67
  },
68
68
  "compiler/config/single-tenant": {
69
- "title": "Single-Tenant Mode",
70
- "content": "Single-tenant mode disables the Better Auth organization plugin, removing the `organizationId` requirement from your API. This is ideal for personal sites, blogs, admin panels, or any app with a single tenant.\n\n## Enabling Single-Tenant Mode\n\nSet `features.organizations` to `false` in your config:\n\n```typescript\n\nexport default defineConfig({\n name: \"my-site\",\n template: \"hono\",\n features: {\n organizations: false,\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## What Changes\n\n| Aspect | Multi-Tenant (default) | Single-Tenant |\n|--------|----------------------|---------------|\n| Organization plugin | Enabled | Disabled |\n| `organizationId` columns | Required on resources | Not used |\n| Role source | Org membership table | `user.role` field |\n| Firewall scopes | `owner`, `organization`, `team`, `exception` | `owner`, `exception` only |\n| Admin org endpoints | Use Better Auth's `/auth/v1/organization/list` (caller's orgs) and `/auth/v1/admin/list-organizations` when `cms.sysadmin: true` (cross-tenant) | N/A (no org plugin) |\n| `ctx.activeOrgId` | From session/JWT | Always `undefined` |\n| `ctx.roles` | From org member role | From `user.role` |\n\n## Firewall Configuration\n\nIn single-tenant mode, resources use either **owner** scope (user-scoped data) or **exception** (public/system data):\n\n```typescript\n// User-scoped data (requires authentication)\nexport default defineTable(posts, {\n firewall: [{ field: 'ownerId', equals: 'ctx.userId' }],\n read: {\n access: { roles: ['user', 'admin'] },\n },\n create: { access: { roles: ['admin'] } },\n});\n\n// Public data (no ownership filtering)\nexport default defineTable(pages, {\n firewall: [{ exception: true }],\n read: {\n access: { roles: ['PUBLIC'] },\n },\n create: { access: { roles: ['admin'] } },\n update: { access: { roles: ['admin'] } },\n delete: { access: { roles: ['admin'] } },\n});\n```\n\n## Public Routes\n\nUse the `PUBLIC` role to expose routes without authentication. This works the same as in multi-tenant mode:\n\n```typescript\nread: {\n access: { roles: ['PUBLIC'] }, // GET / and GET /:id — no auth required\n},\ncreate: { access: { roles: ['admin'] } }, // Admin only\n```\n\n## Role-Based Access\n\nRoles come from the `user.role` field (managed by Better Auth's [admin plugin](https://www.better-auth.com/docs/plugins/admin)).\n\n| Role | Description |\n|------|-------------|\n| `admin` | Full access, set via Better Auth admin plugin |\n| `user` | Default role for authenticated users |\n| `PUBLIC` | Unauthenticated access (special keyword) |\n\n```typescript\n// Admin-only action\nexport default defineActions({\n publish: {\n access: { roles: ['admin'] },\n execute: async ({ ctx, db }) => {\n // ctx.userRole === 'admin'\n // ctx.roles === ['admin']\n },\n },\n});\n```\n\n## Consuming the API\n\nSince single-tenant mode produces a JSON API, pair it with any frontend framework:\n\n```typescript\n// Astro, Next.js, SvelteKit, etc.\nconst posts = await fetch('https://api.mysite.com/api/v1/posts').then(r => r.json());\n\n// Admin operations require authentication\nconst res = await fetch('https://api.mysite.com/api/v1/posts', {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ title: 'New Post', content: '...' }),\n});\n```"
69
+ "title": "Pinned Organization Mode",
70
+ "content": "Single-tenant mode has been removed. If you want a one-org deployment without org switching overhead, use `features.pinnedOrganizationId` instead.\n\nPinned organization mode keeps Better Auth's organization plugin, organization membership roles, and org-scoped firewalls enabled. The only difference is that Quickback hard-codes one active organization id at runtime and hides the switching UI.\n\n## Enabling Pinned Organization Mode\n\nSet a real organization id in your config:\n\n```typescript\n\nexport default defineConfig({\n name: \"my-site\",\n template: \"hono\",\n features: {\n pinnedOrganizationId: \"org_123\",\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## Removed Single-Tenant Settings\n\nThese older settings now fail the compile with a migration error:\n\n- `features.organizations: false`\n- `providers.database.config.organizations: false`\n- `providers.auth.config.plugins.organization = false`\n\nReplace them with `features.pinnedOrganizationId`.\n\n## What Changes\n\n| Aspect | Default Org Mode | Pinned Organization Mode |\n|--------|------------------|--------------------------|\n| Organization plugin | Enabled | Enabled |\n| Role source | Org membership table | Org membership table in the pinned org |\n| Firewall scopes | `owner`, `organization`, `team`, `exception` | Same |\n| `ctx.activeOrgId` | From session / JWT / API key context | Always the configured org id |\n| CMS org selector | Visible when caller can switch orgs | Hidden |\n| CMS org gate | Requires an active org selection | Bypassed; pinned org is injected automatically |\n\n## Access and Roles\n\nPinned organization mode does **not** bring back the old `user.role` mirror on `ctx.roles`.\n\n- Use `roles: [\"owner\" | \"admin\" | \"member\"]` for data-plane access based on membership in the pinned org.\n- Use `userRole: [...]` for platform-wide Better Auth roles stored on `user.role` (`appmanager`, `sysadmin`, etc.).\n\n```typescript\nexport default defineActions({\n publish: {\n access: {\n or: [\n { roles: [\"admin\"] }, // admin in the pinned org\n { userRole: [\"appmanager\"] }, // platform control-plane role\n ],\n },\n execute: async () => ({ ok: true }),\n },\n});\n```\n\n## Firewalls and Resource Scopes\n\nOrganization-scoped resources keep working in pinned mode. `q.scope(\"organization\")`, `q.scope(\"team\")`, and any firewall predicate that references `ctx.activeOrgId` still compile and run normally — they just see the pinned organization id instead of a user-selected one.\n\nOwner-scoped and public resources are unchanged.\n\n## CMS Behavior\n\nWhen `features.pinnedOrganizationId` is set:\n\n- the CMS hides the org switcher\n- the CMS skips the org-selection gate\n- API calls and realtime connections use the pinned org automatically\n- role checks still come from the caller's membership in that org\n\nThis is the intended replacement for the old single-tenant CMS flow.\n\n## Migration from Single-Tenant Mode\n\n1. Remove `features.organizations: false`.\n2. Add `features.pinnedOrganizationId: \"<real-org-id>\"`.\n3. Remove any assumptions that `ctx.roles` mirrors `user.role`.\n4. If you need platform-wide roles, keep those checks on `userRole`, not `roles`.\n\n## Consuming the API\n\nPinned organization mode still produces the same JSON API shape. Pair it with any frontend framework:\n\n```typescript\nconst posts = await fetch(\"https://api.mysite.com/api/v1/posts\").then((r) => r.json());\n\nconst res = await fetch(\"https://api.mysite.com/api/v1/posts\", {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${token}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ title: \"New Post\", content: \"...\" }),\n});\n```"
71
71
  },
72
72
  "compiler/config/variables": {
73
73
  "title": "Environment Variables",
@@ -75,23 +75,35 @@ export const DOCS = {
75
75
  },
76
76
  "compiler/definitions/access": {
77
77
  "title": "Access - Role & Condition-Based Access Control",
78
- "content": "Define who can perform read and write operations and under what conditions.\n\n## Basic Usage\n\n```typescript\n// features/applications/applications.ts\n\nexport const applications = sqliteTable('applications', {\n id: text('id').primaryKey(),\n candidateId: text('candidate_id').notNull(),\n jobId: text('job_id').notNull(),\n stage: text('stage').notNull(),\n notes: text('notes'),\n organizationId: text('organization_id').notNull(),\n});\n\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: { createable: [\"candidateId\", \"jobId\", \"notes\"], updatable: [\"notes\"] },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n});\n```\n\n## Role Hierarchy\n\nIf your project uses a tiered role system (e.g., `member` < `admin` < `owner`), you can define a hierarchy in your config and use the `+` suffix to mean \"this role and above\":\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n name: \"my-app\",\n auth: {\n roleHierarchy: ['member', 'admin', 'owner'], // lowest → highest\n },\n // ...\n});\n```\n\nThen in your resource definitions:\n\n```typescript\nread: { access: { roles: [\"member+\"] } }, // member, admin, owner\ncreate: { access: { roles: [\"admin+\"] } }, // admin, owner\ndelete: { access: { roles: [\"owner\"] } }, // owner only (no +)\n```\n\nThe `+` suffix expands at compile time — `\"member+\"` becomes `[\"member\", \"admin\", \"owner\"]` in the generated code. You can mix hierarchical and exact roles: `roles: [\"member+\", \"finance\"]` expands to `[\"member\", \"admin\", \"owner\", \"finance\"]`.\n\n- Roles without `+` are exact matches (no expansion)\n- Pseudo-roles (`PUBLIC`, `AUTHENTICATED`, `USER`, `ADMIN`, `SYSADMIN`) cannot use the `+` suffix — they're terminal markers\n- Using `+` with a role not in the hierarchy throws a compile error\n- Using `+` without configuring `auth.roleHierarchy` throws a compile error\n\n## Configuration Options\n\n```typescript\ninterface Access {\n // Org-membership roles (OR logic — user needs at least one)\n // Matched against ctx.roles. Use \"role+\" suffix for hierarchy expansion.\n roles?: string[];\n\n // User-table role (OR logic). Matched against ctx.userRole from the\n // user.role column — independent of org membership. See userRole below.\n userRole?: string[];\n\n // Record-level conditions\n record?: {\n [field: string]: FieldCondition;\n };\n\n // Combinators\n or?: Access[];\n and?: Access[];\n}\n```\n\n## `userRole` vs `roles`\n\n`roles` and `userRole` check **two different fields** and are often confused — get this wrong and you'll grant access too broadly.\n\n| Primitive | Checks | Source | Example values |\n|-----------|--------|--------|----------------|\n| `roles` | `ctx.roles` | Org membership (multi-tenant) or single-tenant mirror of `user.role` | `\"owner\"`, `\"admin\"`, `\"member\"` |\n| `userRole` | `ctx.userRole` | The `user.role` column (Better Auth admin plugin) | `\"user\"`, `\"admin\"` |\n\nIn multi-tenant mode, **`roles: [\"admin\"]` means \"org admin\" — not a platform-wide admin.** An org-admin of Acme Corp has no elevated rights across other orgs. If you want to let Better Auth system admins through regardless of org membership (e.g., for support/ops), use `userRole: [\"admin\"]`.\n\nIn single-tenant mode (`features.organizations: false`), `ctx.roles` mirrors `user.role`, so `roles: [\"admin\"]` and `userRole: [\"admin\"]` behave the same. Using `userRole` in single-tenant code is still preferred — it documents intent and keeps the gate correct if you later enable orgs.\n\n### When to use `userRole`\n\n```typescript\n// Platform admin can see SSNs on every customer record, regardless of org\nmasking: {\n ssn: { type: 'ssn', show: { userRole: ['admin'] } },\n}\n\n// Support staff (user.role === 'admin') OR the org owner can refund\naccess: {\n or: [\n { userRole: ['admin'] },\n { roles: ['owner'] },\n ],\n}\n\n// CMS-internal resource: only platform admins\nread: { access: { userRole: ['admin'] } },\ncreate: { access: { userRole: ['admin'] } },\nupdate: { access: { userRole: ['admin'] } },\ndelete: { access: { userRole: ['admin'] } },\n```\n\nWhen `roles` and `userRole` both appear in a single `Access` node, they're combined with AND — the user must satisfy both. Use `or:` to express \"one or the other\".\n\n`userRole` doesn't expand with the `+` hierarchy suffix — user-table roles are flat (typically just `\"user\"` and `\"admin\"`). If you've added custom user-table roles via Better Auth, list them explicitly.\n\n### Pseudo-roles\n\nQuickback ships five UPPERCASE role markers that are **not backed by a Better Auth role column** — they're system-level shortcuts handled directly by the compiler. The casing carries the boundary: UPPERCASE = pseudo-role (no plugin context required), lowercase = real role from a plugin's table (e.g. `members.role` from the org plugin).\n\n| Role | Auth gate | Compile-time requirement | Runtime check |\n|------|-----------|-------------------------|---------------|\n| `PUBLIC` | bypassed | none — explicit opt-in for unauthenticated access | always passes (auth skipped) |\n| `AUTHENTICATED` | required | none | `ctx.authenticated === true` |\n| `USER` | required | resource firewall **must** scope by `userId` | `ctx.authenticated` AND (`ctx.userRole` is unset OR `ctx.userRole === \"user\"`) |\n| `ADMIN` | required | Better Auth admin plugin **must** be enabled | `ctx.authenticated && ctx.userRole === \"admin\"` |\n| `SYSADMIN` | required | `cms: { sysadmin: true }` **must** be set on the project | `ctx.authenticated && ctx.userRole === \"sysadmin\"` |\n\nYou can mix pseudo-roles with real roles in the same list — they're OR'd together.\n\n#### `PUBLIC` — unauthenticated access\n\nUse `roles: [\"PUBLIC\"]` for public-facing endpoints like contact forms, public listings, or webhooks. Skips both the auth gate and the role check.\n\n```typescript\naccess: { roles: [\"PUBLIC\"] }\n```\n\n**Important:**\n- `PUBLIC` skips authentication and role checks — anyone can call the endpoint\n- **`PUBLIC` is the explicit, uppercase opt-in for unauthenticated access.** It works on every access node — reads, top-level writes (`create`/`update`/`delete`/`upsert`), views, and actions. The compiler trusts the marker; row-level safety comes from the firewall, masking, and (for token-gated endpoints like RSVP confirm, magic-link redemption, List-Unsubscribe-Post, webhook ingest) your handler's own validation. Anonymous write endpoints typically pair `roles: [\"PUBLIC\"]` with `firewall: { exception: true }` on the resource so the row predicate doesn't reject every unauthenticated caller.\n- **Firewall still applies** — data is scoped by the firewall (organization, owner, team)\n- Every `PUBLIC` action invocation is **mandatory audit logged** to the security audit table (IP address, input, result, timing)\n- The wildcard `\"*\"` is **not supported** — using it throws a compile-time error\n- Tables with no isolation columns and any `PUBLIC` route do not require `firewall: [{ exception: true }]`\n\nFor org-scoped tables, `PUBLIC` routes still filter by organization. Since the user isn't authenticated, the organization ID must be passed as a query parameter:\n\n```\nGET /api/v1/listings?organizationId=org_abc123\n```\n\nThe firewall WHERE clause is always enforced. If no `organizationId` is provided, the API returns a `400` with code `ORG_REQUIRED`.\n\n```typescript\n// Public listing page — anyone can browse, but scoped to an org\nexport default defineTable(listings, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: { access: { roles: [\"PUBLIC\"] } }, // Public browsing + detail\n create: { access: { roles: [\"admin\", \"member\"] } }, // Auth required to create\n});\n```\n\n#### `AUTHENTICATED` — any signed-in user\n\nUse `roles: [\"AUTHENTICATED\"]` for endpoints that any logged-in user can hit, regardless of role or org membership. No plugin context required.\n\n```typescript\n// Public events feed — any signed-in user can list/read; anonymous gets 401\nread: { access: { roles: [\"AUTHENTICATED\"] } }\n```\n\n#### `USER` — per-user records\n\nUse `roles: [\"USER\"]` for resources where each user only sees their own records. **Requires the firewall to scope by `userId`** — the role marker is the access half of the pair, the firewall is the row-filter half.\n\n```typescript\n// \"My todos\" — each caller sees only their own rows\nexport default defineTable(todos, {\n firewall: [{ field: 'userId', equals: 'ctx.userId' }],\n read: { access: { roles: [\"USER\"] } },\n create: { access: { roles: [\"USER\"] } },\n update: { access: { roles: [\"USER\"] } },\n delete: { access: { roles: [\"USER\"] } },\n});\n```\n\nIf you forget the `userId` firewall predicate, the compiler throws:\n\n> `roles: [\"USER\"]` requires the resource to be scoped per-user. Add a `userId` column (auto-scoped) or an explicit owner predicate. If you want any signed-in user to read all records, use `roles: [\"AUTHENTICATED\"]` instead.\n\nWhen the Better Auth admin plugin is enabled, `USER` matches `user.role === \"user\"` specifically — admins are excluded and should use `[\"USER\", \"ADMIN\"]` if the same route should serve both.\n\n#### `ADMIN` — Better Auth admin-plugin admins\n\nUse `roles: [\"ADMIN\"]` for system-administrator endpoints. **Requires the Better Auth admin plugin** so `user.role` exists. Compiles to `ctx.userRole === \"admin\"`.\n\n```typescript\n// Platform-admin-only audit log\nread: { access: { roles: [\"ADMIN\"] } }\n```\n\nWithout the admin plugin you get a compile error pointing you to either enable the plugin or use lowercase `roles: [\"admin\"]` (the org-membership admin role).\n\n#### `SYSADMIN` — cross-tenant DB-admin tier\n\nUse `roles: [\"SYSADMIN\"]` for endpoints that should only be reachable by platform sysadmins — the cross-tenant DB-admin tier introduced in v0.15.0. Compiles to `ctx.userRole === \"sysadmin\"`. **Requires `cms: { sysadmin: true }` on the project config**; without that flag, using `SYSADMIN` fails the compile so the role can't sit as dead code.\n\n```typescript\n// Cross-tenant audit dashboard, sysadmin-only\nread: { access: { roles: [\"SYSADMIN\"] } }\n```\n\n`ADMIN` and `SYSADMIN` are **independent** at the evaluator level — `ADMIN` admits `userRole === 'admin'` only, `SYSADMIN` admits `userRole === 'sysadmin'` only. Routes that need both write `access: { roles: ['ADMIN', 'SYSADMIN'] }` explicitly. The one place sysadmin gets implicit extra powers is **the firewall escape hatch**: when `cms.sysadmin: true`, every `buildFirewallConditions` emits an `if (ctx.userRole === 'sysadmin') return undefined;` (or just the soft-delete predicate when present) at the top — so sysadmins see every tenant's rows, not just their own org's. That escape hatch does NOT fire for `userRole === 'admin'`; admins still go through the firewall like everyone else.\n\nThis separation exists so Better Auth admin-plugin powers (user management, impersonation) and DB-admin powers (cross-tenant data inspection) stay decoupled. A user can have `user.role === 'admin'` without DB-level cross-tenant access; a user can have `user.role === 'sysadmin'` without org-membership context. See [CMS Configuration](/compiler/config#cms-configuration) for the `cms.sysadmin` flag, the cross-tenant `/auth/v1/admin/list-organizations` endpoint, and the SPA's \"All organizations\" sentinel.\n\n#### Mixing pseudo-roles with real roles\n\nPseudo-roles and lowercase real roles compose with OR:\n\n```typescript\n// Record owner OR a system admin can read\nread: { access: { roles: [\"USER\", \"ADMIN\"] } }\n\n// Org owner OR system admin\ndelete: { access: { roles: [\"owner\", \"ADMIN\"] } }\n```\n\n> Note: today, an `ADMIN` match still goes through the `userId` firewall scope on USER-scoped resources — admins see only records they own on those routes. Use `firewall: { exception: true }` on a separate admin-only route if you need cross-user visibility.\n\n#### Quick reference\n\n```typescript\n// Unauthenticated public\naccess: { roles: [\"PUBLIC\"] }\n\n// Any signed-in user, no scoping\naccess: { roles: [\"AUTHENTICATED\"] }\n\n// Per-user records (requires userId firewall scope)\naccess: { roles: [\"USER\"] }\n\n// System admin (requires admin plugin)\naccess: { roles: [\"ADMIN\"] }\n\n// Org-membership roles with hierarchy expansion\naccess: { roles: [\"member+\"] } // expands to [\"member\", \"admin\", \"owner\"]\naccess: { roles: [\"admin+\"] } // expands to [\"admin\", \"owner\"]\naccess: { roles: [\"admin\"] } // exact match (no expansion)\n```\n\n```typescript\n// Field conditions - value can be string | number | boolean\ntype FieldCondition =\n | { equals: value | '$ctx.userId' | '$ctx.activeOrgId' }\n | { notEquals: value }\n | { in: value[] }\n | { notIn: value[] }\n | { lessThan: number }\n | { greaterThan: number }\n | { lessThanOrEqual: number }\n | { greaterThanOrEqual: number };\n```\n\n## Relationship-based authorization\n\nBeyond Better Auth roles (org membership, user-table role) and pseudo-roles, Quickback supports **relationship-based authorization roles** — names that bind to a declared relationship between the caller and a resource. Use these when access should follow a domain-table membership (\"user is a confirmed guest of this event\") rather than an org/admin gate.\n\n### `authz.relationships`\n\nDeclare relationships once in `quickback.config.ts`:\n\n```typescript\n// quickback.config.ts\n\nexport default defineConfig({\n // ...providers...\n authz: {\n relationships: {\n guestOf: {\n from: 'event_guests', // table name string\n subject: { column: 'userId', equals: 'ctx.userId' }, // caller side\n resource: { column: 'eventId' }, // resource side\n where: { status: 'confirmed' }, // optional filter\n },\n },\n roles: {\n guest: { via: 'guestOf' },\n // Composite: any guest OR an org owner/admin\n eventStaff: {\n or: [\n { via: 'guestOf' },\n { roles: ['admin', 'owner'] },\n ],\n },\n },\n },\n});\n```\n\n### Using relationship-roles in resources\n\nResource definitions reference declared roles by name in `roles: [...]` arrays exactly like BA roles or pseudo-roles. The compiler rewrites the access tree at build time so the runtime route does an inline relationship lookup against the declared table.\n\n**Today (v1) this works on:**\n\n| Surface | Status | Notes |\n|---|---|---|\n| `firewall:` `via:` predicate | ✓ Supported | Subquery composes as outermost AND |\n| `crud.*.access` `roles: ['guest']` | ✓ Supported | Inline async lookup per request |\n| `read.access` / `read.views.*.access` `roles: ['guest']` | ✓ Supported | Same inline path |\n| `masking.<field>.show` `roles: ['guest']` | ⚠ Refused at compile | v1 limitation — async/batched mask functions deferred |\n| **Standalone** `actions.<name>.access` `roles: ['guest']` | ✓ Supported (v0.19+) | Inline gate; surface must expose `resource.column` as path param or input field |\n| **Record-based** `actions.<name>.access` `roles: ['guest']` | ⚠ Fail-closed at runtime | Runtime helper denies; inline emission is a planned follow-up. Use `firewall: { exception: true }` or move the check into `execute()` until then |\n\nFor the surfaces that are not yet supported, the compiler refuses at build time with a clear error pointing to a workaround. The runtime evaluator fails closed on relationship arms regardless, so silent grants are impossible.\n\n### Standalone actions: surface keys and `loads` / `exposeAs` (v0.19+)\n\nWhen a standalone action's `access.roles` references a relationship-role, the compiler emits a runtime gate between input validation and `execute()`. The gate reads the relationship's `resource.column` value from the action surface — either a path parameter (`:eventId`) or an input field (`input.eventId`). If neither is present, the compiler:\n\n- **v0.19** — emits a `[quickback:authz]` warning and skips resolver emission. The action's own hand-rolled gate (if any) keeps the route working at runtime.\n- **v0.20** — hard compile error. Set `firewall: { exception: true }` to opt out (cross-tenant/admin routes only).\n\nPair the relationship with `loads` + `exposeAs` to hydrate the loaded resource onto `ctx`:\n\n```typescript\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events', // ← v0.19+: load matching event row\n exposeAs: 'event', // ← onto ctx.event for the action body\n },\n },\n roles: {\n attendee: { via: 'attendeeOf' },\n },\n}\n```\n\nThe resolver (v0.20):\n\n1. **Cheap in-memory role check** first — `ctx.roles?.includes('admin')` and friends. If the caller has a qualifying role, this short-circuits and no DB queries fire for the access gate.\n2. **Firewall-gated relationship match** if the role check failed — `SELECT { organizationId, teamId } FROM guests WHERE userId=ctx.userId AND eventId=input.eventId AND status='confirmed'` with the `guests` table's full firewall AND-applied. If neither role nor relationship qualifies → 403.\n3. **Tenant stamping from the matched row** — for any tenant column the `from` table carries (`organizationId`, `teamId`), the resolver stamps `ctx.activeOrgId ??= matchedRow.organizationId` (and similar for team). This is **in-memory mutation of the request-scoped ctx only** — no JWT remint, no session-record write, no persistent grant.\n4. **Firewall-gated load of the loaded resource** — `SELECT * FROM events WHERE id = :eventId AND buildEventsFirewallConditions(ctx, db)`. The events firewall is applied as normal; it succeeds for attendees because tenant was just stamped from the relationship row.\n5. Assigns the loaded row to `ctx.event` for the action body.\n\n**No firewall bypass anywhere.** Both queries run with their respective tables' full firewalls. The relationship row's existence is the proof that the caller is authorized; its tenant columns are the source of the stamped claim.\n\n### Conditional tenant preconditions (v0.20+)\n\nStandalone actions in features with org/team-scoped tables previously emitted unconditional preconditions:\n\n```ts\nif (!ctx.activeOrgId) return c.json(AccessErrors.noOrg(), 403);\nif (!ctx.activeTeamId) return c.json(AccessErrors.noTeam(), 403);\n```\n\nThese ran **before** the relationship resolver, which 403'd attendees whose sessions don't carry an active tenant claim (the canonical event-attendee shape).\n\nv0.20 makes these preconditions **conditional on relationship supply**. If the access tree contains a relationship arm whose `from` table carries the matching tenant column, the precondition is skipped — the resolver runs first and stamps the value. Pseudo-role short-circuits (PUBLIC / AUTHENTICATED / USER / ADMIN / SYSADMIN) and `firewall: { exception: true }` still bypass the preconditions as before.\n\nTypical event-attendee setup (`guests` table carries `organizationId`): the org precondition is dropped on every action whose access references `attendee` or `eventStaff`. Org admins still get `ctx.activeOrgId` from their session as today; attendees get it from the relationship row, mid-request. Both paths converge on a valid tenant claim before `execute()` runs.\n\n### Requirement on the relationship's `from` table\n\nFor the v0.20 tenant-stamping to work, the relationship's `from` table must carry tenant columns:\n\n- For org stamping: an `organizationId` column (or whatever spelling the project's auth-provider defaults pick).\n- For team stamping: a `teamId` column.\n\nWhen the `from` table has **neither**, the compiler emits a `[quickback:authz]` warning at compile time:\n\n```\nRelationship \"X\" at authz.relationships.X has no organization or team columns\non its `from` table (\"guests\"). Action \"Y\" will compile, but downstream\nscoped-db queries inside execute() may 403 because ctx.activeOrgId /\nactiveTeamId cannot be stamped from the match row. Either add the tenant\ncolumn to \"guests\", or set firewall: { exception: true } on the action.\n```\n\nThe relationship match still works (existence check), but no tenant gets stamped — so the conventional precondition still fires and the action still 403s for callers without a session-resident tenant claim. Add the tenant column (or denormalize it onto the relationship table during writes) to enable the stamping path.\n\nThe body can then trust `ctx.event` and drop the hand-rolled `SELECT … FROM guests WHERE …` boilerplate:\n\n```ts\n// features/chat/actions/getInbox.ts\nexport default defineAction({\n path: '/chat/get-inbox',\n input: z.object({ eventId: z.number().int().positive() }),\n access: { roles: ['admin', 'member', 'attendee'] }, // attendee is a relationship-role\n execute: async ({ db, ctx, input }) => {\n // No hand-rolled attendance check needed — the resolver already ran.\n // ctx.event is the loaded events row. Typed as `any` here because the\n // hand-rolled `roles: ['attendee']` action gates per-action, not per-\n // namespace — see \"Narrow ctx.<exposeAs> typing\" below for the typed\n // import flip available when the same hydration runs through a\n // namespace mount.\n const event = ctx.event as typeof events.$inferSelect;\n // … domain logic only.\n },\n});\n```\n\n`loads` and `exposeAs` are co-required (set both or neither). `exposeAs` must be a valid JS identifier and must not collide with built-in `ctx` fields (`userId`, `activeOrgId`, `activeTeamId`, `db`, etc.).\n\n### Action firewall escape hatch (v0.19+)\n\n`defineAction({ firewall: { exception: true } })` opts the action out of the inherited session-key preconditions (`ctx.activeOrgId` / `ctx.activeTeamId` requirements) AND the relationship resolver. The handler receives `unsafeDb` for raw Drizzle access. Use for cross-tenant or admin routes whose surface intentionally doesn't name a session/relationship key:\n\n```ts\ndefineAction({\n path: '/admin/cross-tenant-report',\n firewall: { exception: true },\n unsafe: { reason: 'cross-tenant audit', adminOnly: true, targetScope: 'all' },\n access: { roles: ['ADMIN'] },\n execute: async ({ unsafeDb, ctx }) => { /* cross-org query */ },\n});\n```\n\n`firewall: { exception: true }` is the declarative twin of `unsafe: true` — they're conceptually distinct: `firewall.exception` opts out of the gate-emission pillars; `unsafe` signals audit/cross-tenant intent (and still applies for logging). Most cross-tenant actions set both.\n\n### Recommended pattern: gate at the firewall layer\n\nMost of the time, relationship-based row visibility is what you want, and putting it at the **firewall** layer is the cleanest expression. The firewall is row-filter; the access layer is route/role-filter; let each do its job:\n\n```typescript\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' }, // ← row visibility\n],\nread: {\n access: { roles: ['admin', 'member'] }, // ← who can hit the route\n views: {\n cms: { access: { roles: ['admin', 'member'] }, fields: [...] },\n guest: { access: { roles: ['member', 'admin'] }, fields: [...] },\n },\n},\n```\n\nA guest who's in your org as `member` can hit the endpoint and the firewall filters them down to events they're guests of. Cross-tenant access is impossible because the org filter is the outermost AND.\n\n### Cross-tenant \"my events\" dashboards are NOT this\n\nA common adjacent pattern — \"logged-in user wants `GET /my-events` returning events they're a guest of *across all tenants*\" — is **not** solved by relationship-roles. The tenant firewall is enforced at the outermost AND, so a guest of an event in another tenant remains correctly blocked.\n\nFor cross-tenant aggregation, use one of:\n\n- **User-scoped firewall**: `firewall: { owner: { column: 'userId' } }` — a flat per-user table.\n- **A standalone action that walks the relationship table itself** — see worked example below.\n\nDon't reach for relationship-roles first and then get confused when the tenant firewall blocks. The two patterns serve different problems.\n\n#### Worked example: `GET /my-events` standalone action\n\nThe cleanest expression of the cross-tenant attendee dashboard is a standalone action with a custom path that does its own join against the relationship table. The action is gated by `roles: ['AUTHENTICATED']` (any signed-in user can hit it; per-row scoping is the query itself), and the SQL filters by `ctx.userId` so each caller sees exactly the events they're a guest of:\n\n```ts\n// features/dashboard/actions/myEvents.ts\n\nexport default defineAction({\n description: \"List events the caller is a confirmed guest of, across all tenants.\",\n path: '/my-events',\n method: 'GET',\n input: z.object({}),\n // Any signed-in user. Row visibility comes from the query, not the role.\n access: { roles: ['AUTHENTICATED'] },\n async execute({ db, ctx }) {\n // 1. Find every event the caller has a confirmed guest row for.\n const guestRows = await db\n .select({ eventId: guests.eventId })\n .from(guests)\n .where(\n and(\n eq(guests.userId, ctx.userId!),\n eq(guests.status, 'confirmed'),\n // guests.organizationId is NOT filtered here — that's the whole\n // point of the cross-tenant lane. The relationship row's org is\n // ambient information that this action explicitly traverses.\n )\n );\n\n if (guestRows.length === 0) return { events: [] };\n\n // 2. Pull the matching events. NOTE: this query also bypasses\n // `events.organizationId` scope — by design — so explicitly filter\n // out soft-deleted rows yourself if your `events` table uses them.\n const eventIds = guestRows.map((r) => r.eventId);\n const rows = await db\n .select()\n .from(events)\n .where(inArray(events.id, eventIds));\n\n return { events: rows };\n },\n});\n```\n\nWhy this is a standalone action and not a CRUD route:\n\n- **Tenant firewall would block it.** The default `firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }]` on `events` is correct for every other read — only the cross-tenant dashboard wants to step outside it, and that's a deliberate, explicit step taken in handler code.\n- **The join is the access control.** A relationship-role at the firewall layer can't express \"filter by this user's relationships, ignoring the org context.\" The handler does that join directly.\n- **Audit-logged automatically.** Standalone actions are mandatorily audit-logged in the runtime — the cross-tenant traversal is recorded with `ctx.userId`, IP, and timing.\n\nTwo important guardrails when you write one of these:\n\n1. **Always filter by `ctx.userId` in the relationship lookup.** If you accept a `userId` from the request body and trust it, you've built an IDOR. The example above uses `ctx.userId!` directly so the only events returned are the caller's.\n2. **You take responsibility for soft-delete and other invariants the firewall would otherwise apply.** Add the `deletedAt` filter, status checks, and any other row-level predicates by hand. The action is OUTSIDE the firewall pipeline by design — the cost is that you can't lean on the auto-applied predicates.\n\nIf you find yourself writing more than one of these per project, that's usually a signal to revisit the schema (could a user-owned `userEvents` materialized view replace the join?) rather than a sign Quickback should ship a higher-level abstraction. Cross-tenant lanes are intentionally explicit.\n\n### Compile-time refusals (consolidated)\n\nThe validator and resolver reject:\n\n- Unknown key in `authz` block (typo guard — `realtionships` would otherwise silently produce a permanently-denied role).\n- Reserved role-name (auth-provider-derived). Names like `guest`, `speaker`, `attendee` are free; `admin`/`owner`/`member` are reserved when the BA org plugin is on.\n- Cycle in role composition (`a → b → a`).\n- Relationship `from` references unknown table.\n- Relationship-role used on a resource missing the `resource.column`.\n- Relationship table with `firewall: { exception: true }` (would let cross-tenant grants slip through).\n- `lowering: 'session'` (reserved for v2 — staleness/invalidation ergonomics not yet shipped).\n- `+` hierarchy suffix on a relationship-role name (terminal, like pseudo-roles).\n- Relationship-roles in `masking.show` / `actions.access` (deferred surfaces — see the table above).\n\n## Namespace mounts (hoisted relationship middleware)\n\nWhen several standalone actions share a path prefix and the same relationship gate — `/event/:eventId/announce`, `/event/:eventId/cancel`, `/event/:eventId/respond` — declaring the gate per-action means writing the same `roles: ['attendee']` over and over AND paying the relationship-resolver cost N times per request (one subquery + one row-load, multiplied by the number of actions).\n\nNamespace mounts hoist the resolver into one Hono middleware that runs once per request. Every action under the prefix skips the inline gate; `ctx.<exposeAs>` is hydrated by the middleware before the action's `execute()` runs. With the per-namespace helper (v0.27+, [below](#narrow-ctxexposeas-typing-v027)), that field is also statically typed as the loaded row.\n\n### When to use roles vs. relationships\n\nA user is authorized for a row when **any** of the following is true:\n\n- they have a **per-row relationship** to it (e.g. an attendee row, a named organizer row), or\n- they have a **role on the row's tenant** (org admin/owner of the row's `organizationId`), or\n- they have **team membership** matching the row's `teamId`.\n\nUse **relationships** when membership is specific to *this row* — external collaborators who aren't in your org, attendees, anyone connected to the resource by virtue of data rather than payroll. Use **roles / team** when staff at your org/team should see everything in their scope by default.\n\nThe two compose at the action level (`access.or` accepts both relationship-roles and tenant roles) and — as of v0.25 — at the namespace level too: `namespace.via` accepts an array of lanes, first match wins.\n\n> **Rule of thumb.** If the answer is *\"yes if you work here,\"* reach for org/team roles. If the answer is *\"yes if you have something to do with **this** row,\"* reach for a per-row relationship. Reach for both together — at the namespace or via `access.or` — when an action should let either side in.\n\nTwo declaration sites depending on whether the participating actions live in one feature or many:\n\n### Single feature: `defineTable({ namespace })` (v0.23+)\n\nUse when every action under the prefix lives in the same feature directory. The namespace travels with the table that owns it — no addition to `quickback.config.ts` needed.\n\n```typescript\n// features/events/events.ts\nexport default defineTable(events, {\n firewall: [...],\n crud: { ... },\n namespace: {\n prefix: '/event/:eventId', // absolute URL path\n via: 'attendeeOf', // relationship gate (must exist in authz.relationships)\n },\n});\n\n// features/events/actions/post-announcement.ts\nexport default defineAction({\n path: '/event/:eventId/announcements',\n method: 'POST',\n // No gate boilerplate. ctx.event is typed inside execute().\n});\n```\n\nThe compiler emits one `app.use(...)` on the events feature's Hono app. Every standalone action in `features/events/actions/` whose path starts with `/event/:eventId/` joins the namespace automatically.\n\nMulti-lane via (v0.25+) and bulk-grant lanes (v0.26+) work identically on the table-level declaration — `via:` accepts the same shapes documented below for the project-level form.\n\n### Cross-feature: `authz.namespaces` (v0.24+)\n\nUse when the namespace spans multiple features. The declaration sits next to your other authz config in `quickback.config.ts`.\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n namespaces: {\n eventScope: { prefix: '/event/:eventId', via: 'attendeeOf' },\n },\n}\n```\n\nWith the namespace declared, any standalone action whose `path:` matches the prefix joins the gate — regardless of which feature owns it:\n\n```typescript\n// features/feeds/actions/feed-moments.ts (in one feature)\nexport default defineAction({\n path: '/event/:eventId/feed-moments',\n method: 'POST',\n});\n\n// features/rsvp/actions/respond.ts (in a different feature)\nexport default defineAction({\n path: '/event/:eventId/respond',\n method: 'POST',\n});\n```\n\nThe compiler emits one synthetic `src/routes/__namespace-event-scope.routes.ts` that imports each contributing feature's `actions` map under a distinct alias, mounts the resolver middleware once, and dispatches to the matching action. Worker-root mount order ensures the middleware fires before any per-feature route handler under the prefix.\n\n### Multi-lane via (v0.25+) — first match wins\n\nWhen more than one relationship can authorize a caller for the namespaced resource, pass `via:` as an array. The middleware tries each lane in declaration order and stops at the first match — `ctx.<exposeAs>` is hydrated from whichever lane fired.\n\n```typescript\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'linkedUserId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events',\n exposeAs: 'event',\n },\n // Named per-event organizers (potentially EXTERNAL — these users may\n // not be a member of the event's org. That's the point: lets you grant\n // event-level access to freelancers / partner staff without adding\n // them to the org's member list.)\n organizerOf: {\n from: 'eventOrganizers',\n subject: { column: 'linkedUserId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n namespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: ['attendeeOf', 'organizerOf'],\n },\n },\n}\n```\n\nAll relationship lanes in a namespace **must agree on `loads:` + `exposeAs:`** — that's what guarantees `ctx.event` has the same shape regardless of which lane matched. The compiler rejects heterogeneous lanes at parse time.\n\n### Bulk-grant lanes (v0.26+)\n\nRelationship lanes cover \"specifically connected to this row.\" Bulk-grant lanes cover \"anyone with this role / team membership in the row's tenant\" — the case where an org admin or a team member should see every event in their scope without writing per-event relationship rows.\n\n```typescript\nnamespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: [\n 'attendeeOf',\n 'organizerOf',\n { roles: ['admin', 'owner'] }, // org-role bulk grant\n { team: true }, // active-team-membership bulk grant\n ],\n },\n}\n```\n\nEach bulk-grant lane:\n\n- **`{ roles: [...] }`** — passes when the caller's BA org-role for the loaded resource's tenant includes any listed role. Short-circuits the relationship loop entirely; the role check is in-memory and cheap. Use for the \"company admin sees everything\" case.\n- **`{ team: true }`** — passes when `ctx.activeTeamId` is set. The loads-table firewall does the actual `events.teamId === ctx.activeTeamId` check during hydration. Use when the resource is team-scoped and you want active-team membership to grant access.\n\nBoth bulk-grant lanes piggyback on the namespace's relationship lane(s) for hydration — they don't fetch a separate per-row subject; they just gate access and let the loads-table firewall handle the tenant scoping. **At least one relationship lane is required** alongside bulk-grant lanes in v0.26 (to anchor `loads:` + `exposeAs:`).\n\nWhen a request misses every lane, the 403 deny payload lists every authorization path the caller could have taken — relationship names, role names, and `\"team-membership\"` for `{ team: true }` lanes — so a developer debugging an unexpected 403 sees the full surface they need to satisfy.\n\n### Discovery is path-prefix-only\n\nActions opt in by matching `path:` against a declared namespace prefix. There's no `namespace: 'foo'` field on `defineAction` — the path string is the discoverable surface, consistent with how `path:` already determines an action's URL.\n\n### Requirements (enforced at compile time)\n\nBoth forms share the same shape checks:\n\n- **`via:` accepts one of three shapes.** A single relationship name (v0.23+), an array of relationship names (v0.25+, first match wins), or — as of v0.26 — an array mixing relationship names with bulk-grant guards (`{ roles: [...] }`, `{ team: true }`).\n- **Every relationship lane must declare `loads + exposeAs`.** Without `loads` there's nothing for the middleware to hydrate; the namespace gate would be indistinguishable from a per-action access rule.\n- **All relationship lanes in one namespace must agree on `loads:` + `exposeAs:`.** Otherwise `ctx.<exposeAs>` would change shape depending on which lane matched.\n- **Bulk-grant lanes inherit `loads:` + `exposeAs:` from sibling relationship lanes.** Pure bulk-grant namespaces (no relationship lane at all) are also accepted — set `loads:` + `exposeAs:` directly on the namespace declaration so hydration has somewhere to anchor.\n- **`prefix:` must contain at least one `:param` segment** (e.g. `/event/:eventId`). The middleware reads the relationship key from `c.req.param()` because no request body has been parsed at middleware time.\n- **One declaration per namespace name.** The same name in both `defineTable({ namespace })` and `authz.namespaces` is rejected. The project-level form is canonical for cross-feature; the table-level form is the single-feature shorthand.\n\nProject-level only:\n\n- **Ambiguous prefixes** like `/a/:x` and `/a/:y` (same shape, different `:param` names) are rejected. Strict super/sub-set relationships (`/event/:e` vs `/event/:e/admin`) are fine — the harvester routes each action to the longest matching prefix.\n- **Unused namespace** emits a `[quickback:authz]` warning when no action's path matches the declared prefix. Not a hard error — the namespace may be staged ahead of the actions.\n\n### What namespace actions get for free\n\nInside a namespace action's `execute()`:\n\n- `ctx.<exposeAs>` is populated by the middleware with the loaded resource row. Statically `any` by default — narrowed to `typeof <loadsTable>.$inferSelect` when the action's import points at the per-namespace helper (see [below](#narrow-ctxexposeas-typing-v027)).\n- Tenant context (`ctx.activeOrgId` / `ctx.activeTeamId`) is stamped from the matched relationship row when its `from` table carries those columns. Downstream scoped queries work without further setup.\n- The action's own `access:` block (additional roles, userRole, record predicates, OTHER relationship arms) still runs after the namespace gate — namespace handles entry, per-action gates further.\n\n### Narrow `ctx.<exposeAs>` typing (v0.27+)\n\nThe namespace middleware hydrates `ctx.<exposeAs>` at runtime — that's been true since v0.23. The static type of that field, though, is `any` via the `AppContext` index signature: useful for not blocking access, but a missed opportunity for autocomplete and typo-catching.\n\nv0.27 emits one **per-namespace `defineAction` helper** alongside the standard `<feature>/.quickback/define-action.ts`. Importing from the narrowed helper retypes `ctx.<exposeAs>` inside `execute({ ctx })` to the loaded row's `$inferSelect` shape. Nothing else changes — runtime behavior, action discovery, and the `path:` namespace match are identical.\n\n```ts title=\"features/feeds/actions/feed-moments.ts\"\n// One-line flip per namespace-scoped action:\n\n// └──────┬──────┘\n// kebab(namespaceName)\n\nexport default defineAction({\n path: '/event/:eventId/feed-moments',\n method: 'POST',\n input: z.object({ body: z.string() }),\n access: { roles: ['attendee'] },\n async execute({ ctx, input }) {\n ctx.event.id // ✓ string\n ctx.event.startsAt // ✓ Date — autocomplete works\n ctx.event.organizerId // ✓ narrows on the field's declared type\n\n ctx.event.idd // ✗ TS2339 — typo caught at compile time\n },\n});\n```\n\nThe compiler emits one helper per `(feature, namespace)` pair where the feature owns at least one action whose `path:` falls under the namespace prefix. Filename is `define-action.<kebab(namespaceName)>.ts` — `eventScope` becomes `define-action.event-scope.ts`. Helpers live next to the standard `define-action.ts` in `<feature>/.quickback/`, so the relative import is the same shape as every other action file in your project.\n\n#### Opt-in, not breaking\n\nActions that keep their existing `import { defineAction } from '../.quickback/define-action'` continue to compile unchanged — `ctx.<exposeAs>` is `any` via the `AppContext` index signature, which is exactly the v0.23–v0.26 behavior. You flip imports per action at your own pace.\n\n#### Compile-time advisory\n\nWhen `quickback compile` sees a namespace-scoped action still importing the generic helper, it emits a one-line advisory pointing at the narrowed path:\n\n```text\n[quickback:typing] action \"feedMoments\" in feature \"feeds\" lives under\n namespace \"eventScope\" — switch its import to\n `../.quickback/define-action.event-scope` for narrow ctx.<exposeAs> typing.\n (Runtime behavior is unchanged; the narrowed helper only refines TS types.)\n```\n\nNon-blocking — same `[quickback:typing]` family as `[quickback:authz]`. The advisory only mentions actions the compiler can be confident about (namespace-claimed actions whose source still imports the generic helper).\n\n#### Multi-namespace features\n\nA single feature can contribute actions to several namespaces — say, an `interviews` feature with actions under both `interviewScope` and `eventScope`. The compiler emits one narrowed helper per namespace the feature participates in, and each action picks the import that matches its path.\n\n```text\nsrc/features/interviews/.quickback/\n├── define-action.ts # generic — standard fallback\n├── define-action.interview-scope.ts # ctx.interview typed\n└── define-action.event-scope.ts # ctx.event typed\n```\n\n#### Why per-namespace and not per-action\n\nA `defineAction` helper that's narrow to *one* exposed key (the namespace's `exposeAs`) is enough — every action under a namespace sees the same hydrated key. The alternative (per-action emit) duplicates the same prelude N times for the same shape; per-namespace keeps emission proportional to the number of distinct hydration shapes in the project.\n\n## Read & Write Configuration\n\nReads (`GET /` and `GET /:id`) live under `read:`; mutations live under top-level `create:`, `update:`, `delete:`, and `upsert:`. See [Read](/compiler/definitions/read) for the full read pipeline reference.\n\n```typescript\nread: {\n // LIST + GET - GET /resource and GET /resource/:id\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n pageSize: 25, // Default page size\n maxPageSize: 100, // Client can't exceed this\n views: { // Per-view field projections\n summary: {\n fields: ['id', 'candidateId', 'jobId', 'stage'],\n access: { roles: [\"interviewer\"] },\n },\n },\n}\n\ncreate: {\n // CREATE - POST /resource\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] },\n defaults: { // Default values for new records\n stage: 'applied',\n },\n},\n\nupdate: {\n // UPDATE - PATCH /resource/:id\n access: {\n or: [\n { roles: [\"hiring-manager\", \"recruiter\"] },\n { roles: [\"interviewer\"], record: { stage: { equals: \"interview\" } } }\n ]\n },\n},\n\ndelete: {\n // DELETE - DELETE /resource/:id\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"soft\", // 'soft' (default) or 'hard'\n},\n\nupsert: {\n // PUT - PUT /resource/:id (only when generateId: false + guards: false)\n access: { roles: [\"hiring-manager\", \"sync-service\"] },\n}\n```\n\n## Evaluation Order\n\nGenerated `/:id` and batch handlers evaluate access in this fixed order:\n\n1. **Auth gate** — 401 if unauthenticated\n2. **Pre-record access** — role-only check (skips `access.record` predicates)\n3. **Firewall query** — `WHERE` clause filters by ownership\n4. **Post-record access** — full check including record-level predicates\n5. **Masking** — applied to the response\n\nStep 2 closes the 404-vs-403 ID-probe channel: an unauthorized caller without\na matching role gets 403 before the database is touched, so they can't tell\napart \"row exists out-of-scope\" from \"row doesn't exist.\" A caller with the\nright role but the wrong tenant gets 403 by default (firewall reveals via\nthe access layer); set\n[`firewallErrorMode: 'hide'`](/compiler/definitions/firewall) to return an\nopaque 404 instead.\n\nFunction-form access (`access: async (ctx, record) => ...`) is opaque to\nthe pre-record phase and always passes there; it's fully evaluated post-record.\n\n## List Filtering (Query Parameters)\n\nThe LIST endpoint automatically supports filtering via query params:\n\n```\nGET /jobs?status=open # Exact match\nGET /jobs?salaryMin.gt=50000 # Greater than\nGET /jobs?salaryMin.gte=50000 # Greater than or equal\nGET /jobs?salaryMax.lt=200000 # Less than\nGET /jobs?salaryMax.lte=200000 # Less than or equal\nGET /jobs?status.ne=closed # Not equal\nGET /jobs?title.like=Engineer # Pattern match (LIKE %value%)\nGET /jobs?status.in=open,draft # IN clause\n```\n\n| Operator | Query Param | SQL Equivalent |\n|----------|-------------|----------------|\n| Equals | `?field=value` | `WHERE field = value` |\n| Not equals | `?field.ne=value` | `WHERE field != value` |\n| Greater than | `?field.gt=value` | `WHERE field > value` |\n| Greater or equal | `?field.gte=value` | `WHERE field >= value` |\n| Less than | `?field.lt=value` | `WHERE field < value` |\n| Less or equal | `?field.lte=value` | `WHERE field <= value` |\n| Pattern match | `?field.like=value` | `WHERE field LIKE '%value%'` |\n| In list | `?field.in=a,b,c` | `WHERE field IN ('a','b','c')` |\n\n## Sorting & Pagination\n\n```\nGET /jobs?sort=createdAt&order=desc # Sort by field\nGET /jobs?limit=25&offset=50 # Pagination\n```\n\n- **Default limit**: 50\n- **Max limit**: 100 (or `maxPageSize` if configured)\n- **Default order**: `asc`\n\n## Delete Modes\n\n```typescript\ndelete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"soft\", // Sets deletedAt/deletedBy, record stays in DB\n}\n\ndelete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"hard\", // Permanent deletion from database\n}\n```\n\n## Context Variables\n\nUse `$ctx.` prefix to reference context values in conditions:\n\n```typescript\n// User can only view their own records\naccess: {\n record: { userId: { equals: \"$ctx.userId\" } }\n}\n\n// Nested path support for complex context objects\naccess: {\n record: { ownerId: { equals: \"$ctx.user.id\" } }\n}\n```\n\n### AppContext Reference\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `$ctx.userId` | `string` | Current authenticated user's ID |\n| `$ctx.activeOrgId` | `string` | User's active organization ID |\n| `$ctx.activeTeamId` | `string \\| null` | User's active team ID (if applicable) |\n| `$ctx.roles` | `string[]` | User's roles in current context |\n| `$ctx.isAnonymous` | `boolean` | Whether user is anonymous |\n| `$ctx.user` | `object` | Full user object from auth provider |\n| `$ctx.user.id` | `string` | User ID (nested path example) |\n| `$ctx.user.email` | `string` | User's email address |\n| `$ctx.{property}` | `any` | Any custom context property |\n\n## Function-Based Access\n\nFor complex access logic that can't be expressed declaratively, use a function:\n\n```typescript\nupdate: {\n access: async (ctx, record) => {\n // Custom logic - return true to allow, false to deny\n if (ctx.roles.includes('admin')) return true;\n if (record.ownerId === ctx.userId) return true;\n\n // Check custom business logic\n const membership = await checkTeamMembership(ctx.userId, record.teamId);\n return membership.canEdit;\n }\n}\n```\n\nFunction access receives:\n- `ctx`: The full AppContext object\n- `record`: The record being accessed (for get/update/delete operations)"
78
+ "content": "Define who can perform read and write operations and under what conditions.\n\n## Basic Usage\n\n```typescript\n// features/applications/applications.ts\n\nexport const applications = sqliteTable('applications', {\n id: text('id').primaryKey(),\n candidateId: text('candidate_id').notNull(),\n jobId: text('job_id').notNull(),\n stage: text('stage').notNull(),\n notes: text('notes'),\n organizationId: text('organization_id').notNull(),\n});\n\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: { createable: [\"candidateId\", \"jobId\", \"notes\"], updatable: [\"notes\"] },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n});\n```\n\n## Role Hierarchy\n\nIf your project uses a tiered role system (e.g., `member` < `admin` < `owner`), you can define a hierarchy in your config and use the `+` suffix to mean \"this role and above\":\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n name: \"my-app\",\n auth: {\n roleHierarchy: ['member', 'admin', 'owner'], // lowest → highest\n },\n // ...\n});\n```\n\nThen in your resource definitions:\n\n```typescript\nread: { access: { roles: [\"member+\"] } }, // member, admin, owner\ncreate: { access: { roles: [\"admin+\"] } }, // admin, owner\ndelete: { access: { roles: [\"owner\"] } }, // owner only (no +)\n```\n\nThe `+` suffix expands at compile time — `\"member+\"` becomes `[\"member\", \"admin\", \"owner\"]` in the generated code. You can mix hierarchical and exact roles: `roles: [\"member+\", \"finance\"]` expands to `[\"member\", \"admin\", \"owner\", \"finance\"]`.\n\n- Roles without `+` are exact matches (no expansion)\n- Pseudo-roles / reserved markers (`PUBLIC`, `AUTHENTICATED`, `USER`, `ADMIN`, `SYSADMIN`) cannot use the `+` suffix — they're terminal markers\n- Using `+` with a role not in the hierarchy throws a compile error\n- Using `+` without configuring `auth.roleHierarchy` throws a compile error\n\n## Configuration Options\n\n```typescript\ninterface Access {\n // Org-membership roles (OR logic — user needs at least one)\n // Matched against ctx.roles. Use \"role+\" suffix for hierarchy expansion.\n roles?: string[];\n\n // User-table role (OR logic). Matched against ctx.userRole from the\n // user.role column — independent of org membership. See userRole below.\n userRole?: string[];\n\n // Record-level conditions\n record?: {\n [field: string]: FieldCondition;\n };\n\n // Combinators\n or?: Access[];\n and?: Access[];\n}\n```\n\n## `userRole` vs `roles`\n\n`roles` and `userRole` check **two different fields** and are often confused — get this wrong and you'll grant access too broadly.\n\n| Primitive | Checks | Source | Example values |\n|-----------|--------|--------|----------------|\n| `roles` | `ctx.roles` | Org membership roles | `\"owner\"`, `\"admin\"`, `\"member\"` |\n| `userRole` | `ctx.userRole` | The `user.role` column (Better Auth / platform control-plane roles) | `\"user\"`, `\"appmanager\"`, `\"sysadmin\"` |\n\nIn multi-tenant mode, **`roles: [\"admin\"]` means \"org admin\" — not a platform-wide role.** An org-admin of Acme Corp has no elevated rights across other orgs. If you want platform control-plane operators through regardless of org membership (CMS, Better Auth admin surfaces, support tooling), use `userRole: [\"appmanager\"]`. If you need true cross-tenant data-plane access, use `roles: [\"SYSADMIN\"]` (with `cms: { sysadmin: true }`).\n\nPinned organization mode does not change this split. `roles` still come from organization membership in the pinned org, while `userRole` still comes from Better Auth's `user.role` column.\n\n### When to use `userRole`\n\n```typescript\n// Platform control-plane users can see SSNs on every customer record, regardless of org\nmasking: {\n ssn: { type: 'ssn', show: { userRole: ['appmanager'] } },\n}\n\n// Platform ops (user.role === 'appmanager') OR the org owner can refund\naccess: {\n or: [\n { userRole: ['appmanager'] },\n { roles: ['owner'] },\n ],\n}\n\n// CMS-internal resource: only platform control-plane users\nread: { access: { userRole: ['appmanager'] } },\ncreate: { access: { userRole: ['appmanager'] } },\nupdate: { access: { userRole: ['appmanager'] } },\ndelete: { access: { userRole: ['appmanager'] } },\n```\n\nWhen `roles` and `userRole` both appear in a single `Access` node, they're combined with AND — the user must satisfy both. Use `or:` to express \"one or the other\".\n\n`userRole` doesn't expand with the `+` hierarchy suffix — user-table roles are flat (typically just `\"user\"`, `\"appmanager\"`, and `\"sysadmin\"`). If you've added custom user-table roles via Better Auth, list them explicitly.\n\n### Pseudo-roles\n\nQuickback ships five reserved UPPERCASE markers. Four are real pseudo-roles handled directly by the compiler; `ADMIN` is retained only as a reserved legacy marker so the compiler can fail loudly with migration guidance. The casing carries the boundary: UPPERCASE = compiler-owned marker, lowercase = real role from a plugin's table (e.g. `members.role` from the org plugin).\n\n| Role | Auth gate | Compile-time requirement | Runtime check |\n|------|-----------|-------------------------|---------------|\n| `PUBLIC` | bypassed | none — explicit opt-in for unauthenticated access | always passes (auth skipped) |\n| `AUTHENTICATED` | required | none | `ctx.authenticated === true` |\n| `USER` | required | resource firewall **must** scope by `userId` | `ctx.authenticated` AND (`ctx.userRole` is unset OR `ctx.userRole === \"user\"`) |\n| `ADMIN` | required | reserved legacy marker — compiler rejects it | `false` |\n| `SYSADMIN` | required | `cms: { sysadmin: true }` **must** be set on the project | `ctx.authenticated && ctx.userRole === \"sysadmin\"` |\n\nYou can mix pseudo-roles with real roles in the same list — they're OR'd together.\n\n#### `PUBLIC` — unauthenticated access\n\nUse `roles: [\"PUBLIC\"]` for public-facing endpoints like contact forms, public listings, or webhooks. Skips both the auth gate and the role check.\n\n```typescript\naccess: { roles: [\"PUBLIC\"] }\n```\n\n**Important:**\n- `PUBLIC` skips authentication and role checks — anyone can call the endpoint\n- **`PUBLIC` is the explicit, uppercase opt-in for unauthenticated access.** It works on every access node — reads, top-level writes (`create`/`update`/`delete`/`upsert`), views, and actions. The compiler trusts the marker; row-level safety comes from the firewall, masking, and (for token-gated endpoints like RSVP confirm, magic-link redemption, List-Unsubscribe-Post, webhook ingest) your handler's own validation. Anonymous write endpoints typically pair `roles: [\"PUBLIC\"]` with `firewall: { exception: true }` on the resource so the row predicate doesn't reject every unauthenticated caller.\n- **Firewall still applies** — data is scoped by the firewall (organization, owner, team)\n- Every `PUBLIC` action invocation is **mandatory audit logged** to the security audit table (IP address, input, result, timing)\n- The wildcard `\"*\"` is **not supported** — using it throws a compile-time error\n- Tables with no isolation columns and any `PUBLIC` route do not require `firewall: [{ exception: true }]`\n\nFor org-scoped tables, `PUBLIC` routes still filter by organization. Since the user isn't authenticated, the organization ID must be passed as a query parameter:\n\n```\nGET /api/v1/listings?organizationId=org_abc123\n```\n\nThe firewall WHERE clause is always enforced. If no `organizationId` is provided, the API returns a `400` with code `ORG_REQUIRED`.\n\n```typescript\n// Public listing page — anyone can browse, but scoped to an org\nexport default defineTable(listings, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: { access: { roles: [\"PUBLIC\"] } }, // Public browsing + detail\n create: { access: { roles: [\"admin\", \"member\"] } }, // Auth required to create\n});\n```\n\n#### `AUTHENTICATED` — any signed-in user\n\nUse `roles: [\"AUTHENTICATED\"]` for endpoints that any logged-in user can hit, regardless of role or org membership. No plugin context required.\n\n```typescript\n// Public events feed — any signed-in user can list/read; anonymous gets 401\nread: { access: { roles: [\"AUTHENTICATED\"] } }\n```\n\n#### `USER` — per-user records\n\nUse `roles: [\"USER\"]` for resources where each user only sees their own records. **Requires the firewall to scope by `userId`** — the role marker is the access half of the pair, the firewall is the row-filter half.\n\n```typescript\n// \"My todos\" — each caller sees only their own rows\nexport default defineTable(todos, {\n firewall: [{ field: 'userId', equals: 'ctx.userId' }],\n read: { access: { roles: [\"USER\"] } },\n create: { access: { roles: [\"USER\"] } },\n update: { access: { roles: [\"USER\"] } },\n delete: { access: { roles: [\"USER\"] } },\n});\n```\n\nIf you forget the `userId` firewall predicate, the compiler throws:\n\n> `roles: [\"USER\"]` requires the resource to be scoped per-user. Add a `userId` column (auto-scoped) or an explicit owner predicate. If you want any signed-in user to read all records, use `roles: [\"AUTHENTICATED\"]` instead.\n\nWhen the Better Auth admin plugin is enabled, `USER` matches `user.role === \"user\"` specifically — appmanagers and sysadmins are excluded. If the same route should serve both, express it explicitly with `or: [{ roles: [\"USER\"] }, { userRole: [\"appmanager\"] }]`.\n\n#### `ADMIN` — legacy reserved marker (compile-time error)\n\n`roles: [\"ADMIN\"]` is no longer supported. The compiler fails hard on any use of `ADMIN` so platform and tenant roles can't be confused.\n\n```typescript\n// Platform control-plane audit log\nread: { access: { userRole: [\"appmanager\"] } }\n```\n\nUse one of these instead:\n\n- `userRole: [\"appmanager\"]` for platform control-plane access\n- `roles: [\"admin\"]` for org-membership admin access\n- `roles: [\"SYSADMIN\"]` for true cross-tenant access\n\n#### `SYSADMIN` — cross-tenant DB-admin tier\n\nUse `roles: [\"SYSADMIN\"]` for endpoints that should only be reachable by platform sysadmins — the cross-tenant DB-admin tier introduced in v0.15.0. Compiles to `ctx.userRole === \"sysadmin\"`. **Requires `cms: { sysadmin: true }` on the project config**; without that flag, using `SYSADMIN` fails the compile so the role can't sit as dead code.\n\n```typescript\n// Cross-tenant audit dashboard, sysadmin-only\nread: { access: { roles: [\"SYSADMIN\"] } }\n```\n\n`SYSADMIN` is distinct from `userRole: [\"appmanager\"]`. Appmanager is the platform control-plane tier (CMS shell, Better Auth admin surfaces, support tooling); sysadmin is the cross-tenant data-plane tier. The one place sysadmin gets implicit extra powers is **the firewall escape hatch**: when `cms.sysadmin: true`, every `buildFirewallConditions` emits an `if (ctx.userRole === 'sysadmin') return undefined;` (or just the soft-delete predicate when present) at the top — so sysadmins see every tenant's rows, not just their own org's. That escape hatch does NOT fire for `userRole === 'appmanager'`; appmanagers still go through the firewall like everyone else.\n\nThis separation exists so Better Auth admin-plugin powers (user management, impersonation, org creation) and DB-admin powers (cross-tenant data inspection) stay decoupled. A user can have `user.role === 'appmanager'` without DB-level cross-tenant access; a user can have `user.role === 'sysadmin'` without org-membership context. See [CMS Configuration](/compiler/config#cms-configuration) for the `cms.sysadmin` flag, the cross-tenant `/auth/v1/admin/list-organizations` endpoint, and the SPA's \"All organizations\" sentinel.\n\n#### Mixing pseudo-roles with real roles\n\nPseudo-roles and lowercase real roles compose with OR:\n\n```typescript\n// Record owner OR a platform control-plane user can read\nread: { access: { or: [{ roles: [\"USER\"] }, { userRole: [\"appmanager\"] }] } }\n\n// Org owner OR sysadmin\ndelete: { access: { or: [{ roles: [\"owner\"] }, { roles: [\"SYSADMIN\"] }] } }\n```\n\n> Note: `userRole: [\"appmanager\"]` never bypasses a `userId` firewall scope. If you need cross-user visibility, expose a separate route with `firewall: { exception: true }` or a `SYSADMIN`-gated cross-tenant surface.\n\n#### Quick reference\n\n```typescript\n// Unauthenticated public\naccess: { roles: [\"PUBLIC\"] }\n\n// Any signed-in user, no scoping\naccess: { roles: [\"AUTHENTICATED\"] }\n\n// Per-user records (requires userId firewall scope)\naccess: { roles: [\"USER\"] }\n\n// Platform control-plane\naccess: { userRole: [\"appmanager\"] }\n\n// Cross-tenant DB-admin tier\naccess: { roles: [\"SYSADMIN\"] }\n\n// Org-membership roles with hierarchy expansion\naccess: { roles: [\"member+\"] } // expands to [\"member\", \"admin\", \"owner\"]\naccess: { roles: [\"admin+\"] } // expands to [\"admin\", \"owner\"]\naccess: { roles: [\"admin\"] } // exact match (no expansion)\n```\n\n```typescript\n// Field conditions - value can be string | number | boolean\ntype FieldCondition =\n | { equals: value | '$ctx.userId' | '$ctx.activeOrgId' }\n | { notEquals: value }\n | { in: value[] }\n | { notIn: value[] }\n | { lessThan: number }\n | { greaterThan: number }\n | { lessThanOrEqual: number }\n | { greaterThanOrEqual: number };\n```\n\n## Relationship-based authorization\n\nBeyond Better Auth roles (org membership, user-table role) and pseudo-roles, Quickback supports **relationship-based authorization roles** — names that bind to a declared relationship between the caller and a resource. Use these when access should follow a domain-table membership (\"user is a confirmed guest of this event\") rather than an org/admin gate.\n\n### `authz.relationships`\n\nDeclare relationships once in `quickback.config.ts`:\n\n```typescript\n// quickback.config.ts\n\nexport default defineConfig({\n // ...providers...\n authz: {\n relationships: {\n guestOf: {\n from: 'event_guests', // table name string\n subject: { column: 'userId', equals: 'ctx.userId' }, // caller side\n resource: { column: 'eventId' }, // resource side\n where: { status: 'confirmed' }, // optional filter\n },\n },\n roles: {\n guest: { via: 'guestOf' },\n // Composite: any guest OR an org owner/admin\n eventStaff: {\n or: [\n { via: 'guestOf' },\n { roles: ['admin', 'owner'] },\n ],\n },\n },\n },\n});\n```\n\n### Using relationship-roles in resources\n\nResource definitions reference declared roles by name in `roles: [...]` arrays exactly like BA roles or pseudo-roles. The compiler rewrites the access tree at build time so the runtime route does an inline relationship lookup against the declared table.\n\n**Today (v1) this works on:**\n\n| Surface | Status | Notes |\n|---|---|---|\n| `firewall:` `via:` predicate | ✓ Supported | Subquery composes as outermost AND |\n| `crud.*.access` `roles: ['guest']` | ✓ Supported | Inline async lookup per request |\n| `read.access` / `read.views.*.access` `roles: ['guest']` | ✓ Supported | Same inline path |\n| `masking.<field>.show` `roles: ['guest']` | ⚠ Refused at compile | v1 limitation — async/batched mask functions deferred |\n| **Standalone** `actions.<name>.access` `roles: ['guest']` | ✓ Supported (v0.19+) | Inline gate; surface must expose `resource.column` as path param or input field |\n| **Record-based** `actions.<name>.access` `roles: ['guest']` | ⚠ Fail-closed at runtime | Runtime helper denies; inline emission is a planned follow-up. Use `firewall: { exception: true }` or move the check into `execute()` until then |\n\nFor the surfaces that are not yet supported, the compiler refuses at build time with a clear error pointing to a workaround. The runtime evaluator fails closed on relationship arms regardless, so silent grants are impossible.\n\n### Standalone actions: surface keys and `loads` / `exposeAs` (v0.19+)\n\nWhen a standalone action's `access.roles` references a relationship-role, the compiler emits a runtime gate between input validation and `execute()`. The gate reads the relationship's `resource.column` value from the action surface — either a path parameter (`:eventId`) or an input field (`input.eventId`). If neither is present, the compiler:\n\n- **v0.19** — emits a `[quickback:authz]` warning and skips resolver emission. The action's own hand-rolled gate (if any) keeps the route working at runtime.\n- **v0.20** — hard compile error. Set `firewall: { exception: true }` to opt out (cross-tenant/admin routes only).\n\nPair the relationship with `loads` + `exposeAs` to hydrate the loaded resource onto `ctx`:\n\n```typescript\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events', // ← v0.19+: load matching event row\n exposeAs: 'event', // ← onto ctx.event for the action body\n },\n },\n roles: {\n attendee: { via: 'attendeeOf' },\n },\n}\n```\n\nThe resolver (v0.20):\n\n1. **Cheap in-memory role check** first — `ctx.roles?.includes('admin')` and friends. If the caller has a qualifying role, this short-circuits and no DB queries fire for the access gate.\n2. **Firewall-gated relationship match** if the role check failed — `SELECT { organizationId, teamId } FROM guests WHERE userId=ctx.userId AND eventId=input.eventId AND status='confirmed'` with the `guests` table's full firewall AND-applied. If neither role nor relationship qualifies → 403.\n3. **Tenant stamping from the matched row** — for any tenant column the `from` table carries (`organizationId`, `teamId`), the resolver stamps `ctx.activeOrgId ??= matchedRow.organizationId` (and similar for team). This is **in-memory mutation of the request-scoped ctx only** — no JWT remint, no session-record write, no persistent grant.\n4. **Firewall-gated load of the loaded resource** — `SELECT * FROM events WHERE id = :eventId AND buildEventsFirewallConditions(ctx, db)`. The events firewall is applied as normal; it succeeds for attendees because tenant was just stamped from the relationship row.\n5. Assigns the loaded row to `ctx.event` for the action body.\n\n**No firewall bypass anywhere.** Both queries run with their respective tables' full firewalls. The relationship row's existence is the proof that the caller is authorized; its tenant columns are the source of the stamped claim.\n\n### Conditional tenant preconditions (v0.20+)\n\nStandalone actions in features with org/team-scoped tables previously emitted unconditional preconditions:\n\n```ts\nif (!ctx.activeOrgId) return c.json(AccessErrors.noOrg(), 403);\nif (!ctx.activeTeamId) return c.json(AccessErrors.noTeam(), 403);\n```\n\nThese ran **before** the relationship resolver, which 403'd attendees whose sessions don't carry an active tenant claim (the canonical event-attendee shape).\n\nv0.20 makes these preconditions **conditional on relationship supply**. If the access tree contains a relationship arm whose `from` table carries the matching tenant column, the precondition is skipped — the resolver runs first and stamps the value. Pseudo-role short-circuits (PUBLIC / AUTHENTICATED / USER / SYSADMIN) and `firewall: { exception: true }` still bypass the preconditions as before. `ADMIN` is now rejected at compile time.\n\nTypical event-attendee setup (`guests` table carries `organizationId`): the org precondition is dropped on every action whose access references `attendee` or `eventStaff`. Org admins still get `ctx.activeOrgId` from their session as today; attendees get it from the relationship row, mid-request. Both paths converge on a valid tenant claim before `execute()` runs.\n\n### Requirement on the relationship's `from` table\n\nFor the v0.20 tenant-stamping to work, the relationship's `from` table must carry tenant columns:\n\n- For org stamping: an `organizationId` column (or whatever spelling the project's auth-provider defaults pick).\n- For team stamping: a `teamId` column.\n\nWhen the `from` table has **neither**, the compiler emits a `[quickback:authz]` warning at compile time:\n\n```\nRelationship \"X\" at authz.relationships.X has no organization or team columns\non its `from` table (\"guests\"). Action \"Y\" will compile, but downstream\nscoped-db queries inside execute() may 403 because ctx.activeOrgId /\nactiveTeamId cannot be stamped from the match row. Either add the tenant\ncolumn to \"guests\", or set firewall: { exception: true } on the action.\n```\n\nThe relationship match still works (existence check), but no tenant gets stamped — so the conventional precondition still fires and the action still 403s for callers without a session-resident tenant claim. Add the tenant column (or denormalize it onto the relationship table during writes) to enable the stamping path.\n\nThe body can then trust `ctx.event` and drop the hand-rolled `SELECT … FROM guests WHERE …` boilerplate:\n\n```ts\n// features/chat/actions/getInbox.ts\nexport default defineAction({\n path: '/chat/get-inbox',\n input: z.object({ eventId: z.number().int().positive() }),\n access: { roles: ['admin', 'member', 'attendee'] }, // attendee is a relationship-role\n execute: async ({ db, ctx, input }) => {\n // No hand-rolled attendance check needed — the resolver already ran.\n // ctx.event is the loaded events row. Typed as `any` here because the\n // hand-rolled `roles: ['attendee']` action gates per-action, not per-\n // namespace — see \"Narrow ctx.<exposeAs> typing\" below for the typed\n // import flip available when the same hydration runs through a\n // namespace mount.\n const event = ctx.event as typeof events.$inferSelect;\n // … domain logic only.\n },\n});\n```\n\n`loads` and `exposeAs` are co-required (set both or neither). `exposeAs` must be a valid JS identifier and must not collide with built-in `ctx` fields (`userId`, `activeOrgId`, `activeTeamId`, `db`, etc.).\n\n### Action firewall escape hatch (v0.19+)\n\n`defineAction({ firewall: { exception: true } })` opts the action out of the inherited session-key preconditions (`ctx.activeOrgId` / `ctx.activeTeamId` requirements) AND the relationship resolver. The handler receives `unsafeDb` for raw Drizzle access. Use for cross-tenant or admin routes whose surface intentionally doesn't name a session/relationship key:\n\n```ts\ndefineAction({\n path: '/admin/cross-tenant-report',\n firewall: { exception: true },\n unsafe: { reason: 'cross-tenant audit', adminOnly: true, targetScope: 'all' },\n access: { roles: ['ADMIN'] },\n execute: async ({ unsafeDb, ctx }) => { /* cross-org query */ },\n});\n```\n\n`firewall: { exception: true }` is the declarative twin of `unsafe: true` — they're conceptually distinct: `firewall.exception` opts out of the gate-emission pillars; `unsafe` signals audit/cross-tenant intent (and still applies for logging). Most cross-tenant actions set both.\n\n### Recommended pattern: gate at the firewall layer\n\nMost of the time, relationship-based row visibility is what you want, and putting it at the **firewall** layer is the cleanest expression. The firewall is row-filter; the access layer is route/role-filter; let each do its job:\n\n```typescript\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' }, // ← row visibility\n],\nread: {\n access: { roles: ['admin', 'member'] }, // ← who can hit the route\n views: {\n cms: { access: { roles: ['admin', 'member'] }, fields: [...] },\n guest: { access: { roles: ['member', 'admin'] }, fields: [...] },\n },\n},\n```\n\nA guest who's in your org as `member` can hit the endpoint and the firewall filters them down to events they're guests of. Cross-tenant access is impossible because the org filter is the outermost AND.\n\n### Cross-tenant \"my events\" dashboards are NOT this\n\nA common adjacent pattern — \"logged-in user wants `GET /my-events` returning events they're a guest of *across all tenants*\" — is **not** solved by relationship-roles. The tenant firewall is enforced at the outermost AND, so a guest of an event in another tenant remains correctly blocked.\n\nFor cross-tenant aggregation, use one of:\n\n- **User-scoped firewall**: `firewall: { owner: { column: 'userId' } }` — a flat per-user table.\n- **A standalone action that walks the relationship table itself** — see worked example below.\n\nDon't reach for relationship-roles first and then get confused when the tenant firewall blocks. The two patterns serve different problems.\n\n#### Worked example: `GET /my-events` standalone action\n\nThe cleanest expression of the cross-tenant attendee dashboard is a standalone action with a custom path that does its own join against the relationship table. The action is gated by `roles: ['AUTHENTICATED']` (any signed-in user can hit it; per-row scoping is the query itself), and the SQL filters by `ctx.userId` so each caller sees exactly the events they're a guest of:\n\n```ts\n// features/dashboard/actions/myEvents.ts\n\nexport default defineAction({\n description: \"List events the caller is a confirmed guest of, across all tenants.\",\n path: '/my-events',\n method: 'GET',\n input: z.object({}),\n // Any signed-in user. Row visibility comes from the query, not the role.\n access: { roles: ['AUTHENTICATED'] },\n async execute({ db, ctx }) {\n // 1. Find every event the caller has a confirmed guest row for.\n const guestRows = await db\n .select({ eventId: guests.eventId })\n .from(guests)\n .where(\n and(\n eq(guests.userId, ctx.userId!),\n eq(guests.status, 'confirmed'),\n // guests.organizationId is NOT filtered here — that's the whole\n // point of the cross-tenant lane. The relationship row's org is\n // ambient information that this action explicitly traverses.\n )\n );\n\n if (guestRows.length === 0) return { events: [] };\n\n // 2. Pull the matching events. NOTE: this query also bypasses\n // `events.organizationId` scope — by design — so explicitly filter\n // out soft-deleted rows yourself if your `events` table uses them.\n const eventIds = guestRows.map((r) => r.eventId);\n const rows = await db\n .select()\n .from(events)\n .where(inArray(events.id, eventIds));\n\n return { events: rows };\n },\n});\n```\n\nWhy this is a standalone action and not a CRUD route:\n\n- **Tenant firewall would block it.** The default `firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }]` on `events` is correct for every other read — only the cross-tenant dashboard wants to step outside it, and that's a deliberate, explicit step taken in handler code.\n- **The join is the access control.** A relationship-role at the firewall layer can't express \"filter by this user's relationships, ignoring the org context.\" The handler does that join directly.\n- **Audit-logged automatically.** Standalone actions are mandatorily audit-logged in the runtime — the cross-tenant traversal is recorded with `ctx.userId`, IP, and timing.\n\nTwo important guardrails when you write one of these:\n\n1. **Always filter by `ctx.userId` in the relationship lookup.** If you accept a `userId` from the request body and trust it, you've built an IDOR. The example above uses `ctx.userId!` directly so the only events returned are the caller's.\n2. **You take responsibility for soft-delete and other invariants the firewall would otherwise apply.** Add the `deletedAt` filter, status checks, and any other row-level predicates by hand. The action is OUTSIDE the firewall pipeline by design — the cost is that you can't lean on the auto-applied predicates.\n\nIf you find yourself writing more than one of these per project, that's usually a signal to revisit the schema (could a user-owned `userEvents` materialized view replace the join?) rather than a sign Quickback should ship a higher-level abstraction. Cross-tenant lanes are intentionally explicit.\n\n### Compile-time refusals (consolidated)\n\nThe validator and resolver reject:\n\n- Unknown key in `authz` block (typo guard — `realtionships` would otherwise silently produce a permanently-denied role).\n- Reserved role-name (auth-provider-derived). Names like `guest`, `speaker`, `attendee` are free; `admin`/`owner`/`member` are reserved when the BA org plugin is on.\n- Cycle in role composition (`a → b → a`).\n- Relationship `from` references unknown table.\n- Relationship-role used on a resource missing the `resource.column`.\n- Relationship table with `firewall: { exception: true }` (would let cross-tenant grants slip through).\n- `lowering: 'session'` (reserved for v2 — staleness/invalidation ergonomics not yet shipped).\n- `+` hierarchy suffix on a relationship-role name (terminal, like pseudo-roles).\n- Relationship-roles in `masking.show` / `actions.access` (deferred surfaces — see the table above).\n\n## Namespace mounts (hoisted relationship middleware)\n\nWhen several standalone actions share a path prefix and the same relationship gate — `/event/:eventId/announce`, `/event/:eventId/cancel`, `/event/:eventId/respond` — declaring the gate per-action means writing the same `roles: ['attendee']` over and over AND paying the relationship-resolver cost N times per request (one subquery + one row-load, multiplied by the number of actions).\n\nNamespace mounts hoist the resolver into one Hono middleware that runs once per request. Every action under the prefix skips the inline gate; `ctx.<exposeAs>` is hydrated by the middleware before the action's `execute()` runs. With the per-namespace helper (v0.27+, [below](#narrow-ctxexposeas-typing-v027)), that field is also statically typed as the loaded row.\n\n### When to use roles vs. relationships\n\nA user is authorized for a row when **any** of the following is true:\n\n- they have a **per-row relationship** to it (e.g. an attendee row, a named organizer row), or\n- they have a **role on the row's tenant** (org admin/owner of the row's `organizationId`), or\n- they have **team membership** matching the row's `teamId`.\n\nUse **relationships** when membership is specific to *this row* — external collaborators who aren't in your org, attendees, anyone connected to the resource by virtue of data rather than payroll. Use **roles / team** when staff at your org/team should see everything in their scope by default.\n\nThe two compose at the action level (`access.or` accepts both relationship-roles and tenant roles) and — as of v0.25 — at the namespace level too: `namespace.via` accepts an array of lanes, first match wins.\n\n> **Rule of thumb.** If the answer is *\"yes if you work here,\"* reach for org/team roles. If the answer is *\"yes if you have something to do with **this** row,\"* reach for a per-row relationship. Reach for both together — at the namespace or via `access.or` — when an action should let either side in.\n\nTwo declaration sites depending on whether the participating actions live in one feature or many:\n\n### Single feature: `defineTable({ namespace })` (v0.23+)\n\nUse when every action under the prefix lives in the same feature directory. The namespace travels with the table that owns it — no addition to `quickback.config.ts` needed.\n\n```typescript\n// features/events/events.ts\nexport default defineTable(events, {\n firewall: [...],\n crud: { ... },\n namespace: {\n prefix: '/event/:eventId', // absolute URL path\n via: 'attendeeOf', // relationship gate (must exist in authz.relationships)\n },\n});\n\n// features/events/actions/post-announcement.ts\nexport default defineAction({\n path: '/event/:eventId/announcements',\n method: 'POST',\n // No gate boilerplate. ctx.event is typed inside execute().\n});\n```\n\nThe compiler emits one `app.use(...)` on the events feature's Hono app. Every standalone action in `features/events/actions/` whose path starts with `/event/:eventId/` joins the namespace automatically.\n\nMulti-lane via (v0.25+) and bulk-grant lanes (v0.26+) work identically on the table-level declaration — `via:` accepts the same shapes documented below for the project-level form.\n\n### Cross-feature: `authz.namespaces` (v0.24+)\n\nUse when the namespace spans multiple features. The declaration sits next to your other authz config in `quickback.config.ts`.\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n namespaces: {\n eventScope: { prefix: '/event/:eventId', via: 'attendeeOf' },\n },\n}\n```\n\nWith the namespace declared, any standalone action whose `path:` matches the prefix joins the gate — regardless of which feature owns it:\n\n```typescript\n// features/feeds/actions/feed-moments.ts (in one feature)\nexport default defineAction({\n path: '/event/:eventId/feed-moments',\n method: 'POST',\n});\n\n// features/rsvp/actions/respond.ts (in a different feature)\nexport default defineAction({\n path: '/event/:eventId/respond',\n method: 'POST',\n});\n```\n\nThe compiler emits one synthetic `src/routes/__namespace-event-scope.routes.ts` that imports each contributing feature's `actions` map under a distinct alias, mounts the resolver middleware once, and dispatches to the matching action. Worker-root mount order ensures the middleware fires before any per-feature route handler under the prefix.\n\n### Multi-lane via (v0.25+) — first match wins\n\nWhen more than one relationship can authorize a caller for the namespaced resource, pass `via:` as an array. The middleware tries each lane in declaration order and stops at the first match — `ctx.<exposeAs>` is hydrated from whichever lane fired.\n\n```typescript\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'linkedUserId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events',\n exposeAs: 'event',\n },\n // Named per-event organizers (potentially EXTERNAL — these users may\n // not be a member of the event's org. That's the point: lets you grant\n // event-level access to freelancers / partner staff without adding\n // them to the org's member list.)\n organizerOf: {\n from: 'eventOrganizers',\n subject: { column: 'linkedUserId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n namespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: ['attendeeOf', 'organizerOf'],\n },\n },\n}\n```\n\nAll relationship lanes in a namespace **must agree on `loads:` + `exposeAs:`** — that's what guarantees `ctx.event` has the same shape regardless of which lane matched. The compiler rejects heterogeneous lanes at parse time.\n\n### Bulk-grant lanes (v0.26+)\n\nRelationship lanes cover \"specifically connected to this row.\" Bulk-grant lanes cover \"anyone with this role / team membership in the row's tenant\" — the case where an org admin or a team member should see every event in their scope without writing per-event relationship rows.\n\n```typescript\nnamespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: [\n 'attendeeOf',\n 'organizerOf',\n { roles: ['admin', 'owner'] }, // org-role bulk grant\n { team: true }, // active-team-membership bulk grant\n ],\n },\n}\n```\n\nEach bulk-grant lane:\n\n- **`{ roles: [...] }`** — passes when the caller's BA org-role for the loaded resource's tenant includes any listed role. Short-circuits the relationship loop entirely; the role check is in-memory and cheap. Use for the \"company admin sees everything\" case.\n- **`{ team: true }`** — passes when `ctx.activeTeamId` is set. The loads-table firewall does the actual `events.teamId === ctx.activeTeamId` check during hydration. Use when the resource is team-scoped and you want active-team membership to grant access.\n\nBoth bulk-grant lanes piggyback on the namespace's relationship lane(s) for hydration — they don't fetch a separate per-row subject; they just gate access and let the loads-table firewall handle the tenant scoping. **At least one relationship lane is required** alongside bulk-grant lanes in v0.26 (to anchor `loads:` + `exposeAs:`).\n\nWhen a request misses every lane, the 403 deny payload lists every authorization path the caller could have taken — relationship names, role names, and `\"team-membership\"` for `{ team: true }` lanes — so a developer debugging an unexpected 403 sees the full surface they need to satisfy.\n\n### Discovery is path-prefix-only\n\nActions opt in by matching `path:` against a declared namespace prefix. There's no `namespace: 'foo'` field on `defineAction` — the path string is the discoverable surface, consistent with how `path:` already determines an action's URL.\n\n### Requirements (enforced at compile time)\n\nBoth forms share the same shape checks:\n\n- **`via:` accepts one of three shapes.** A single relationship name (v0.23+), an array of relationship names (v0.25+, first match wins), or — as of v0.26 — an array mixing relationship names with bulk-grant guards (`{ roles: [...] }`, `{ team: true }`).\n- **Every relationship lane must declare `loads + exposeAs`.** Without `loads` there's nothing for the middleware to hydrate; the namespace gate would be indistinguishable from a per-action access rule.\n- **All relationship lanes in one namespace must agree on `loads:` + `exposeAs:`.** Otherwise `ctx.<exposeAs>` would change shape depending on which lane matched.\n- **Bulk-grant lanes inherit `loads:` + `exposeAs:` from sibling relationship lanes.** Pure bulk-grant namespaces (no relationship lane at all) are also accepted — set `loads:` + `exposeAs:` directly on the namespace declaration so hydration has somewhere to anchor.\n- **`prefix:` must contain at least one `:param` segment** (e.g. `/event/:eventId`). The middleware reads the relationship key from `c.req.param()` because no request body has been parsed at middleware time.\n- **One declaration per namespace name.** The same name in both `defineTable({ namespace })` and `authz.namespaces` is rejected. The project-level form is canonical for cross-feature; the table-level form is the single-feature shorthand.\n\nProject-level only:\n\n- **Ambiguous prefixes** like `/a/:x` and `/a/:y` (same shape, different `:param` names) are rejected. Strict super/sub-set relationships (`/event/:e` vs `/event/:e/admin`) are fine — the harvester routes each action to the longest matching prefix.\n- **Unused namespace** emits a `[quickback:authz]` warning when no action's path matches the declared prefix. Not a hard error — the namespace may be staged ahead of the actions.\n\n### What namespace actions get for free\n\nInside a namespace action's `execute()`:\n\n- `ctx.<exposeAs>` is populated by the middleware with the loaded resource row. Statically `any` by default — narrowed to `typeof <loadsTable>.$inferSelect` when the action's import points at the per-namespace helper (see [below](#narrow-ctxexposeas-typing-v027)).\n- Tenant context (`ctx.activeOrgId` / `ctx.activeTeamId`) is stamped from the matched relationship row when its `from` table carries those columns. Downstream scoped queries work without further setup.\n- The action's own `access:` block (additional roles, userRole, record predicates, OTHER relationship arms) still runs after the namespace gate — namespace handles entry, per-action gates further.\n\n### Narrow `ctx.<exposeAs>` typing (v0.27+)\n\nThe namespace middleware hydrates `ctx.<exposeAs>` at runtime — that's been true since v0.23. The static type of that field, though, is `any` via the `AppContext` index signature: useful for not blocking access, but a missed opportunity for autocomplete and typo-catching.\n\nv0.27 emits one **per-namespace `defineAction` helper** alongside the standard `<feature>/.quickback/define-action.ts`. Importing from the narrowed helper retypes `ctx.<exposeAs>` inside `execute({ ctx })` to the loaded row's `$inferSelect` shape. Nothing else changes — runtime behavior, action discovery, and the `path:` namespace match are identical.\n\n```ts title=\"features/feeds/actions/feed-moments.ts\"\n// One-line flip per namespace-scoped action:\n\n// └──────┬──────┘\n// kebab(namespaceName)\n\nexport default defineAction({\n path: '/event/:eventId/feed-moments',\n method: 'POST',\n input: z.object({ body: z.string() }),\n access: { roles: ['attendee'] },\n async execute({ ctx, input }) {\n ctx.event.id // ✓ string\n ctx.event.startsAt // ✓ Date — autocomplete works\n ctx.event.organizerId // ✓ narrows on the field's declared type\n\n ctx.event.idd // ✗ TS2339 — typo caught at compile time\n },\n});\n```\n\nThe compiler emits one helper per `(feature, namespace)` pair where the feature owns at least one action whose `path:` falls under the namespace prefix. Filename is `define-action.<kebab(namespaceName)>.ts` — `eventScope` becomes `define-action.event-scope.ts`. Helpers live next to the standard `define-action.ts` in `<feature>/.quickback/`, so the relative import is the same shape as every other action file in your project.\n\n#### Opt-in, not breaking\n\nActions that keep their existing `import { defineAction } from '../.quickback/define-action'` continue to compile unchanged — `ctx.<exposeAs>` is `any` via the `AppContext` index signature, which is exactly the v0.23–v0.26 behavior. You flip imports per action at your own pace.\n\n#### Compile-time advisory\n\nWhen `quickback compile` sees a namespace-scoped action still importing the generic helper, it emits a one-line advisory pointing at the narrowed path:\n\n```text\n[quickback:typing] action \"feedMoments\" in feature \"feeds\" lives under\n namespace \"eventScope\" — switch its import to\n `../.quickback/define-action.event-scope` for narrow ctx.<exposeAs> typing.\n (Runtime behavior is unchanged; the narrowed helper only refines TS types.)\n```\n\nNon-blocking — same `[quickback:typing]` family as `[quickback:authz]`. The advisory only mentions actions the compiler can be confident about (namespace-claimed actions whose source still imports the generic helper).\n\n#### Multi-namespace features\n\nA single feature can contribute actions to several namespaces — say, an `interviews` feature with actions under both `interviewScope` and `eventScope`. The compiler emits one narrowed helper per namespace the feature participates in, and each action picks the import that matches its path.\n\n```text\nsrc/features/interviews/.quickback/\n├── define-action.ts # generic — standard fallback\n├── define-action.interview-scope.ts # ctx.interview typed\n└── define-action.event-scope.ts # ctx.event typed\n```\n\n#### Why per-namespace and not per-action\n\nA `defineAction` helper that's narrow to *one* exposed key (the namespace's `exposeAs`) is enough — every action under a namespace sees the same hydrated key. The alternative (per-action emit) duplicates the same prelude N times for the same shape; per-namespace keeps emission proportional to the number of distinct hydration shapes in the project.\n\n## Read & Write Configuration\n\nReads (`GET /` and `GET /:id`) live under `read:`; mutations live under top-level `create:`, `update:`, `delete:`, and `upsert:`. See [Read](/compiler/definitions/read) for the full read pipeline reference.\n\n```typescript\nread: {\n // LIST + GET - GET /resource and GET /resource/:id\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n pageSize: 25, // Default page size\n maxPageSize: 100, // Client can't exceed this\n views: { // Per-view field projections\n summary: {\n fields: ['id', 'candidateId', 'jobId', 'stage'],\n access: { roles: [\"interviewer\"] },\n },\n },\n}\n\ncreate: {\n // CREATE - POST /resource\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] },\n defaults: { // Default values for new records\n stage: 'applied',\n },\n},\n\nupdate: {\n // UPDATE - PATCH /resource/:id\n access: {\n or: [\n { roles: [\"hiring-manager\", \"recruiter\"] },\n { roles: [\"interviewer\"], record: { stage: { equals: \"interview\" } } }\n ]\n },\n},\n\ndelete: {\n // DELETE - DELETE /resource/:id\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"soft\", // 'soft' (default) or 'hard'\n},\n\nupsert: {\n // PUT - PUT /resource/:id (only when generateId: false + guards: false)\n access: { roles: [\"hiring-manager\", \"sync-service\"] },\n}\n```\n\n## Evaluation Order\n\nGenerated `/:id` and batch handlers evaluate access in this fixed order:\n\n1. **Auth gate** — 401 if unauthenticated\n2. **Pre-record access** — role-only check (skips `access.record` predicates)\n3. **Firewall query** — `WHERE` clause filters by ownership\n4. **Post-record access** — full check including record-level predicates\n5. **Masking** — applied to the response\n\nStep 2 closes the 404-vs-403 ID-probe channel: an unauthorized caller without\na matching role gets 403 before the database is touched, so they can't tell\napart \"row exists out-of-scope\" from \"row doesn't exist.\" A caller with the\nright role but the wrong tenant gets 403 by default (firewall reveals via\nthe access layer); set\n[`firewallErrorMode: 'hide'`](/compiler/definitions/firewall) to return an\nopaque 404 instead.\n\nFunction-form access (`access: async (ctx, record) => ...`) is opaque to\nthe pre-record phase and always passes there; it's fully evaluated post-record.\n\n## List Filtering (Query Parameters)\n\nThe LIST endpoint automatically supports filtering via query params:\n\n```\nGET /jobs?status=open # Exact match\nGET /jobs?salaryMin.gt=50000 # Greater than\nGET /jobs?salaryMin.gte=50000 # Greater than or equal\nGET /jobs?salaryMax.lt=200000 # Less than\nGET /jobs?salaryMax.lte=200000 # Less than or equal\nGET /jobs?status.ne=closed # Not equal\nGET /jobs?title.like=Engineer # Pattern match (LIKE %value%)\nGET /jobs?status.in=open,draft # IN clause\n```\n\n| Operator | Query Param | SQL Equivalent |\n|----------|-------------|----------------|\n| Equals | `?field=value` | `WHERE field = value` |\n| Not equals | `?field.ne=value` | `WHERE field != value` |\n| Greater than | `?field.gt=value` | `WHERE field > value` |\n| Greater or equal | `?field.gte=value` | `WHERE field >= value` |\n| Less than | `?field.lt=value` | `WHERE field < value` |\n| Less or equal | `?field.lte=value` | `WHERE field <= value` |\n| Pattern match | `?field.like=value` | `WHERE field LIKE '%value%'` |\n| In list | `?field.in=a,b,c` | `WHERE field IN ('a','b','c')` |\n\n## Sorting & Pagination\n\n```\nGET /jobs?sort=createdAt&order=desc # Sort by field\nGET /jobs?limit=25&offset=50 # Pagination\n```\n\n- **Default limit**: 50\n- **Max limit**: 100 (or `maxPageSize` if configured)\n- **Default order**: `asc`\n\n## Delete Modes\n\n```typescript\ndelete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"soft\", // Sets deletedAt/deletedBy, record stays in DB\n}\n\ndelete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"hard\", // Permanent deletion from database\n}\n```\n\n## Context Variables\n\nUse `$ctx.` prefix to reference context values in conditions:\n\n```typescript\n// User can only view their own records\naccess: {\n record: { userId: { equals: \"$ctx.userId\" } }\n}\n\n// Nested path support for complex context objects\naccess: {\n record: { ownerId: { equals: \"$ctx.user.id\" } }\n}\n```\n\n### AppContext Reference\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `$ctx.userId` | `string` | Current authenticated user's ID |\n| `$ctx.activeOrgId` | `string` | User's active organization ID |\n| `$ctx.activeTeamId` | `string \\| null` | User's active team ID (if applicable) |\n| `$ctx.roles` | `string[]` | User's roles in current context |\n| `$ctx.isAnonymous` | `boolean` | Whether user is anonymous |\n| `$ctx.user` | `object` | Full user object from auth provider |\n| `$ctx.user.id` | `string` | User ID (nested path example) |\n| `$ctx.user.email` | `string` | User's email address |\n| `$ctx.{property}` | `any` | Any custom context property |\n\n## Function-Based Access\n\nFor complex access logic that can't be expressed declaratively, use a function:\n\n```typescript\nupdate: {\n access: async (ctx, record) => {\n // Custom logic - return true to allow, false to deny\n if (ctx.roles.includes('admin')) return true;\n if (record.ownerId === ctx.userId) return true;\n\n // Check custom business logic\n const membership = await checkTeamMembership(ctx.userId, record.teamId);\n return membership.canEdit;\n }\n}\n```\n\nFunction access receives:\n- `ctx`: The full AppContext object\n- `record`: The record being accessed (for get/update/delete operations)"
79
79
  },
80
80
  "compiler/definitions/actions": {
81
81
  "title": "Actions",
82
- "content": "Actions are custom API endpoints for business logic beyond CRUD operations. They enable workflows, integrations, and complex operations.\n\n## Overview\n\nQuickback supports two types of actions:\n\n| Aspect | Record-Based | Standalone |\n|--------|--------------|------------|\n| Route | `{METHOD} /:id/{actionName}` | Custom `path` (required) |\n| Record fetching | Automatic | None (`record` is `undefined`) |\n| Firewall applied | Yes | No |\n| Preconditions | Supported via `access.record` | Not applicable |\n| Response types | JSON only | JSON, stream, file |\n| Use case | Advance application, reject candidate | AI chat, bulk import from job board, webhooks |\n\nStandalone actions are signalled by the presence of a `path:` field in the action config. Record-based actions omit `path` and bind to the feature's primary table.\n\n## Where do actions live?\n\n**One file per action.** Each action is its own module under the feature's\n`actions/` directory:\n\n```\nfeatures/applications/\n├── applications.ts ← defineTable (primary table)\n├── candidates.ts ← defineTable (sibling table)\n├── actions/\n│ ├── advance.ts ← defineAction, binds to applications\n│ ├── reject.ts ← defineAction, binds to applications\n│ ├── stats.ts ← defineAction, standalone (has `path:`)\n│ └── candidates/\n│ └── disqualify.ts ← defineAction, binds to candidates\n└── lib/\n └── inputs.ts ← shared schemas (optional, copied verbatim)\n```\n\n| Layout | Binds to |\n|--------|----------|\n| `actions/<name>.ts` | The feature's primary table (table file matching the feature name), or standalone if `path:` is set. |\n| `actions/<table>/<name>.ts` | The sibling table file `<table>.ts` at the feature root. Standalone actions inside a subdir ignore the binding. |\n\nThe action's filename (sans `.ts`) is the action name and the URL segment.\nUniqueness is enforced per `(bound table, name)` pair — sibling-bound\nactions on **different** tables may share a verb (`actions/episodes/publish.ts`\nand `actions/shows/publish.ts` mount at `/episodes/:id/publish` and\n`/shows/:id/publish` and compile cleanly). The compiler errors only when\ntwo action files would mount at the same URL — for example, a flat\n`actions/foo.ts` (binds to primary) plus `actions/<primary>/foo.ts`, or\ntwo standalones with the same `(method, path)`. Standalone actions are\nunique per `(method, path)`.\n\nTableless features have no top-level `*.ts` files; every action under\n`actions/` must be standalone (have `path:`). Use this for utility endpoints\nlike webhooks, reports, or integrations that don't operate on a specific\nrecord.\n\n### Retired layouts\n\nThese are rejected at load time with migration guidance:\n\n- **`actions.ts`** (bundled multi-action file)\n- **`_feature.ts`** (shared schemas + non-table-bound actions)\n- **`handlers/`** (separate handler-file directory)\n- **`defineActions(table, {...})`** (the multi-action factory)\n- **`defineActions(null, {...})`** (tableless variant)\n- **`*-actions.ts` / `*.actions.ts`** filename patterns\n\nFor shared Zod schemas or helpers, put them under `<feature>/lib/` and import\nfrom each action file. Files under `lib/` are copied verbatim into the\ngenerated output.\n\n## Defining Actions\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n notes: z.string().max(2000).optional(),\n }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: {\n applied: [\"screening\"],\n screening: [\"interview\"],\n interview: [\"offer\"],\n },\n },\n async execute({ db, record, input, whereTransition }) {\n const [updated] = await db\n .update(applications)\n .set({\n status: input.nextStatus,\n notes: input.notes ?? record.notes,\n })\n .where(whereTransition!(applications))\n .returning();\n return updated;\n },\n});\n```\n\n> **`defineAction` import.** Import from `\"../.quickback/define-action\"` —\n> the `.quickback/` directory is generated alongside your feature with a\n> typed helper that infers `record` and `input` types from the rest of the\n> action config. Audit fields (`createdAt`, `createdBy`, `modifiedAt`,\n> `modifiedBy`) are hard-stamped by the audit DB wrapper on every\n> `db.insert().values()` and `db.update().set()` — handlers don't pass\n> them and can't override them.\n\n### Configuration Options\n\n| Option | Required | Description |\n|--------|----------|-------------|\n| `description` | Yes | Human-readable description of the action |\n| `input` | Yes | Zod schema for request validation |\n| `access` | Yes | Access control (roles, record conditions, or function) |\n| `execute` | Yes | Inline async arrow function (`async (ctx) => { … }`) |\n| `path` | Standalone only | Custom route path. Presence of `path` makes the action standalone. |\n| `method` | No | HTTP method: GET, POST, PUT, PATCH, DELETE (default: POST). GET actions parse `input` from query params; all other methods parse from the JSON body. See [GET vs POST for input](#get-vs-post-for-input). |\n| `responseType` | No | Response format: json, stream, file (default: json) |\n| `sideEffects` | No | Hint for AI tools: `'sync'`, `'async'`, or `'fire-and-forget'` |\n| `allowRawSql` | No | Explicit compile-time opt-in for raw SQL in execute code |\n| `unsafe` | No | Unsafe raw DB mode. Object config (`reason`, `adminOnly`, `crossTenant`, `targetScope`). |\n| `transition` | No | State-machine policy enforcing the from/to pair (record-based actions). See [Transitions](#transition-state-machine-policy) |\n| `bulkVariant` | No | Auto-generate a `POST /:resource/batch/{action}` route alongside the per-record route (record-based actions). See [Bulk Variant](#bulk-variant) |\n| `cms` | No | Pass-through metadata blob for CMS surfaces |\n\n`execute` must be an `async (ctx) => { … }` arrow function. `async function`\ndeclarations and non-async forms are rejected at parse time.\n\n## Record-Based Actions\n\nRecord-based actions operate on an existing record. The record is automatically loaded and validated before your action executes.\n\n**Route pattern:** `{METHOD} /:id/{actionName}`\n\n```\nPOST /applications/:id/advance\nPOST /applications/:id/reject\nPOST /applications/:id/schedule-interview\n```\n\n### Runtime Flow\n\n1. **Authentication** - User token is validated\n2. **Record Loading** - The record is fetched by ID\n3. **Firewall Check** - Ensures user can access this record\n4. **Access Check** - Validates roles and preconditions\n5. **Input Validation** - Request body validated against Zod schema\n6. **Execution** - Your action handler runs\n7. **Response** - Result is returned to client\n\n### Example: Advance Application Stage\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move application to the next pipeline stage\",\n input: z.object({\n stage: z.enum([\"screening\", \"interview\", \"offer\", \"hired\"]),\n notes: z.string().optional(),\n }),\n access: {\n roles: [\"owner\", \"hiring-manager\"],\n record: { stage: { notEquals: \"rejected\" } },\n },\n async execute({ db, record, input }) {\n const [updated] = await db\n .update(applications)\n .set({\n stage: input.stage,\n notes: input.notes ?? record.notes,\n })\n .where(eq(applications.id, record.id))\n .returning();\n return updated;\n },\n});\n```\n\n### Request Example\n\n```\nPOST /applications/app_123/advance\nContent-Type: application/json\n\n{\n \"stage\": \"interview\",\n \"notes\": \"Strong technical background, moving to interview\"\n}\n```\n\n### Response Example\n\n```json\n{\n \"data\": {\n \"id\": \"app_123\",\n \"stage\": \"interview\",\n \"notes\": \"Strong technical background, moving to interview\"\n }\n}\n```\n\n### Bulk variant\n\nSet `bulkVariant: true` to auto-generate a bulk version of the action at\n`POST /:resource/batch/{action}`. The compiler emits a second route alongside\nthe per-record one, looping the same access + transition + execute pipeline\nover an array of ids. This is the answer to \"I need to advance 50\napplications at once\" — you don't have to hand-roll a parallel standalone\naction that duplicates the per-record logic.\n\n```typescript\n// features/applications/actions/advance.ts\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n bulkVariant: true,\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: { applied: [\"screening\"], screening: [\"interview\"], interview: [\"offer\"] },\n },\n async execute({ db, record, input, whereTransition }) {\n const [updated] = await db\n .update(applications)\n .set({ status: input.nextStatus })\n .where(whereTransition!(applications))\n .returning();\n if (!updated) throw new TransitionLostError(\"status\", record.status, input.nextStatus);\n return updated;\n },\n});\n```\n\n**Request shape:**\n\n```http\nPOST /applications/batch/advance\nContent-Type: application/json\n\n{\n \"ids\": [\"app_001\", \"app_002\", \"app_003\"],\n \"input\": { \"nextStatus\": \"interview\" },\n \"failFast\": false\n}\n```\n\nThe `input` is shared across the batch — the action's Zod schema is\nvalidated once, not per id. For per-record input variation, use the\nsingle-record endpoint (`POST /:id/{action}`) or write a standalone action.\n\n**Response (207 Multi-Status when any record fails, 200 when clean):**\n\n```json\n{\n \"success\": [{ \"id\": \"app_001\", \"status\": \"interview\" }],\n \"errors\": [\n {\n \"index\": 1,\n \"id\": \"app_002\",\n \"error\": {\n \"error\": \"Action not allowed for current state\",\n \"code\": \"ACCESS_ACTION_NOT_ALLOWED_FOR_STATE\",\n \"details\": { \"field\": \"status\", \"currentValue\": \"rejected\" }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"failFast\": false,\n \"transactional\": false\n }\n}\n```\n\n**Per-record pipeline** mirrors the single-record route exactly — the same\nfirewall fetch, access reason split (403 vs 409), transition pre-check,\n`whereTransition` factory, and `TransitionLostError` handling. Per-record\nfailures land in `errors[]` with their original index; successful records\nland in `success[]` masked the same way the single-record response is.\n\n**Transactional matrix** (same as `PATCH /batch`):\n\n| Provider | failFast | transactional | Behavior |\n|---|---|---|---|\n| neon (Postgres via Hyperdrive) | `true` | `true` | `db.transaction()` wraps the loop; any throw rolls back all writes |\n| (any) | `false` | `false` | Independent per-record outcomes, partial success |\n| cloudflare-d1 | `true` | `false` | Fail-fast loop without rollback — earlier records stay committed (D1 has no `db.transaction`) |\n\n**Constraints:**\n\n- Record-based actions only. Standalone actions reject `bulkVariant: true`\n at compile time (no record context to loop over).\n- `unsafe` actions reject `bulkVariant: true` in v1 — the cross-tenant\n per-record audit story is not yet wired through.\n- Method is forced to POST regardless of the action's `method` setting. The\n semantic asymmetry (one row → many rows) makes inheriting GET/DELETE\n confusing.\n- Max batch size is 100 ids per request.\n\n## Standalone Actions\n\nStandalone actions are independent endpoints that don't require a record context. Set a `path:` to declare the action standalone.\n\n**Route pattern:** Custom `path`\n\n```\nPOST /chat\nGET /reports/summary\nPOST /webhooks/stripe\n```\n\n### Example: AI Chat with Streaming\n\n```typescript\n// features/sessions/actions/chat.ts\n\nexport default defineAction({\n description: \"Send a message to AI\",\n path: \"/chat\",\n method: \"POST\",\n responseType: \"stream\",\n input: z.object({\n message: z.string().min(1).max(2000),\n }),\n access: { roles: [\"recruiter\", \"hiring-manager\"] },\n async execute({ input, c }) {\n // Stream response back to client...\n return c.newResponse(/* ReadableStream */);\n },\n});\n```\n\n### Streaming Response Example\n\nFor actions with `responseType: 'stream'`:\n\n```\nContent-Type: text/event-stream\n\ndata: {\"type\": \"start\"}\ndata: {\"type\": \"chunk\", \"content\": \"Hello\"}\ndata: {\"type\": \"chunk\", \"content\": \"! I'm\"}\ndata: {\"type\": \"chunk\", \"content\": \" here to help.\"}\ndata: {\"type\": \"done\"}\n```\n\n### Tableless Features\n\nA feature directory with no top-level `*.ts` files is \"tableless\" — every\naction under `actions/` must be standalone. Use this for utility endpoints\nlike reports, integrations, or webhooks that don't map to a specific\nresource.\n\n```\nquickback/features/\n└── reports/\n └── actions/\n ├── trial-balance.ts ← standalone (has path:)\n └── profit-loss.ts ← standalone (has path:)\n```\n\n```typescript\n// features/reports/actions/trial-balance.ts\n\nexport default defineAction({\n description: \"Generate trial balance report\",\n path: \"/reports/trial-balance\",\n method: \"GET\",\n input: z.object({\n startDate: z.string(),\n endDate: z.string(),\n }),\n access: { roles: [\"admin\", \"accountant\"] },\n async execute({ db, input }) {\n // ... build report\n return { rows: [] };\n },\n});\n```\n\n### GET vs POST for input\n\nGET actions read `input` from URL query parameters; every other method (POST,\nPUT, PATCH, DELETE) reads from the JSON body. The Zod schema is the same in\nboth cases — the compiler picks the right parser based on `method`.\n\n```typescript\n// GET — input populated from ?q=…&limit=…\ndefineAction({\n method: \"GET\",\n path: \"/search\",\n input: z.object({\n q: z.string(),\n limit: z.coerce.number().int().positive().max(100).default(20),\n }),\n access: { roles: [\"AUTHENTICATED\"] },\n async execute({ input }) {\n // input is { q: string, limit: number } — fully typed.\n },\n});\n```\n\nRepeated query keys (`?tag=a&tag=b`) come through as arrays automatically;\nsingle values stay as strings. Use Zod's `.coerce.number()` /\n`.coerce.boolean()` when you want typed primitives from the parsed strings.\n\n**Use POST when input is structured.** GET requests cannot carry a JSON body\nin any of the surfaces Quickback APIs are commonly called from:\n\n- Browsers throw on `fetch(url, { method: 'GET', body })`.\n- CDNs and caches key on URL+method; a GET with a body either gets the body\n stripped at the edge or cache-collides with semantically different requests.\n- OpenAPI client generators (axios, openapi-fetch, openapi-typescript-codegen)\n refuse to emit GET-with-body, so the generated SDKs break.\n- The MCP agent surface treats GET as parameter-only — agents calling a GET\n action will only see what the URL exposes.\n\nIf your action takes nested objects, arrays of objects, or large inputs that\ndon't serialize cleanly to a query string, set `method: \"POST\"`. POST doesn't\nimply \"this writes data\" — it's the right method whenever the request body is\nload-bearing. Use the response shape (`responseType: \"json\"`, or just the data\nyour handler returns) to convey read semantics; HTTP method choice is about\ninput transport, not action intent.\n\n## Access Configuration\n\nAccess controls who can execute an action and under what conditions.\n\n### Role-Based Access\n\n```typescript\naccess: {\n roles: [\"hiring-manager\", \"recruiter\"] // OR logic: user needs any of these roles\n}\n```\n\n### Public Access\n\nUse `roles: [\"PUBLIC\"]` for unauthenticated endpoints (contact forms, webhooks, public APIs). Every invocation is **mandatory audit logged** with IP address, input, result, and timing.\n\n```typescript\n// features/contact/actions/submit.ts\n\nexport default defineAction({\n description: \"Public contact form submission\",\n path: \"/submit\",\n input: z.object({\n name: z.string().min(1),\n email: z.string().email(),\n message: z.string().min(10),\n }),\n access: { roles: [\"PUBLIC\"] },\n async execute({ db, input }) {\n // ... persist submission\n return { ok: true };\n },\n});\n```\n\nThe wildcard `\"*\"` is not supported and will throw a compile-time error. Use `\"PUBLIC\"` explicitly.\n\n### Record Conditions\n\nFor record-based actions, you can require the record to be in a specific state:\n\n```typescript\naccess: {\n roles: [\"hiring-manager\"],\n record: {\n stage: { equals: \"screening\" } // Precondition\n }\n}\n```\n\n**Supported operators:**\n\n| Operator | Description |\n|----------|-------------|\n| `equals` | Field must equal value |\n| `notEquals` | Field must not equal value |\n| `in` | Field must be one of the values |\n| `notIn` | Field must not be one of the values |\n\n### Context Substitution\n\nUse `$ctx` to reference the current user's context:\n\n```typescript\naccess: {\n record: {\n ownerId: { equals: \"$ctx.userId\" },\n 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```"
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- sysadmin gate (`ctx.userRole === \"sysadmin\"`)\n- mandatory audit logging on deny/success/error\n\n`PUBLIC` actions also receive mandatory audit logging (same audit table), since unauthenticated endpoints are high-risk by nature.\n\nWithout unsafe mode, `unsafeDb` is `undefined` in the executor params.\n\n### Raw SQL Policy\n\nBy default, the compiler rejects raw SQL in action code. Use Drizzle query-builder syntax whenever possible.\n\nIf a specific action must use raw SQL, opt in explicitly:\n\n```typescript\n// features/ledgers/actions/reconcile.ts\n\nexport default defineAction({\n description: \"Run custom reconciliation query\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n allowRawSql: true,\n async execute({ db }) {\n return db.execute(sql`select 1`);\n },\n});\n```\n\nWithout `allowRawSql: true`, compilation fails with a loud error pointing to the action and snippet.\n\nThe detector checks for SQL keywords in string arguments, so non-SQL method calls like `headers.get(\"X-Forwarded-For\")` or `map.get(\"key\")` will not trigger false positives.\n\n## Sharing Code Between Actions\n\nFor Zod schemas, helpers, or constants used across multiple actions in a\nfeature, put them under `<feature>/lib/` and import from each action file.\nFiles under `lib/` are copied verbatim into the generated output.\n\n```\nfeatures/applications/\n├── applications.ts\n├── actions/\n│ ├── advance.ts\n│ └── reject.ts\n└── lib/\n ├── inputs.ts ← shared Zod schemas\n └── transitions.ts ← state-machine helpers\n```\n\n```typescript\n// features/applications/lib/inputs.ts\n\nexport const advanceInput = z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n notes: z.string().max(2000).optional(),\n});\n```\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move forward\",\n input: advanceInput,\n access: { roles: [\"owner\"] },\n async execute({ db, record, input }) { /* … */ },\n});\n```\n\n### Importing Tables\n\nAction files import tables from their own feature or other features. The compiler generates alias files for each table, so you import by the table's file name:\n\n```typescript\n// features/applications/actions/advance.ts\n\n// Same feature — import from parent directory using the table's file name\n\n// Cross-feature — go up to the features directory, then into the other feature\n\n```\n\n**Path pattern from `features/{name}/actions/`:**\n- Same feature table: `../{table-file-name}` (e.g., `../applications`)\n- Other feature table: `../../{other-feature}/{table-file-name}` (e.g., `../../candidates/candidates`)\n- Generated lib files: `../../../lib/{module}` (e.g., `../../../lib/realtime`, `../../../lib/webhooks`)\n\n### Executor Parameters\n\n```typescript\n\ninterface ActionExecutorParams {\n db: DrizzleDB; // Scoped database (auto-applies org/owner/soft-delete filters)\n unsafeDb?: DrizzleDB; // Unscoped database (only available when unsafe mode is enabled)\n ctx: AppContext; // User context (userId, roles, 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
+ },
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```"
83
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 appmanager.** `userRole === 'appmanager'` callers still go through the firewall normally — only `userRole === 'sysadmin'` triggers the bypass. Appmanager is the platform control-plane tier, expressed with plain `userRole` checks; sysadmin is the opt-in cross-tenant 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,13 +117,21 @@ 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"
111
127
  },
112
128
  "compiler/definitions/schema": {
113
129
  "title": "Database Schema",
114
- "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"
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 provider-driven 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. This keeps q's output decoupled from any specific ID library.\n\nFor `generateId: \"cuid\"`, there is one important nuance: import-capable runtime\npaths can emit real `createId()` usage, but compiler-managed schema\nauto-injection may keep the same `createId()` call site and back it with a\nfile-local `crypto.randomUUID()` polyfill so schema-generation sandboxes do not\ndepend on project `node_modules`.\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"
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)."
115
135
  },
116
136
  "compiler/definitions/validation": {
117
137
  "title": "Validation",
@@ -119,7 +139,7 @@ export const DOCS = {
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",
@@ -143,7 +163,7 @@ export const DOCS = {
143
163
  },
144
164
  "compiler/getting-started/template-blog": {
145
165
  "title": "Blog Template",
146
- "content": "The blog template creates a single-tenant backend for a blog or CMS, deployed to Cloudflare Workers with D1. Public visitors can read content without authentication, while admins manage posts via Better Auth's admin plugin.\n\nThis template uses [single-tenant mode](/compiler/config/single-tenant) — no organizations, no `organizationId` columns. Roles come from `user.role` instead of org membership.\n\n## Create the Project\n\n```bash\nquickback create blog my-site\ncd my-site\n```\n\nThis scaffolds a project with:\n\n```\nmy-site/\n├── quickback/\n│ ├── quickback.config.ts # Single-tenant config\n│ └── features/\n│ └── posts/\n│ ├── posts.ts # Schema + security (defineTable)\n│ └── actions.ts # Publish/unpublish actions\n├── src/ # Compiled output (generated)\n├── package.json\n├── tsconfig.json\n├── wrangler.toml\n└── drizzle.config.ts\n```\n\n## Generated Configuration\n\n### quickback.config.ts\n\n```typescript\nexport default {\n name: \"my-site\",\n template: \"hono\",\n features: {\n organizations: false,\n },\n providers: {\n runtime: { name: \"cloudflare\", config: {} },\n database: {\n name: \"cloudflare-d1\",\n config: { binding: \"DB\" },\n },\n auth: { name: \"better-auth\", config: {} },\n },\n};\n```\n\nKey difference from the multi-tenant templates: `organizations: false` disables the Better Auth organization plugin. See [Single-Tenant Mode](/compiler/config/single-tenant) for details.\n\n### Posts Feature (posts.ts)\n\nThe template includes a `posts` feature with public read access and admin-only write access:\n\n```typescript\n\nexport const posts = sqliteTable(\"posts\", {\n id: text(\"id\").primaryKey(),\n title: text(\"title\").notNull(),\n slug: text(\"slug\").notNull().unique(),\n content: text(\"content\"),\n excerpt: text(\"excerpt\"),\n status: text(\"status\").notNull().default(\"draft\"),\n publishedAt: text(\"published_at\"),\n ownerId: text(\"owner_id\").notNull(),\n});\n\nexport default defineTable(posts, {\n firewall: [\n { field: 'ownerId', equals: 'ctx.userId' },\n { field: 'deletedAt', isNull: true },\n ],\n guards: {\n createable: [\"title\", \"slug\", \"content\", \"excerpt\", \"status\", \"publishedAt\"],\n updatable: [\"title\", \"slug\", \"content\", \"excerpt\", \"status\", \"publishedAt\"],\n immutable: [\"id\", \"ownerId\"],\n },\n read: {\n access: { roles: [\"PUBLIC\"] },\n },\n create: { access: { roles: [\"admin\"] } },\n update: { access: { roles: [\"admin\"] } },\n delete: { access: { roles: [\"admin\"] }, mode: \"soft\" },\n});\n```\n\n- **`PUBLIC`** role on `read.access` means no authentication required for `GET /` and `GET /:id`\n- **`admin`** role on `create`, `update`, and `delete` requires an authenticated user with `role: \"admin\"` (set via Better Auth's admin plugin)\n- **`owner`** firewall scope tracks who created each post via `ownerId`\n- **`softDelete`** marks posts as deleted rather than removing them from the database\n\n### Post Actions (actions.ts)\n\nThe template includes publish/unpublish actions with guard conditions:\n\n```typescript\n\nexport default defineActions(posts, {\n publish: {\n description: \"Publish a draft post\",\n input: z.object({}),\n guard: {\n roles: [\"admin\"],\n record: { status: { equals: \"draft\" } },\n },\n sideEffects: \"sync\",\n },\n unpublish: {\n description: \"Revert a published post to draft\",\n input: z.object({}),\n guard: {\n roles: [\"admin\"],\n record: { status: { equals: \"published\" } },\n },\n sideEffects: \"sync\",\n },\n});\n```\n\nThese actions are admin-only and include record-level guards — you can only publish drafts and unpublish published posts.\n\n## Setup Steps\n\n### 1. Install Dependencies\n\n```bash\nnpm install\n```\n\n### 2. Log In to the Compiler\n\n```bash\nquickback login\n```\n\n### 3. Compile Your Definitions\n\n```bash\nquickback compile\n```\n\n### 4. Create D1 Database\n\nThe blog template uses a single D1 database (no split databases):\n\n```bash\nnpx wrangler d1 create my-site\n```\n\nCopy the database ID from the output and update your `wrangler.toml`:\n\n```toml\n[[d1_databases]]\nbinding = \"DB\"\ndatabase_name = \"my-site\"\ndatabase_id = \"paste-id-here\"\n```\n\n### 5. Run Migrations (Local)\n\n```bash\nnpm run db:migrate:local\n```\n\n### 6. Start Development Server\n\n```bash\nnpm run dev\n```\n\nYour API is running at `http://localhost:8787`.\n\n## Using the API\n\n### Public Endpoints (No Auth Required)\n\n```bash\n# List all posts\ncurl http://localhost:8787/api/v1/posts\n\n# Get a single post\ncurl http://localhost:8787/api/v1/posts/post-id-here\n```\n\n### Admin Endpoints (Auth Required)\n\n```bash\n# Create a post (admin only)\ncurl -X POST http://localhost:8787/api/v1/posts \\\n -H \"Authorization: Bearer $TOKEN\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"title\": \"Hello World\", \"slug\": \"hello-world\", \"content\": \"...\"}'\n\n# Publish a post (admin only)\ncurl -X POST http://localhost:8787/api/v1/posts/post-id/actions/publish \\\n -H \"Authorization: Bearer $TOKEN\"\n```\n\n### Pairing with a Frontend\n\nSince this is a JSON API, pair it with any frontend framework:\n\n```typescript\n// Astro, Next.js, SvelteKit, etc.\nconst posts = await fetch('https://api.mysite.com/api/v1/posts').then(r => r.json());\n\n// Admin operations require authentication\nconst res = await fetch('https://api.mysite.com/api/v1/posts', {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ title: 'New Post', slug: 'new-post', content: '...' }),\n});\n```\n\n## Adding More Features\n\nAdd new content types by creating feature directories. For example, a `pages` feature for static pages:\n\n```typescript\n// quickback/features/pages/pages.ts\n\nexport const pages = sqliteTable(\"pages\", {\n id: text(\"id\").primaryKey(),\n title: text(\"title\").notNull(),\n slug: text(\"slug\").notNull().unique(),\n content: text(\"content\"),\n ownerId: text(\"owner_id\").notNull(),\n});\n\nexport default defineTable(pages, {\n firewall: [{ field: 'ownerId', equals: 'ctx.userId' }],\n read: {\n access: { roles: [\"PUBLIC\"] },\n },\n create: { access: { roles: [\"admin\"] } },\n update: { access: { roles: [\"admin\"] } },\n delete: { access: { roles: [\"admin\"] } },\n});\n```\n\nThen recompile:\n\n```bash\nquickback compile\n```\n\n## Deploying to Production\n\n```bash\n# Apply remote migrations\nnpm run db:migrate:remote\n\n# Deploy to Cloudflare\nnpm run deploy\n```\n\n## Next Steps\n\n- [Single-Tenant Mode](/compiler/config/single-tenant) — How single-tenant mode works\n- [Access Control](/compiler/definitions/access) — PUBLIC role and role-based permissions\n- [Custom Actions](/compiler/definitions/actions) — Add business logic beyond CRUD\n- [Cloudflare Template](/compiler/getting-started/template-cloudflare) — Multi-tenant alternative"
166
+ "content": "The blog template creates a fixed-org backend for a blog or CMS, deployed to Cloudflare Workers with D1. Public visitors can read content without authentication, while admins manage posts through their membership in one pinned organization.\n\nThis template uses [pinned organization mode](/compiler/config/single-tenant). Organization support stays on, but the generated project hard-codes one organization id and hides org switching UI.\n\n## Create the Project\n\n```bash\nquickback create blog my-site\ncd my-site\n```\n\nThis scaffolds a project with:\n\n```\nmy-site/\n├── quickback/\n│ ├── quickback.config.ts # Pinned-organization config\n│ └── features/\n│ └── posts/\n│ ├── posts.ts # Schema + security (defineTable)\n│ └── actions.ts # Publish/unpublish actions\n├── src/ # Compiled output (generated)\n├── package.json\n├── tsconfig.json\n├── wrangler.toml\n└── drizzle.config.ts\n```\n\n## Generated Configuration\n\n### quickback.config.ts\n\n```typescript\nexport default {\n name: \"my-site\",\n template: \"hono\",\n features: {\n pinnedOrganizationId: \"org_replace_me\",\n },\n providers: {\n runtime: { name: \"cloudflare\", config: {} },\n database: {\n name: \"cloudflare-d1\",\n config: { binding: \"DB\" },\n },\n auth: { name: \"better-auth\", config: {} },\n },\n};\n```\n\nReplace `org_replace_me` with a real Better Auth organization id before deploying. Unlike the removed single-tenant mode, this template keeps the Better Auth organization plugin and resolves roles from membership in that pinned org. See [Pinned Organization Mode](/compiler/config/single-tenant) for details.\n\n### Posts Feature (posts.ts)\n\nThe template includes a `posts` feature with public read access and admin-only write access:\n\n```typescript\n\nexport const posts = sqliteTable(\"posts\", {\n id: text(\"id\").primaryKey(),\n title: text(\"title\").notNull(),\n slug: text(\"slug\").notNull().unique(),\n content: text(\"content\"),\n excerpt: text(\"excerpt\"),\n status: text(\"status\").notNull().default(\"draft\"),\n publishedAt: text(\"published_at\"),\n ownerId: text(\"owner_id\").notNull(),\n});\n\nexport default defineTable(posts, {\n firewall: [\n { field: 'ownerId', equals: 'ctx.userId' },\n { field: 'deletedAt', isNull: true },\n ],\n guards: {\n createable: [\"title\", \"slug\", \"content\", \"excerpt\", \"status\", \"publishedAt\"],\n updatable: [\"title\", \"slug\", \"content\", \"excerpt\", \"status\", \"publishedAt\"],\n immutable: [\"id\", \"ownerId\"],\n },\n read: {\n access: { roles: [\"PUBLIC\"] },\n },\n create: { access: { roles: [\"admin\"] } },\n update: { access: { roles: [\"admin\"] } },\n delete: { access: { roles: [\"admin\"] }, mode: \"soft\" },\n});\n```\n\n- **`PUBLIC`** role on `read.access` means no authentication required for `GET /` and `GET /:id`\n- **`admin`** role on `create`, `update`, and `delete` requires an authenticated user with `member.role === \"admin\"` in the pinned organization\n- **`owner`** firewall scope tracks who created each post via `ownerId`\n- **`softDelete`** marks posts as deleted rather than removing them from the database\n\n### Post Actions (actions.ts)\n\nThe template includes publish/unpublish actions with guard conditions:\n\n```typescript\n\nexport default defineActions(posts, {\n publish: {\n description: \"Publish a draft post\",\n input: z.object({}),\n guard: {\n roles: [\"admin\"],\n record: { status: { equals: \"draft\" } },\n },\n sideEffects: \"sync\",\n },\n unpublish: {\n description: \"Revert a published post to draft\",\n input: z.object({}),\n guard: {\n roles: [\"admin\"],\n record: { status: { equals: \"published\" } },\n },\n sideEffects: \"sync\",\n },\n});\n```\n\nThese actions are admin-only and include record-level guards — you can only publish drafts and unpublish published posts.\n\n## Setup Steps\n\n### 1. Install Dependencies\n\n```bash\nnpm install\n```\n\n### 2. Log In to the Compiler\n\n```bash\nquickback login\n```\n\n### 3. Compile Your Definitions\n\n```bash\nquickback compile\n```\n\n### 4. Create D1 Database\n\nThe blog template uses a single D1 database (no split databases):\n\n```bash\nnpx wrangler d1 create my-site\n```\n\nCopy the database ID from the output and update your `wrangler.toml`:\n\n```toml\n[[d1_databases]]\nbinding = \"DB\"\ndatabase_name = \"my-site\"\ndatabase_id = \"paste-id-here\"\n```\n\n### 5. Run Migrations (Local)\n\n```bash\nnpm run db:migrate:local\n```\n\n### 6. Start Development Server\n\n```bash\nnpm run dev\n```\n\nYour API is running at `http://localhost:8787`.\n\n## Using the API\n\n### Public Endpoints (No Auth Required)\n\n```bash\n# List all posts\ncurl http://localhost:8787/api/v1/posts\n\n# Get a single post\ncurl http://localhost:8787/api/v1/posts/post-id-here\n```\n\n### Admin Endpoints (Auth Required)\n\n```bash\n# Create a post (admin only)\ncurl -X POST http://localhost:8787/api/v1/posts \\\n -H \"Authorization: Bearer $TOKEN\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"title\": \"Hello World\", \"slug\": \"hello-world\", \"content\": \"...\"}'\n\n# Publish a post (admin only)\ncurl -X POST http://localhost:8787/api/v1/posts/post-id/actions/publish \\\n -H \"Authorization: Bearer $TOKEN\"\n```\n\n### Pairing with a Frontend\n\nSince this is a JSON API, pair it with any frontend framework:\n\n```typescript\n// Astro, Next.js, SvelteKit, etc.\nconst posts = await fetch('https://api.mysite.com/api/v1/posts').then(r => r.json());\n\n// Admin operations require authentication\nconst res = await fetch('https://api.mysite.com/api/v1/posts', {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ title: 'New Post', slug: 'new-post', content: '...' }),\n});\n```\n\n## Adding More Features\n\nAdd new content types by creating feature directories. For example, a `pages` feature for static pages:\n\n```typescript\n// quickback/features/pages/pages.ts\n\nexport const pages = sqliteTable(\"pages\", {\n id: text(\"id\").primaryKey(),\n title: text(\"title\").notNull(),\n slug: text(\"slug\").notNull().unique(),\n content: text(\"content\"),\n ownerId: text(\"owner_id\").notNull(),\n});\n\nexport default defineTable(pages, {\n firewall: [{ field: 'ownerId', equals: 'ctx.userId' }],\n read: {\n access: { roles: [\"PUBLIC\"] },\n },\n create: { access: { roles: [\"admin\"] } },\n update: { access: { roles: [\"admin\"] } },\n delete: { access: { roles: [\"admin\"] } },\n});\n```\n\nThen recompile:\n\n```bash\nquickback compile\n```\n\n## Deploying to Production\n\n```bash\n# Apply remote migrations\nnpm run db:migrate:remote\n\n# Deploy to Cloudflare\nnpm run deploy\n```\n\n## Next Steps\n\n- [Pinned Organization Mode](/compiler/config/single-tenant) — How fixed-org mode works\n- [Access Control](/compiler/definitions/access) — PUBLIC role and role-based permissions\n- [Custom Actions](/compiler/definitions/actions) — Add business logic beyond CRUD\n- [Cloudflare Template](/compiler/getting-started/template-cloudflare) — Multi-tenant alternative"
147
167
  },
148
168
  "compiler/getting-started/template-cloudflare": {
149
169
  "title": "Cloudflare Template",
@@ -151,11 +171,11 @@ export const DOCS = {
151
171
  },
152
172
  "compiler/getting-started/template-empty": {
153
173
  "title": "Empty Scaffolding Templates",
154
- "content": "The `empty` template creates a project with only the configuration file — no example features. Use this when you know exactly what you want to build and don't need starter code.\n\n## Available Empty Templates\n\n| Template | Runtime | Database | Command |\n|----------|---------|----------|---------|\n| `empty` | Cloudflare Workers | D1 | `quickback create empty my-app` |\n\nAlias: `quickback create scaffold my-app` (same as `empty`)\n\n## Create the Project\n\n```bash\nquickback create empty my-app\n```\n\nThis scaffolds a minimal project:\n\n```\nmy-app/\n├── quickback/\n│ ├── quickback.config.ts # Compiler configuration\n│ └── features/ # Empty — add your own\n├── package.json\n└── tsconfig.json\n```\n\n## Generated Configuration\n\n```typescript\nexport default {\n name: \"my-app\",\n template: \"hono\",\n features: {\n organizations: true,\n },\n providers: {\n runtime: { name: \"cloudflare\", config: {} },\n database: {\n name: \"cloudflare-d1\",\n config: { binding: \"DB\" },\n },\n auth: { name: \"better-auth\", config: {} },\n },\n};\n```\n\nMulti-tenant mode (`organizations: true`) is the default. Change to `organizations: false` for [single-tenant mode](/compiler/config/single-tenant).\n\n## Adding Your First Feature\n\nCreate a feature directory with a schema file:\n\n```bash\nmkdir -p quickback/features/products\n```\n\n```typescript\n// quickback/features/products/products.ts\n\nexport const products = sqliteTable(\"products\", {\n id: text(\"id\").primaryKey(),\n name: text(\"name\").notNull(),\n description: text(\"description\"),\n price: integer(\"price\").notNull(),\n organizationId: text(\"organization_id\").notNull(),\n userId: text(\"user_id\").notNull(),\n});\n\nexport default defineTable(products, {\n firewall: {\n organization: {},\n owner: {},\n softDelete: {},\n },\n guards: {\n createable: [\"name\", \"description\", \"price\"],\n updatable: [\"name\", \"description\", \"price\"],\n },\n read: {\n access: { roles: [\"member+\"] },\n },\n create: { access: { roles: [\"member+\"] } },\n update: { access: { roles: [\"member+\"] } },\n delete: { access: { roles: [\"admin+\"] }, mode: \"soft\" },\n});\n```\n\nThen compile:\n\n```bash\nquickback login # First time only\nquickback compile\n```\n\n## Setup Steps\n\nFollow the same setup steps as the [Cloudflare template](/compiler/getting-started/template-cloudflare#setup-steps). The only difference is you'll need to add at least one feature before compiling.\n\n## Next Steps\n\n- [Schema Definitions](/compiler/definitions/schema) — Define tables with Drizzle ORM\n- [Firewall](/compiler/definitions/firewall) — Data isolation and tenant scoping\n- [Access Control](/compiler/definitions/access) — Role-based permissions\n- [Guards](/compiler/definitions/guards) — Field-level write protection\n- [Full Example](/compiler/getting-started/full-example) — Complete feature walkthrough"
174
+ "content": "The `empty` template creates a project with only the configuration file — no example features. Use this when you know exactly what you want to build and don't need starter code.\n\n## Available Empty Templates\n\n| Template | Runtime | Database | Command |\n|----------|---------|----------|---------|\n| `empty` | Cloudflare Workers | D1 | `quickback create empty my-app` |\n\nAlias: `quickback create scaffold my-app` (same as `empty`)\n\n## Create the Project\n\n```bash\nquickback create empty my-app\n```\n\nThis scaffolds a minimal project:\n\n```\nmy-app/\n├── quickback/\n│ ├── quickback.config.ts # Compiler configuration\n│ └── features/ # Empty — add your own\n├── package.json\n└── tsconfig.json\n```\n\n## Generated Configuration\n\n```typescript\nexport default {\n name: \"my-app\",\n template: \"hono\",\n providers: {\n runtime: { name: \"cloudflare\", config: {} },\n database: {\n name: \"cloudflare-d1\",\n config: { binding: \"DB\" },\n },\n auth: { name: \"better-auth\", config: {} },\n },\n};\n```\n\nOrganization-backed auth is the default. If you want a fixed-org deployment with no org switching UI, add `features.pinnedOrganizationId` as described in [Pinned Organization Mode](/compiler/config/single-tenant).\n\n## Adding Your First Feature\n\nCreate a feature directory with a schema file:\n\n```bash\nmkdir -p quickback/features/products\n```\n\n```typescript\n// quickback/features/products/products.ts\n\nexport const products = sqliteTable(\"products\", {\n id: text(\"id\").primaryKey(),\n name: text(\"name\").notNull(),\n description: text(\"description\"),\n price: integer(\"price\").notNull(),\n organizationId: text(\"organization_id\").notNull(),\n userId: text(\"user_id\").notNull(),\n});\n\nexport default defineTable(products, {\n firewall: {\n organization: {},\n owner: {},\n softDelete: {},\n },\n guards: {\n createable: [\"name\", \"description\", \"price\"],\n updatable: [\"name\", \"description\", \"price\"],\n },\n read: {\n access: { roles: [\"member+\"] },\n },\n create: { access: { roles: [\"member+\"] } },\n update: { access: { roles: [\"member+\"] } },\n delete: { access: { roles: [\"admin+\"] }, mode: \"soft\" },\n});\n```\n\nThen compile:\n\n```bash\nquickback login # First time only\nquickback compile\n```\n\n## Setup Steps\n\nFollow the same setup steps as the [Cloudflare template](/compiler/getting-started/template-cloudflare#setup-steps). The only difference is you'll need to add at least one feature before compiling.\n\n## Next Steps\n\n- [Schema Definitions](/compiler/definitions/schema) — Define tables with Drizzle ORM\n- [Firewall](/compiler/definitions/firewall) — Data isolation and tenant scoping\n- [Access Control](/compiler/definitions/access) — Role-based permissions\n- [Guards](/compiler/definitions/guards) — Field-level write protection\n- [Full Example](/compiler/getting-started/full-example) — Complete feature walkthrough"
155
175
  },
156
176
  "compiler/getting-started/templates": {
157
177
  "title": "Templates",
158
- "content": "Quickback provides pre-configured templates to get you started quickly. Each template combines a runtime, database, and auth provider into a working project.\n\nThe fastest way to start is `quickback start` — an interactive picker that asks for a template + project name and scaffolds in the current directory if it's empty, otherwise creates a subfolder. Every template below can be reached either via `start`'s picker (free tier) or scriptably via `quickback create <template> <name>`.\n\n```bash\n# Interactive (recommended for first-time use)\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n```\n\n## Available Templates\n\n### Multi-tenant scaffolds (free)\n\nCloudflare Workers + D1 + Better Auth with the organization plugin and a `member` / `admin` / `owner` role hierarchy wired in.\n\n| Template | Includes | Command |\n|----------|----------|---------|\n| `cloudflare` | Bare scaffold — auth + DB + Hono, no example feature | `quickback create cloudflare my-app` |\n| `todos` | Working todos feature: schema, masking, two actions (`complete` / `uncomplete`), and a `dashboard` named view | `quickback create todos my-app` |\n\nThe **todos** template is the recommended first read — it exercises every security pillar (firewall, access, guards, masking) plus actions and views in ~80 lines you can scan in five minutes.\n\n### Single-tenant starter (free)\n\n| Template | Includes | Command |\n|----------|----------|---------|\n| `blog` | Single-tenant blog with PUBLIC reads, admin writes, `publish` / `unpublish` actions | `quickback create blog my-site` |\n\nThe **blog** template uses Better Auth's admin plugin (not the org plugin) and [single-tenant mode](/compiler/config/single-tenant) (`organizations: false`).\n\n### Empty scaffold (free)\n\n| Template | Includes | Command |\n|----------|----------|---------|\n| `empty` | `quickback.config.ts` only — no example features | `quickback create empty my-app` |\n\nThe empty template creates the project structure with `quickback.config.ts` only. Add your first feature by creating a file under `quickback/features/<name>/<name>.ts` exporting `defineTable(...)` — there is no separate `init` step.\n\n### B2B SaaS (Pro)\n\n| Template | Includes | Command |\n|----------|----------|---------|\n| `saas` | Multi-tenant + **R2 file storage** + **outbound webhooks** + split databases + realtime + named views | `quickback create saas my-app` |\n\n## What Each Template Includes\n\nThe `cloudflare`, `todos`, `blog`, and `saas` templates all scaffold:\n\n- **`quickback.config.ts`** — Pre-configured with the right providers\n- **`quickback/features/`** — Feature definitions (empty for `cloudflare`; populated for `todos` / `blog` / `saas`)\n- **Deployment scripts** — `npm run deploy` for Cloudflare via wrangler\n\nThe `empty` template includes only:\n\n- **`quickback.config.ts`**\n- **`package.json`** — dependencies ready to install\n\n## Choosing a Template\n\n### Cloudflare bare scaffold\n\nBest when you already know the conventions and want empty walls. Multi-tenant orgs are wired in; you add your own feature files.\n\n### Todos (recommended for newcomers)\n\nBest for learning by reading. Full multi-tenant security pillars, two actions, a named view (`/api/v1/todos/views/dashboard`), and field masking on the `description` column — all in a single ~80-line file you can copy-edit into your own table.\n\n### Blog (single-tenant CMS)\n\nBest for personal sites, blogs, or any app with a single tenant. Uses [single-tenant mode](/compiler/config/single-tenant) — no organizations, roles come from `user.role` via Better Auth's admin plugin.\n\n- Public JSON API for content\n- Admin-only editing\n- Pair with any frontend (Astro, Next.js, SvelteKit, etc.)\n\n### Empty\n\nBest when you know exactly what you want to build. Gets you the project structure and config without any opinionated features.\n\n### SaaS (Pro)\n\nBest for production B2B work. Adds R2 file uploads, outbound webhooks (with retry/dedupe), split auth/features/webhooks databases, realtime broadcast, and named views.\n\n## Template Aliases\n\nFor convenience, templates have short aliases:\n\n| Alias | Full id |\n|-------|---------|\n| `cloudflare` / `cf` | `betterauth-d1-cloudflare` |\n| `todos` | `todos-cloudflare` |\n| `blog` | `blog-cloudflare` |\n| `saas` | `b2bsaas-cloudflare` |\n| `empty` / `scaffold` | `empty-cloudflare` |\n\n## After Scaffolding\n\n`quickback start` runs scaffold + login + compile + install + drizzle in one flow. If you used the scriptable `quickback create` instead (or cancelled at the login prompt), finish setup with:\n\n```bash\ncd my-app\nquickback compile # prompts for login on first run; reuses session after\nnpm run dev\n```\n\nSee the individual template guides for detailed setup:\n- [Cloudflare Template](/compiler/getting-started/template-cloudflare)\n- [Blog Template](/compiler/getting-started/template-blog)\n- [Empty Scaffolding](/compiler/getting-started/template-empty)\n- [Single-Tenant Mode](/compiler/config/single-tenant)"
178
+ "content": "Quickback provides pre-configured templates to get you started quickly. Each template combines a runtime, database, and auth provider into a working project.\n\nThe fastest way to start is `quickback start` — an interactive picker that asks for a template + project name and scaffolds in the current directory if it's empty, otherwise creates a subfolder. Every template below can be reached either via `start`'s picker (free tier) or scriptably via `quickback create <template> <name>`.\n\n```bash\n# Interactive (recommended for first-time use)\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n```\n\n## Available Templates\n\n### Multi-tenant scaffolds (free)\n\nCloudflare Workers + D1 + Better Auth with the organization plugin and a `member` / `admin` / `owner` role hierarchy wired in.\n\n| Template | Includes | Command |\n|----------|----------|---------|\n| `cloudflare` | Bare scaffold — auth + DB + Hono, no example feature | `quickback create cloudflare my-app` |\n| `todos` | Working todos feature: schema, masking, two actions (`complete` / `uncomplete`), and a `dashboard` named view | `quickback create todos my-app` |\n\nThe **todos** template is the recommended first read — it exercises every security pillar (firewall, access, guards, masking) plus actions and views in ~80 lines you can scan in five minutes.\n\n### Fixed-org starter (free)\n\n| Template | Includes | Command |\n|----------|----------|---------|\n| `blog` | Blog with PUBLIC reads, admin writes, `publish` / `unpublish` actions, and a pinned organization id placeholder | `quickback create blog my-site` |\n\nThe **blog** template uses [pinned organization mode](/compiler/config/single-tenant) and scaffolds `features.pinnedOrganizationId: \"org_replace_me\"`.\n\n### Empty scaffold (free)\n\n| Template | Includes | Command |\n|----------|----------|---------|\n| `empty` | `quickback.config.ts` only — no example features | `quickback create empty my-app` |\n\nThe empty template creates the project structure with `quickback.config.ts` only. Add your first feature by creating a file under `quickback/features/<name>/<name>.ts` exporting `defineTable(...)` — there is no separate `init` step.\n\n### B2B SaaS (Pro)\n\n| Template | Includes | Command |\n|----------|----------|---------|\n| `saas` | Multi-tenant + **R2 file storage** + **outbound webhooks** + split databases + realtime + named views | `quickback create saas my-app` |\n\n## What Each Template Includes\n\nThe `cloudflare`, `todos`, `blog`, and `saas` templates all scaffold:\n\n- **`quickback.config.ts`** — Pre-configured with the right providers\n- **`quickback/features/`** — Feature definitions (empty for `cloudflare`; populated for `todos` / `blog` / `saas`)\n- **Deployment scripts** — `npm run deploy` for Cloudflare via wrangler\n\nThe `empty` template includes only:\n\n- **`quickback.config.ts`**\n- **`package.json`** — dependencies ready to install\n\n## Choosing a Template\n\n### Cloudflare bare scaffold\n\nBest when you already know the conventions and want empty walls. Multi-tenant orgs are wired in; you add your own feature files.\n\n### Todos (recommended for newcomers)\n\nBest for learning by reading. Full multi-tenant security pillars, two actions, a named view (`/api/v1/todos/views/dashboard`), and field masking on the `description` column — all in a single ~80-line file you can copy-edit into your own table.\n\n### Blog (pinned-organization CMS)\n\nBest for personal sites, blogs, or any app that only needs one organization at runtime. Uses [pinned organization mode](/compiler/config/single-tenant) — organization support stays on, but the generated app hard-codes one org id and hides org switching.\n\n- Public JSON API for content\n- Admin-only editing\n- Pair with any frontend (Astro, Next.js, SvelteKit, etc.)\n\n### Empty\n\nBest when you know exactly what you want to build. Gets you the project structure and config without any opinionated features.\n\n### SaaS (Pro)\n\nBest for production B2B work. Adds R2 file uploads, outbound webhooks (with retry/dedupe), split auth/features/webhooks databases, realtime broadcast, and named views.\n\n## Template Aliases\n\nFor convenience, templates have short aliases:\n\n| Alias | Full id |\n|-------|---------|\n| `cloudflare` / `cf` | `betterauth-d1-cloudflare` |\n| `todos` | `todos-cloudflare` |\n| `blog` | `blog-cloudflare` |\n| `saas` | `b2bsaas-cloudflare` |\n| `empty` / `scaffold` | `empty-cloudflare` |\n\n## After Scaffolding\n\n`quickback start` runs scaffold + login + compile + install + drizzle in one flow. If you used the scriptable `quickback create` instead (or cancelled at the login prompt), finish setup with:\n\n```bash\ncd my-app\nquickback compile # prompts for login on first run; reuses session after\nnpm run dev\n```\n\nSee the individual template guides for detailed setup:\n- [Cloudflare Template](/compiler/getting-started/template-cloudflare)\n- [Blog Template](/compiler/getting-started/template-blog)\n- [Empty Scaffolding](/compiler/getting-started/template-empty)\n- [Pinned Organization Mode](/compiler/config/single-tenant)"
159
179
  },
160
180
  "compiler": {
161
181
  "title": "Quickback Compiler",
@@ -187,7 +207,7 @@ export const DOCS = {
187
207
  },
188
208
  "compiler/targets/hono-api/using-the-api/actions-api": {
189
209
  "title": "Actions API",
190
- "content": "Actions provide custom endpoints beyond CRUD operations. They support input validation, access conditions, and multiple response types including streaming.\n\n## Record-Based Actions\n\nRecord-based actions operate on a specific record identified by ID.\n\n```\nPOST /api/v1/{resource}/:id/{action-name}\n```\n\n### Request\n\n```bash\n# With JSON body\ncurl -X POST /api/v1/applications/app_123/advance-stage \\\n -H \"Authorization: Bearer <token>\" \\\n -H \"Content-Type: application/json\" \\\n -d '{ \"notes\": \"Strong technical interview, moving to offer stage\" }'\n```\n\nThe action's input schema validates the request body using Zod. Invalid input returns a 400 error.\n\n### Response\n\n```json\n{\n \"success\": true,\n \"data\": {\n \"id\": \"app_123\",\n \"stage\": \"offer\",\n \"previousStage\": \"interview\",\n \"notes\": \"Strong technical interview, moving to offer stage\"\n }\n}\n```\n\n### Security Flow\n\n1. **Authentication** — User must be logged in (401 if not)\n2. **Firewall** — Record must exist and be accessible to the user (404 if not found or not owned)\n3. **Access** — User must have the required role (403 if insufficient)\n4. **Input validation** — Request body validated against the action's Zod schema (400 if invalid)\n5. **Access conditions** — Record must match access conditions (400 if not met)\n6. **Masking** — Applied to the response data\n\n### Access Conditions\n\nActions can require the record to be in a specific state:\n\n```typescript\n// In actions.ts\nreject: {\n access: {\n roles: [\"owner\", \"hiring-manager\", \"recruiter\"],\n record: { stage: { notEquals: \"rejected\" } },\n },\n}\n```\n\nIf the record doesn't match (`stage` is already `rejected`), the action returns 400.\n\n## Standalone Actions\n\nStandalone actions don't require a record ID. They're for operations that aren't tied to a specific record.\n\n```\nPOST /api/v1/{resource}/{action-name}\n```\n\n### Request\n\n```bash\ncurl -X POST /api/v1/candidates/bulk-import \\\n -H \"Authorization: Bearer <token>\" \\\n -H \"Content-Type: application/json\" \\\n -d '{ \"source\": \"LinkedIn\", \"candidates\": [{\"name\": \"Alice Johnson\", \"email\": \"alice@example.com\"}, {\"name\": \"Bob Martinez\", \"email\": \"bob@example.com\"}] }'\n```\n\n### Response\n\nSame format as record-based actions. The difference is no record lookup or firewall check.\n\n### Security Flow\n\n1. **Authentication** — Required (401)\n2. **Organization check** — For org-scoped resources, user must have an active organization (403)\n3. **Access** — Role-based check (403)\n4. **Scoped DB** — The `db` passed to the handler is auto-scoped based on table columns (org isolation, owner filtering, soft delete)\n5. **Input validation** — Zod schema validation (400)\n\n### Scoped Database\n\nAll actions (both standalone and record-based) receive a **scoped `db`** instance that automatically enforces security based on the table's columns:\n\n- Tables with `organizationId` — org isolation (`WHERE organizationId = ?`)\n- Tables with `ownerId` — owner isolation (`WHERE ownerId = ?`)\n- Tables with `deletedAt` — soft delete filter (`WHERE deletedAt IS NULL`)\n- `INSERT` operations auto-inject `organizationId` and `ownerId` from context\n\n#### `userId` vs `ownerId` on feature tables\n\nUse `ownerId` (not `userId`) for the row-owner column on a feature table. The compiler:\n\n- Auto-firewalls reads on `ownerId` (`WHERE ownerId = ctx.userId`).\n- Auto-stamps `ownerId` on insert from `ctx.userId`.\n- Treats a `userId` column on a feature table as **informational** — almost always \"a user this row references\" (member, contact, invitee), not \"the row owner.\"\n\nA `userId` column on a feature table emits a compile-time warning. To resolve it:\n\n- **Rename to `ownerId`** if the column controls access (most common case).\n- **Rename to `linkedUserId`** (or similar) if the column is informational — explicit naming prevents future confusion.\n- **Declare explicit firewall** if `userId` really is the access column on that table:\n ```ts\n firewall: [{ field: 'userId', equals: 'ctx.userId' }]\n ```\n\nBetter Auth's own internal tables (`session`, `account`, `member`, `passkey`, `subscriptions`) use `userId` by convention. Those are not feature tables and don't pass through the auto-firewall — the warning only fires on resources you define in your `quickback/` folder.\n\n```typescript\n// Your handler receives a scoped db — no manual filtering needed\nexecute: async ({ db, ctx, input }) => {\n // This query automatically includes WHERE organizationId = ? AND ownerId = ? AND deletedAt IS NULL\n const items = await db.select().from(applications).where(eq(applications.stage, 'interview'));\n\n // Inserts automatically include organizationId and ownerId\n await db.insert(applications).values({ candidateId: input.candidateId, jobId: input.jobId, stage: 'applied' });\n\n return items;\n}\n```\n\nIf you need unscoped access (for example, audited platform admin operations), declare `unsafe` on the action:\n\n```typescript\nadminReport: {\n unsafe: {\n reason: 'Platform support report',\n adminOnly: true,\n crossTenant: true,\n targetScope: 'all',\n },\n execute: async ({ db, unsafeDb, ctx, input }) => {\n // unsafeDb bypasses scoped filters\n const allOrgs = await unsafeDb.select().from(applications);\n return allOrgs;\n },\n}\n```\n\nCross-tenant unsafe actions are generated with:\n\n- Better Auth authentication required\n- platform admin gate (`ctx.userRole === 'admin'`)\n- mandatory audit logging on denial/success/error\n\nWithout unsafe mode, `unsafeDb` is `undefined`.\n\nRaw SQL in action code is blocked by default at compile time. If you need it for a specific action, set `allowRawSql: true` on that action explicitly.\n\n### Explicit scope with `unsafeDb.scopeTo`\n\nUnsafe handlers often need to derive the tenant from somewhere other than the ambient request context — an inbound webhook reads it from a mailbox record, a cron job iterates over every organization, a background worker acts on behalf of a specific user. `unsafeDb.scopeTo({ organizationId?, userId?, teamId? })` returns a scoped db that applies the firewall with your explicit scope instead of `ctx`:\n\n```typescript\n// Inbound mail webhook — PUBLIC + unsafe:true\ningestInbound: {\n standalone: true,\n access: { roles: ['PUBLIC'] },\n unsafe: {\n reason: 'Inbound mail webhook — tenant derived from mailbox record',\n targetScope: 'organization',\n },\n input: z.object({ mailboxId: z.string(), body: z.string() }),\n execute: async ({ unsafeDb, input }) => {\n // Look up the mailbox without a tenant in ctx (unsafe handler, unscoped client)\n const [mailbox] = await unsafeDb.select().from(mailboxes)\n .where(eq(mailboxes.id, input.mailboxId));\n if (!mailbox) return { ok: false };\n\n // Pin scope to the mailbox's organization — every downstream query gets\n // WHERE organizationId = mailbox.organizationId, inserts get it injected.\n const db = unsafeDb.scopeTo({ organizationId: mailbox.organizationId });\n await db.insert(messages).values({ mailboxId: mailbox.id, body: input.body });\n return { ok: true };\n },\n}\n```\n\nWhy this is safer than hand-rolling `organizationId` on every query:\n\n- The firewall still runs. `scopeTo` just tells it which scope to use.\n- `insert().values()` auto-injects `organizationId` / `ownerId` / `teamId` per the scope.\n- Soft-delete and team-isolation filters continue to apply unchanged.\n- No chance of forgetting a `WHERE organizationId = ?` clause on a single query.\n\n`x-unsafe: true` is emitted on each unsafe operation in `openapi.json`, and MCP tool lists prefix the description with `[UNSAFE]` and set `annotations.destructiveHint` so agents and reviewers can see at a glance which endpoints cross trust boundaries.\n\n## Input Validation\n\nActions use Zod schemas for input validation. The schema is defined in your `actions.ts` file:\n\n```typescript\n\nexport default defineActions(\"applications\", {\n \"advance-stage\": {\n type: \"record\",\n input: z.object({\n notes: z.string().optional(),\n }),\n access: {\n roles: [\"hiring-manager\", \"recruiter\"],\n record: { stage: { notEquals: \"hired\" } },\n },\n },\n reject: {\n type: \"record\",\n input: z.object({\n reason: z.string().min(1),\n }),\n access: {\n roles: [\"hiring-manager\", \"recruiter\"],\n record: { stage: { notEquals: \"rejected\" } },\n },\n },\n});\n```\n\nWhen validation fails:\n\n```json\n{\n \"error\": \"Validation failed\",\n \"layer\": \"guards\",\n \"code\": \"GUARD_VALIDATION_FAILED\",\n \"details\": {\n \"issues\": [\n { \"path\": [\"reason\"], \"message\": \"String must contain at least 1 character(s)\" }\n ]\n }\n}\n```\n\n## Response Types\n\nActions support three response types:\n\n### JSON (Default)\n\nReturns a JSON object wrapped in `{ success: true, data: ... }`. Masking is applied to the data.\n\n### Streaming\n\nFor long-running operations, actions can return a streaming response:\n\n```typescript\ngenerateReport: {\n type: \"standalone\",\n responseType: \"stream\",\n // ...\n}\n```\n\nThe action handler returns a `ReadableStream` directly — no JSON wrapper.\n\n### File\n\nFor file downloads, actions can return a raw `Response` object:\n\n```typescript\nexportCsv: {\n type: \"record\",\n responseType: \"file\",\n // ...\n}\n```\n\n## Action Handler\n\nThe compiler generates a handler skeleton. Your action receives:\n\n```typescript\n{\n db, // Scoped database (auto-enforces org/owner/soft-delete filters)\n unsafeDb, // Raw database (only available when unsafe mode is enabled)\n ctx, // Auth context (user, session, org)\n record, // The existing record (record-based only, undefined for standalone)\n input, // Validated input from Zod schema\n services, // Injected services\n c, // Hono context\n env, // Runtime bindings (Cloudflare env / process env). Alias for c.env.\n}\n```\n\n## HTTP Methods\n\nActions default to `POST` but can use any HTTP method:\n\n```typescript\ngetStatus: {\n type: \"record\",\n method: \"GET\",\n // GET actions receive input from query parameters instead of body\n}\n```\n\nWhen using `GET`, input is parsed from query parameters instead of the request body.\n\n## Cascading Soft Delete\n\nWhen soft-deleting a parent record, Quickback automatically soft-deletes related records in child/junction tables **within the same feature**. The compiler detects foreign key references at build time.\n\nFor example, if your feature has `jobs` and `applications` tables where `applications` has a `.references(() => jobs.id)`, deleting a job will also soft-delete all its applications:\n\n```\nDELETE /api/v1/jobs/job_123\n```\n\nGenerated code:\n```typescript\n// Soft delete parent\nawait db.update(jobs).set({ deletedAt: now, modifiedAt: now })\n .where(and(buildFirewallConditions(ctx), eq(jobs.id, id)));\n\n// Cascade soft delete to child tables\nawait db.update(applications).set({ deletedAt: now, modifiedAt: now })\n .where(eq(applications.jobId, id));\n```\n\n**Cascade rules:**\n- **Soft delete (default)**: Application-level cascade via generated UPDATE statements\n- **Hard delete (`mode: 'hard'`)**: No compiler cascade — relies on DB-level `ON DELETE CASCADE`\n- **Cross-feature**: No cascade — only within the same feature's tables\n\n## See Also\n\n- [Defining Actions](/compiler/definitions/actions) — How to define actions in your feature\n- [Guards](/compiler/definitions/guards) — Guard conditions reference\n- [Error Responses](/compiler/targets/hono-api/using-the-api/errors) — Error format reference"
210
+ "content": "Actions provide custom endpoints beyond CRUD operations. They support input validation, access conditions, and multiple response types including streaming.\n\n## Record-Based Actions\n\nRecord-based actions operate on a specific record identified by ID.\n\n```\nPOST /api/v1/{resource}/:id/{action-name}\n```\n\n### Request\n\n```bash\n# With JSON body\ncurl -X POST /api/v1/applications/app_123/advance-stage \\\n -H \"Authorization: Bearer <token>\" \\\n -H \"Content-Type: application/json\" \\\n -d '{ \"notes\": \"Strong technical interview, moving to offer stage\" }'\n```\n\nThe action's input schema validates the request body using Zod. Invalid input returns a 400 error.\n\n### Response\n\n```json\n{\n \"success\": true,\n \"data\": {\n \"id\": \"app_123\",\n \"stage\": \"offer\",\n \"previousStage\": \"interview\",\n \"notes\": \"Strong technical interview, moving to offer stage\"\n }\n}\n```\n\n### Security Flow\n\n1. **Authentication** — User must be logged in (401 if not)\n2. **Firewall** — Record must exist and be accessible to the user (404 if not found or not owned)\n3. **Access** — User must have the required role (403 if insufficient)\n4. **Input validation** — Request body validated against the action's Zod schema (400 if invalid)\n5. **Access conditions** — Record must match access conditions (400 if not met)\n6. **Masking** — Applied to the response data\n\n### Access Conditions\n\nActions can require the record to be in a specific state:\n\n```typescript\n// In actions.ts\nreject: {\n access: {\n roles: [\"owner\", \"hiring-manager\", \"recruiter\"],\n record: { stage: { notEquals: \"rejected\" } },\n },\n}\n```\n\nIf the record doesn't match (`stage` is already `rejected`), the action returns 400.\n\n## Standalone Actions\n\nStandalone actions don't require a record ID. They're for operations that aren't tied to a specific record.\n\n```\nPOST /api/v1/{resource}/{action-name}\n```\n\n### Request\n\n```bash\ncurl -X POST /api/v1/candidates/bulk-import \\\n -H \"Authorization: Bearer <token>\" \\\n -H \"Content-Type: application/json\" \\\n -d '{ \"source\": \"LinkedIn\", \"candidates\": [{\"name\": \"Alice Johnson\", \"email\": \"alice@example.com\"}, {\"name\": \"Bob Martinez\", \"email\": \"bob@example.com\"}] }'\n```\n\n### Response\n\nSame format as record-based actions. The difference is no record lookup or firewall check.\n\n### Security Flow\n\n1. **Authentication** — Required (401)\n2. **Organization check** — For org-scoped resources, user must have an active organization (403)\n3. **Access** — Role-based check (403)\n4. **Scoped DB** — The `db` passed to the handler is auto-scoped based on table columns (org isolation, owner filtering, soft delete)\n5. **Input validation** — Zod schema validation (400)\n\n### Scoped Database\n\nAll actions (both standalone and record-based) receive a **scoped `db`** instance that automatically enforces security based on the table's columns:\n\n- Tables with `organizationId` — org isolation (`WHERE organizationId = ?`)\n- Tables with `ownerId` — owner isolation (`WHERE ownerId = ?`)\n- Tables with `deletedAt` — soft delete filter (`WHERE deletedAt IS NULL`)\n- `INSERT` operations auto-inject `organizationId` and `ownerId` from context\n\n#### `userId` vs `ownerId` on feature tables\n\nUse `ownerId` (not `userId`) for the row-owner column on a feature table. The compiler:\n\n- Auto-firewalls reads on `ownerId` (`WHERE ownerId = ctx.userId`).\n- Auto-stamps `ownerId` on insert from `ctx.userId`.\n- Treats a `userId` column on a feature table as **informational** — almost always \"a user this row references\" (member, contact, invitee), not \"the row owner.\"\n\nA `userId` column on a feature table emits a compile-time warning. To resolve it:\n\n- **Rename to `ownerId`** if the column controls access (most common case).\n- **Rename to `linkedUserId`** (or similar) if the column is informational — explicit naming prevents future confusion.\n- **Declare explicit firewall** if `userId` really is the access column on that table:\n ```ts\n firewall: [{ field: 'userId', equals: 'ctx.userId' }]\n ```\n\nBetter Auth's own internal tables (`session`, `account`, `member`, `passkey`, `subscriptions`) use `userId` by convention. Those are not feature tables and don't pass through the auto-firewall — the warning only fires on resources you define in your `quickback/` folder.\n\n```typescript\n// Your handler receives a scoped db — no manual filtering needed\nexecute: async ({ db, ctx, input }) => {\n // This query automatically includes WHERE organizationId = ? AND ownerId = ? AND deletedAt IS NULL\n const items = await db.select().from(applications).where(eq(applications.stage, 'interview'));\n\n // Inserts automatically include organizationId and ownerId\n await db.insert(applications).values({ candidateId: input.candidateId, jobId: input.jobId, stage: 'applied' });\n\n return items;\n}\n```\n\nIf you need unscoped access (for example, audited cross-tenant sysadmin operations), declare `unsafe` on the action:\n\n```typescript\nadminReport: {\n unsafe: {\n reason: 'Platform support report',\n adminOnly: true,\n crossTenant: true,\n targetScope: 'all',\n },\n execute: async ({ db, unsafeDb, ctx, input }) => {\n // unsafeDb bypasses scoped filters\n const allOrgs = await unsafeDb.select().from(applications);\n return allOrgs;\n },\n}\n```\n\nCross-tenant unsafe actions are generated with:\n\n- Better Auth authentication required\n- sysadmin gate (`ctx.userRole === 'sysadmin'`)\n- mandatory audit logging on denial/success/error\n\nWithout unsafe mode, `unsafeDb` is `undefined`.\n\nRaw SQL in action code is blocked by default at compile time. If you need it for a specific action, set `allowRawSql: true` on that action explicitly.\n\n### Explicit scope with `unsafeDb.scopeTo`\n\nUnsafe handlers often need to derive the tenant from somewhere other than the ambient request context — an inbound webhook reads it from a mailbox record, a cron job iterates over every organization, a background worker acts on behalf of a specific user. `unsafeDb.scopeTo({ organizationId?, userId?, teamId? })` returns a scoped db that applies the firewall with your explicit scope instead of `ctx`:\n\n```typescript\n// Inbound mail webhook — PUBLIC + unsafe:true\ningestInbound: {\n standalone: true,\n access: { roles: ['PUBLIC'] },\n unsafe: {\n reason: 'Inbound mail webhook — tenant derived from mailbox record',\n targetScope: 'organization',\n },\n input: z.object({ mailboxId: z.string(), body: z.string() }),\n execute: async ({ unsafeDb, input }) => {\n // Look up the mailbox without a tenant in ctx (unsafe handler, unscoped client)\n const [mailbox] = await unsafeDb.select().from(mailboxes)\n .where(eq(mailboxes.id, input.mailboxId));\n if (!mailbox) return { ok: false };\n\n // Pin scope to the mailbox's organization — every downstream query gets\n // WHERE organizationId = mailbox.organizationId, inserts get it injected.\n const db = unsafeDb.scopeTo({ organizationId: mailbox.organizationId });\n await db.insert(messages).values({ mailboxId: mailbox.id, body: input.body });\n return { ok: true };\n },\n}\n```\n\nWhy this is safer than hand-rolling `organizationId` on every query:\n\n- The firewall still runs. `scopeTo` just tells it which scope to use.\n- `insert().values()` auto-injects `organizationId` / `ownerId` / `teamId` per the scope.\n- Soft-delete and team-isolation filters continue to apply unchanged.\n- No chance of forgetting a `WHERE organizationId = ?` clause on a single query.\n\n`x-unsafe: true` is emitted on each unsafe operation in `openapi.json`, and MCP tool lists prefix the description with `[UNSAFE]` and set `annotations.destructiveHint` so agents and reviewers can see at a glance which endpoints cross trust boundaries.\n\n## Input Validation\n\nActions use Zod schemas for input validation. The schema is defined in your `actions.ts` file:\n\n```typescript\n\nexport default defineActions(\"applications\", {\n \"advance-stage\": {\n type: \"record\",\n input: z.object({\n notes: z.string().optional(),\n }),\n access: {\n roles: [\"hiring-manager\", \"recruiter\"],\n record: { stage: { notEquals: \"hired\" } },\n },\n },\n reject: {\n type: \"record\",\n input: z.object({\n reason: z.string().min(1),\n }),\n access: {\n roles: [\"hiring-manager\", \"recruiter\"],\n record: { stage: { notEquals: \"rejected\" } },\n },\n },\n});\n```\n\nWhen validation fails:\n\n```json\n{\n \"error\": \"Validation failed\",\n \"layer\": \"guards\",\n \"code\": \"GUARD_VALIDATION_FAILED\",\n \"details\": {\n \"issues\": [\n { \"path\": [\"reason\"], \"message\": \"String must contain at least 1 character(s)\" }\n ]\n }\n}\n```\n\n## Response Types\n\nActions support three response types:\n\n### JSON (Default)\n\nReturns a JSON object wrapped in `{ success: true, data: ... }`. Masking is applied to the data.\n\n### Streaming\n\nFor long-running operations, actions can return a streaming response:\n\n```typescript\ngenerateReport: {\n type: \"standalone\",\n responseType: \"stream\",\n // ...\n}\n```\n\nThe action handler returns a `ReadableStream` directly — no JSON wrapper.\n\n### File\n\nFor file downloads, actions can return a raw `Response` object:\n\n```typescript\nexportCsv: {\n type: \"record\",\n responseType: \"file\",\n // ...\n}\n```\n\n## Action Handler\n\nThe compiler generates a handler skeleton. Your action receives:\n\n```typescript\n{\n db, // Scoped database (auto-enforces org/owner/soft-delete filters)\n unsafeDb, // Raw database (only available when unsafe mode is enabled)\n ctx, // Auth context (user, session, org)\n record, // The existing record (record-based only, undefined for standalone)\n input, // Validated input from Zod schema\n services, // Injected services\n c, // Hono context\n env, // Runtime bindings (Cloudflare env / process env). Alias for c.env.\n}\n```\n\n## HTTP Methods\n\nActions default to `POST` but can use any HTTP method:\n\n```typescript\ngetStatus: {\n type: \"record\",\n method: \"GET\",\n // GET actions receive input from query parameters instead of body\n}\n```\n\nWhen using `GET`, input is parsed from query parameters instead of the request body.\n\n## Cascading Soft Delete\n\nWhen soft-deleting a parent record, Quickback automatically soft-deletes related records in child/junction tables **within the same feature**. The compiler detects foreign key references at build time.\n\nFor example, if your feature has `jobs` and `applications` tables where `applications` has a `.references(() => jobs.id)`, deleting a job will also soft-delete all its applications:\n\n```\nDELETE /api/v1/jobs/job_123\n```\n\nGenerated code:\n```typescript\n// Soft delete parent\nawait db.update(jobs).set({ deletedAt: now, modifiedAt: now })\n .where(and(buildFirewallConditions(ctx), eq(jobs.id, id)));\n\n// Cascade soft delete to child tables\nawait db.update(applications).set({ deletedAt: now, modifiedAt: now })\n .where(eq(applications.jobId, id));\n```\n\n**Cascade rules:**\n- **Soft delete (default)**: Application-level cascade via generated UPDATE statements\n- **Hard delete (`mode: 'hard'`)**: No compiler cascade — relies on DB-level `ON DELETE CASCADE`\n- **Cross-feature**: No cascade — only within the same feature's tables\n\n## See Also\n\n- [Defining Actions](/compiler/definitions/actions) — How to define actions in your feature\n- [Guards](/compiler/definitions/guards) — Guard conditions reference\n- [Error Responses](/compiler/targets/hono-api/using-the-api/errors) — Error format reference"
191
211
  },
192
212
  "compiler/targets/hono-api/using-the-api/batch-operations": {
193
213
  "title": "Batch Operations",
@@ -243,7 +263,7 @@ export const DOCS = {
243
263
  },
244
264
  "stack/account-ui/features/admin": {
245
265
  "title": "Admin Panel",
246
- "content": "The admin panel provides a user management dashboard for administrators. It's part of the Account UI SPA — when enabled, the `/admin` route is included in the build.\n\n## Enabling Admin\n\nSet `auth.admin` to `true` in your account config:\n\n```typescript title=\"quickback/quickback.config.ts\"\naccount: {\n auth: {\n admin: true,\n },\n},\n```\n\nThis does two things:\n1. Includes admin route files in the Account SPA build (compile-time gating)\n2. Ensures the Better Auth `admin` plugin is enabled on the backend\n\nWhen `auth.admin` is `false` (the default), admin routes are excluded from the SPA bundle entirely — they don't exist in production.\n\n## What It Can Do\n\n- **View all users** — Paginated list with search\n- **Create users** — Manually create accounts with email/password\n- **Ban/unban users** — Suspend or reactivate user accounts\n- **Reset passwords** — Generate password reset for any user\n- **View sessions** — See active sessions for any user\n\n## Access Control\n\nThe admin panel is restricted to users with `role: \"admin\"` on their Better Auth user record. Non-admin users are redirected away from `/admin`.\n\nTo grant admin access to a user, use the Better Auth admin plugin:\n\n```bash\ncurl -X POST https://api.example.com/auth/v1/admin/set-role \\\n -H \"Authorization: Bearer $TOKEN\" \\\n -H \"Content-Type: application/json\" \\\n -d '{ \"userId\": \"user_123\", \"role\": \"admin\" }'\n```\n\n## Custom Admin Domain\n\nGive the admin panel its own subdomain with `adminDomain`:\n\n```typescript title=\"quickback/quickback.config.ts\"\naccount: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n auth: { password: true, admin: true },\n},\ntrustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n],\n```\n\nThe admin domain serves the same Account SPA at root (`/`). The SPA's client-side router handles showing the admin page at `admin.example.com/admin`. Authentication cookies are shared across subdomains automatically via [cross-subdomain cookie configuration](/compiler/config/domains#cross-subdomain-authentication).\n\n## CMS Access Control\n\nWhen both CMS and Account UI are enabled, the admin panel's profile page shows a \"Go to CMS\" button. You can restrict this to admin users only:\n\n```typescript\ncms: { domain: \"cms.example.com\", access: \"admin\" },\n```\n\nWith `access: \"admin\"`, non-admin users can't access the CMS at any layer: the link is hidden in Account UI, the SPA shell returns `403` before serving `index.html`, `/api/v1/schema` returns `403`, and the `custom_view` CRUD is locked to admins. See [CMS Connecting](/stack/cms/connecting#restrict-cms-access-to-admin-users-only) for the full enforcement model.\n\n## Related\n\n- [Configuration](/compiler/config) — `auth.admin` and `adminDomain` options\n- [Multi-Domain Architecture](/compiler/config/domains) — Custom domains and hostname routing\n- [Access Control](/compiler/definitions/access) — Role-based permissions in your API"
266
+ "content": "The admin panel provides a user management dashboard for administrators. It's part of the Account UI SPA — when enabled, the `/admin` route is included in the build.\n\n## Enabling Admin\n\nSet `auth.admin` to `true` in your account config:\n\n```typescript title=\"quickback/quickback.config.ts\"\naccount: {\n auth: {\n admin: true,\n },\n},\n```\n\nThis does two things:\n1. Includes admin route files in the Account SPA build (compile-time gating)\n2. Ensures the Better Auth `admin` plugin is enabled on the backend\n\nWhen `auth.admin` is `false` (the default), admin routes are excluded from the SPA bundle entirely — they don't exist in production.\n\n## What It Can Do\n\n- **View all users** — Paginated list with search\n- **Create users** — Manually create accounts with email/password\n- **Ban/unban users** — Suspend or reactivate user accounts\n- **Reset passwords** — Generate password reset for any user\n- **View sessions** — See active sessions for any user\n\n## Access Control\n\nThe admin panel is restricted to users with `role: \"admin\"` on their Better Auth user record. Non-admin users are redirected away from `/admin`.\n\nTo grant admin access to a user, use the Better Auth admin plugin:\n\n```bash\ncurl -X POST https://api.example.com/auth/v1/admin/set-role \\\n -H \"Authorization: Bearer $TOKEN\" \\\n -H \"Content-Type: application/json\" \\\n -d '{ \"userId\": \"user_123\", \"role\": \"admin\" }'\n```\n\n## Custom Admin Domain\n\nGive the admin panel its own subdomain with `adminDomain`:\n\n```typescript title=\"quickback/quickback.config.ts\"\naccount: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n auth: { password: true, admin: true },\n},\ntrustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n],\n```\n\nThe admin domain serves the same Account SPA at root (`/`). The SPA's client-side router handles showing the admin page at `admin.example.com/admin`. Authentication cookies are shared across subdomains automatically via [cross-subdomain cookie configuration](/compiler/config/domains#cross-subdomain-authentication).\n\n## CMS Access Control\n\nWhen both CMS and Account UI are enabled, the admin panel's profile page shows a \"Go to CMS\" button. You can restrict this to admin users only:\n\n```typescript\ncms: { domain: \"cms.example.com\", access: \"admin\" },\n```\n\nWith `access: \"admin\"`, callers outside the platform control-plane roles can't access the CMS at any layer: the link is hidden in Account UI, the SPA shell returns `403` before serving `index.html`, `/api/v1/schema` returns `403`, and the `custom_view` CRUD is locked to `userRole: [\"appmanager\"]` (plus `sysadmin` when enabled). See [CMS Connecting](/stack/cms/connecting#restrict-cms-access-to-admin-users-only) for the full enforcement model.\n\n## Related\n\n- [Configuration](/compiler/config) — `auth.admin` and `adminDomain` options\n- [Multi-Domain Architecture](/compiler/config/domains) — Custom domains and hostname routing\n- [Access Control](/compiler/definitions/access) — Role-based permissions in your API"
247
267
  },
248
268
  "stack/account-ui/features/api-keys": {
249
269
  "title": "API Key Management",
@@ -259,7 +279,7 @@ export const DOCS = {
259
279
  },
260
280
  "stack/account-ui/features": {
261
281
  "title": "Feature Flags",
262
- "content": "# Feature Flags\n\nControl which features are available in your Account UI deployment using feature flags. All features are configured via environment variables.\n\n## Authentication Features\n\n### User Signup\n\n```bash\nENABLE_SIGNUP=true # default: true\n```\n\nControls whether new users can register. Wired to the `ENABLE_SIGNUP` env var.\n\n**When enabled:**\n- Shows \"Sign Up\" link on login page\n- `/signup` route is accessible\n- New users can create accounts\n\n**When disabled:**\n- Signup route returns 404\n- Only existing users can log in\n- Useful for invite-only applications\n\n### Email Verification\n\n```bash\nENABLE_EMAIL_VERIFICATION=true # default: true\n```\n\nControls the email verification flow. Wired to the frontend via the `ENABLE_EMAIL_VERIFICATION` env var.\n\n**When enabled:**\n- Users must verify email before full access\n- Verification email sent on signup\n- \"Resend verification email\" option available\n- Unverified users see verification prompt\n\n**When disabled:**\n- Email addresses are trusted without verification\n- Users have immediate access after signup\n\n### Email Deliverability Check\n\n```bash\nDISABLE_EMAIL_STATUS_CHECK=false # default: false\n```\n\n**When `false` (checking enabled):**\n- System validates email addresses are deliverable\n- Rejects disposable/temporary email providers\n- Prevents typos in domain names\n\n**When `true` (checking disabled):**\n- Accepts all email formats\n- Useful for development/testing\n- Allows `@test.com`, `@localhost`, etc.\n\n### Passkey Login\n\n```bash\nENABLE_PASSKEY=true # default: true\n```\n\nControls passkey LOGIN only (not signup). When enabled, users can authenticate using passkeys.\n\n**When enabled:**\n- Users can register passkeys (fingerprint, Face ID, hardware keys)\n- Passwordless login option\n- \"Manage Passkeys\" page available\n\n**When disabled:**\n- No passkey registration\n- No passkey login option\n\n**Requirements:**\n- HTTPS (passkeys require secure context)\n- Modern browser with WebAuthn support\n\n### Email OTP\n\n```bash\nENABLE_EMAIL_OTP=true # default: true\n```\n\n**When enabled:**\n- Users can receive one-time passwords via email\n- Alternative to password login\n- `/email-otp` route available\n\n**When disabled:**\n- No email OTP option\n- Password or passkey required\n\n### Password Authentication\n\n```bash\nENABLE_PASSWORD=false # default: false\n```\n\n**When enabled:**\n- Email + password fields on login page\n- Password field on signup page\n- Traditional username/password authentication\n\n**When disabled:**\n- No password fields shown\n- Users authenticate via email OTP or passkey\n\n## Account Management Features\n\n### File Uploads\n\n```bash\nVITE_ENABLE_FILE_UPLOADS=false # default: false\n```\n\n**When enabled:**\n- Avatar/profile picture upload\n- Image cropping and editing\n- File upload to R2/S3\n\n**When disabled:**\n- No file upload functionality\n- Users can only use default avatars\n\n**Requirements:**\n- R2 bucket or S3 configured\n- Upload endpoints in your API\n\n## Organization Features\n\n### Organizations (Multi-Tenancy)\n\n```bash\nENABLE_ORGANIZATIONS=true # default: true\n```\n\n**When enabled:**\n- Users can create organizations\n- Organization management pages\n- Member invitations and roles\n- `/organizations/*` routes\n\n**When disabled:**\n- Single-user mode only\n- No organization features\n- Simpler user experience\n\n**Includes:**\n- Organization creation and deletion\n- Member management (owner, admin, member roles)\n- Invitation system\n- Organization settings\n\n## Admin Features\n\n### Admin Panel\n\n```bash\nENABLE_ADMIN=true # default: true\n```\n\n**When enabled:**\n- `/admin` route accessible to admin users\n- User management dashboard\n- Subscription management\n- Admin-only features:\n - Create users manually\n - Ban/unban users\n - Reset user passwords\n - View all sessions\n - Manage subscriptions\n\n**When disabled:**\n- No admin panel\n- Admin must use database directly\n\n**Requirements:**\n- User must have admin role in database\n\n## Feature Combinations\n\n### Minimal Configuration (Password-Only)\n\n```bash\nENABLE_PASSKEY=false\nENABLE_EMAIL_OTP=false\nENABLE_PASSWORD=true\nENABLE_ORGANIZATIONS=false\nENABLE_ADMIN=false\n```\n\nSimple email/password authentication for single-tenant apps.\n\n### Maximum Security\n\n```bash\nENABLE_PASSKEY=true\nENABLE_EMAIL_OTP=true\nENABLE_PASSWORD=false\nENABLE_EMAIL_VERIFICATION=true\n```\n\nAll authentication methods with email verification and deliverability checks.\n\n### Multi-Tenant SaaS\n\n```bash\nENABLE_PASSKEY=true\nENABLE_EMAIL_OTP=true\nENABLE_ORGANIZATIONS=true\nENABLE_ADMIN=true\n```\n\nFull-featured SaaS with organizations, teams, and admin panel.\n\n### Invite-Only Platform\n\n```bash\nENABLE_SIGNUP=false\nENABLE_PASSKEY=true\nENABLE_ORGANIZATIONS=true\nENABLE_ADMIN=true\n```\n\nNo public signup - users must be created by admin or invited to organizations.\n\n## Feature Detection\n\nCheck if a feature is enabled in your code:\n\n```ts\n\nif (isFeatureEnabled('organizations')) {\n // Show organizations menu\n}\n\nif (isFeatureEnabled('passkey')) {\n // Offer passkey setup\n}\n```\n\n## Dynamic Feature Configuration\n\nOverride features at runtime:\n\n```ts\n\nsetAppConfig({\n features: {\n organizations: false, // Disable organizations\n passkey: true, // Enable passkey\n },\n});\n```\n\n## Testing Features\n\nFor local development, create `.env.local`:\n\n```bash title=\".env.local\"\n# Test with all features enabled\nENABLE_SIGNUP=true\nENABLE_EMAIL_VERIFICATION=true\nENABLE_PASSKEY=true\nENABLE_EMAIL_OTP=true\nENABLE_PASSWORD=true\nENABLE_ORGANIZATIONS=true\nENABLE_ADMIN=true\nVITE_ENABLE_FILE_UPLOADS=true\nDISABLE_EMAIL_STATUS_CHECK=true # Allow test emails\n```\n\n## Next Steps\n\n- **[Environment Variables](/stack/account-ui/environment-variables)** - Complete variable reference\n- **[Customization](/stack/account-ui/customization)** - Customize UI text and labels\n- **[With Quickback](/stack/account-ui/with-quickback)** - How the compiler builds Account UI into your Worker"
282
+ "content": "# Feature Flags\n\nControl which features are available in your Account UI deployment using feature flags. All features are configured via environment variables.\n\n## Authentication Features\n\n### User Signup\n\n```bash\nENABLE_SIGNUP=true # default: true\n```\n\nControls whether new users can register. Wired to the `ENABLE_SIGNUP` env var.\n\n**When enabled:**\n- Shows \"Sign Up\" link on login page\n- `/signup` route is accessible\n- New users can create accounts\n\n**When disabled:**\n- Signup route returns 404\n- Only existing users can log in\n- Useful for invite-only applications\n\n### Email Verification\n\n```bash\nENABLE_EMAIL_VERIFICATION=true # default: true\n```\n\nControls the email verification flow. Wired to the frontend via the `ENABLE_EMAIL_VERIFICATION` env var.\n\n**When enabled:**\n- Users must verify email before full access\n- Verification email sent on signup\n- \"Resend verification email\" option available\n- Unverified users see verification prompt\n\n**When disabled:**\n- Email addresses are trusted without verification\n- Users have immediate access after signup\n\n### Email Deliverability Check\n\n```bash\nDISABLE_EMAIL_STATUS_CHECK=false # default: false\n```\n\n**When `false` (checking enabled):**\n- System validates email addresses are deliverable\n- Rejects disposable/temporary email providers\n- Prevents typos in domain names\n\n**When `true` (checking disabled):**\n- Accepts all email formats\n- Useful for development/testing\n- Allows `@test.com`, `@localhost`, etc.\n\n### Passkey Login\n\n```bash\nENABLE_PASSKEY=true # default: true\n```\n\nControls passkey LOGIN only (not signup). When enabled, users can authenticate using passkeys.\n\n**When enabled:**\n- Users can register passkeys (fingerprint, Face ID, hardware keys)\n- Passwordless login option\n- \"Manage Passkeys\" page available\n\n**When disabled:**\n- No passkey registration\n- No passkey login option\n\n**Requirements:**\n- HTTPS (passkeys require secure context)\n- Modern browser with WebAuthn support\n\n### Email OTP\n\n```bash\nENABLE_EMAIL_OTP=true # default: true\n```\n\n**When enabled:**\n- Users can receive one-time passwords via email\n- Alternative to password login\n- `/email-otp` route available\n\n**When disabled:**\n- No email OTP option\n- Password or passkey required\n\n### Password Authentication\n\n```bash\nENABLE_PASSWORD=false # default: false\n```\n\n**When enabled:**\n- Email + password fields on login page\n- Password field on signup page\n- Traditional username/password authentication\n\n**When disabled:**\n- No password fields shown\n- Users authenticate via email OTP or passkey\n\n## Account Management Features\n\n### File Uploads\n\n```bash\nVITE_ENABLE_FILE_UPLOADS=false # default: false\n```\n\n**When enabled:**\n- Avatar/profile picture upload\n- Image cropping and editing\n- File upload to R2/S3\n\n**When disabled:**\n- No file upload functionality\n- Users can only use default avatars\n\n**Requirements:**\n- R2 bucket or S3 configured\n- Upload endpoints in your API\n\n## Organization Features\n\n### Organizations (Multi-Tenancy)\n\n```bash\nENABLE_ORGANIZATIONS=true # default: true\n```\n\n**When enabled:**\n- Users can create organizations\n- Organization management pages\n- Member invitations and roles\n- `/organizations/*` routes\n\n**When disabled:**\n- Single-user mode only\n- No organization features\n- Simpler user experience\n\n**Includes:**\n- Organization creation and deletion\n- Member management (owner, admin, member roles)\n- Invitation system\n- Organization settings\n\n## Admin Features\n\n### Admin Panel\n\n```bash\nENABLE_ADMIN=true # default: true\n```\n\n**When enabled:**\n- `/admin` route accessible to admin users\n- User management dashboard\n- Subscription management\n- Admin-only features:\n - Create users manually\n - Ban/unban users\n - Reset user passwords\n - View all sessions\n - Manage subscriptions\n\n**When disabled:**\n- No admin panel\n- Admin must use database directly\n\n**Requirements:**\n- User must have admin role in database\n\n## Feature Combinations\n\n### Minimal Configuration (Password-Only)\n\n```bash\nENABLE_PASSKEY=false\nENABLE_EMAIL_OTP=false\nENABLE_PASSWORD=true\nENABLE_ORGANIZATIONS=false\nENABLE_ADMIN=false\n```\n\nSimple email/password authentication for apps that do not need advanced auth methods.\n\n### Maximum Security\n\n```bash\nENABLE_PASSKEY=true\nENABLE_EMAIL_OTP=true\nENABLE_PASSWORD=false\nENABLE_EMAIL_VERIFICATION=true\n```\n\nAll authentication methods with email verification and deliverability checks.\n\n### Multi-Tenant SaaS\n\n```bash\nENABLE_PASSKEY=true\nENABLE_EMAIL_OTP=true\nENABLE_ORGANIZATIONS=true\nENABLE_ADMIN=true\n```\n\nFull-featured SaaS with organizations, teams, and admin panel.\n\n### Invite-Only Platform\n\n```bash\nENABLE_SIGNUP=false\nENABLE_PASSKEY=true\nENABLE_ORGANIZATIONS=true\nENABLE_ADMIN=true\n```\n\nNo public signup - users must be created by admin or invited to organizations.\n\n## Feature Detection\n\nCheck if a feature is enabled in your code:\n\n```ts\n\nif (isFeatureEnabled('organizations')) {\n // Show organizations menu\n}\n\nif (isFeatureEnabled('passkey')) {\n // Offer passkey setup\n}\n```\n\n## Dynamic Feature Configuration\n\nOverride features at runtime:\n\n```ts\n\nsetAppConfig({\n features: {\n organizations: false, // Hide organization-management UI\n passkey: true, // Enable passkey\n },\n});\n```\n\n## Testing Features\n\nFor local development, create `.env.local`:\n\n```bash title=\".env.local\"\n# Test with all features enabled\nENABLE_SIGNUP=true\nENABLE_EMAIL_VERIFICATION=true\nENABLE_PASSKEY=true\nENABLE_EMAIL_OTP=true\nENABLE_PASSWORD=true\nENABLE_ORGANIZATIONS=true\nENABLE_ADMIN=true\nVITE_ENABLE_FILE_UPLOADS=true\nDISABLE_EMAIL_STATUS_CHECK=true # Allow test emails\n```\n\n## Next Steps\n\n- **[Environment Variables](/stack/account-ui/environment-variables)** - Complete variable reference\n- **[Customization](/stack/account-ui/customization)** - Customize UI text and labels\n- **[With Quickback](/stack/account-ui/with-quickback)** - How the compiler builds Account UI into your Worker"
263
283
  },
264
284
  "stack/account-ui/features/organizations": {
265
285
  "title": "Organizations",
@@ -347,7 +367,7 @@ export const DOCS = {
347
367
  },
348
368
  "stack/cms/connecting": {
349
369
  "title": "Connecting",
350
- "content": "# Connecting\n\nThe CMS supports two modes: **demo mode** for development and testing, and **live mode** for connecting to a real Quickback API.\n\n## Demo Mode\n\nWhen no `VITE_QUICKBACK_API_URL` is set, the CMS runs in demo mode:\n\n- Uses a **mock API client** backed by `localStorage`\n- Loads seed data from JSON files in `data/mock/`\n- Provides a **role switcher** in the header to test owner/admin/member access\n- Simulates authentication sessions without a real backend\n\nDemo mode is useful for prototyping your schema, testing guard behavior across roles, and verifying masking rules before deploying.\n\n```bash title=\".env.development\"\n# No VITE_QUICKBACK_API_URL — CMS runs in demo mode\n```\n\n### Mock Data\n\nPlace JSON files in `data/mock/` matching your table names:\n\n```\ndata/mock/\n contact.json # Array of contact records\n project.json # Array of project records\n invoice.json # Array of invoice records\n _meta.json # Mock session and org metadata\n```\n\nEach file contains an array of records. The mock client loads them on startup and persists changes to `localStorage`.\n\n### Role Switcher\n\nIn demo mode, the header displays a role switcher dropdown allowing you to switch between `owner`, `admin`, and `member` roles in real time. This lets you verify:\n\n- Which CRUD buttons appear per role\n- Which form fields are editable\n- Which masking rules apply\n- Which actions are available\n- Which views are accessible\n\n## Live Mode\n\nSet `VITE_QUICKBACK_API_URL` to connect to a real Quickback API:\n\n```bash title=\".env.production\"\nVITE_QUICKBACK_API_URL=https://api.example.com\n```\n\nIn live mode, the CMS:\n\n- Reads the **Better Auth session** from cookies\n- Fetches the user's **organization membership** and role\n- Makes real API calls to the Quickback backend for all CRUD operations\n- Applies server-side security (firewall, guards, masking) in addition to client-side UI filtering\n\n## API Client Interface\n\nThe CMS communicates with the backend through a standard interface:\n\n```typescript\ninterface IApiClient {\n list(table: string, params?: ListParams): Promise\n\n## How the Client is Created\n\nThe CMS auto-creates the API client based on configuration:\n\n1. **No `VITE_QUICKBACK_API_URL`** — Instantiates the mock client, loads seed data from `data/mock/`, and uses `localStorage` for persistence.\n2. **`VITE_QUICKBACK_API_URL` is set** — Instantiates the live client, reads the auth session cookie, and makes fetch requests to the Quickback API using the standard REST endpoints (`/api/v1/{table}`).\n\nThe client is provided via React context (`ApiClientContext`) and available throughout the component tree.\n\n## Embedded Mode (Recommended)\n\nSet `cms: true` in your config to embed the CMS directly in your compiled Worker:\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default defineConfig({\n name: \"my-app\",\n cms: true,\n // ...providers\n});\n```\n\nWhen you run `quickback compile`, the CLI:\n1. Builds the CMS SPA from source and places assets in `src/apps/cms/`\n2. Adds `[assets]` config to `wrangler.toml` with `run_worker_first = true`\n3. Generates Worker routing to serve the CMS SPA\n\nRun `wrangler dev` and the CMS is served at `/cms/`. API routes (`/api/*`, `/auth/*`, etc.) pass through to your Hono app. Same origin — no CORS, auth cookies work naturally. On a custom domain, the CMS is served at root (`/`).\n\n### Custom CMS Domain\n\nOptionally serve the CMS on a separate subdomain:\n\n```typescript\ncms: { domain: \"cms.example.com\" }\n```\n\nThis adds a custom domain route to `wrangler.toml`. Both `api.example.com` and `cms.example.com` point to the same Worker. The compiler auto-configures hostname-based routing and cross-subdomain cookies.\n\nCMS access defaults to `access: \"admin\"` — only `user.role === \"admin\"` (the Better Auth platform-admin tier) can reach `/cms/*`. Non-admin authenticated users are redirected to `/account/profile`. The gate is enforced at multiple layers:\n\n- **Account UI** hides the \"Go to CMS\" button for non-admins.\n- **CMS SPA shell** — the Worker returns `403` (or redirects unauthenticated requests to login) before serving `index.html` to a non-admin. A non-admin who types the CMS URL directly cannot load the app.\n- **`/api/v1/schema`** returns `403 Admin access required` to non-admin callers, so schema metadata can't be scraped by hitting the API directly.\n- **`custom_view` routes** are gated on `userRole: [\"admin\"]` rather than org membership, so saved views can't be listed or modified without admin rights.\n- **In-SPA gate** — if any earlier layer is bypassed, the SPA still redirects the user to `/account/profile`.\n\nYour resource API endpoints (the ones generated for your features) are unaffected — they continue to use the per-resource `read`, `create`, `update`, `delete`, and `upsert` access rules you defined.\n\nTo allow any authenticated user to access the CMS, opt out explicitly:\n\n```typescript\ncms: { access: \"user\" }\n```\n\nSee [Multi-Domain Architecture](/compiler/config/domains) for details on multi-domain routing.\n\n## Multi-Tenant vs Single-Tenant\n\nThe CMS supports two authentication modes depending on your project's organization configuration.\n\n### Multi-Tenant (Default)\n\nIn multi-tenant mode, the CMS gates access behind organization membership:\n\n1. User logs in via Better Auth session\n2. CMS fetches the user's organization memberships\n3. If the user belongs to multiple organizations, an **org selector** is displayed\n4. Once an org is selected, the user's role within that org determines their CMS permissions\n\nThis is the default behavior for all Quickback projects.\n\n### Single-Tenant Mode\n\nWhen your project disables organizations (`features.organizations: false` in config), the compiler sets `singleTenant: true` in the schema registry. In this mode:\n\n- No org gate or org selector is shown\n- The user's role is read directly from `user.role` on the session\n- All data is unscoped (no `organizationId` filtering)\n\nSingle-tenant mode is useful for internal tools, personal projects, or apps that don't need multi-org isolation.\n\n## Next Steps\n\n- **[Table Views](/stack/cms/table-views)** — Browse and Data Table view modes\n- **[Security](/stack/cms/security)** — How roles, guards, and masking work in the CMS"
370
+ "content": "# Connecting\n\nThe CMS supports two modes: **demo mode** for development and testing, and **live mode** for connecting to a real Quickback API.\n\n## Demo Mode\n\nWhen no `VITE_QUICKBACK_API_URL` is set, the CMS runs in demo mode:\n\n- Uses a **mock API client** backed by `localStorage`\n- Loads seed data from JSON files in `data/mock/`\n- Provides a **role switcher** in the header to test owner/admin/member access\n- Simulates authentication sessions without a real backend\n\nDemo mode is useful for prototyping your schema, testing guard behavior across roles, and verifying masking rules before deploying.\n\n```bash title=\".env.development\"\n# No VITE_QUICKBACK_API_URL — CMS runs in demo mode\n```\n\n### Mock Data\n\nPlace JSON files in `data/mock/` matching your table names:\n\n```\ndata/mock/\n contact.json # Array of contact records\n project.json # Array of project records\n invoice.json # Array of invoice records\n _meta.json # Mock session and org metadata\n```\n\nEach file contains an array of records. The mock client loads them on startup and persists changes to `localStorage`.\n\n### Role Switcher\n\nIn demo mode, the header displays a role switcher dropdown allowing you to switch between `owner`, `admin`, and `member` roles in real time. This lets you verify:\n\n- Which CRUD buttons appear per role\n- Which form fields are editable\n- Which masking rules apply\n- Which actions are available\n- Which views are accessible\n\n## Live Mode\n\nSet `VITE_QUICKBACK_API_URL` to connect to a real Quickback API:\n\n```bash title=\".env.production\"\nVITE_QUICKBACK_API_URL=https://api.example.com\n```\n\nIn live mode, the CMS:\n\n- Reads the **Better Auth session** from cookies\n- Fetches the user's **organization membership** and role\n- Makes real API calls to the Quickback backend for all CRUD operations\n- Applies server-side security (firewall, guards, masking) in addition to client-side UI filtering\n\n## API Client Interface\n\nThe CMS communicates with the backend through a standard interface:\n\n```typescript\ninterface IApiClient {\n list(table: string, params?: ListParams): Promise\n\n## How the Client is Created\n\nThe CMS auto-creates the API client based on configuration:\n\n1. **No `VITE_QUICKBACK_API_URL`** — Instantiates the mock client, loads seed data from `data/mock/`, and uses `localStorage` for persistence.\n2. **`VITE_QUICKBACK_API_URL` is set** — Instantiates the live client, reads the auth session cookie, and makes fetch requests to the Quickback API using the standard REST endpoints (`/api/v1/{table}`).\n\nThe client is provided via React context (`ApiClientContext`) and available throughout the component tree.\n\n## Embedded Mode (Recommended)\n\nSet `cms: true` in your config to embed the CMS directly in your compiled Worker:\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default defineConfig({\n name: \"my-app\",\n cms: true,\n // ...providers\n});\n```\n\nWhen you run `quickback compile`, the CLI:\n1. Builds the CMS SPA from source and places assets in `src/apps/cms/`\n2. Adds `[assets]` config to `wrangler.toml` with `run_worker_first = true`\n3. Generates Worker routing to serve the CMS SPA\n\nRun `wrangler dev` and the CMS is served at `/cms/`. API routes (`/api/*`, `/auth/*`, etc.) pass through to your Hono app. Same origin — no CORS, auth cookies work naturally. On a custom domain, the CMS is served at root (`/`).\n\n### Custom CMS Domain\n\nOptionally serve the CMS on a separate subdomain:\n\n```typescript\ncms: { domain: \"cms.example.com\" }\n```\n\nThis adds a custom domain route to `wrangler.toml`. Both `api.example.com` and `cms.example.com` point to the same Worker. The compiler auto-configures hostname-based routing and cross-subdomain cookies.\n\nCMS access defaults to `access: \"admin\"` — only `user.role === \"appmanager\"` (the Better Auth platform control-plane tier) can reach `/cms/*`. When `cms.sysadmin: true`, `user.role === \"sysadmin\"` is also admitted. Other authenticated users are redirected to `/account/profile`. The gate is enforced at multiple layers:\n\n- **Account UI** hides the \"Go to CMS\" button for callers outside those roles.\n- **CMS SPA shell** — the Worker returns `403` (or redirects unauthenticated requests to login) before serving `index.html` to a non-operator. A non-operator who types the CMS URL directly cannot load the app.\n- **`/api/v1/schema`** returns `403 Platform operator access required` to callers outside those roles, so schema metadata can't be scraped by hitting the API directly.\n- **`custom_view` routes** are gated on `userRole: [\"appmanager\"]` rather than org membership, so saved views can't be listed or modified without platform-control-plane rights.\n- **In-SPA gate** — if any earlier layer is bypassed, the SPA still redirects the user to `/account/profile`.\n\nYour resource API endpoints (the ones generated for your features) are unaffected — they continue to use the per-resource `read`, `create`, `update`, `delete`, and `upsert` access rules you defined.\n\nTo allow any authenticated user to access the CMS, opt out explicitly:\n\n```typescript\ncms: { access: \"user\" }\n```\n\nSee [Multi-Domain Architecture](/compiler/config/domains) for details on multi-domain routing.\n\n## Default Org Mode vs Pinned Organization Mode\n\nThe CMS supports two organization flows depending on your project's config.\n\n### Default Org Mode\n\nBy default, the CMS gates access behind organization membership:\n\n1. User logs in via Better Auth session\n2. CMS fetches the user's organization memberships\n3. If the user belongs to multiple organizations, an **org selector** is displayed\n4. Once an org is selected, the user's role within that org determines their CMS permissions\n\nThis is the default behavior for Quickback projects with no pinned org.\n\n### Pinned Organization Mode\n\nWhen your project sets `features.pinnedOrganizationId`, the CMS keeps org-backed auth but fixes the active org at runtime. In this mode:\n\n- No org selector is shown\n- The org gate is bypassed because the active org is known up front\n- The user's `roles` still come from membership in the pinned org\n- Org-scoped data remains scoped by `organizationId`\n\nPinned organization mode is useful for internal tools, blogs, and one-customer deployments that still want org-backed roles and schema conventions without runtime org switching.\n\n## Next Steps\n\n- **[Table Views](/stack/cms/table-views)** — Browse and Data Table view modes\n- **[Security](/stack/cms/security)** — How roles, guards, and masking work in the CMS"
351
371
  },
352
372
  "stack/cms/dashboard": {
353
373
  "title": "Dashboard",
@@ -355,7 +375,7 @@ export const DOCS = {
355
375
  },
356
376
  "stack/cms": {
357
377
  "title": "Quickback CMS",
358
- "content": "# Quickback CMS\n\nA schema-driven admin interface that reads `schema-registry.json` generated by the Quickback compiler. Every table, column, action, view, and security rule is rendered automatically. Zero UI code per table.\n\n## Overview\n\nThe CMS generates its entire UI from your Quickback definitions. Define a table with columns, guards, masking, views, and actions in your feature files. Run the compiler. The CMS reads the resulting schema registry and renders a complete admin interface — data tables, inline editing, action dialogs, role-based access, and field masking — all without writing a single line of UI code.\n\n## Key Features\n\n- **Schema-driven** — Zero UI code per table. Add a table, recompile, and it appears in the CMS.\n- **Dashboard** — Stats grid and feature cards showing tables, columns, actions, views, and masked fields at a glance.\n- **Custom pages** — Split-panel layouts with drag-and-drop, matching engine, and page-level actions for workflows like reconciliation.\n- **Embedded in your Worker** — Set `cms: true` in config. The CMS is served as static assets from the same Cloudflare Worker as your API — same origin, no CORS, auth cookies work naturally.\n- **Dual view modes** — Table browse mode for navigation and Data Table mode for spreadsheet-style editing.\n- **Role-based access** — Owner, admin, and member roles with live switching. CRUD buttons hidden when unauthorized.\n- **Multi-tenant & single-tenant** — Org-scoped access by default, with single-tenant mode for simpler projects.\n- **Inline spreadsheet editing** — Excel/Google Sheets-like editing with keyboard navigation (arrows, Tab, Enter, Escape).\n- **FK typeahead** — Server-side search for foreign key fields with debounced queries and keyboard navigation.\n- **Field masking** — Email, phone, SSN, and redaction patterns applied per role. Masked fields show a lock icon.\n- **Custom actions** — Action dialogs with auto-generated input forms, access filtering, CMS metadata (icons, categories, confirmations), and side effects warnings.\n- **Views** — Named column-level projections per role. \"All Fields\" plus custom views in the toolbar.\n- **Auto-form generation** — Create and edit forms built from guards (createable/updatable fields).\n- **Display column auto-detection** — FK labels resolved automatically from `name`, `title`, `label`, `code`, and other common patterns.\n\n## Architecture\n\nThe CMS sits at the end of the Quickback compilation pipeline:\n\n```\nQuickback Definitions (feature files)\n |\n v\n Compiler\n |\n v\n schema-registry.json\n |\n v\n CMS reads it\n |\n v\n Renders admin UI\n```\n\nYour feature definitions are the single source of truth. The compiler extracts all metadata — columns, types, guards, masking rules, views, actions, validation, and firewall config — into a static JSON file. The CMS consumes that file and renders the appropriate UI for each table.\n\n### How Embedded Serving Works\n\nWhen `cms: true` is set, the compiler builds the CMS SPA from source at compile time (with your project-specific env vars baked in) and outputs the assets to `src/apps/cms/`. It also configures `wrangler.toml`:\n\n```toml\n[assets]\nbinding = \"ASSETS\"\ndirectory = \"src/apps\"\nnot_found_handling = \"none\"\nrun_worker_first = true\n```\n\nAll requests go through the Worker first. The Worker handles SPA routing — serving CMS at `/cms/` on the unified domain and at root (`/`) on a custom CMS domain. API paths (`/api/*`, `/auth/*`, etc.) are handled by Hono as normal.\n\nSee [Multi-Domain Architecture](/compiler/config/domains) for details on hostname-based routing.\n\n## Quick Start\n\n### 1. Enable CMS in config\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default defineConfig({\n name: \"my-app\",\n cms: true,\n // ...providers\n});\n```\n\n### 2. Compile\n\n```bash\nquickback compile\n```\n\nThe compiler generates `schema-registry.json` and copies CMS static assets to `src/apps/`. It also adds an `[assets]` section to `wrangler.toml` so Cloudflare serves the CMS SPA automatically.\n\n### 3. Run\n\n```bash\nnpm run dev\n```\n\nOpen your Worker URL in a browser — the CMS is served at the root. API routes (`/api/*`, `/auth/*`, etc.) pass through to your Hono app as normal. Everything runs on the same origin — no CORS configuration needed, auth cookies work naturally.\n\n### Optional: Custom CMS domain\n\n```typescript\ncms: { domain: \"cms.example.com\" }\n```\n\nThis adds a custom domain route to `wrangler.toml`. Both domains serve the same Worker — `api.example.com` for the API, `cms.example.com` for the CMS. The compiler also auto-infers a unified `quickback.example.com` domain where everything is available. See [Multi-Domain Architecture](/compiler/config/domains).\n\n### Access gate (admin-only by default)\n\nCMS access defaults to `access: \"admin\"` — only `user.role === \"admin\"` (the user-table role from Better Auth's admin plugin) can reach `/cms/*`. Non-admin authenticated users are redirected to `/account/profile`. The gate is enforced at **four layers** — defense in depth:\n\n1. **Account UI link** — the \"Go to CMS\" button is hidden for non-admins.\n2. **CMS SPA shell** — the Worker returns `403 Admin access required` before serving `index.html` to a non-admin. Unauthenticated requests are redirected to the login page.\n3. **`/api/v1/schema`** — the CMS metadata endpoint checks `ctx.userRole === \"admin\"` and returns `403` otherwise.\n4. **`custom_view` routes** — the CMS-internal saved-views table is gated on `userRole: [\"admin\"]` (see the [`userRole` access primitive](/compiler/definitions/access#userrole)) rather than org membership.\n\nYour resource API endpoints (`/api/v1/<resource>`) are **not** affected — they continue to use the per-resource `read`, `create`, `update`, `delete`, and `upsert` access rules you defined.\n\nTo allow any authenticated user, opt out explicitly:\n\n```typescript\ncms: { access: \"user\" }\n```\n\n### Optional: Skip SPA rebuild\n\nAfter the first compile, you can skip rebuilding the CMS SPA on subsequent compiles:\n\n```typescript\ncms: { build: false }\n```\n\nThis is useful when you're iterating on API features and don't need to rebuild the CMS UI each time — it saves significant compile time. Set `build: true` (or omit it) when you need to update the CMS assets.\n\n### Optional: Custom output directory\n\n```typescript\ncms: { outputDir: \"my-custom-path/cms\" }\n```\n\nThis changes where the compiled CMS assets are placed (relative to project root), instead of the default `src/apps/cms/`.\n\n## Next Steps\n\n- **[Schema Registry](/stack/cms/schema-registry)** — Understand the JSON format the compiler generates\n- **[Connecting](/stack/cms/connecting)** — Demo mode, live mode, CLI command, and auth modes\n- **[Dashboard](/stack/cms/dashboard)** — Stats grid and feature navigation\n- **[Table Views](/stack/cms/table-views)** — Browse and Data Table view modes\n- **[Custom Pages](/stack/cms/pages)** — Split-panel layouts, matching engine, and drag-drop\n- **[Inline Editing](/stack/cms/inline-editing)** — Spreadsheet-style editing and FK typeahead\n- **[Security](/stack/cms/security)** — How the CMS enforces all four security layers\n- **[Actions](/stack/cms/actions)** — Custom actions with input forms, access filtering, and CMS metadata\n- **[Schema Format Reference](/stack/cms/schema-format)** — Full TypeScript types for schema-registry.json\n- **[Components Reference](/stack/cms/components)** — All CMS components and their props"
378
+ "content": "# Quickback CMS\n\nA schema-driven admin interface that reads `schema-registry.json` generated by the Quickback compiler. Every table, column, action, view, and security rule is rendered automatically. Zero UI code per table.\n\n## Overview\n\nThe CMS generates its entire UI from your Quickback definitions. Define a table with columns, guards, masking, views, and actions in your feature files. Run the compiler. The CMS reads the resulting schema registry and renders a complete admin interface — data tables, inline editing, action dialogs, role-based access, and field masking — all without writing a single line of UI code.\n\n## Key Features\n\n- **Schema-driven** — Zero UI code per table. Add a table, recompile, and it appears in the CMS.\n- **Dashboard** — Stats grid and feature cards showing tables, columns, actions, views, and masked fields at a glance.\n- **Custom pages** — Split-panel layouts with drag-and-drop, matching engine, and page-level actions for workflows like reconciliation.\n- **Embedded in your Worker** — Set `cms: true` in config. The CMS is served as static assets from the same Cloudflare Worker as your API — same origin, no CORS, auth cookies work naturally.\n- **Dual view modes** — Table browse mode for navigation and Data Table mode for spreadsheet-style editing.\n- **Role-based access** — Owner, admin, and member roles with live switching. CRUD buttons hidden when unauthorized.\n- **Multi-tenant & fixed-org** — Org-scoped access by default, with pinned-organization mode for simpler deployments.\n- **Inline spreadsheet editing** — Excel/Google Sheets-like editing with keyboard navigation (arrows, Tab, Enter, Escape).\n- **FK typeahead** — Server-side search for foreign key fields with debounced queries and keyboard navigation.\n- **Field masking** — Email, phone, SSN, and redaction patterns applied per role. Masked fields show a lock icon.\n- **Custom actions** — Action dialogs with auto-generated input forms, access filtering, CMS metadata (icons, categories, confirmations), and side effects warnings.\n- **Views** — Named column-level projections per role. \"All Fields\" plus custom views in the toolbar.\n- **Auto-form generation** — Create and edit forms built from guards (createable/updatable fields).\n- **Display column auto-detection** — FK labels resolved automatically from `name`, `title`, `label`, `code`, and other common patterns.\n\n## Architecture\n\nThe CMS sits at the end of the Quickback compilation pipeline:\n\n```\nQuickback Definitions (feature files)\n |\n v\n Compiler\n |\n v\n schema-registry.json\n |\n v\n CMS reads it\n |\n v\n Renders admin UI\n```\n\nYour feature definitions are the single source of truth. The compiler extracts all metadata — columns, types, guards, masking rules, views, actions, validation, and firewall config — into a static JSON file. The CMS consumes that file and renders the appropriate UI for each table.\n\n### How Embedded Serving Works\n\nWhen `cms: true` is set, the compiler builds the CMS SPA from source at compile time (with your project-specific env vars baked in) and outputs the assets to `src/apps/cms/`. It also configures `wrangler.toml`:\n\n```toml\n[assets]\nbinding = \"ASSETS\"\ndirectory = \"src/apps\"\nnot_found_handling = \"none\"\nrun_worker_first = true\n```\n\nAll requests go through the Worker first. The Worker handles SPA routing — serving CMS at `/cms/` on the unified domain and at root (`/`) on a custom CMS domain. API paths (`/api/*`, `/auth/*`, etc.) are handled by Hono as normal.\n\nSee [Multi-Domain Architecture](/compiler/config/domains) for details on hostname-based routing.\n\n## Quick Start\n\n### 1. Enable CMS in config\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default defineConfig({\n name: \"my-app\",\n cms: true,\n // ...providers\n});\n```\n\n### 2. Compile\n\n```bash\nquickback compile\n```\n\nThe compiler generates `schema-registry.json` and copies CMS static assets to `src/apps/`. It also adds an `[assets]` section to `wrangler.toml` so Cloudflare serves the CMS SPA automatically.\n\n### 3. Run\n\n```bash\nnpm run dev\n```\n\nOpen your Worker URL in a browser — the CMS is served at the root. API routes (`/api/*`, `/auth/*`, etc.) pass through to your Hono app as normal. Everything runs on the same origin — no CORS configuration needed, auth cookies work naturally.\n\n### Optional: Custom CMS domain\n\n```typescript\ncms: { domain: \"cms.example.com\" }\n```\n\nThis adds a custom domain route to `wrangler.toml`. Both domains serve the same Worker — `api.example.com` for the API, `cms.example.com` for the CMS. The compiler also auto-infers a unified `quickback.example.com` domain where everything is available. See [Multi-Domain Architecture](/compiler/config/domains).\n\n### Access gate (platform-control-plane by default)\n\nCMS access defaults to `access: \"admin\"` — only `user.role === \"appmanager\"` (the user-table platform control-plane role) can reach `/cms/*`. When `cms.sysadmin: true`, `user.role === \"sysadmin\"` is also admitted. Other authenticated users are redirected to `/account/profile`. The gate is enforced at **four layers** — defense in depth:\n\n1. **Account UI link** — the \"Go to CMS\" button is hidden for callers outside those roles.\n2. **CMS SPA shell** — the Worker returns `403 Platform operator access required` before serving `index.html` to a non-operator. Unauthenticated requests are redirected to the login page.\n3. **`/api/v1/schema`** — the CMS metadata endpoint checks `ctx.userRole === \"appmanager\"` (and admits `sysadmin` when enabled) and returns `403` otherwise.\n4. **`custom_view` routes** — the CMS-internal saved-views table is gated on `userRole: [\"appmanager\"]` (see the [`userRole` access primitive](/compiler/definitions/access#userrole)) rather than org membership.\n\nYour resource API endpoints (`/api/v1/<resource>`) are **not** affected — they continue to use the per-resource `read`, `create`, `update`, `delete`, and `upsert` access rules you defined.\n\nTo allow any authenticated user, opt out explicitly:\n\n```typescript\ncms: { access: \"user\" }\n```\n\n### Optional: Skip SPA rebuild\n\nAfter the first compile, you can skip rebuilding the CMS SPA on subsequent compiles:\n\n```typescript\ncms: { build: false }\n```\n\nThis is useful when you're iterating on API features and don't need to rebuild the CMS UI each time — it saves significant compile time. Set `build: true` (or omit it) when you need to update the CMS assets.\n\n### Optional: Custom output directory\n\n```typescript\ncms: { outputDir: \"my-custom-path/cms\" }\n```\n\nThis changes where the compiled CMS assets are placed (relative to project root), instead of the default `src/apps/cms/`.\n\n## Next Steps\n\n- **[Schema Registry](/stack/cms/schema-registry)** — Understand the JSON format the compiler generates\n- **[Connecting](/stack/cms/connecting)** — Demo mode, live mode, CLI command, and auth modes\n- **[Dashboard](/stack/cms/dashboard)** — Stats grid and feature navigation\n- **[Table Views](/stack/cms/table-views)** — Browse and Data Table view modes\n- **[Custom Pages](/stack/cms/pages)** — Split-panel layouts, matching engine, and drag-drop\n- **[Inline Editing](/stack/cms/inline-editing)** — Spreadsheet-style editing and FK typeahead\n- **[Security](/stack/cms/security)** — How the CMS enforces all four security layers\n- **[Actions](/stack/cms/actions)** — Custom actions with input forms, access filtering, and CMS metadata\n- **[Schema Format Reference](/stack/cms/schema-format)** — Full TypeScript types for schema-registry.json\n- **[Components Reference](/stack/cms/components)** — All CMS components and their props"
359
379
  },
360
380
  "stack/cms/inline-editing": {
361
381
  "title": "Inline Editing",
@@ -371,15 +391,15 @@ export const DOCS = {
371
391
  },
372
392
  "stack/cms/schema-format": {
373
393
  "title": "Schema Format Reference",
374
- "content": "# Schema Format Reference\n\nThe schema registry is a JSON file with a well-defined structure. Below are the complete TypeScript type definitions used by both the compiler (to generate) and the CMS (to consume).\n\n## SchemaRegistry\n\nThe top-level type:\n\n```typescript\ninterface SchemaRegistry {\n generatedAt: string;\n generatedBy: string;\n version: string;\n singleTenant?: boolean;\n features: Record<string, string[]>;\n tables: Record<string, TableMeta>;\n tablesByFeature: Record<string, string[]>;\n featureActions: Record<string, ActionMeta[]>;\n pages: Record<string, PageMeta>;\n pagesByFeature: Record<string, string[]>;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `generatedAt` | ISO 8601 timestamp of when the registry was generated |\n| `generatedBy` | Always `\"quickback-compiler\"` |\n| `version` | Compiler version string |\n| `singleTenant` | When `true`, project has no organization layer (single-tenant mode) |\n| `features` | Map of feature name to array of source file names |\n| `tables` | Map of camelCase table name to full table metadata |\n| `tablesByFeature` | Map of feature name to array of table names in that feature |\n| `featureActions` | Map of feature name to standalone actions not attached to one table |\n| `pages` | Map of page slug to full page metadata |\n| `pagesByFeature` | Map of feature name to array of page slugs in that feature |\n\n## TableMeta\n\nFull metadata for a single table:\n\n```typescript\ninterface TableMeta {\n name: string;\n dbName: string;\n feature: string;\n columns: ColumnMeta[];\n firewall: Record<string, unknown>;\n crud: Record<string, CrudConfig>;\n create?: WriteOperationConfig | false;\n update?: WriteOperationConfig | false;\n delete?: WriteOperationConfig | false;\n upsert?: WriteOperationConfig | false;\n guards: GuardsConfig;\n masking: Record<string, MaskingRule>;\n views: Record<string, ViewConfig>;\n validation: Record<string, ValidationRule>;\n actions: ActionMeta[];\n displayColumn?: string;\n defaultSort?: { field: string; order: 'asc' | 'desc' };\n inputHints?: Record<string, string>;\n layouts?: Record<string, CmsLayout>;\n internal?: boolean;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `name` | camelCase table name (e.g., `\"accountCode\"`) |\n| `dbName` | Snake_case SQL table name (e.g., `\"account_code\"`) |\n| `feature` | Parent feature name (e.g., `\"accounting\"`) |\n| `columns` | Ordered array of column metadata |\n| `firewall` | Tenant isolation config (organization, owner, softDelete, exception) |\n| `crud` | Legacy normalized write config kept for backwards compatibility |\n| `create` / `update` / `delete` / `upsert` | Flat write-operation aliases mirroring the authored `defineTable(...)` DSL |\n| `guards` | Field-level create/update/immutable/protected rules |\n| `masking` | Per-field masking rules keyed by column name |\n| `views` | Named column projections keyed by view name |\n| `validation` | Per-field validation rules keyed by column name |\n| `actions` | Array of action definitions scoped to this table |\n| `displayColumn` | Column used as human-readable label (auto-detected or explicit) |\n| `defaultSort` | Default sort for CMS table list view (e.g., `{ field: \"createdAt\", order: \"desc\" }`) |\n| `inputHints` | Map of column name to preferred CMS input type (e.g., `\"richtext\"`, `\"select\"`, `\"textarea\"`, `\"checkbox\"`) |\n| `layouts` | Named record page layouts keyed by layout name (see CmsLayout below) |\n| `internal` | When `true`, table is hidden from CMS sidebar |\n\n## ColumnMeta\n\nMetadata for a single column:\n\n```typescript\ninterface ColumnMeta {\n name: string;\n dbName: string;\n type: \"text\" | \"integer\" | \"real\" | \"blob\";\n mode?: \"boolean\";\n primaryKey: boolean;\n notNull: boolean;\n defaultValue?: string | number | boolean;\n fkTarget?: string;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `name` | camelCase property name |\n| `dbName` | Snake_case SQL column name |\n| `type` | SQLite storage type |\n| `mode` | When `\"boolean\"`, an integer column represents true/false |\n| `primaryKey` | Whether this column is the primary key |\n| `notNull` | Whether the column has a NOT NULL constraint |\n| `defaultValue` | Static default value (strings, numbers, or booleans) |\n| `fkTarget` | Target table name for FK columns (e.g., `\"contact\"` for a `vendorId` column) |\n\n## CRUDConfig\n\nPer-operation access control:\n\n```typescript\ninterface CrudConfig {\n access?: AccessRule;\n mode?: string;\n}\n\ninterface WriteOperationConfig extends CrudConfig {\n defaults?: Record<string, unknown>;\n computed?: Record<string, unknown>;\n fields?: string[];\n maxBatchSize?: number;\n allowFailFast?: boolean;\n batch?: false | Record<string, unknown>;\n}\n\ninterface AccessRule {\n roles?: string[];\n or?: Array<{\n roles?: string[];\n record?: Record<string, unknown>;\n }>;\n record?: Record<string, unknown>;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `access.roles` | Array of roles allowed for this operation |\n| `access.or` | Alternative access conditions (any must match) |\n| `access.record` | Record-level conditions for access |\n| `mode` | Operation mode (e.g., `\"batch\"` for bulk create) |\n| `defaults` / `computed` | Create-time defaults and computed field metadata |\n| `maxBatchSize` / `allowFailFast` | Batch-write controls when the config describes a batch operation |\n| `batch` | Nested batch config for the flat `create` / `update` / `delete` / `upsert` aliases |\n\n## GuardsConfig\n\nField-level control for create and update operations:\n\n```typescript\ninterface GuardsConfig {\n createable: string[];\n updatable: string[];\n immutable: string[];\n protected: Record<string, string[]>;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `createable` | Fields that can be set during record creation |\n| `updatable` | Fields that can be modified on existing records |\n| `immutable` | Fields that can be set on create but never changed |\n| `protected` | Fields only modifiable via named actions (field name to action names) |\n\n## ActionMeta\n\nMetadata for a custom action:\n\n```typescript\ninterface ActionMeta {\n name: string;\n description: string;\n inputFields: ActionInputField[];\n access?: {\n roles: string[];\n record?: Record<string, unknown>;\n };\n standalone?: boolean;\n path?: string;\n method?: string;\n responseType?: string;\n sideEffects?: string;\n cms?: CmsConfig;\n}\n\ninterface CmsConfig {\n label?: string;\n icon?: string;\n confirm?: string | boolean;\n destructive?: boolean;\n category?: string;\n hidden?: boolean;\n placement?: 'feature' | 'tables';\n tables?: string[];\n successMessage?: string;\n onSuccess?: 'refresh' | 'redirect:list' | 'close';\n order?: number;\n}\n\ninterface ActionInputField {\n name: string;\n type: string;\n required: boolean;\n default?: unknown;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `name` | Action identifier (e.g., `\"approve\"`, `\"applyPayment\"`) |\n| `description` | Human-readable description shown in dialog |\n| `inputFields` | Array of input field definitions |\n| `access.roles` | Roles allowed to execute this action |\n| `access.record` | Record conditions (e.g., `{ status: { equals: \"pending\" } }`) |\n| `standalone` | When `true`, action is not tied to a specific record |\n| `path` | Custom API path (overrides default) |\n| `method` | HTTP method (defaults to POST) |\n| `responseType` | `\"file\"` for download responses |\n| `sideEffects` | `\"sync\"` for actions with synchronous side effects |\n| `cms` | Optional CMS rendering metadata (label, icon, confirm, destructive, category, hidden, placement, tables, successMessage, onSuccess, order) |\n\n### CmsConfig placement rules\n\n`placement` is only relevant for standalone actions in multi-table features:\n\n- `\"feature\"` shows the action in the toolbar for every table in the feature.\n- `\"tables\"` shows the action only for the tables listed in `tables`.\n\nIf the action is already unambiguously table-scoped, the compiler can infer placement and `placement` is optional.\n\n### ActionInputField\n\n| Field | Description |\n|-------|-------------|\n| `name` | Field identifier |\n| `type` | Zod type string: `\"string\"`, `\"number\"`, `\"boolean\"`, `\"array<string>\"` |\n| `required` | Whether the field must be provided |\n| `default` | Default value pre-filled in the form |\n\n## ViewConfig\n\nNamed column projection with access control:\n\n```typescript\ninterface ViewConfig {\n fields: string[];\n access: AccessRule;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `fields` | Array of column names to include in this view |\n| `access` | Role-based access rules (same shape as CrudConfig access) |\n\n## CmsLayout\n\nNamed record page layout with ordered sections:\n\n```typescript\ninterface CmsLayout {\n sections: CmsLayoutSection[];\n}\n\ninterface CmsLayoutSection {\n label: string;\n fields: string[];\n columns?: 1 | 2;\n collapsed?: boolean;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `sections` | Ordered array of field sections |\n\n### CmsLayoutSection\n\n| Field | Description |\n|-------|-------------|\n| `label` | Section header text |\n| `fields` | Array of column names to display in this section |\n| `columns` | `1` (default) or `2` for two-column field layout |\n| `collapsed` | When `true`, section starts collapsed with a toggle to expand |\n\nFields not assigned to any section in the active layout are collected into an \"Other Fields\" section.\n\n## MaskingRule\n\nPer-field data masking:\n\n```typescript\ninterface MaskingRule {\n type: \"email\" | \"phone\" | \"ssn\" | \"redact\";\n show: {\n roles: string[];\n or?: string;\n };\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `type` | Masking pattern to apply |\n| `show.roles` | Roles that see the unmasked value |\n| `show.or` | Alternative condition for showing unmasked value |\n\n### Masking Patterns\n\n| Type | Input | Output |\n|------|-------|--------|\n| `email` | `john@acme.com` | `j***@acme.com` |\n| `phone` | `(555) 123-4567` | `***-***-4567` |\n| `ssn` | `123-45-6789` | `***-**-6789` |\n| `redact` | Any string | `------` |\n\n## ValidationRule\n\nPer-field validation constraints:\n\n```typescript\ninterface ValidationRule {\n minLength?: number;\n maxLength?: number;\n min?: number;\n max?: number;\n enum?: string[];\n email?: boolean;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `minLength` | Minimum string length |\n| `maxLength` | Maximum string length |\n| `min` | Minimum numeric value |\n| `max` | Maximum numeric value |\n| `enum` | Array of allowed string values |\n| `email` | When `true`, validates email format |\n\n## PageMeta\n\nFull metadata for a custom page:\n\n```typescript\ninterface PageMeta {\n slug: string;\n title: string;\n description?: string;\n icon?: string;\n feature: string;\n access?: { roles: string[] };\n dataSources: Record<string, PageDataSource>;\n layout: PageLayout;\n matching?: PageMatching;\n pageActions?: Record<string, PageAction>;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `slug` | URL-safe page identifier |\n| `title` | Display title |\n| `description` | Human-readable description |\n| `icon` | Icon name for sidebar |\n| `feature` | Parent feature name |\n| `access` | Role-based access control |\n| `dataSources` | Named data source bindings |\n| `layout` | Layout configuration |\n| `matching` | Matching/reconciliation rules |\n| `pageActions` | Actions triggered from the page |\n\n### PageDataSource\n\n```typescript\ninterface PageDataSource {\n table: string;\n defaultFilters?: Record<string, unknown>;\n defaultSort?: { field: string; order: 'asc' | 'desc' };\n displayColumns?: string[];\n}\n```\n\n### PageLayout\n\n```typescript\ninterface PageLayout {\n type: 'split-panel';\n panels: PagePanel[];\n}\n\ninterface PagePanel {\n id: string;\n title: string;\n dataSource: string;\n position: 'left' | 'right';\n features?: string[];\n}\n```\n\nPanel `features` can include `\"drag-source\"` and `\"drop-target\"` for drag-and-drop interactions.\n\n### PageMatching\n\n```typescript\ninterface PageMatching {\n enabled: boolean;\n rules: MatchingRule[];\n confidenceThreshold?: number;\n}\n\ninterface MatchingRule {\n name: string;\n weight: number;\n condition: {\n left: string;\n right: string;\n operator: 'abs-equals' | 'within-days' | 'fuzzy-match';\n value?: number;\n };\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `enabled` | Whether matching is active |\n| `rules` | Array of matching rules with weights (0-1) |\n| `confidenceThreshold` | Minimum score to display a match suggestion (0-1, default 0.5) |\n| `condition.left` | Left field reference (`dataSourceName.fieldName`) |\n| `condition.right` | Right field reference |\n| `condition.operator` | Comparison operator |\n| `condition.value` | Operator parameter (e.g., max days for `within-days`) |\n\n### PageAction\n\n```typescript\ninterface PageAction {\n table: string;\n action: string;\n inputMapping: Record<string, string>;\n label?: string;\n icon?: string;\n confirm?: string;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `table` | Target table for the action |\n| `action` | Action name on that table |\n| `inputMapping` | Maps action input fields to data source field references (`\"dataSourceName.$fieldName\"`) |\n| `label` | Button label (defaults to action name) |\n| `icon` | Button icon name |\n| `confirm` | Confirmation prompt shown before execution |\n\n## Next Steps\n\n- **[Schema Registry](/stack/cms/schema-registry)** — How the registry is generated and used\n- **[Components Reference](/stack/cms/components)** — All CMS React components"
394
+ "content": "# Schema Format Reference\n\nThe schema registry is a JSON file with a well-defined structure. Below are the complete TypeScript type definitions used by both the compiler (to generate) and the CMS (to consume).\n\n## SchemaRegistry\n\nThe top-level type:\n\n```typescript\ninterface SchemaRegistry {\n generatedAt: string;\n generatedBy: string;\n version: string;\n features: Record<string, string[]>;\n tables: Record<string, TableMeta>;\n tablesByFeature: Record<string, string[]>;\n featureActions: Record<string, ActionMeta[]>;\n pages: Record<string, PageMeta>;\n pagesByFeature: Record<string, string[]>;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `generatedAt` | ISO 8601 timestamp of when the registry was generated |\n| `generatedBy` | Always `\"quickback-compiler\"` |\n| `version` | Compiler version string |\n| `features` | Map of feature name to array of source file names |\n| `tables` | Map of camelCase table name to full table metadata |\n| `tablesByFeature` | Map of feature name to array of table names in that feature |\n| `featureActions` | Map of feature name to standalone actions not attached to one table |\n| `pages` | Map of page slug to full page metadata |\n| `pagesByFeature` | Map of feature name to array of page slugs in that feature |\n\n## TableMeta\n\nFull metadata for a single table:\n\n```typescript\ninterface TableMeta {\n name: string;\n dbName: string;\n feature: string;\n columns: ColumnMeta[];\n firewall: Record<string, unknown>;\n crud: Record<string, CrudConfig>;\n create?: WriteOperationConfig | false;\n update?: WriteOperationConfig | false;\n delete?: WriteOperationConfig | false;\n upsert?: WriteOperationConfig | false;\n guards: GuardsConfig;\n masking: Record<string, MaskingRule>;\n views: Record<string, ViewConfig>;\n validation: Record<string, ValidationRule>;\n actions: ActionMeta[];\n displayColumn?: string;\n defaultSort?: { field: string; order: 'asc' | 'desc' };\n inputHints?: Record<string, string>;\n layouts?: Record<string, CmsLayout>;\n internal?: boolean;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `name` | camelCase table name (e.g., `\"accountCode\"`) |\n| `dbName` | Snake_case SQL table name (e.g., `\"account_code\"`) |\n| `feature` | Parent feature name (e.g., `\"accounting\"`) |\n| `columns` | Ordered array of column metadata |\n| `firewall` | Tenant isolation config (organization, owner, softDelete, exception) |\n| `crud` | Legacy normalized write config kept for backwards compatibility |\n| `create` / `update` / `delete` / `upsert` | Flat write-operation aliases mirroring the authored `defineTable(...)` DSL |\n| `guards` | Field-level create/update/immutable/protected rules |\n| `masking` | Per-field masking rules keyed by column name |\n| `views` | Named column projections keyed by view name |\n| `validation` | Per-field validation rules keyed by column name |\n| `actions` | Array of action definitions scoped to this table |\n| `displayColumn` | Column used as human-readable label (auto-detected or explicit) |\n| `defaultSort` | Default sort for CMS table list view (e.g., `{ field: \"createdAt\", order: \"desc\" }`) |\n| `inputHints` | Map of column name to preferred CMS input type (e.g., `\"richtext\"`, `\"select\"`, `\"textarea\"`, `\"checkbox\"`) |\n| `layouts` | Named record page layouts keyed by layout name (see CmsLayout below) |\n| `internal` | When `true`, table is hidden from CMS sidebar |\n\n## ColumnMeta\n\nMetadata for a single column:\n\n```typescript\ninterface ColumnMeta {\n name: string;\n dbName: string;\n type: \"text\" | \"integer\" | \"real\" | \"blob\";\n mode?: \"boolean\";\n primaryKey: boolean;\n notNull: boolean;\n defaultValue?: string | number | boolean;\n fkTarget?: string;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `name` | camelCase property name |\n| `dbName` | Snake_case SQL column name |\n| `type` | SQLite storage type |\n| `mode` | When `\"boolean\"`, an integer column represents true/false |\n| `primaryKey` | Whether this column is the primary key |\n| `notNull` | Whether the column has a NOT NULL constraint |\n| `defaultValue` | Static default value (strings, numbers, or booleans) |\n| `fkTarget` | Target table name for FK columns (e.g., `\"contact\"` for a `vendorId` column) |\n\n## CRUDConfig\n\nPer-operation access control:\n\n```typescript\ninterface CrudConfig {\n access?: AccessRule;\n mode?: string;\n}\n\ninterface WriteOperationConfig extends CrudConfig {\n defaults?: Record<string, unknown>;\n computed?: Record<string, unknown>;\n fields?: string[];\n maxBatchSize?: number;\n allowFailFast?: boolean;\n batch?: false | Record<string, unknown>;\n}\n\ninterface AccessRule {\n roles?: string[];\n or?: Array<{\n roles?: string[];\n record?: Record<string, unknown>;\n }>;\n record?: Record<string, unknown>;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `access.roles` | Array of roles allowed for this operation |\n| `access.or` | Alternative access conditions (any must match) |\n| `access.record` | Record-level conditions for access |\n| `mode` | Operation mode (e.g., `\"batch\"` for bulk create) |\n| `defaults` / `computed` | Create-time defaults and computed field metadata |\n| `maxBatchSize` / `allowFailFast` | Batch-write controls when the config describes a batch operation |\n| `batch` | Nested batch config for the flat `create` / `update` / `delete` / `upsert` aliases |\n\n## GuardsConfig\n\nField-level control for create and update operations:\n\n```typescript\ninterface GuardsConfig {\n createable: string[];\n updatable: string[];\n immutable: string[];\n protected: Record<string, string[]>;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `createable` | Fields that can be set during record creation |\n| `updatable` | Fields that can be modified on existing records |\n| `immutable` | Fields that can be set on create but never changed |\n| `protected` | Fields only modifiable via named actions (field name to action names) |\n\n## ActionMeta\n\nMetadata for a custom action:\n\n```typescript\ninterface ActionMeta {\n name: string;\n description: string;\n inputFields: ActionInputField[];\n access?: {\n roles: string[];\n record?: Record<string, unknown>;\n };\n standalone?: boolean;\n path?: string;\n method?: string;\n responseType?: string;\n sideEffects?: string;\n cms?: CmsConfig;\n}\n\ninterface CmsConfig {\n label?: string;\n icon?: string;\n confirm?: string | boolean;\n destructive?: boolean;\n category?: string;\n hidden?: boolean;\n placement?: 'feature' | 'tables';\n tables?: string[];\n successMessage?: string;\n onSuccess?: 'refresh' | 'redirect:list' | 'close';\n order?: number;\n}\n\ninterface ActionInputField {\n name: string;\n type: string;\n required: boolean;\n default?: unknown;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `name` | Action identifier (e.g., `\"approve\"`, `\"applyPayment\"`) |\n| `description` | Human-readable description shown in dialog |\n| `inputFields` | Array of input field definitions |\n| `access.roles` | Roles allowed to execute this action |\n| `access.record` | Record conditions (e.g., `{ status: { equals: \"pending\" } }`) |\n| `standalone` | When `true`, action is not tied to a specific record |\n| `path` | Custom API path (overrides default) |\n| `method` | HTTP method (defaults to POST) |\n| `responseType` | `\"file\"` for download responses |\n| `sideEffects` | `\"sync\"` for actions with synchronous side effects |\n| `cms` | Optional CMS rendering metadata (label, icon, confirm, destructive, category, hidden, placement, tables, successMessage, onSuccess, order) |\n\n### CmsConfig placement rules\n\n`placement` is only relevant for standalone actions in multi-table features:\n\n- `\"feature\"` shows the action in the toolbar for every table in the feature.\n- `\"tables\"` shows the action only for the tables listed in `tables`.\n\nIf the action is already unambiguously table-scoped, the compiler can infer placement and `placement` is optional.\n\n### ActionInputField\n\n| Field | Description |\n|-------|-------------|\n| `name` | Field identifier |\n| `type` | Zod type string: `\"string\"`, `\"number\"`, `\"boolean\"`, `\"array<string>\"` |\n| `required` | Whether the field must be provided |\n| `default` | Default value pre-filled in the form |\n\n## ViewConfig\n\nNamed column projection with access control:\n\n```typescript\ninterface ViewConfig {\n fields: string[];\n access: AccessRule;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `fields` | Array of column names to include in this view |\n| `access` | Role-based access rules (same shape as CrudConfig access) |\n\n## CmsLayout\n\nNamed record page layout with ordered sections:\n\n```typescript\ninterface CmsLayout {\n sections: CmsLayoutSection[];\n}\n\ninterface CmsLayoutSection {\n label: string;\n fields: string[];\n columns?: 1 | 2;\n collapsed?: boolean;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `sections` | Ordered array of field sections |\n\n### CmsLayoutSection\n\n| Field | Description |\n|-------|-------------|\n| `label` | Section header text |\n| `fields` | Array of column names to display in this section |\n| `columns` | `1` (default) or `2` for two-column field layout |\n| `collapsed` | When `true`, section starts collapsed with a toggle to expand |\n\nFields not assigned to any section in the active layout are collected into an \"Other Fields\" section.\n\n## MaskingRule\n\nPer-field data masking:\n\n```typescript\ninterface MaskingRule {\n type: \"email\" | \"phone\" | \"ssn\" | \"redact\";\n show: {\n roles: string[];\n or?: string;\n };\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `type` | Masking pattern to apply |\n| `show.roles` | Roles that see the unmasked value |\n| `show.or` | Alternative condition for showing unmasked value |\n\n### Masking Patterns\n\n| Type | Input | Output |\n|------|-------|--------|\n| `email` | `john@acme.com` | `j***@acme.com` |\n| `phone` | `(555) 123-4567` | `***-***-4567` |\n| `ssn` | `123-45-6789` | `***-**-6789` |\n| `redact` | Any string | `------` |\n\n## ValidationRule\n\nPer-field validation constraints:\n\n```typescript\ninterface ValidationRule {\n minLength?: number;\n maxLength?: number;\n min?: number;\n max?: number;\n enum?: string[];\n email?: boolean;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `minLength` | Minimum string length |\n| `maxLength` | Maximum string length |\n| `min` | Minimum numeric value |\n| `max` | Maximum numeric value |\n| `enum` | Array of allowed string values |\n| `email` | When `true`, validates email format |\n\n## PageMeta\n\nFull metadata for a custom page:\n\n```typescript\ninterface PageMeta {\n slug: string;\n title: string;\n description?: string;\n icon?: string;\n feature: string;\n access?: { roles: string[] };\n dataSources: Record<string, PageDataSource>;\n layout: PageLayout;\n matching?: PageMatching;\n pageActions?: Record<string, PageAction>;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `slug` | URL-safe page identifier |\n| `title` | Display title |\n| `description` | Human-readable description |\n| `icon` | Icon name for sidebar |\n| `feature` | Parent feature name |\n| `access` | Role-based access control |\n| `dataSources` | Named data source bindings |\n| `layout` | Layout configuration |\n| `matching` | Matching/reconciliation rules |\n| `pageActions` | Actions triggered from the page |\n\n### PageDataSource\n\n```typescript\ninterface PageDataSource {\n table: string;\n defaultFilters?: Record<string, unknown>;\n defaultSort?: { field: string; order: 'asc' | 'desc' };\n displayColumns?: string[];\n}\n```\n\n### PageLayout\n\n```typescript\ninterface PageLayout {\n type: 'split-panel';\n panels: PagePanel[];\n}\n\ninterface PagePanel {\n id: string;\n title: string;\n dataSource: string;\n position: 'left' | 'right';\n features?: string[];\n}\n```\n\nPanel `features` can include `\"drag-source\"` and `\"drop-target\"` for drag-and-drop interactions.\n\n### PageMatching\n\n```typescript\ninterface PageMatching {\n enabled: boolean;\n rules: MatchingRule[];\n confidenceThreshold?: number;\n}\n\ninterface MatchingRule {\n name: string;\n weight: number;\n condition: {\n left: string;\n right: string;\n operator: 'abs-equals' | 'within-days' | 'fuzzy-match';\n value?: number;\n };\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `enabled` | Whether matching is active |\n| `rules` | Array of matching rules with weights (0-1) |\n| `confidenceThreshold` | Minimum score to display a match suggestion (0-1, default 0.5) |\n| `condition.left` | Left field reference (`dataSourceName.fieldName`) |\n| `condition.right` | Right field reference |\n| `condition.operator` | Comparison operator |\n| `condition.value` | Operator parameter (e.g., max days for `within-days`) |\n\n### PageAction\n\n```typescript\ninterface PageAction {\n table: string;\n action: string;\n inputMapping: Record<string, string>;\n label?: string;\n icon?: string;\n confirm?: string;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `table` | Target table for the action |\n| `action` | Action name on that table |\n| `inputMapping` | Maps action input fields to data source field references (`\"dataSourceName.$fieldName\"`) |\n| `label` | Button label (defaults to action name) |\n| `icon` | Button icon name |\n| `confirm` | Confirmation prompt shown before execution |\n\n## Next Steps\n\n- **[Schema Registry](/stack/cms/schema-registry)** — How the registry is generated and used\n- **[Components Reference](/stack/cms/components)** — All CMS React components"
375
395
  },
376
396
  "stack/cms/schema-registry": {
377
397
  "title": "Schema Registry",
378
- "content": "# Schema Registry\n\nThe schema registry is a static JSON file generated by the Quickback compiler. It contains full metadata about every table in your project — columns, types, guards, masking rules, views, actions, validation, and firewall config. The CMS reads this file to render its entire UI.\n\n## Generation\n\nSchema registry generation is **enabled by default**. Run `quickback compile` and the compiler outputs `schema-registry.json` alongside your compiled API files.\n\nTo disable generation:\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default defineConfig({\n schemaRegistry: { generate: false },\n // ... rest of your config\n});\n```\n\n## Output Shape\n\nThe top-level structure of `schema-registry.json`:\n\n```json\n{\n \"generatedAt\": \"2026-02-14T06:26:53.554Z\",\n \"generatedBy\": \"quickback-compiler\",\n \"version\": \"1.0.0\",\n \"singleTenant\": false,\n \"features\": { ... },\n \"tables\": { ... },\n \"tablesByFeature\": { ... },\n \"featureActions\": { ... },\n \"pages\": { ... },\n \"pagesByFeature\": { ... }\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `generatedAt` | `string` | ISO timestamp of generation |\n| `generatedBy` | `string` | Always `\"quickback-compiler\"` |\n| `version` | `string` | Compiler version used |\n| `singleTenant` | `boolean?` | When `true`, no organization layer |\n| `features` | `Record<string, string[]>` | Feature name to file list mapping |\n| `tables` | `Record<string, TableMeta>` | Table name to full metadata |\n| `tablesByFeature` | `Record<string, string[]>` | Feature name to table name list |\n| `featureActions` | `Record<string, ActionMeta[]>` | Feature name to standalone actions not owned by one table |\n| `pages` | `Record<string, PageMeta>` | Page slug to full page metadata |\n| `pagesByFeature` | `Record<string, string[]>` | Feature name to page slug list |\n\n## TableMeta\n\nEach table entry contains everything the CMS needs to render its UI:\n\n```typescript\ninterface TableMeta {\n name: string; // camelCase table name (e.g., \"accountCode\")\n dbName: string; // SQL table name (e.g., \"account_code\")\n feature: string; // Parent feature name\n columns: ColumnMeta[]; // All columns including audit fields\n firewall: Record<string, unknown>; // Tenant isolation config\n crud: Record<string, CrudConfig>; // Legacy normalized write surface\n create?: WriteOperationConfig | false; // Flat create config\n update?: WriteOperationConfig | false; // Flat update config\n delete?: WriteOperationConfig | false; // Flat delete config\n upsert?: WriteOperationConfig | false; // Flat upsert config\n guards: {\n createable: string[]; // Fields allowed on create\n updatable: string[]; // Fields allowed on update\n immutable: string[]; // Fields locked after creation\n protected: Record<string, string[]>; // Fields only updatable via actions\n };\n masking: Record<string, MaskingRule>; // Per-field masking rules\n views: Record<string, ViewConfig>; // Named column projections\n validation: Record<string, ValidationRule>; // Per-field validation\n actions: ActionMeta[]; // Table-scoped actions for this table\n displayColumn?: string; // Human-readable label column\n internal?: boolean; // Hidden from CMS sidebar when true\n}\n```\n\n`create`, `update`, `delete`, and `upsert` mirror the preferred flat DSL from `defineTable(...)`. The legacy `crud` block is still emitted for backwards compatibility with older consumers.\n\n## Feature Actions\n\nStandalone actions do not always belong to a single table. When an action is attached to a multi-table feature root, the compiler emits it under `featureActions[featureName]` instead of duplicating it across every table.\n\n```typescript\ninterface SchemaRegistry {\n featureActions: Record<string, ActionMeta[]>;\n}\n```\n\nThe CMS uses `featureActions` for toolbar-style actions that apply to the feature as a whole. Use `cms.placement` on standalone actions to control whether they show for the whole feature or only selected tables.\n\n## ColumnMeta\n\nEach column in the `columns` array:\n\n```typescript\ninterface ColumnMeta {\n name: string; // Property name (camelCase)\n dbName: string; // SQL column name (snake_case)\n type: \"text\" | \"integer\" | \"real\" | \"blob\"; // SQLite type\n mode?: \"boolean\"; // When an integer represents a boolean\n primaryKey: boolean;\n notNull: boolean;\n defaultValue?: string | number | boolean;\n fkTarget?: string; // Target table name for FK columns\n}\n```\n\nThe compiler automatically includes the system columns (`id`, `organizationId`), the audit fields (`createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`), and the soft-delete pair (`deletedAt`, `deletedBy` — when soft delete is enabled) at the beginning of every table's column list.\n\n### fkTarget — FK Resolution\n\nColumns ending in `Id` may have a `fkTarget` property indicating which table they reference. This is resolved in priority order:\n\n1. **Explicit `references`** — from your `defineTable()` config (highest priority)\n2. **Drizzle `.references()`** — parsed from schema source code\n3. **Convention** — strip `Id` suffix, match table name directly\n\n```json\n{\n \"name\": \"vendorId\",\n \"type\": \"text\",\n \"fkTarget\": \"contact\"\n}\n```\n\nThe CMS uses `fkTarget` to render typeahead/lookup inputs that search the correct table instead of showing raw IDs.\n\n## Input Hints\n\nTables with `inputHints` configured in `defineTable()` include an `inputHints` map in their metadata:\n\n```json\n{\n \"name\": \"invoice\",\n \"inputHints\": {\n \"status\": \"select\",\n \"sortOrder\": \"radio\",\n \"isPartialPaymentDisabled\": \"checkbox\",\n \"headerMessage\": \"textarea\",\n \"description\": \"richtext\"\n }\n}\n```\n\nThe CMS reads these hints to render the appropriate form control for each field. The `\"richtext\"` hint renders a tiptap editor in edit mode and formatted HTML in view mode. See [Input Hints](/compiler/definitions/schema#input-hints) for the full list of supported values.\n\n## Display Column\n\nThe `displayColumn` field tells the CMS which column to use as a human-readable label for a record. This is used in:\n\n- FK typeahead dropdowns (showing names instead of IDs)\n- Record titles in detail views\n- Breadcrumb labels\n\n### Auto-Detection\n\nIf you don't explicitly set `displayColumn` in your resource config, the compiler auto-detects it by scanning column names in priority order:\n\n1. `name`\n2. `title`\n3. `label`\n4. `headline`\n5. `subject`\n6. `code`\n7. `displayName`\n8. `fullName`\n9. `description`\n\nThe first match wins. If no candidate matches, the table has no display column and the CMS falls back to showing IDs.\n\n### Explicit Config\n\nSet it explicitly in your table definition:\n\n```typescript\nexport default defineTable(contacts, {\n displayColumn: \"companyName\",\n // ...\n});\n```\n\n## FK Label Resolution\n\nWhen a table has foreign key columns (ending in `Id`), the API enriches list responses with `_label` fields. For example, a `roomTypeId` column gets a corresponding `roomType_label` field containing the display column value from the referenced table.\n\nThe CMS uses these `_label` fields to show human-readable names in table cells and FK typeahead dropdowns instead of raw UUIDs.\n\n```\nroomTypeId: \"rt_abc123\" → displayed as \"Master Bedroom\"\naccountCodeId: \"ac_xyz789\" → displayed as \"4100 - Revenue\"\n```\n\nThe FK target table is resolved from the `fkTarget` property on each column. For simple cases like `roomTypeId` → `roomType`, the compiler auto-detects it. For non-obvious mappings (e.g., `vendorId` → `contact`), use explicit [`references`](/compiler/definitions/schema#references) in your `defineTable()` config.\n\n## Pages\n\nWhen features include `definePage()` files (in `features/{name}/pages/`), the compiler includes them in the registry under two fields:\n\n- **`pages`** — Map of page slug to full `PageMeta` object (data sources, layout, matching rules, page actions)\n- **`pagesByFeature`** — Map of feature name to array of page slugs belonging to that feature\n\nThe CMS reads these fields to render custom pages in the sidebar and route to the page renderer. See [Custom Pages](/stack/cms/pages) for the full `definePage()` API.\n\n## Single-Tenant Mode\n\nWhen `singleTenant` is `true` in the registry (set when the project config has `features.organizations: false`), the CMS skips the organization gate and reads the user's role directly from `user.role` on the session instead of from organization membership.\n\n## Next Steps\n\n- **[Connecting](/stack/cms/connecting)** — Demo mode vs. live mode setup\n- **[Schema Format Reference](/stack/cms/schema-format)** — Full TypeScript types"
398
+ "content": "# Schema Registry\n\nThe schema registry is a static JSON file generated by the Quickback compiler. It contains full metadata about every table in your project — columns, types, guards, masking rules, views, actions, validation, and firewall config. The CMS reads this file to render its entire UI.\n\n## Generation\n\nSchema registry generation is **enabled by default**. Run `quickback compile` and the compiler outputs `schema-registry.json` alongside your compiled API files.\n\nTo disable generation:\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default defineConfig({\n schemaRegistry: { generate: false },\n // ... rest of your config\n});\n```\n\n## Output Shape\n\nThe top-level structure of `schema-registry.json`:\n\n```json\n{\n \"generatedAt\": \"2026-02-14T06:26:53.554Z\",\n \"generatedBy\": \"quickback-compiler\",\n \"version\": \"1.0.0\",\n \"features\": { ... },\n \"tables\": { ... },\n \"tablesByFeature\": { ... },\n \"featureActions\": { ... },\n \"pages\": { ... },\n \"pagesByFeature\": { ... }\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `generatedAt` | `string` | ISO timestamp of generation |\n| `generatedBy` | `string` | Always `\"quickback-compiler\"` |\n| `version` | `string` | Compiler version used |\n| `features` | `Record<string, string[]>` | Feature name to file list mapping |\n| `tables` | `Record<string, TableMeta>` | Table name to full metadata |\n| `tablesByFeature` | `Record<string, string[]>` | Feature name to table name list |\n| `featureActions` | `Record<string, ActionMeta[]>` | Feature name to standalone actions not owned by one table |\n| `pages` | `Record<string, PageMeta>` | Page slug to full page metadata |\n| `pagesByFeature` | `Record<string, string[]>` | Feature name to page slug list |\n\n## TableMeta\n\nEach table entry contains everything the CMS needs to render its UI:\n\n```typescript\ninterface TableMeta {\n name: string; // camelCase table name (e.g., \"accountCode\")\n dbName: string; // SQL table name (e.g., \"account_code\")\n feature: string; // Parent feature name\n columns: ColumnMeta[]; // All columns including audit fields\n firewall: Record<string, unknown>; // Tenant isolation config\n crud: Record<string, CrudConfig>; // Legacy normalized write surface\n create?: WriteOperationConfig | false; // Flat create config\n update?: WriteOperationConfig | false; // Flat update config\n delete?: WriteOperationConfig | false; // Flat delete config\n upsert?: WriteOperationConfig | false; // Flat upsert config\n guards: {\n createable: string[]; // Fields allowed on create\n updatable: string[]; // Fields allowed on update\n immutable: string[]; // Fields locked after creation\n protected: Record<string, string[]>; // Fields only updatable via actions\n };\n masking: Record<string, MaskingRule>; // Per-field masking rules\n views: Record<string, ViewConfig>; // Named column projections\n validation: Record<string, ValidationRule>; // Per-field validation\n actions: ActionMeta[]; // Table-scoped actions for this table\n displayColumn?: string; // Human-readable label column\n internal?: boolean; // Hidden from CMS sidebar when true\n}\n```\n\n`create`, `update`, `delete`, and `upsert` mirror the preferred flat DSL from `defineTable(...)`. The legacy `crud` block is still emitted for backwards compatibility with older consumers.\n\n## Feature Actions\n\nStandalone actions do not always belong to a single table. When an action is attached to a multi-table feature root, the compiler emits it under `featureActions[featureName]` instead of duplicating it across every table.\n\n```typescript\ninterface SchemaRegistry {\n featureActions: Record<string, ActionMeta[]>;\n}\n```\n\nThe CMS uses `featureActions` for toolbar-style actions that apply to the feature as a whole. Use `cms.placement` on standalone actions to control whether they show for the whole feature or only selected tables.\n\n## ColumnMeta\n\nEach column in the `columns` array:\n\n```typescript\ninterface ColumnMeta {\n name: string; // Property name (camelCase)\n dbName: string; // SQL column name (snake_case)\n type: \"text\" | \"integer\" | \"real\" | \"blob\"; // SQLite type\n mode?: \"boolean\"; // When an integer represents a boolean\n primaryKey: boolean;\n notNull: boolean;\n defaultValue?: string | number | boolean;\n fkTarget?: string; // Target table name for FK columns\n}\n```\n\nThe compiler automatically includes the system columns (`id`, `organizationId`), the audit fields (`createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`), and the soft-delete pair (`deletedAt`, `deletedBy` — when soft delete is enabled) at the beginning of every table's column list.\n\n### fkTarget — FK Resolution\n\nColumns ending in `Id` may have a `fkTarget` property indicating which table they reference. This is resolved in priority order:\n\n1. **Explicit `references`** — from your `defineTable()` config (highest priority)\n2. **Drizzle `.references()`** — parsed from schema source code\n3. **Convention** — strip `Id` suffix, match table name directly\n\n```json\n{\n \"name\": \"vendorId\",\n \"type\": \"text\",\n \"fkTarget\": \"contact\"\n}\n```\n\nThe CMS uses `fkTarget` to render typeahead/lookup inputs that search the correct table instead of showing raw IDs.\n\n## Input Hints\n\nTables with `inputHints` configured in `defineTable()` include an `inputHints` map in their metadata:\n\n```json\n{\n \"name\": \"invoice\",\n \"inputHints\": {\n \"status\": \"select\",\n \"sortOrder\": \"radio\",\n \"isPartialPaymentDisabled\": \"checkbox\",\n \"headerMessage\": \"textarea\",\n \"description\": \"richtext\"\n }\n}\n```\n\nThe CMS reads these hints to render the appropriate form control for each field. The `\"richtext\"` hint renders a tiptap editor in edit mode and formatted HTML in view mode. See [Input Hints](/compiler/definitions/schema#input-hints) for the full list of supported values.\n\n## Display Column\n\nThe `displayColumn` field tells the CMS which column to use as a human-readable label for a record. This is used in:\n\n- FK typeahead dropdowns (showing names instead of IDs)\n- Record titles in detail views\n- Breadcrumb labels\n\n### Auto-Detection\n\nIf you don't explicitly set `displayColumn` in your resource config, the compiler auto-detects it by scanning column names in priority order:\n\n1. `name`\n2. `title`\n3. `label`\n4. `headline`\n5. `subject`\n6. `code`\n7. `displayName`\n8. `fullName`\n9. `description`\n\nThe first match wins. If no candidate matches, the table has no display column and the CMS falls back to showing IDs.\n\n### Explicit Config\n\nSet it explicitly in your table definition:\n\n```typescript\nexport default defineTable(contacts, {\n displayColumn: \"companyName\",\n // ...\n});\n```\n\n## FK Label Resolution\n\nWhen a table has foreign key columns (ending in `Id`), the API enriches list responses with `_label` fields. For example, a `roomTypeId` column gets a corresponding `roomType_label` field containing the display column value from the referenced table.\n\nThe CMS uses these `_label` fields to show human-readable names in table cells and FK typeahead dropdowns instead of raw UUIDs.\n\n```\nroomTypeId: \"rt_abc123\" → displayed as \"Master Bedroom\"\naccountCodeId: \"ac_xyz789\" → displayed as \"4100 - Revenue\"\n```\n\nThe FK target table is resolved from the `fkTarget` property on each column. For simple cases like `roomTypeId` → `roomType`, the compiler auto-detects it. For non-obvious mappings (e.g., `vendorId` → `contact`), use explicit [`references`](/compiler/definitions/schema#references) in your `defineTable()` config.\n\n## Pages\n\nWhen features include `definePage()` files (in `features/{name}/pages/`), the compiler includes them in the registry under two fields:\n\n- **`pages`** — Map of page slug to full `PageMeta` object (data sources, layout, matching rules, page actions)\n- **`pagesByFeature`** — Map of feature name to array of page slugs belonging to that feature\n\nThe CMS reads these fields to render custom pages in the sidebar and route to the page renderer. See [Custom Pages](/stack/cms/pages) for the full `definePage()` API.\n\n## Next Steps\n\n- **[Connecting](/stack/cms/connecting)** — Demo mode vs. live mode setup\n- **[Schema Format Reference](/stack/cms/schema-format)** — Full TypeScript types"
379
399
  },
380
400
  "stack/cms/security": {
381
401
  "title": "Security",
382
- "content": "# Security\n\nThe CMS respects all four Quickback security layers. Every UI element — buttons, form fields, table columns, action menus — adapts based on the current user's role and the security rules defined in your feature files.\n\n## CMS Access (admin-only by default)\n\nThe CMS is restricted to Better Auth platform admins (`user.role === \"admin\"`) by default — non-admin authenticated users are redirected to `/account/profile`. To allow any authenticated user, opt out explicitly:\n\n```typescript\ncms: { access: \"user\" }\n```\n\nUnder the default `access: \"admin\"`, the compiler emits server-side gates on every CMS-facing surface so a non-admin can't reach the CMS even by bypassing the SPA:\n\n1. **Account UI** — the \"Go to CMS\" button is hidden.\n2. **CMS SPA shell** — the Worker checks `ctx.userRole === \"admin\"` before serving `index.html`. Unauthenticated requests are redirected to login; authenticated non-admins get `403 Admin access required`.\n3. **`/api/v1/schema`** — the CMS metadata endpoint returns `403` to non-admins.\n4. **`custom_view` routes** — the CMS-internal saved-views table uses `userRole: [\"admin\"]` (see [`userRole`](/compiler/definitions/access#userrole-vs-roles)), so saved views can't be read or modified from outside the CMS by non-admin accounts.\n5. **In-SPA gate** — if any earlier layer is bypassed, the SPA still redirects the user to `/account/profile`.\n\nYour resource API endpoints keep whatever `read`, `create`, `update`, `delete`, or `upsert` access rules you defined — they're the app's data API and unaffected by the CMS gate.\n\n## The Four Layers\n\nQuickback enforces security through four complementary layers:\n\n| Layer | Purpose | CMS Behavior |\n|-------|---------|-------------|\n| **Firewall** | Tenant isolation (org-scoped data) | Handled server-side. CMS cannot bypass it. |\n| **Operation Access** | Per-operation role requirements | Buttons hidden when role lacks permission |\n| **Guards** | Field-level create/update control | Form fields enabled/disabled per guard rules |\n| **Masking** | Sensitive field redaction | Masked values with lock icons per role |\n\n## Role-Based Access\n\nThe CMS header includes a **role switcher** (in demo mode) or reads the user's actual role from their organization membership (in live mode). The three roles are:\n\n- **owner** — Full access to all operations and data\n- **admin** — Elevated access, typically all write operations and most actions\n- **member** — Standard access with restrictions on sensitive data and destructive actions\n\n### Operation Button Visibility\n\nCreate, edit, and delete buttons are shown or hidden based on the current role's access:\n\n```typescript\nread: { access: { roles: ['member', 'admin', 'owner'] } },\ncreate: { access: { roles: ['admin', 'owner'] } },\nupdate: { access: { roles: ['admin', 'owner'] } },\ndelete: { access: { roles: ['owner'] } },\n```\n\nWith the config above:\n\n- **Members** see the table (read) but no Create, Edit, or Delete buttons\n- **Admins** see Create and Edit buttons but no Delete\n- **Owners** see all buttons\n\nThe row action menu also adapts — Edit and Delete entries only appear when the role has the corresponding permission.\n\n## Guards\n\nGuards control which fields appear in create and edit forms, and which cells are editable in Data Table mode.\n\n### Createable Fields\n\nFields listed in `guards.createable` appear in the create form. Fields not in this list are hidden from the form entirely:\n\n```typescript\nguards: {\n createable: ['name', 'email', 'phone', 'status'],\n}\n```\n\n### Updatable Fields\n\nFields listed in `guards.updatable` are editable in the edit form and in Data Table inline editing:\n\n```typescript\nguards: {\n updatable: ['name', 'email', 'phone'],\n}\n```\n\n### Immutable Fields\n\nFields in `guards.immutable` can be set during creation but cannot be changed afterward. In edit mode, they appear as disabled inputs with a lock icon:\n\n```typescript\nguards: {\n immutable: ['accountCode', 'type'],\n}\n```\n\n### Protected Fields\n\nFields in `guards.protected` can only be updated via specific actions. They appear as disabled inputs with the message \"Updated via actions only\":\n\n```typescript\nguards: {\n protected: {\n status: ['approve', 'void'], // Updated by approve or void actions\n balance: ['applyPayment'], // Updated by applyPayment action\n },\n}\n```\n\n## Masking\n\nMasking rules redact sensitive data based on the user's role. The CMS applies masking client-side for display and the API enforces it server-side in responses.\n\n### Masking Types\n\n| Type | Example Input | Masked Output |\n|------|--------------|---------------|\n| `email` | `john@acme.com` | `j***@acme.com` |\n| `phone` | `(555) 123-4567` | `***-***-4567` |\n| `ssn` | `123-45-6789` | `***-**-6789` |\n| `redact` | `Confidential notes` | `------` |\n\n### Configuration\n\n```typescript\nmasking: {\n email: { type: 'email', show: { roles: ['admin', 'owner'] } },\n phone: { type: 'phone', show: { roles: ['admin', 'owner'] } },\n ssn: { type: 'ssn', show: { roles: ['owner'] } },\n}\n```\n\nWith the above config:\n\n- **Members** see masked values for email, phone, and SSN\n- **Admins** see unmasked email and phone, but masked SSN\n- **Owners** see all values unmasked\n\n### Visual Indicator\n\nMasked fields display a lock icon next to the redacted value, making it clear that the field contains hidden data:\n\n```\nEmail: [lock] j***@acme.com\nSSN: [lock] ***-**-6789\n```\n\n## Views\n\nViews provide column-level projections per role. Only authorized views appear in the toolbar dropdown.\n\n```typescript\nread: {\n views: {\n summary: {\n fields: ['id', 'name', 'status'],\n access: { roles: ['member', 'admin', 'owner'] },\n },\n financial: {\n fields: ['id', 'name', 'balance', 'creditLimit', 'paymentTerms'],\n access: { roles: ['admin', 'owner'] },\n },\n },\n}\n```\n\nMembers only see the \"summary\" view option. Admins and owners see both \"summary\" and \"financial\". The \"All Fields\" option is always available.\n\n## Firewall\n\nThe firewall layer handles tenant isolation — ensuring users can only access data within their organization. This is enforced entirely server-side:\n\n- `organization_id` columns are filtered automatically by the API\n- `owner` predicates restrict records to the creating user\n- The CMS never sees data outside the user's organization scope\n\nThe CMS does not display firewall config in its UI because there is nothing for the user to control. Tenant isolation is transparent and automatic.\n\n## Actions\n\nAction visibility is controlled by access conditions on each action:\n\n```typescript\nactions: {\n approve: {\n access: {\n roles: ['admin', 'owner'],\n record: { status: { equals: 'pending' } },\n },\n cms: { destructive: true, confirm: true },\n },\n}\n```\n\nThe CMS evaluates both the role requirement and the record condition. In this example, the \"Approve\" action only appears for admins and owners, and only on records where `status === \"pending\"`.\n\nDestructive actions (`cms.destructive: true`, or named `void`/`delete`) receive special warning styling with red text and an alert icon. Actions with `cms.hidden: true` are hidden from the CMS entirely (API-only).\n\n## Next Steps\n\n- **[Actions](/stack/cms/actions)** — Action dialogs and input forms\n- **[Table Views](/stack/cms/table-views)** — View projections and toolbar\n- **[Inline Editing](/stack/cms/inline-editing)** — How guards affect editability"
402
+ "content": "# Security\n\nThe CMS respects all four Quickback security layers. Every UI element — buttons, form fields, table columns, action menus — adapts based on the current user's role and the security rules defined in your feature files.\n\n## CMS Access (platform-control-plane by default)\n\nThe CMS is restricted to Better Auth platform control-plane users (`user.role === \"appmanager\"`) by default. If `cms.sysadmin: true` is enabled, `user.role === \"sysadmin\"` is also admitted. Other authenticated users are redirected to `/account/profile`. To allow any authenticated user, opt out explicitly:\n\n```typescript\ncms: { access: \"user\" }\n```\n\nUnder the default `access: \"admin\"`, the compiler emits server-side gates on every CMS-facing surface so a non-operator can't reach the CMS even by bypassing the SPA:\n\n1. **Account UI** — the \"Go to CMS\" button is hidden.\n2. **CMS SPA shell** — the Worker checks `ctx.userRole === \"appmanager\"` before serving `index.html`. When `cms.sysadmin: true`, sysadmins are also admitted. Unauthenticated requests are redirected to login; authenticated non-operators get `403 Platform operator access required`.\n3. **`/api/v1/schema`** — the CMS metadata endpoint returns `403` to callers outside those roles.\n4. **`custom_view` routes** — the CMS-internal saved-views table uses `userRole: [\"appmanager\"]` (and, when `cms.sysadmin: true`, also admits `sysadmin`), so saved views can't be read or modified from outside the CMS by non-operator accounts.\n5. **In-SPA gate** — if any earlier layer is bypassed, the SPA still redirects the user to `/account/profile`.\n\nYour resource API endpoints keep whatever `read`, `create`, `update`, `delete`, or `upsert` access rules you defined — they're the app's data API and unaffected by the CMS gate.\n\n## The Four Layers\n\nQuickback enforces security through four complementary layers:\n\n| Layer | Purpose | CMS Behavior |\n|-------|---------|-------------|\n| **Firewall** | Tenant isolation (org-scoped data) | Handled server-side. CMS cannot bypass it. |\n| **Operation Access** | Per-operation role requirements | Buttons hidden when role lacks permission |\n| **Guards** | Field-level create/update control | Form fields enabled/disabled per guard rules |\n| **Masking** | Sensitive field redaction | Masked values with lock icons per role |\n\n## Role-Based Access\n\nThe CMS header includes a **role switcher** (in demo mode) or reads the user's actual role from their organization membership (in live mode). The three roles are:\n\n- **owner** — Full access to all operations and data\n- **admin** — Elevated access, typically all write operations and most actions\n- **member** — Standard access with restrictions on sensitive data and destructive actions\n\n### Operation Button Visibility\n\nCreate, edit, and delete buttons are shown or hidden based on the current role's access:\n\n```typescript\nread: { access: { roles: ['member', 'admin', 'owner'] } },\ncreate: { access: { roles: ['admin', 'owner'] } },\nupdate: { access: { roles: ['admin', 'owner'] } },\ndelete: { access: { roles: ['owner'] } },\n```\n\nWith the config above:\n\n- **Members** see the table (read) but no Create, Edit, or Delete buttons\n- **Admins** see Create and Edit buttons but no Delete\n- **Owners** see all buttons\n\nThe row action menu also adapts — Edit and Delete entries only appear when the role has the corresponding permission.\n\n## Guards\n\nGuards control which fields appear in create and edit forms, and which cells are editable in Data Table mode.\n\n### Createable Fields\n\nFields listed in `guards.createable` appear in the create form. Fields not in this list are hidden from the form entirely:\n\n```typescript\nguards: {\n createable: ['name', 'email', 'phone', 'status'],\n}\n```\n\n### Updatable Fields\n\nFields listed in `guards.updatable` are editable in the edit form and in Data Table inline editing:\n\n```typescript\nguards: {\n updatable: ['name', 'email', 'phone'],\n}\n```\n\n### Immutable Fields\n\nFields in `guards.immutable` can be set during creation but cannot be changed afterward. In edit mode, they appear as disabled inputs with a lock icon:\n\n```typescript\nguards: {\n immutable: ['accountCode', 'type'],\n}\n```\n\n### Protected Fields\n\nFields in `guards.protected` can only be updated via specific actions. They appear as disabled inputs with the message \"Updated via actions only\":\n\n```typescript\nguards: {\n protected: {\n status: ['approve', 'void'], // Updated by approve or void actions\n balance: ['applyPayment'], // Updated by applyPayment action\n },\n}\n```\n\n## Masking\n\nMasking rules redact sensitive data based on the user's role. The CMS applies masking client-side for display and the API enforces it server-side in responses.\n\n### Masking Types\n\n| Type | Example Input | Masked Output |\n|------|--------------|---------------|\n| `email` | `john@acme.com` | `j***@acme.com` |\n| `phone` | `(555) 123-4567` | `***-***-4567` |\n| `ssn` | `123-45-6789` | `***-**-6789` |\n| `redact` | `Confidential notes` | `------` |\n\n### Configuration\n\n```typescript\nmasking: {\n email: { type: 'email', show: { roles: ['admin', 'owner'] } },\n phone: { type: 'phone', show: { roles: ['admin', 'owner'] } },\n ssn: { type: 'ssn', show: { roles: ['owner'] } },\n}\n```\n\nWith the above config:\n\n- **Members** see masked values for email, phone, and SSN\n- **Admins** see unmasked email and phone, but masked SSN\n- **Owners** see all values unmasked\n\n### Visual Indicator\n\nMasked fields display a lock icon next to the redacted value, making it clear that the field contains hidden data:\n\n```\nEmail: [lock] j***@acme.com\nSSN: [lock] ***-**-6789\n```\n\n## Views\n\nViews provide column-level projections per role. Only authorized views appear in the toolbar dropdown.\n\n```typescript\nread: {\n views: {\n summary: {\n fields: ['id', 'name', 'status'],\n access: { roles: ['member', 'admin', 'owner'] },\n },\n financial: {\n fields: ['id', 'name', 'balance', 'creditLimit', 'paymentTerms'],\n access: { roles: ['admin', 'owner'] },\n },\n },\n}\n```\n\nMembers only see the \"summary\" view option. Admins and owners see both \"summary\" and \"financial\". The \"All Fields\" option is always available.\n\n## Firewall\n\nThe firewall layer handles tenant isolation — ensuring users can only access data within their organization. This is enforced entirely server-side:\n\n- `organization_id` columns are filtered automatically by the API\n- `owner` predicates restrict records to the creating user\n- The CMS never sees data outside the user's organization scope\n\nThe CMS does not display firewall config in its UI because there is nothing for the user to control. Tenant isolation is transparent and automatic.\n\n## Actions\n\nAction visibility is controlled by access conditions on each action:\n\n```typescript\nactions: {\n approve: {\n access: {\n roles: ['admin', 'owner'],\n record: { status: { equals: 'pending' } },\n },\n cms: { destructive: true, confirm: true },\n },\n}\n```\n\nThe CMS evaluates both the role requirement and the record condition. In this example, the \"Approve\" action only appears for admins and owners, and only on records where `status === \"pending\"`.\n\nDestructive actions (`cms.destructive: true`, or named `void`/`delete`) receive special warning styling with red text and an alert icon. Actions with `cms.hidden: true` are hidden from the CMS entirely (API-only).\n\n## Next Steps\n\n- **[Actions](/stack/cms/actions)** — Action dialogs and input forms\n- **[Table Views](/stack/cms/table-views)** — View projections and toolbar\n- **[Inline Editing](/stack/cms/inline-editing)** — How guards affect editability"
383
403
  },
384
404
  "stack/cms/table-views": {
385
405
  "title": "Table Views",
@@ -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. In action handlers on realtime-enabled projects, Quickback now injects a typed `realtime` helper directly into `execute(...)`; outside actions you still call `createRealtime(env)` yourself.\n\n| Mutation site | Auto-broadcast? | Why |\n|---|---|---|\n| Generated CRUD route (`POST /`, `PATCH /:id`, `DELETE /:id`) | Yes | The compiler emits the call after the write returns. |\n| Generated batch route (`/batch/...`) | Yes | Same pattern, emitted per record. |\n| `scoped.insert/update/delete` inside an action handler | No — manual | Scoped-db is a query-shape wrapper (firewall + soft-delete WHERE injection). It deliberately has no side-effects so explicit handlers can write multiple records, conditionally roll back, etc. without surprise broadcasts. |\n| `unsafeDb` writes in actions (or any custom route) | No — manual | Same reasoning — `unsafeDb` is the un-wrapped escape hatch. |\n| Queue consumers, cron jobs, webhook handlers | No — manual | These run outside the CRUD path entirely. |\n\nThe rule of thumb: if your code calls `db.insert(...)` / `scoped.insert(...)` directly, you also call `realtime.insert(...)` directly on the next line. Otherwise the cross-tab live-update you wired up in the SPA won't fire.\n\n## Generated Helper\n\nAction handlers on realtime-enabled projects receive a typed `realtime` param. The underlying `createRealtime()` factory still powers it and remains the API to use from queues, cron jobs, and other non-action code:\n\n```typescript\nexport const execute: ActionExecutor = async ({ db, ctx, input, realtime }) => {\n // After creating a record\n await realtime.insert('applications', newApplication, ctx.activeOrgId!);\n\n // After updating a record\n await realtime.update('applications', newApplication, oldApplication, ctx.activeOrgId!);\n\n // After deleting a record\n await realtime.delete('applications', { id: applicationId }, ctx.activeOrgId!);\n\n return { success: true };\n};\n```\n\n`env` is also typed in action handlers, so custom bindings like R2, D1, Queues, Durable Objects, and auth env vars no longer need `(env as any)` casts.\n\nFor explicit targeting, pass an object instead of the historical org string:\n\n```typescript\nawait realtime.broadcast(\"event-page-updated\", payload, {\n scopeKey: `events:${input.eventId}`,\n});\n\nawait realtime.broadcast(\"dm\", payload, {\n userId: recipientId,\n});\n```\n\n## Event Format\n\nQuickback broadcasts events in a structured JSON format for easy client-side handling.\n\n### Insert Event\n\n```typescript\nawait realtime.insert('applications', {\n id: 'app_123',\n candidateId: 'cnd_456',\n stage: 'applied'\n}, ctx.activeOrgId!);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"INSERT\",\n \"schema\": \"public\",\n \"new\": {\n \"id\": \"app_123\",\n \"candidateId\": \"cnd_456\",\n \"stage\": \"applied\"\n },\n \"old\": null\n}\n```\n\n### Update Event\n\n```typescript\nawait realtime.update('applications',\n { id: 'app_123', stage: 'interview' }, // new\n { id: 'app_123', stage: 'screening' }, // old\n ctx.activeOrgId!\n);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"UPDATE\",\n \"schema\": \"public\",\n \"new\": { \"id\": \"app_123\", \"stage\": \"interview\" },\n \"old\": { \"id\": \"app_123\", \"stage\": \"screening\" }\n}\n```\n\n### Delete Event\n\n```typescript\nawait realtime.delete('applications',\n { id: 'app_123' },\n ctx.activeOrgId!\n);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"DELETE\",\n \"schema\": \"public\",\n \"new\": null,\n \"old\": { \"id\": \"app_123\" }\n}\n```\n\n## Custom Broadcasts\n\nFor arbitrary events that don't map to CRUD operations:\n\n```typescript\nawait realtime.broadcast('screening-complete', {\n applicationId: 'app_123',\n candidateId: 'cnd_456',\n stage: 'interview'\n}, ctx.activeOrgId!);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"broadcast\",\n \"event\": \"screening-complete\",\n \"payload\": {\n \"applicationId\": \"app_123\",\n \"candidateId\": \"cnd_456\",\n \"stage\": \"interview\"\n }\n}\n```\n\n## User-Specific Broadcasts\n\nTarget a specific user instead of the entire organization:\n\n```typescript\n// Only this user receives the notification\nawait realtime.insert('notifications', newNotification, ctx.activeOrgId!, {\n userId: ctx.userId\n});\n\n// Notify a hiring manager of a new application\nawait realtime.broadcast('application-received', {\n applicationId: 'app_123',\n jobId: 'job_789'\n}, ctx.activeOrgId!, {\n userId: hiringManagerId\n});\n```\n\n## Role-Based Filtering\n\nLimit which roles receive a broadcast using `targetRoles`:\n\n```typescript\n// Only hiring managers and recruiters receive this broadcast\nawait realtime.insert('applications', application, ctx.activeOrgId!, {\n targetRoles: ['hiring-manager', 'recruiter']\n});\n\n// Interviewers only see applications assigned to them\nawait realtime.update('applications', newRecord, oldRecord, ctx.activeOrgId!, {\n targetRoles: ['hiring-manager']\n});\n```\n\nIf `targetRoles` is not specified, all authenticated subscribers in the chosen scope receive the broadcast.\n\n## Per-Role Field Masking\n\nApply different field masking based on the subscriber's role using `maskingConfig`:\n\n```typescript\nawait realtime.insert('candidates', newCandidate, ctx.activeOrgId!, {\n maskingConfig: {\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n email: { type: 'email', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n resumeUrl: { type: 'redact', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n },\n});\n```\n\n**How masking works:**\n- Each subscriber receives a payload masked according to their role\n- Roles in the `show.roles` array see unmasked values\n- All other roles see the masked version\n- Masking is pre-computed per-role (O(roles) not O(subscribers))\n\n**Available mask types:**\n| Type | Example Output |\n|------|----------------|\n| `email` | `j***@y*********.com` |\n| `phone` | `******4567` |\n| `ssn` | `*****6789` |\n| `creditCard` | `**** **** **** 1111` |\n| `name` | `J***` |\n| `redact` | `[REDACTED]` |\n\n### Owner-Based Masking\n\nShow unmasked data to the record owner:\n\n```typescript\nmaskingConfig: {\n phone: {\n type: 'phone',\n show: { roles: ['hiring-manager'], or: 'owner' } // Hiring manager OR owner sees unmasked\n },\n}\n```\n\n## Client-Side Subscription\n\n### WebSocket Authentication\n\nQuickback uses **ticket-based authentication** for WebSocket connections. The client first obtains a short-lived ticket from the main API, then connects with it as a URL parameter. The Broadcaster verifies the ticket cryptographically at upgrade time — no HTTP round-trip needed.\n\n```typescript\n// 1. Get a ws-ticket from your API (requires session auth)\nconst response = await fetch('/broadcast/v1/ws-ticket', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${sessionToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ eventId: 'evt_123' }),\n});\nconst { wsTicket } = await response.json();\n\n// 2. Connect with ticket as URL param\nconst ws = new WebSocket(\n `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}`\n);\n\nws.onopen = () => {\n console.log('Connected and authenticated!');\n // No auth message needed — pre-authenticated at upgrade\n};\n```\n\nTickets expire after 60 seconds, so fetch a fresh one before each connection or reconnection.\n\n### Handling Messages\n\n```typescript\nws.onmessage = (event) => {\n const msg = JSON.parse(event.data);\n\n // Handle CRUD events\n if (msg.type === 'postgres_changes') {\n const { table, eventType, new: newRecord, old: oldRecord } = msg;\n\n if (eventType === 'INSERT') {\n addRecord(table, newRecord);\n } else if (eventType === 'UPDATE') {\n updateRecord(table, newRecord);\n } else if (eventType === 'DELETE') {\n removeRecord(table, oldRecord.id);\n }\n }\n\n // Handle custom broadcasts\n if (msg.type === 'broadcast') {\n const { event, payload } = msg;\n\n if (event === 'screening-complete') {\n refreshApplication(payload.applicationId);\n } else if (event === 'interview-scheduled') {\n showInterviewNotification(payload.applicationId);\n }\n }\n};\n```\n\n## Environment\n\nNo additional environment variables are needed for realtime. The Broadcaster DO runs inline in your main worker and uses `BETTER_AUTH_SECRET` (already required for auth) to sign and verify WebSocket tickets.\n\n| Variable | Description |\n|----------|-------------|\n| `BETTER_AUTH_SECRET` | Signs/verifies WebSocket tickets (already set for auth) |\n\nThe `BROADCASTER` binding is a `DurableObjectNamespace` — the compiler generates this in your `wrangler.toml` automatically:\n\n```toml\n[[durable_objects.bindings]]\nname = \"BROADCASTER\"\nclass_name = \"Broadcaster\"\n\n[[migrations]]\ntag = \"v1\"\nnew_classes = [\"Broadcaster\"]\n```\n\n## Architecture\n\n```\n 1. POST /ws-ticket\n┌───────────────────────────────────────────────┐ ┌─────────────────┐\n│ Quickback Worker │ ◄──│ Browser Client │\n│ │ ──►│ │\n│ ┌──────────┐ DO binding ┌────────────────┐ │ └───────┬─────────┘\n│ │ Hono API │ ───────────► │ Broadcaster DO │ │ │\n│ └──────────┘ (in-process)└───────┬────────┘ │ 2. WS ?ws_ticket=...\n│ │ │ │\n└────────────────────────────────────┼──────────┘ │\n │◄──────────────────────┘\n WebSocket (verified at upgrade)\n```\n\n1. **Client gets a ticket** — `POST /broadcast/v1/ws-ticket` on the main API (session-authenticated). Returns a 60-second HMAC-signed ticket.\n2. **Client connects** — Opens WebSocket with `?ws_ticket=<ticket>`. The Durable Object verifies the ticket cryptographically at upgrade and attaches the socket to the ticket's `scopeKey`, `organizationId`, or `userId`.\n3. **API broadcasts** — After CRUD ops, or from custom handlers, the API calls the Broadcaster DO directly via its binding (in-process, no network hop) using the same target model.\n\n## Best Practices\n\n### Broadcast After Commit\n\nAlways broadcast after the database operation succeeds:\n\n```typescript\n// Good - broadcast after successful insert\nconst [newApp] = await db.insert(applications).values(data).returning();\nawait realtime.insert('applications', newApp, ctx.activeOrgId!);\n\n// Bad - don't broadcast before confirming success\nawait realtime.insert('applications', data, ctx.activeOrgId!);\nawait db.insert(applications).values(data); // Could fail!\n```\n\n### Minimal Payloads\n\nOnly include necessary data in broadcasts:\n\n```typescript\n// Good - minimal payload\nawait realtime.update('applications',\n { id: record.id, stage: 'interview' },\n { id: record.id, stage: 'screening' },\n ctx.activeOrgId!\n);\n\n// Avoid - sending entire record with large content\nawait realtime.update('applications', fullRecord, oldRecord, ctx.activeOrgId!);\n```\n\n### Use Broadcasts for Complex Events\n\nFor events that don't map cleanly to CRUD:\n\n```typescript\n// Hiring pipeline stage completed\nawait realtime.broadcast('pipeline-stage-complete', {\n applicationId: application.id,\n stages: ['applied', 'screening', 'interview'],\n currentStage: 'offer',\n candidateId: application.candidateId\n}, ctx.activeOrgId!);\n```\n\n## Custom Event Namespaces\n\nFor complex applications with many custom events, you can define typed event namespaces using `defineRealtime`. This generates strongly-typed helper methods for your custom events.\n\n### Defining Event Namespaces\n\nCreate a file in `services/realtime/`:\n\n```typescript\n// services/realtime/screening.ts\n\nexport default defineRealtime({\n name: 'screening',\n events: ['started', 'progress', 'completed', 'failed'],\n description: 'Candidate screening pipeline events',\n});\n```\n\n### Generated Helper Methods\n\nAfter compilation, the `createRealtime()` helper includes your custom namespace:\n\n```typescript\n\nexport const execute: ActionExecutor = async ({ ctx, input }) => {\n const realtime = createRealtime(ctx.env);\n\n // Type-safe custom event methods\n await realtime.screening.started({\n applicationId: input.applicationId,\n }, ctx.activeOrgId!);\n\n // Progress updates\n await realtime.screening.progress({\n applicationId: input.applicationId,\n percent: 50,\n step: 'background-check',\n }, ctx.activeOrgId!);\n\n // Completion\n await realtime.screening.completed({\n applicationId: input.applicationId,\n result: 'passed',\n duration: 1234,\n }, ctx.activeOrgId!);\n\n return { success: true };\n};\n```\n\n### Event Format\n\nCustom namespace events use the `broadcast` type with namespaced event names:\n\n```json\n{\n \"type\": \"broadcast\",\n \"event\": \"screening:started\",\n \"payload\": {\n \"applicationId\": \"app_123\"\n }\n}\n```\n\n### Multiple Namespaces\n\nDefine multiple namespaces for different parts of your application:\n\n```typescript\n// services/realtime/notifications.ts\nexport default defineRealtime({\n name: 'notifications',\n events: ['interview-reminder', 'offer-update', 'application-received'],\n description: 'Recruitment notification events',\n});\n\n// services/realtime/presence.ts\nexport default defineRealtime({\n name: 'presence',\n events: ['joined', 'left', 'reviewing', 'idle'],\n description: 'Who is reviewing which candidate',\n});\n```\n\nUsage:\n```typescript\nconst realtime = createRealtime(ctx.env);\n\n// Notification events\nawait realtime.notifications['interview-reminder']({ ... }, ctx.activeOrgId!);\n\n// Presence events — who's reviewing which candidate\nawait realtime.presence.reviewing({ userId: ctx.userId, candidateId: 'cnd_456' }, ctx.activeOrgId!);\n```\n\n### Namespace vs Generic Broadcast\n\n| Use Case | Approach |\n|----------|----------|\n| One-off custom event | `realtime.broadcast('event-name', payload, orgId)` |\n| Repeated event patterns | `defineRealtime` namespace |\n| Type-safe events | `defineRealtime` namespace |\n| Event discovery | `defineRealtime` (appears in generated types) |"
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",
@@ -427,7 +451,7 @@ export const DOCS = {
427
451
  },
428
452
  "stack/storage/r2": {
429
453
  "title": "File Storage (R2)",
430
- "content": "Quickback provides built-in file storage using Cloudflare R2, with role-based access control and a dedicated files worker for serving.\n\n## Architecture\n\n```\n┌─────────────────────────────────────────────────────────────────────┐\n│ Your Application │\n│ │\n│ Upload/Manage Files Serve Files │\n│ ───────────────────── ────────────── │\n│ api.yourdomain.com files.yourdomain.com │\n│ /storage/v1/* /* │\n│ │\n│ ┌─────────────────────┐ ┌─────────────────────┐ │\n│ │ API Worker │ │ Files Worker │ │\n│ │ │ │ │ │\n│ │ POST /bucket │ │ GET /public/* │ │\n│ │ GET /bucket │ │ → No auth │ │\n│ │ POST /object/* │ │ │ │\n│ │ DELETE /object/* │ │ GET /* │ │\n│ │ │ │ → Session + RBAC │ │\n│ └──────────┬──────────┘ └──────────┬──────────┘ │\n│ │ │ │\n│ └───────────┬───────────────────┘ │\n│ │ │\n│ ▼ │\n│ ┌─────────────────────┐ │\n│ │ R2 Bucket │ │\n│ │ quickback-files │ │\n│ └─────────────────────┘ │\n└─────────────────────────────────────────────────────────────────────┘\n```\n\n## Enabling File Storage\n\nAdd the `fileStorage` provider to your `quickback.config.ts`:\n\n```typescript\nexport default {\n name: 'my-app',\n providers: {\n runtime: { name: 'cloudflare' },\n database: { name: 'cloudflare-d1' },\n auth: { name: 'better-auth' },\n fileStorage: {\n name: 'cloudflare-r2',\n config: {\n binding: 'R2_BUCKET',\n bucketName: 'my-app-files',\n filesBinding: 'FILES_DB',\n maxFileSize: 10 * 1024 * 1024, // 10MB\n allowedTypes: ['image/jpeg', 'image/png', 'image/webp'],\n },\n },\n },\n};\n```\n\n## API Endpoints\n\n### Storage API (api.yourdomain.com/storage/v1)\n\n| Method | Endpoint | Description |\n|--------|----------|-------------|\n| POST | `/bucket` | Create a bucket |\n| GET | `/bucket` | List buckets |\n| GET | `/bucket/:name` | Get bucket info |\n| DELETE | `/bucket/:name` | Delete bucket (must be empty) |\n| POST | `/object/:bucket/*path` | Upload file |\n| GET | `/object/:bucket/*path` | Download file |\n| HEAD | `/object/:bucket/*path` | Get file metadata |\n| DELETE | `/object/:bucket/*path` | Delete file (soft delete) |\n| GET | `/object` | List objects |\n| POST | `/url` | Get file URL for serving |\n\n### Files Worker (files.yourdomain.com)\n\n| Method | Path | Auth Required |\n|--------|------|---------------|\n| GET/HEAD | `/public/*` | No |\n| GET/HEAD | `/*` | Yes (session + RBAC) |\n\n## Buckets\n\nBuckets organize files and define access control policies.\n\n### Creating a Bucket\n\n```bash\nPOST /storage/v1/bucket\n{\n \"name\": \"avatars\",\n \"readScope\": \"organization\",\n \"writeScope\": \"organization\",\n \"readRoles\": [\"admin\", \"member\"],\n \"writeRoles\": [\"admin\"],\n \"deleteRoles\": [\"admin\"]\n}\n```\n\n### Scope Options\n\n| Scope | Read Behavior | Write Behavior |\n|-------|---------------|----------------|\n| `public` | Anyone can read | N/A |\n| `organization` | Org members only | Org members only |\n| `user` | Owner only | Owner only |\n\n### Role-Based Access\n\nYou can restrict operations to specific roles:\n\n```json\n{\n \"readRoles\": [\"admin\", \"member\"],\n \"writeRoles\": [\"admin\", \"editor\"],\n \"deleteRoles\": [\"admin\"]\n}\n```\n\nAn empty array `[]` means no role restriction (all authenticated users).\n\n## Uploading Files\n\n```bash\nPOST /storage/v1/object/avatars/profile.jpg\nContent-Type: image/jpeg\nContent-Length: 12345\n\n<binary data>\n```\n\nResponse:\n```json\n{\n \"id\": \"obj_123\",\n \"key\": \"org_abc/avatars/profile.jpg\",\n \"bucket\": \"avatars\",\n \"name\": \"profile.jpg\",\n \"size\": 12345,\n \"mimeType\": \"image/jpeg\",\n \"readScope\": \"organization\"\n}\n```\n\n## Serving Files\n\n### Public Files\n\nFiles in buckets with `readScope: \"public\"` are stored with a `public/` prefix:\n\n```\nhttps://files.yourdomain.com/public/org_abc/avatars/logo.png\n```\n\nNo authentication required.\n\n### Private Files\n\nPrivate files require a valid Better Auth session cookie:\n\n```\nhttps://files.yourdomain.com/org_abc/documents/report.pdf\n```\n\nThe files worker:\n1. Validates the session token\n2. Checks the user's organization matches\n3. Verifies role permissions (if `readRoles` configured)\n4. Serves the file or returns 403\n\n## Generated Files\n\nWhen file storage is configured, the compiler generates:\n\n| File | Purpose |\n|------|---------|\n| `src/routes/storage.ts` | Storage API routes |\n| `src/files.ts` | Files database schema (buckets, objects) |\n| `cloudflare-workers/files/index.ts` | Files worker for serving |\n| `cloudflare-workers/files/wrangler.toml` | Files worker config |\n\n## Deployment\n\nAfter compiling:\n\n1. **Create the R2 bucket:**\n ```bash\n wrangler r2 bucket create my-app-files\n ```\n\n2. **Create the files database:**\n ```bash\n wrangler d1 create my-app-files\n ```\n\n3. **Run migrations:**\n ```bash\n wrangler d1 migrations apply my-app-files --local\n wrangler d1 migrations apply my-app-files --remote\n ```\n\n4. **Deploy the API:**\n ```bash\n wrangler deploy\n ```\n\n5. **Deploy the files worker:**\n ```bash\n cd cloudflare-workers/files\n wrangler deploy\n ```\n\n## Configuration Reference\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `binding` | `string` | `R2_BUCKET` | R2 bucket binding name |\n| `bucketName` | `string` | Required | R2 bucket name |\n| `filesBinding` | `string` | `FILES_DB` | Files metadata D1 binding |\n| `maxFileSize` | `number` | 10MB | Max upload size in bytes |\n| `allowedTypes` | `string[]` | Images only | Allowed MIME types |\n| `publicDomain` | `string` | - | Custom domain for files worker |\n\n## Security Model\n\n- **Upload security**: Enforced by API worker (auth middleware, org check, role check)\n- **Serve security**: Enforced by files worker (session validation, metadata RBAC)\n- **Soft deletes**: Files are marked deleted in metadata but retained in R2\n- **Tenant isolation**: All files are prefixed with organization ID"
454
+ "content": "Quickback provides built-in file storage using Cloudflare R2, with role-based access control and a dedicated files worker for serving.\n\n## Architecture\n\n```\n┌─────────────────────────────────────────────────────────────────────┐\n│ Your Application │\n│ │\n│ Upload/Manage Files Serve Files │\n│ ───────────────────── ────────────── │\n│ api.yourdomain.com files.yourdomain.com │\n│ /storage/v1/* /* │\n│ │\n│ ┌─────────────────────┐ ┌─────────────────────┐ │\n│ │ API Worker │ │ Files Worker │ │\n│ │ │ │ │ │\n│ │ POST /bucket │ │ GET /public/* │ │\n│ │ GET /bucket │ │ → No auth │ │\n│ │ POST /object/* │ │ │ │\n│ │ DELETE /object/* │ │ GET /* │ │\n│ │ │ │ → Session + RBAC │ │\n│ └──────────┬──────────┘ └──────────┬──────────┘ │\n│ │ │ │\n│ └───────────┬───────────────────┘ │\n│ │ │\n│ ▼ │\n│ ┌─────────────────────┐ │\n│ │ R2 Bucket │ │\n│ │ quickback-files │ │\n│ └─────────────────────┘ │\n└─────────────────────────────────────────────────────────────────────┘\n```\n\n## Enabling File Storage\n\nAdd the `fileStorage` provider to your `quickback.config.ts`:\n\n```typescript\nexport default {\n name: 'my-app',\n providers: {\n runtime: { name: 'cloudflare' },\n database: { name: 'cloudflare-d1' },\n auth: { name: 'better-auth' },\n fileStorage: {\n name: 'cloudflare-r2',\n config: {\n binding: 'R2_BUCKET',\n bucketName: 'my-app-files',\n filesBinding: 'FILES_DB',\n maxFileSize: 10 * 1024 * 1024, // 10MB\n allowedTypes: ['image/jpeg', 'image/png', 'image/webp'],\n },\n },\n },\n};\n```\n\n## API Endpoints\n\n### Storage API (api.yourdomain.com/storage/v1)\n\n| Method | Endpoint | Description |\n|--------|----------|-------------|\n| POST | `/bucket` | Create a bucket |\n| GET | `/bucket` | List buckets |\n| GET | `/bucket/:name` | Get bucket info |\n| DELETE | `/bucket/:name` | Delete bucket (must be empty) |\n| POST | `/object/:bucket/*path` | Upload file (bytes through the Worker) |\n| POST | `/presign/:bucket/*path` | **Presigned upload URL (bytes direct to R2)** |\n| POST | `/confirm/:bucket/*path` | Confirm a presigned upload (reconcile size + etag) |\n| GET | `/object/:bucket/*path` | Download file |\n| HEAD | `/object/:bucket/*path` | Get file metadata |\n| DELETE | `/object/:bucket/*path` | Delete file (soft delete) |\n| GET | `/object` | List objects |\n| POST | `/url` | Get file URL for serving |\n\n### Files Worker (files.yourdomain.com)\n\n| Method | Path | Auth Required |\n|--------|------|---------------|\n| GET/HEAD | `/public/*` | No |\n| GET/HEAD | `/*` | Yes (session + RBAC) |\n\n## Buckets\n\nBuckets organize files and define access control policies.\n\n### Creating a Bucket\n\n```bash\nPOST /storage/v1/bucket\n{\n \"name\": \"avatars\",\n \"readScope\": \"organization\",\n \"writeScope\": \"organization\",\n \"readRoles\": [\"admin\", \"member\"],\n \"writeRoles\": [\"admin\"],\n \"deleteRoles\": [\"admin\"]\n}\n```\n\n### Scope Options\n\n| Scope | Read Behavior | Write Behavior |\n|-------|---------------|----------------|\n| `public` | Anyone can read | N/A |\n| `organization` | Org members only | Org members only |\n| `user` | Owner only | Owner only |\n\n### Role-Based Access\n\nYou can restrict operations to specific roles:\n\n```json\n{\n \"readRoles\": [\"admin\", \"member\"],\n \"writeRoles\": [\"admin\", \"editor\"],\n \"deleteRoles\": [\"admin\"]\n}\n```\n\nAn empty array `[]` means no role restriction (all authenticated users).\n\n## Uploading Files\n\n```bash\nPOST /storage/v1/object/avatars/profile.jpg\nContent-Type: image/jpeg\nContent-Length: 12345\n\n<binary data>\n```\n\nResponse:\n```json\n{\n \"id\": \"obj_123\",\n \"key\": \"org_abc/avatars/profile.jpg\",\n \"bucket\": \"avatars\",\n \"name\": \"profile.jpg\",\n \"size\": 12345,\n \"mimeType\": \"image/jpeg\",\n \"readScope\": \"organization\"\n}\n```\n\n## Presigned uploads (recommended)\n\nStreaming bytes through the Worker (`POST /object`) is fine for small files, but\nit puts every byte on the Worker's request path — subject to the body-size cap,\nand billed as Worker CPU/duration. For media (video, audio, large PDFs), use a\n**presigned URL**: the Worker runs all the access checks and hands back a\nshort-lived URL the client uploads to **directly**. The bytes never touch your\nWorker.\n\n```bash\n# 1. Ask the API to sign an upload URL (auth + bucket + role checks run here)\ncurl -X POST https://api.example.com/storage/v1/presign/videos/clip.mp4 \\\n -H \"Authorization: Bearer <token>\" \\\n -H \"Content-Type: application/json\" \\\n -d '{ \"contentType\": \"video/mp4\", \"size\": 73400320 }'\n\n# Response:\n# {\n# \"id\": \"obj_abc\",\n# \"key\": \"org_abc/videos/clip.mp4\",\n# \"uploadUrl\": \"https://<account>.r2.cloudflarestorage.com/...&X-Amz-Signature=...\",\n# \"method\": \"PUT\",\n# \"headers\": { \"Content-Type\": \"video/mp4\" },\n# \"expiresAt\": \"2026-06-02T12:10:00.000Z\"\n# }\n\n# 2. Upload the bytes straight to R2 (replay the returned headers verbatim)\ncurl -X PUT \"<uploadUrl>\" -H \"Content-Type: video/mp4\" --data-binary @clip.mp4\n\n# 3. Confirm — reconciles the recorded size + etag against what actually landed\ncurl -X POST https://api.example.com/storage/v1/confirm/videos/clip.mp4 \\\n -H \"Authorization: Bearer <token>\"\n```\n\n### Required secrets\n\nPresigning uses R2's S3-compatible API, which needs an **R2 API token** — the\nWorkers bucket binding alone cannot presign. Create a token in the Cloudflare\ndashboard (R2 → Manage API Tokens) and set:\n\n```bash\nwrangler secret put R2_ACCOUNT_ID # your Cloudflare account id\nwrangler secret put R2_ACCESS_KEY_ID # R2 API token access key id\nwrangler secret put R2_SECRET_ACCESS_KEY # R2 API token secret\n# Optional: wrangler secret put R2_S3_ENDPOINT # override the derived endpoint\n```\n\n### Signing from your own action\n\nThe same signer is exposed as `ctx.storage` inside any\n[`defineAction`](/compiler/definitions/actions) — so you can author an upload endpoint that\nruns your own access rules (org, team, relationship/scoped roles) and stores the\nkey in **your own table**, instead of the generic `buckets`/`objects` metadata:\n\n```typescript\nexport default defineAction({\n path: '/event/:eventId/media/sign-upload',\n method: 'POST',\n input: z.object({ filename: z.string(), contentType: z.string() }),\n access: { roles: ['admin', 'member', 'scope:event:attendee'] },\n async execute({ input, ctx, db, storage }) {\n // Tenant-scoped key — secure by construction\n const key = `org/${ctx.activeOrgId}/event/${input.eventId}/${crypto.randomUUID()}-${input.filename}`;\n const upload = await storage.signPutUrl(key, {\n contentType: input.contentType,\n expiresIn: 600,\n });\n await db.insert(images).values({ key, eventId: input.eventId /* … */ });\n return { uploadUrl: upload.url, key, headers: upload.headers };\n },\n});\n```\n\n`storage` exposes:\n\n| Method | Returns | Use |\n|--------|---------|-----|\n| `signPutUrl(key, { contentType?, expiresIn? })` | `{ url, method, headers, key, expiresAt }` | Client uploads directly to R2 |\n| `signGetUrl(key, { expiresIn?, downloadFilename? })` | `string` | Client downloads directly from R2 |\n\nThis is the supported replacement for streaming a raw binary body through an\naction — the JSON body parser and its ~1 MiB cap stay on for every other route.\n\n## Serving Files\n\n### Public Files\n\nFiles in buckets with `readScope: \"public\"` are stored with a `public/` prefix:\n\n```\nhttps://files.yourdomain.com/public/org_abc/avatars/logo.png\n```\n\nNo authentication required.\n\n### Private Files\n\nPrivate files require a valid Better Auth session cookie:\n\n```\nhttps://files.yourdomain.com/org_abc/documents/report.pdf\n```\n\nThe files worker:\n1. Validates the session token\n2. Checks the user's organization matches\n3. Verifies role permissions (if `readRoles` configured)\n4. Serves the file or returns 403\n\n## Generated Files\n\nWhen file storage is configured, the compiler generates:\n\n| File | Purpose |\n|------|---------|\n| `src/storage/routes.ts` | Storage API routes (upload, presign, confirm, download) |\n| `src/storage/presign.ts` | R2 presigned-URL signer (`createPresigner`, backs `ctx.storage`) |\n| `src/files/schema.ts` | Files database schema (buckets, objects) |\n| `cloudflare-workers/files/index.ts` | Files worker for serving |\n| `cloudflare-workers/files/wrangler.toml` | Files worker config |\n\nThe compiler also adds [`aws4fetch`](https://github.com/mhart/aws4fetch) to your\n`package.json` (used by the presigner) and the R2 presign secrets to your\ngenerated `CloudflareBindings` type.\n\n## Deployment\n\nAfter compiling:\n\n1. **Create the R2 bucket:**\n ```bash\n wrangler r2 bucket create my-app-files\n ```\n\n2. **Create the files database:**\n ```bash\n wrangler d1 create my-app-files\n ```\n\n3. **Run migrations:**\n ```bash\n wrangler d1 migrations apply my-app-files --local\n wrangler d1 migrations apply my-app-files --remote\n ```\n\n4. **Deploy the API:**\n ```bash\n wrangler deploy\n ```\n\n5. **Deploy the files worker:**\n ```bash\n cd cloudflare-workers/files\n wrangler deploy\n ```\n\n6. **Set the R2 presign secrets** (only if you use presigned uploads — see\n [Presigned uploads](#presigned-uploads-recommended)):\n ```bash\n wrangler secret put R2_ACCOUNT_ID\n wrangler secret put R2_ACCESS_KEY_ID\n wrangler secret put R2_SECRET_ACCESS_KEY\n ```\n\n## Configuration Reference\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `binding` | `string` | `R2_BUCKET` | R2 bucket binding name |\n| `bucketName` | `string` | Required | R2 bucket name |\n| `filesBinding` | `string` | `FILES_DB` | Files metadata D1 binding |\n| `maxFileSize` | `number` | 10MB | Max upload size in bytes |\n| `allowedTypes` | `string[]` | Images only | Allowed MIME types |\n| `publicDomain` | `string` | - | Custom domain for files worker |\n\n## Security Model\n\n- **Upload security**: Enforced by API worker (auth middleware, org check, role check)\n- **Serve security**: Enforced by files worker (session validation, metadata RBAC)\n- **Soft deletes**: Files are marked deleted in metadata but retained in R2\n- **Tenant isolation**: All files are prefixed with organization ID"
431
455
  },
432
456
  "stack/storage/using-kv": {
433
457
  "title": "Using KV",
@@ -435,7 +459,7 @@ export const DOCS = {
435
459
  },
436
460
  "stack/storage/using-r2": {
437
461
  "title": "Using R2",
438
- "content": "Cloudflare R2 provides S3-compatible object storage for file uploads in the Quickback Stack.\n\n## Upload Flow\n\nThe generated API provides a two-step upload process:\n\n1. **Request a presigned URL** — Client calls the upload endpoint to get a time-limited URL\n2. **Upload directly to R2** — Client uploads the file directly to R2 (bypasses your Worker)\n3. **Store the reference** — The API records the file metadata in D1\n\n```bash\n# 1. Request presigned upload URL\ncurl -X POST https://api.example.com/api/v1/files/upload \\\n -H \"Authorization: Bearer <token>\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"filename\": \"report.pdf\", \"contentType\": \"application/pdf\"}'\n\n# Response:\n# { \"uploadUrl\": \"https://bucket.r2.cloudflarestorage.com/...\", \"fileId\": \"file_abc123\" }\n\n# 2. Upload directly to R2 using the presigned URL\ncurl -X PUT \"<uploadUrl>\" \\\n -H \"Content-Type: application/pdf\" \\\n --data-binary @report.pdf\n```\n\n## Download Flow\n\nFiles are served through your Worker with security checks applied:\n\n```bash\n# Download a file (auth + firewall enforced)\ncurl https://api.example.com/api/v1/files/file_abc123/download \\\n -H \"Authorization: Bearer <token>\"\n```\n\nThe download endpoint:\n1. Validates the user's session\n2. Checks firewall — the file must belong to the user's organization\n3. Checks access — the user must have the required role\n4. Streams the file from R2\n\n## Role-Based Access\n\nFile access respects the same security layers as your API:\n\n- **Firewall** — Users can only access files belonging to their organization\n- **Access** — Role-based download permissions\n\n## See Also\n\n- [R2 Setup](/stack/storage/r2) — Bucket creation, wrangler bindings, and configuration\n- [Avatars](/stack/account-ui/features/avatars) — Avatar upload UI integration"
462
+ "content": "Cloudflare R2 provides S3-compatible object storage for file uploads in the Quickback Stack.\n\n## Upload Flow\n\nThe generated API provides a two-step **presigned** upload — the file bytes go\ndirectly to R2 and never stream through your Worker:\n\n1. **Request a presigned URL** — Client calls `/storage/v1/presign/...`; the\n Worker runs auth + bucket + role checks and returns a time-limited URL\n2. **Upload directly to R2** — Client `PUT`s the bytes to R2 (bypasses your Worker)\n3. **Confirm** — `/storage/v1/confirm/...` reconciles the recorded size + etag\n\n```bash\n# 1. Request a presigned upload URL\ncurl -X POST https://api.example.com/storage/v1/presign/documents/report.pdf \\\n -H \"Authorization: Bearer <token>\" \\\n -H \"Content-Type: application/json\" \\\n -d '{ \"contentType\": \"application/pdf\", \"size\": 248000 }'\n\n# Response:\n# {\n# \"id\": \"obj_abc123\",\n# \"key\": \"org_abc/documents/report.pdf\",\n# \"uploadUrl\": \"https://<account>.r2.cloudflarestorage.com/...&X-Amz-Signature=...\",\n# \"method\": \"PUT\",\n# \"headers\": { \"Content-Type\": \"application/pdf\" },\n# \"expiresAt\": \"2026-06-02T12:10:00.000Z\"\n# }\n\n# 2. Upload directly to R2 using the presigned URL (replay the returned headers)\ncurl -X PUT \"<uploadUrl>\" \\\n -H \"Content-Type: application/pdf\" \\\n --data-binary @report.pdf\n\n# 3. Confirm the upload\ncurl -X POST https://api.example.com/storage/v1/confirm/documents/report.pdf \\\n -H \"Authorization: Bearer <token>\"\n```\n\nPresigning needs an R2 API token — set the `R2_ACCOUNT_ID`, `R2_ACCESS_KEY_ID`,\nand `R2_SECRET_ACCESS_KEY` secrets. See [R2 Setup → Presigned uploads](/stack/storage/r2#presigned-uploads-recommended).\n\nFor uploads that should land in **your own table** (with your own access rules),\nsign the URL from inside a `defineAction` via `ctx.storage` — see\n[Signing from your own action](/stack/storage/r2#signing-from-your-own-action).\n\n## Download Flow\n\nFiles are served through your Worker with security checks applied:\n\n```bash\n# Download a file (auth + firewall enforced)\ncurl https://api.example.com/api/v1/files/file_abc123/download \\\n -H \"Authorization: Bearer <token>\"\n```\n\nThe download endpoint:\n1. Validates the user's session\n2. Checks firewall — the file must belong to the user's organization\n3. Checks access — the user must have the required role\n4. Streams the file from R2\n\n## Role-Based Access\n\nFile access respects the same security layers as your API:\n\n- **Firewall** — Users can only access files belonging to their organization\n- **Access** — Role-based download permissions\n\n## See Also\n\n- [R2 Setup](/stack/storage/r2) — Bucket creation, wrangler bindings, and configuration\n- [Avatars](/stack/account-ui/features/avatars) — Avatar upload UI integration"
439
463
  },
440
464
  "stack/vector/embeddings": {
441
465
  "title": "Automatic Embeddings",
@@ -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",