@quickback-dev/cli 0.18.0 → 0.34.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.
- package/dist/commands/compile.d.ts.map +1 -1
- package/dist/commands/compile.js +25 -1
- package/dist/commands/compile.js.map +1 -1
- package/dist/commands/migrations.d.ts +17 -0
- package/dist/commands/migrations.d.ts.map +1 -0
- package/dist/commands/migrations.js +328 -0
- package/dist/commands/migrations.js.map +1 -0
- package/dist/docs/content.d.ts.map +1 -1
- package/dist/docs/content.js +33 -63
- package/dist/docs/content.js.map +1 -1
- package/dist/index.js +7 -1
- package/dist/index.js.map +1 -1
- package/dist/lib/api-client.d.ts +17 -0
- package/dist/lib/api-client.d.ts.map +1 -1
- package/dist/lib/api-client.js.map +1 -1
- package/dist/lib/file-loader.d.ts +39 -0
- package/dist/lib/file-loader.d.ts.map +1 -1
- package/dist/lib/file-loader.js +73 -0
- package/dist/lib/file-loader.js.map +1 -1
- package/dist/lib/file-loader.test.js +22 -1
- package/dist/lib/file-loader.test.js.map +1 -1
- package/dist/skill/docs/changelog.md +1118 -1
- package/dist/skill/docs/compiler/config/domains.md +70 -10
- package/dist/skill/docs/compiler/config/index.md +74 -3
- package/dist/skill/docs/compiler/config/output.md +1 -1
- package/dist/skill/docs/compiler/config/providers.md +6 -12
- package/dist/skill/docs/compiler/config/single-tenant.md +1 -1
- package/dist/skill/docs/compiler/config/variables.md +0 -30
- package/dist/skill/docs/compiler/definitions/access.md +357 -3
- package/dist/skill/docs/compiler/definitions/actions.md +85 -8
- package/dist/skill/docs/compiler/definitions/schema.md +6 -10
- package/dist/skill/docs/compiler/index.md +15 -34
- package/dist/skill/docs/compiler/targets/hono-api/cloudflare.md +1 -2
- package/dist/skill/docs/compiler/targets/hono-api/database/neon.md +0 -1
- package/dist/skill/docs/compiler/targets/hono-api/using-the-api/actions-api.md +19 -0
- package/dist/skill/docs/compiler/targets/hono-api/using-the-api/batch-operations.md +1 -1
- package/dist/skill/docs/compiler/targets/index.md +6 -34
- package/dist/skill/docs/index.md +2 -5
- package/dist/skill/docs/stack/account-ui/customization.md +2 -14
- package/dist/skill/docs/stack/account-ui/environment-variables.md +7 -1
- package/dist/skill/docs/stack/account-ui/features/admin.md +2 -2
- package/dist/skill/docs/stack/account-ui/features/avatars.md +2 -4
- package/dist/skill/docs/stack/account-ui/features/index.md +1 -1
- package/dist/skill/docs/stack/account-ui/features/organizations.md +31 -11
- package/dist/skill/docs/stack/account-ui/hooks.md +4 -0
- package/dist/skill/docs/stack/account-ui/index.md +5 -43
- package/dist/skill/docs/stack/account-ui/with-quickback.md +2 -75
- package/dist/skill/docs/stack/auth/plugins/aws-ses.md +60 -0
- package/dist/skill/docs/stack/auth/plugins/aws-sns.md +169 -0
- package/dist/skill/docs/stack/auth/plugins/index.md +106 -0
- package/package.json +1 -1
- package/src/skill/docs/changelog.md +1057 -0
- package/src/skill/docs/compiler/config/domains.md +26 -0
- package/src/skill/docs/compiler/config/index.md +74 -3
- package/src/skill/docs/compiler/config/providers.md +6 -12
- package/src/skill/docs/compiler/config/single-tenant.md +1 -1
- package/src/skill/docs/compiler/config/variables.md +0 -30
- package/src/skill/docs/compiler/definitions/access.md +357 -3
- package/src/skill/docs/compiler/definitions/actions.md +85 -8
- package/src/skill/docs/compiler/definitions/schema.md +6 -10
- package/src/skill/docs/compiler/index.md +15 -34
- package/src/skill/docs/compiler/targets/hono-api/cloudflare.md +1 -2
- package/src/skill/docs/compiler/targets/hono-api/database/neon.md +0 -1
- package/src/skill/docs/compiler/targets/hono-api/using-the-api/actions-api.md +19 -0
- package/src/skill/docs/compiler/targets/hono-api/using-the-api/batch-operations.md +1 -1
- package/src/skill/docs/compiler/targets/index.md +6 -34
- package/src/skill/docs/index.md +2 -5
- package/src/skill/docs/stack/account-ui/customization.md +2 -14
- package/src/skill/docs/stack/account-ui/environment-variables.md +7 -1
- package/src/skill/docs/stack/account-ui/features/admin.md +2 -2
- package/src/skill/docs/stack/account-ui/features/avatars.md +2 -4
- package/src/skill/docs/stack/account-ui/features/index.md +1 -1
- package/src/skill/docs/stack/account-ui/features/organizations.md +31 -11
- package/src/skill/docs/stack/account-ui/hooks.md +4 -0
- package/src/skill/docs/stack/account-ui/index.md +5 -43
- package/src/skill/docs/stack/account-ui/with-quickback.md +2 -75
- package/src/skill/docs/stack/auth/plugins/aws-ses.md +60 -0
- package/src/skill/docs/stack/auth/plugins/aws-sns.md +169 -0
- package/src/skill/docs/stack/auth/plugins/index.md +32 -0
- package/dist/skill/docs/compiler/targets/supabase-rls/index.md +0 -55
- package/dist/skill/docs/compiler/targets/supabase-rls/limitations.md +0 -48
- package/dist/skill/docs/compiler/targets/supabase-rls/mappings.md +0 -99
- package/dist/skill/docs/compiler/targets/supabase-rls/setup.md +0 -88
- package/dist/skill/docs/stack/account-ui/library-usage.md +0 -257
- package/dist/skill/docs/stack/account-ui/standalone.md +0 -149
- package/dist/skill/docs/stack/account-ui/worker.md +0 -362
- package/src/skill/docs/compiler/targets/supabase-rls/index.md +0 -55
- package/src/skill/docs/compiler/targets/supabase-rls/limitations.md +0 -48
- package/src/skill/docs/compiler/targets/supabase-rls/mappings.md +0 -99
- package/src/skill/docs/compiler/targets/supabase-rls/setup.md +0 -88
- package/src/skill/docs/stack/account-ui/library-usage.md +0 -257
- package/src/skill/docs/stack/account-ui/standalone.md +0 -149
- package/src/skill/docs/stack/account-ui/worker.md +0 -362
package/dist/docs/content.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
export const DOCS = {
|
|
4
4
|
"changelog": {
|
|
5
5
|
"title": "Changelog",
|
|
6
|
-
"content": "# Changelog\n\nRelease notes for the Quickback compiler, CLI, and platform.\n\n---\n\n## v0.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.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",
|
|
@@ -47,19 +47,19 @@ export const DOCS = {
|
|
|
47
47
|
},
|
|
48
48
|
"compiler/config/domains": {
|
|
49
49
|
"title": "Multi-Domain Architecture",
|
|
50
|
-
"content": "A single Quickback-compiled Cloudflare Worker can serve your API, CMS, Account UI, and Admin panel on separate custom domains. The compiler generates hostname-based routing so each domain serves the right content.\n\n## How It Works\n\nWhen you configure custom domains for CMS, Account, or Admin, the compiler:\n\n1. Adds `custom_domain` routes to `wrangler.toml`\n2. Generates hostname-based middleware in the Worker\n3. Auto-configures cross-subdomain cookies for shared authentication\n4. Auto-infers a unified `quickback.{baseDomain}` fallback domain\n\nAll five domains point to the **same Worker** — there's only one deployment.\n\n## Domain Types\n\n| Domain | Config | Serves | API Routes |\n|--------|--------|--------|-----------|\n| `api.example.com` | `providers.runtime.config.routes` | API only | All |\n| `cms.example.com` | `cms: { domain }` | CMS SPA | Blocked (404) |\n| `auth.example.com` | `account: { domain }` | Account SPA | Pass-through |\n| `admin.example.com` | `account: { adminDomain }` | Account SPA | Pass-through |\n| `quickback.example.com` | Auto-inferred | Everything | All |\n\n### CMS Domain\n\nServes the CMS SPA at root (`/`). API routes (`/api/`, `/auth/`, `/admin/`, `/storage/`, `/health`) return 404 — preventing direct API access on the CMS domain.\n\n### Account Domain\n\nServes the Account SPA at root (`/`). API and auth routes pass through to the Worker so authentication flows work directly on this domain.\n\n### Admin Domain\n\nIdentical behavior to the Account domain — serves the same Account SPA at root. The Account SPA's client-side router handles the `/admin` route, restricting access to users with the `admin` role.\n\n### Unified Domain\n\nThe compiler auto-infers a `quickback.{baseDomain}` domain from your configured custom domains. For example, if you have `cms.example.com`, it creates `quickback.example.com`.\n\nOn this domain, **everything is available** on a single origin:\n\n| Path | Content |\n|------|---------|\n| `/` | Redirects to `/cms/` |\n| `/cms/` | CMS SPA |\n| `/account/` | Account SPA |\n| `/api/v1/...` | API routes |\n| `/auth/...` | Auth routes |\n| `/admin/...` | Admin API routes |\n| `/storage/...` | File storage |\n| `/health` | Health check |\n| `/openapi.json` | OpenAPI spec |\n\nThe unified domain is useful for development and debugging. You can override it with an explicit `domain` field in your config.\n\n## Configuration\n\n```typescript title=\"quickback/quickback.config.ts\"\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 auth: { password: true, admin: true },\n },\n trustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n \"https://cms.example.com\",\n ],\n providers: {\n runtime: { name: \"cloudflare\", config: {\n routes: [{ pattern: \"api.example.com\", custom_domain: true }],\n }},\n // ...database, auth\n },\n};\n```\n\nThis generates the following `wrangler.toml` routes:\n\n```toml\nroutes = [\n { pattern = \"api.example.com\", custom_domain = true },\n { pattern = \"cms.example.com\", custom_domain = true },\n { pattern = \"auth.example.com\", custom_domain = true },\n { pattern = \"admin.example.com\", custom_domain = true },\n { pattern = \"quickback.example.com\", custom_domain = true }\n]\n```\n\n## Cross-Subdomain Authentication\n\nWhen two or more custom domains share a parent domain (e.g., `cms.example.com` + `auth.example.com`), the compiler automatically configures Better Auth for cross-subdomain cookie sharing:\n\n- Sets `crossSubDomainCookies: { enabled: true, domain: '.example.com' }`\n- Sets `sameSite: 'none'` and `secure: true` on auth cookies\n\nThis means a user who logs in on `auth.example.com` is automatically authenticated on `cms.example.com` and `admin.example.com` — no additional setup needed.\n\n## Compile-Time Feature Gating\n\nWhen the compiler builds the Account SPA, it excludes route files for disabled features **before** the Vite build. This means disabled features never appear in the JavaScript bundle.\n\n| Feature Flag | Routes Excluded When `false` |\n|-------------|------------------------------|\n| `auth.organizations` | Dashboard, organization CRUD, org switching (`$slug`) |\n| `auth.passkey` | Passkey management and setup |\n| `auth.admin` | Admin panel routes |\n\nThis keeps bundle sizes minimal and prevents dead code in production. Users can't access disabled features even if they navigate to the URL directly — the routes don't exist in the build.\n\n## Hostname Routing Details\n\nThe compiler generates middleware that checks `new URL(c.req.url).hostname` on every request:\n\n**CMS domain** — Blocks API routes with 404. All other paths are mapped to the `/cms/` asset prefix and served with SPA fallback to `/cms/index.html`.\n\n**Account/Admin domain** — API and auth routes (`/api/`, `/auth/`, `/admin/`, `/storage/`, `/health`) pass through to Hono handlers. All other paths are mapped to the `/account/` asset prefix and served with SPA fallback to `/account/index.html`.\n\n**Unified domain** — No hostname filtering. CMS is served at `/cms/`, Account at `/account/`. Root (`/`) redirects to `/cms/`. API routes work at their standard paths.\n\n## Without Custom Domains\n\nIf you enable `cms` and `account` without custom domains, everything is served on a single domain:\n\n- CMS at `/cms/` (root `/` redirects to `/cms/`)\n- Account UI at `/account/`\n- API at `/api/v1/`\n- Auth at `/auth/`\n\nThis is the simplest setup — no DNS configuration needed, no cross-subdomain cookies. Auth cookies work naturally because everything is same-origin.\n\n## See Also\n\n- [Configuration](/compiler/config) — CMS and Account config options\n- [Output Structure](/compiler/config/output) — Generated file and directory layout\n- [CMS](/stack/cms) — Schema-driven admin interface\n- [Account UI](/stack/account-ui) — Authentication and account management"
|
|
50
|
+
"content": "A single Quickback-compiled Cloudflare Worker can serve your API, CMS, Account UI, Admin panel, and your own product SPAs on separate custom domains. The compiler generates hostname-based routing so each domain serves the right content.\n\n## How It Works\n\nWhen you configure custom domains for CMS, Account, Admin, or `apps`, the compiler:\n\n1. Adds `custom_domain` routes to `wrangler.toml`\n2. Generates hostname-based middleware in the Worker\n3. Auto-configures cross-subdomain cookies for shared authentication\n4. Auto-infers a unified `quickback.{baseDomain}` fallback domain\n\nAll configured domains point to the **same Worker** — there's only one deployment.\n\n## Domain Types\n\n| Domain | Config | Serves | API Routes |\n|--------|--------|--------|-----------|\n| `api.example.com` | `providers.runtime.config.routes` | API only | All |\n| `cms.example.com` | `cms: { domain }` | CMS SPA | Blocked (404) |\n| `auth.example.com` | `account: { domain }` | Account SPA | Pass-through |\n| `admin.example.com` | `account: { adminDomain }` | Account SPA | Pass-through |\n| `www.example.com` | `apps: { <name>: { domain } }` | User-authored SPA | Pass-through |\n| `quickback.example.com` | Auto-inferred | Everything | All |\n\n### CMS Domain\n\nServes the CMS SPA at root (`/`). API routes (`/api/`, `/auth/`, `/admin/`, `/storage/`, `/health`) return 404 — preventing direct API access on the CMS domain.\n\n### Account Domain\n\nServes the Account SPA at root (`/`). API and auth routes pass through to the Worker so authentication flows work directly on this domain.\n\n### Admin Domain\n\nIdentical behavior to the Account domain — serves the same Account SPA at root. The Account SPA's client-side router handles the `/admin` route, restricting access to users with the `admin` role.\n\n### App Domains\n\nMount your own product SPAs on dedicated hostnames via the `apps` field. Each entry binds one or more hostnames to a directory under `src/apps/<name>/` and inherits the same API/auth pass-through behavior as the Account domain — so the SPA can hit `/api/v1/...` and `/auth/...` same-origin without CORS.\n\n```typescript\napps: {\n www: {\n domain: \"www.example.com\",\n aliasDomains: [\"example.com\"], // apex serves the same SPA\n },\n marketing: {\n domain: \"marketing.example.com\",\n },\n}\n```\n\n| Option | Required | Description |\n|--------|----------|-------------|\n| `domain` | Yes | Primary custom hostname served at root (`/`) |\n| `aliasDomains` | No | Additional hostnames that serve the same SPA. Each gets its own `custom_domain = true` route. Common case: apex (`example.com`) alongside `www.example.com`. |\n| `assetsDir` | No | Subdirectory under `src/apps/` to serve from. Defaults to the record key. Override only when the on-disk directory needs to differ from the URL-facing name. |\n\nDrop the prebuilt SPA output at `quickback/apps/<name>/` — the source-apps passthrough copies it byte-for-byte into `src/apps/<name>/` on every compile. The compiler doesn't build the SPA; it just emits routing for whatever's already there. See [Output Structure](/compiler/config/output#source-apps-quickbackapps) for the passthrough rules.\n\nThe names `cms`, `account`, and `public` are reserved (they collide with compiler-emitted directories under `src/apps/`). Two app entries can't claim the same hostname, and an app's hostname can't collide with `cms.domain` / `account.domain` / `account.adminDomain`.\n\n### Unified Domain\n\nThe compiler auto-infers a `quickback.{baseDomain}` domain from your configured custom domains. For example, if you have `cms.example.com`, it creates `quickback.example.com`.\n\nOn this domain, **everything is available** on a single origin:\n\n| Path | Content |\n|------|---------|\n| `/` | Redirects to `/cms/` |\n| `/cms/` | CMS SPA |\n| `/account/` | Account SPA |\n| `/api/v1/...` | API routes |\n| `/auth/...` | Auth routes |\n| `/admin/...` | Admin API routes |\n| `/storage/...` | File storage |\n| `/health` | Health check |\n| `/openapi.json` | OpenAPI spec |\n\nThe unified domain is useful for development and debugging. You can override it with an explicit `domain` field in your config.\n\n## Configuration\n\n```typescript title=\"quickback/quickback.config.ts\"\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 auth: { password: true, admin: true },\n },\n apps: {\n www: {\n domain: \"www.example.com\",\n aliasDomains: [\"example.com\"],\n },\n },\n providers: {\n runtime: { name: \"cloudflare\", config: {\n routes: [{ pattern: \"api.example.com\", custom_domain: true }],\n }},\n // ...database, auth\n },\n};\n```\n\n`trustedOrigins` is optional here — every `cms.domain`, `account.domain`, `account.adminDomain`, and `apps[*].domain` (plus aliases) is automatically added. Declare `trustedOrigins` only when you need to allow an origin the compiler can't infer (e.g. a third-party domain).\n\nThis generates the following `wrangler.toml` routes:\n\n```toml\nroutes = [\n { pattern = \"api.example.com\", custom_domain = true },\n { pattern = \"cms.example.com\", custom_domain = true },\n { pattern = \"auth.example.com\", custom_domain = true },\n { pattern = \"admin.example.com\", custom_domain = true },\n { pattern = \"www.example.com\", custom_domain = true },\n { pattern = \"example.com\", custom_domain = true },\n { pattern = \"quickback.example.com\", custom_domain = true }\n]\n```\n\n## Cross-Subdomain Authentication\n\nWhen two or more custom domains share a parent domain (e.g., `cms.example.com` + `auth.example.com` + `www.example.com`), the compiler automatically configures Better Auth for cross-subdomain cookie sharing. App hostnames (primary + aliases) are folded into the shared-parent detection alongside the CMS, Account, Admin, and top-level `domain` slots:\n\n- Sets `crossSubDomainCookies: { enabled: true, domain: '.example.com' }`\n- Sets `sameSite: 'none'` and `secure: true` on auth cookies\n\nThis means a user who logs in on `auth.example.com` is automatically authenticated on `cms.example.com`, `admin.example.com`, and `www.example.com` — no additional setup needed. Apex aliases (e.g. `example.com` listed under `aliasDomains`) are recognized as already being the parent — they don't break shared-parent equality.\n\n## Compile-Time Feature Gating\n\nWhen the compiler builds the Account SPA, it excludes route files for disabled features **before** the Vite build. This means disabled features never appear in the JavaScript bundle.\n\n| Feature Flag | Routes Excluded When `false` |\n|-------------|------------------------------|\n| `auth.organizations` | Dashboard, organization CRUD, org switching (`$slug`) |\n| `auth.passkey` | Passkey management and setup |\n| `auth.admin` | Admin panel routes |\n\nThis keeps bundle sizes minimal and prevents dead code in production. Users can't access disabled features even if they navigate to the URL directly — the routes don't exist in the build.\n\n## Hostname Routing Details\n\nThe compiler generates middleware that checks `new URL(c.req.url).hostname` on every request:\n\n**CMS domain** — Blocks API routes with 404. All other paths are mapped to the `/cms/` asset prefix and served with SPA fallback to `/cms/index.html`.\n\n**Account/Admin domain** — API and auth routes (`/api/`, `/auth/`, `/admin/`, `/storage/`, `/health`) pass through to Hono handlers. All other paths are mapped to the `/account/` asset prefix and served with SPA fallback to `/account/index.html`.\n\n**App domain** — Identical to Account: API/auth/admin/storage/health pass through, other paths map to `/<assetsDir>/` with SPA fallback. The multi-domain catchall (emitted when both CMS and Account are configured) explicitly skips app hostnames, so an API miss on an app host lands in `app.notFound` (404 JSON) instead of stray-serving a sibling SPA's HTML.\n\n**Unified domain** — No hostname filtering. CMS is served at `/cms/`, Account at `/account/`. Root (`/`) redirects to `/cms/`. API routes work at their standard paths.\n\n## Without Custom Domains\n\nIf you enable `cms` and `account` without custom domains, everything is served on a single domain:\n\n- CMS at `/cms/` (root `/` redirects to `/cms/`)\n- Account UI at `/account/`\n- API at `/api/v1/`\n- Auth at `/auth/`\n\nThis is the simplest setup — no DNS configuration needed, no cross-subdomain cookies. Auth cookies work naturally because everything is same-origin.\n\n## Preview Deploys\n\nThe same compiled bundle can be deployed to additional hostnames — preview environments, staging, per-PR URLs — without recompiling. Set the `EXTRA_APP_HOSTS` env var on the deploy target (a comma-separated list of hostnames) and the worker treats each one like an entry in `apps[*].domain`:\n\n- Apps hostname middleware serves the SPA at root.\n- CORS / Better Auth `trustedOrigins` trusts requests whose `Origin` hostname matches.\n\nEmpty or unset means no extension and zero behavior change for production.\n\n```toml title=\"wrangler.preview.toml\"\n[vars]\nEXTRA_APP_HOSTS = \"app-preview.example.com,pr-42.example.com\"\n```\n\n```bash\n# Or set as a secret per deploy target\nwrangler secret put EXTRA_APP_HOSTS --env preview\n```\n\nMirrors the existing `BETTER_AUTH_URL` auto-trust behavior, where the deployed worker auto-trusts its own configured base origin without needing an explicit `trustedOrigins` entry. With `EXTRA_APP_HOSTS`, one env var extends both the apps allowlist and the CORS allowlist.\n\n## See Also\n\n- [Configuration](/compiler/config) — CMS and Account config options\n- [Output Structure](/compiler/config/output) — Generated file and directory layout\n- [CMS](/stack/cms) — Schema-driven admin interface\n- [Account UI](/stack/account-ui) — Authentication and account management"
|
|
51
51
|
},
|
|
52
52
|
"compiler/config": {
|
|
53
53
|
"title": "Configuration",
|
|
54
|
-
"content": "The `quickback.config.ts` file configures your Quickback project. It defines which providers to use, which features to enable, and how the compiler generates code.\n\n```typescript\n\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n features: { organizations: true },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## Discoverable options block\n\nAfter your first `quickback compile`, the file gets a managed block bracketed by sentinel comments:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: cloudflare({}),\n\n // [quickback:options-start]\n // ── Project ──\n //\n // Primary custom domain (auto-inferred from cms/account/api domains if unset).\n // domain: \"example.com\",\n //\n // ── Embedded UIs (CMS / Account) ──\n //\n // Login/signup/profile/orgs SPA. Set `true` for default, or object to customize.\n // account: {\n // fileUploads: false, // show the avatar upload UI on the profile page\n // auth: { passkey: false, emailOTP: false, ... },\n // ...\n // },\n //\n // ... every other option Quickback supports\n // [quickback:options-end]\n});\n```\n\nThis block is **regenerated on every compile** — the compiler is the source of truth, so newly added options surface automatically when you upgrade Quickback (no CLI bump needed).\n\n**To enable an option**, copy the line you care about *above* the `[quickback:options-start]` sentinel and uncomment it:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: cloudflare({}),\n\n account: {\n fileUploads: true, // ← lifted out of the managed block\n },\n\n // [quickback:options-start]\n // ... account is now omitted from this block on next compile\n // [quickback:options-end]\n});\n```\n\nQuickback notices that `account` is set above the marker and drops it from the managed block on the next compile to avoid duplicate definitions. Anything outside the marker block is yours and never touched.\n\nIf you ever want to opt out of the auto-managed block, run:\n\n```bash\nquickback compile --no-sync-config\n```\n\n## Required Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `name` | `string` | Project name |\n| `template` | `\"hono\"` | Application template (`\"nextjs\"` is experimental) |\n| `providers` | `object` | Runtime, database, and auth provider configuration |\n\n## Optional Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `features` | `object` | Feature flags — see [Single-Tenant Mode](/compiler/config/single-tenant) |\n| `build` | `object` | Build options (`outputDir`, `packageManager`, `dependencies`) |\n| `compiler` | `object` | Compiler options — `features.auditFields: false` disables audit field injection project-wide; `migrations.renames` provides rename hints for headless CI; `securityContracts` tunes the route/SQL invariants checker |\n| `openapi` | `object` | OpenAPI spec generation (`generate`, `publish`, `docs: 'scalar' \\| 'swagger'` for an in-browser API reference) — see [OpenAPI](/compiler/targets/hono-api/using-the-api/openapi) |\n| `schemaRegistry` | `object` | Schema registry generation for the CMS (enabled by default, `{ generate: false }` to disable) — see [Schema Registry](/stack/cms/schema-registry) |\n| `etag` | `object` | ETag caching for GET responses (enabled by default, `{ enabled: false }` to disable) — see [Caching & ETags](/compiler/targets/hono-api/using-the-api/caching) |\n| `cms` | `boolean \\| object` | Embed CMS in compiled Worker — see [CMS](/stack/cms) |\n| `account` | `boolean \\| object` | Embed Account UI in compiled Worker — see [Account UI](/stack/account-ui) |\n| `trustedOrigins` | `string[]` | CORS trusted origins for cross-domain auth |\n| `domain` | `string` | Primary API domain (auto-inferred from custom domains if not set) |\n| `dev` | `object` | Local development settings (`port`) |\n| `auth` | `object` | App-level auth settings (`roleHierarchy`) — see [Access](/compiler/definitions/access#role-hierarchy) |\n| `email` | `object` | Email delivery config (`provider`, `from`, `fromName`) |\n\n## Custom Dependencies\n\nAdd third-party npm packages to the generated `package.json` using `build.dependencies`. This is useful when your action handlers import external libraries.\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n build: {\n dependencies: {\n \"fast-xml-parser\": \"^4.5.0\",\n \"lodash-es\": \"^4.17.21\",\n },\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\nThese are merged into the generated `package.json` alongside Quickback's own dependencies. Run `npm install` after compiling to install them.\n\n## Headless Migration Rename Hints\n\nWhen `drizzle-kit generate` detects a potential rename, it normally prompts for confirmation. Cloud/CI compiles are non-interactive, so you must provide explicit rename hints.\n\nAdd hints in `compiler.migrations.renames`:\n\n```typescript\nexport default defineConfig({\n // ...\n compiler: {\n migrations: {\n renames: {\n // Keys are NEW names, values are OLD names\n tables: {\n events_v2: \"events\",\n },\n columns: {\n events: {\n summary_text: \"summary\",\n },\n },\n },\n },\n },\n});\n```\n\nRules:\n- `tables`: `new_table_name -> old_table_name`\n- `columns.<table>`: `new_column_name -> old_column_name`\n- Keys must match the names in your current schema (the new names)\n- Validation fails fast for malformed rename config, unsupported keys, or conflicting legacy/new rename paths.\n\n## Disable Audit Field Injection\n\nBy default, Quickback auto-injects four **audit fields** (`createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`) into every feature table, plus two **soft-delete fields** (`deletedAt`, `deletedBy`) into tables that use soft delete (the default delete mode). The audit fields drive record-provenance queries and the CMS audit panel; the soft-delete pair drives soft-delete filtering.\n\nTo opt out project-wide:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n compiler: {\n features: {\n auditFields: false, // skip audit-field injection globally\n },\n },\n providers: { /* ... */ },\n});\n```\n\nWhen disabled, you're responsible for supplying these columns yourself if you want soft delete, audit trails, or modifiedAt-based optimistic concurrency. See the [Schema → Audit Fields](/compiler/definitions/schema#audit-fields) section for the full list and what each field drives.\n\n## Security Contract Reports and Signing\n\nAfter generation, Quickback verifies machine-checkable security contracts for Hono routes and RLS SQL.\n\nIt also emits a report artifact and signature artifact by default:\n\n- `reports/security-contracts.report.json`\n- `reports/security-contracts.report.sig.json`\n\nYou can configure output paths and signing behavior:\n\n```typescript\nexport default defineConfig({\n // ...\n compiler: {\n securityContracts: {\n failMode: \"error\", // or \"warn\"\n report: {\n path: \"reports/security-contracts.report.json\",\n signature: {\n enabled: true,\n required: true,\n keyEnv: \"QUICKBACK_SECURITY_REPORT_SIGNING_KEY\",\n keyId: \"prod-k1\",\n path: \"reports/security-contracts.report.sig.json\",\n },\n },\n },\n },\n});\n```\n\nIf `signature.required: true` and no key is available, compilation fails with a clear error message (or warning in `failMode: \"warn\"`).\n\n## CMS Configuration\n\nEmbed the [Quickback CMS](/stack/cms) in your compiled Worker. The CMS reads your schema registry and renders a complete admin interface — zero UI code per table.\n\n```typescript\n// Simple — embed CMS at root\ncms: true,\n\n// With custom domain\ncms: { domain: \"cms.example.com\" },\n\n// With access control (only admins can access CMS)\ncms: { domain: \"cms.example.com\", access: \"admin\" },\n\n// Cross-tenant DB-admin tier — sysadmins see every tenant's data\ncms: { domain: \"cms.example.com\", sysadmin: true },\n```\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `domain` | `string` | — | Custom domain for CMS. Adds a `custom_domain` route to `wrangler.toml`. |\n| `access` | `\"user\" \\| \"admin\"` | `\"user\"` | Controls who can access the CMS. When `\"admin\"`, only users with `user.role === \"admin\"` can enter — enforced at the Worker level (SPA shell, `/api/v1/schema`, and `custom_view` CRUD all return 403 to non-admins) and in the SPA. Also hides the CMS link in Account UI. See [CMS Connecting](/stack/cms/connecting) for the full enforcement model. |\n| `sysadmin` | `boolean` | `false` | Cross-tenant DB-admin tier. When `true`, opts into the `SYSADMIN` pseudo-role (`user.role === \"sysadmin\"`), the firewall escape hatch (sysadmins bypass tenant scopes, soft-delete still enforced), the cross-tenant `/admin/v1/sysadmin/organizations` endpoint, and the SPA's \"All organizations\" sentinel. The CMS HTML gate admits `userRole === \"sysadmin\"` alongside `\"admin\"` — sysadmin is a strict superset. Off by default. See [`SYSADMIN` pseudo-role](/compiler/definitions/access#sysadmin--cross-tenant-db-admin-tier). |\n\n### Sysadmin tier (`cms.sysadmin: true`)\n\nQuickback's default model assumes every CMS user belongs to at least one organization (`member` row in the auth DB). For platforms that need a Supabase-style cross-tenant DB-admin tool — debugging a tenant's data, running cross-tenant queries, supporting a customer — that's a poor fit: a sysadmin without `member` rows would dead-end, and auto-filling their active org from \"first membership\" silently scopes them to a tenant they have no relationship with.\n\n`cms: { sysadmin: true }` introduces a separate role tier:\n\n- **Role**: `user.role === \"sysadmin\"` (set on the Better Auth user table). Distinct from `\"admin\"` — admins keep org-scoped CMS access via the membership switcher; sysadmins get cross-tenant.\n- **Firewall**: every `buildFirewallConditions()` emits an `if (ctx.userRole === \"sysadmin\") return undefined` (or just the soft-delete predicate when present) at the top, so sysadmins see every tenant's rows. See [Firewall escape hatch](/compiler/definitions/firewall#sysadmin-escape-hatch).\n- **Org listing**: a new `GET /admin/v1/sysadmin/organizations` endpoint selects directly from the auth-schema `organization` table — every row, every tenant. The existing `/admin/v1/organizations` (membership-bound, used by org admins) is unchanged.\n- **CMS SPA**: when the user is a sysadmin, the header switcher loads from the cross-tenant endpoint, defaults to \"All organizations\" (which omits `?organizationId=` and reaches the firewall escape), and pins selected tenants via `?organizationId=` on every API call. Org admins keep the existing membership-based switcher.\n- **CMS HTML gate**: admits `userRole === \"sysadmin\"` alongside `\"admin\"`. Org admins are not locked out — both roles can enter the CMS in `cms.access: \"admin\"` mode.\n\nOff by default. Projects that don't enable it get zero behavior change; setting `cms.sysadmin: true` and granting a user `user.role = \"sysadmin\"` is the only way to unlock the cross-tenant view.\n\n## Account UI Configuration\n\nEmbed the [Account UI](/stack/account-ui) in your compiled Worker. Provides login, signup, profile management, organization management, and admin — all built from your config at compile time.\n\nFor post-signup logic — auto-provisioning a workspace, gating signup, setting an active organization — drop a file in `quickback/hooks/`. See [Auth Hooks](/stack/account-ui/hooks).\n\n```typescript\n// Simple — embed Account UI with defaults\naccount: true,\n\n// Full configuration\naccount: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n companyName: \"My Company\",\n auth: {\n password: true,\n emailOTP: false,\n passkey: true,\n organizations: true,\n admin: true,\n },\n},\n```\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `domain` | `string` | Custom domain for Account UI (e.g., `auth.example.com`) |\n| `adminDomain` | `string` | Custom domain for admin-only access (e.g., `admin.example.com`). Serves the same Account SPA — the client-side router handles admin routing. |\n| `appUrl` | `string` | URL of the tenant's main application — where users are redirected after login. Baked into the Account SPA as `VITE_QUICKBACK_APP_URL`. Independent from `domain`. |\n| `name` | `string` | App display name shown on login, profile, and email templates |\n| `companyName` | `string` | Company name for branding |\n| `tagline` | `string` | App tagline shown on login page |\n| `description` | `string` | App description |\n\n### Auth Feature Flags\n\nControl which authentication features are 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 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"
|
|
55
55
|
},
|
|
56
56
|
"compiler/config/output": {
|
|
57
57
|
"title": "Output Structure",
|
|
58
|
-
"content": "The compiler generates a complete project structure based on your definitions and provider configuration. The output varies depending on your runtime (Cloudflare vs Bun) and enabled features.\n\n**Warning:** Never edit files in `src/` directly. They are overwritten on every compile. Make changes in your `quickback/` definitions instead.\n\n## Cloudflare Output\n\n```\nsrc/\n├── index.ts # Hono app entry point (Workers export)\n├── env.d.ts # Cloudflare bindings TypeScript types\n├── db/\n│ ├── index.ts # Database connection factory\n│ ├── auth-schema.ts # Auth table schemas (dual mode)\n│ └── features-schema.ts # Feature table schemas (dual mode)\n├── auth/\n│ └── index.ts # Better Auth instance & config\n├── features/\n│ └── {feature}/\n│ ├── schema.ts # Drizzle table definition\n│ ├── routes.ts # CRUD + action endpoints\n│ └── actions.ts # Action handlers (if defined)\n├── lib/\n│ ├── access.ts # Access control helpers\n│ ├── types.ts # Runtime type definitions\n│ ├── masks.ts # Field masking utilities\n│ ├── services.ts # Service layer\n│ ├── audit-wrapper.ts # Auto-inject audit fields\n│ └── security-audit.ts # Unsafe cross-tenant audit logger (when needed)\n└── middleware/\n ├── auth.ts # Auth context middleware\n ├── db.ts # Database instance middleware\n └── services.ts # Service injection middleware\n\nquickback/drizzle/\n├── auth/ # Auth migrations (dual mode)\n│ ├── meta/\n│ │ ├── _journal.json\n│ │ └── 0000_snapshot.json\n│ └── 0000_initial.sql\n├── features/ # Feature migrations (dual mode)\n│ ├── meta/\n│ │ ├── _journal.json\n│ │ └── 0000_snapshot.json\n│ └── 0000_initial.sql\n└── audit/ # Unsafe cross-tenant action audit migrations (when needed)\n ├── meta/\n └── 0000_initial.sql\n\n# Root config files\n├── package.json\n├── tsconfig.json\n├── wrangler.toml # Cloudflare Workers config\n├── drizzle.config.ts # Features DB drizzle config\n├── drizzle.auth.config.ts # Auth DB drizzle config (dual mode)\n└── drizzle.audit.config.ts # Audit DB drizzle config (when unsafe actions exist)\n```\n\n## Bun Output\n\n```\nsrc/\n├── index.ts # Hono app entry point (Bun server)\n├── db/\n│ ├── index.ts # SQLite connection (bun:sqlite)\n│ └── schema.ts # Combined schema (single DB)\n├── auth/\n│ └── index.ts # Better Auth instance\n├── features/\n│ └── {feature}/\n│ ├── schema.ts\n│ ├── routes.ts\n│ └── actions.ts\n├── lib/\n│ ├── access.ts\n│ ├── types.ts\n│ ├── masks.ts\n│ ├── services.ts\n│ └── audit-wrapper.ts\n└── middleware/\n ├── auth.ts\n ├── db.ts\n └── services.ts\n\nquickback/drizzle/ # Single migration directory\n├── meta/\n│ ├── _journal.json\n│ └── 0000_snapshot.json\n└── 0000_initial.sql\n\ndata/ # SQLite database files\n└── app.db\n\n├── package.json\n├── tsconfig.json\n└── drizzle.config.ts\n```\n\n## Key Differences by Runtime\n\n| Aspect | Cloudflare | Bun |\n|--------|-----------|-----|\n| Entry point | Workers `export default` | `Bun.serve()` with port |\n| Database | D1 bindings (dual mode) | SQLite file (single DB) |\n| Types | `env.d.ts` for bindings | No extra types needed |\n| Config | `wrangler.toml` | `.env` file |\n| Migrations | `quickback/drizzle/auth/` + `quickback/drizzle/features/` | `quickback/drizzle/` |\n| Drizzle configs | 2 configs (auth + features) | 1 config |\n\n## Optional Output Files\n\nThese files are generated only when the corresponding features are configured:\n\n### Embeddings\n\nWhen any feature has `embeddings` configured:\n\n```\nsrc/\n├── lib/\n│ └── embeddings.ts # Embedding helpers\n├── routes/\n│ └── embeddings.ts # POST /api/v1/embeddings endpoint\n└── queue-consumer.ts # Queue handler for async embedding jobs\n```\n\n### File Storage (R2)\n\nWhen `fileStorage` is configured:\n\n```\nsrc/\n└── routes/\n └── storage.ts # File upload/download endpoints\nquickback/drizzle/\n└── files/ # File metadata migrations\n ├── meta/\n └── 0000_*.sql\n```\n\n### Webhooks\n\nWhen webhooks are enabled:\n\n```\nsrc/\n└── lib/\n └── webhooks/\n ├── index.ts # Webhook module entry\n ├── sign.ts # Webhook payload signing\n ├── handlers.ts # Handler registry\n ├── emit.ts # Queue emission helpers\n ├── routes.ts # Inbound/outbound endpoints\n └── providers/\n ├── index.ts\n └── stripe.ts # Stripe webhook handler\nquickback/drizzle/\n└── webhooks/ # Webhook schema migrations\n ├── meta/\n └── 0000_*.sql\n```\n\n### Security Audit Database (Unsafe Actions)\n\nWhen any action enables unsafe cross-tenant mode (`unsafe.crossTenant: true`):\n\n```\nsrc/\n├── db/\n│ └── audit-schema.ts # audit_events table\n└── lib/\n └── security-audit.ts # mandatory audit writer\n\nquickback/drizzle/\n└── audit/\n ├── meta/\n └── 0000_*.sql\n\n# Root\n└── drizzle.audit.config.ts\n```\n\nCloudflare output also includes an `AUDIT_DB` D1 binding in `wrangler.toml` and migration scripts:\n\n- `db:migrate:audit:local`\n- `db:migrate:audit:remote`\n\n### Security Contract Report and Signature\n\nGenerated on every compile (unless disabled via `compiler.securityContracts.report.enabled: false`):\n\n```\nreports/\n├── security-contracts.report.json # Contract evaluation summary + violations\n└── security-contracts.report.sig.json # Signature / digest envelope for the report\n```\n\nThe signature file uses HMAC-SHA256 when a signing key is configured, otherwise it falls back to SHA-256 digest mode. \nSet `compiler.securityContracts.report.signature.required: true` to fail compilation when a signing key is missing.\n\n### Realtime\n\nWhen any feature has `realtime` configured:\n\n```\nsrc/\n├── lib/\n│ ├── realtime.ts # Broadcast helpers\n│ ├── Broadcaster.ts # Durable Object class (inline in main worker)\n│ └── ws-ticket.ts # WebSocket ticket auth utility\n└── routes/\n └── ws-ticket.ts # POST /realtime/v1/ws-ticket endpoint\n```\n\nThe Broadcaster DO class is exported from your main worker entry point and runs inline — no separate `cloudflare-workers/broadcast/` deployment needed.\n\n### Device Authorization\n\nWhen the `deviceAuthorization` plugin is enabled:\n\n```\nsrc/\n└── routes/\n └── cli-auth.ts # Device auth flow endpoints\n```\n\n## Database Schemas\n\n### Dual Database Mode (Cloudflare Default)\n\nThe compiler separates schemas into two files:\n\n**`src/db/auth-schema.ts`** — Re-exports Better Auth table schemas:\n- `users`, `sessions`, `accounts`\n- `organizations`, `members`, `invitations` (if organizations enabled)\n- Plugin-specific tables (`apiKeys`, etc.)\n\n**`src/db/features-schema.ts`** — Re-exports your feature schemas:\n- All tables defined with `defineTable()`\n- Audit field columns added automatically\n\n### Single Database Mode (Bun Default)\n\n**`src/db/schema.ts`** — Combined re-export of all schemas (auth + features).\n\n## Generated Routes\n\nFor each feature, the compiler generates a routes file at `src/features/{name}/routes.ts` containing:\n\n| Route | Generated When |\n|-------|----------------|\n| `GET /` | `crud.list` configured |\n| `GET /:id` | `crud.get` configured |\n| `POST /` | `crud.create` configured |\n| `PATCH /:id` | `crud.update` configured |\n| `DELETE /:id` | `crud.delete` configured |\n| `PUT /:id` | `crud.put` configured |\n| `POST /batch` | `crud.create` exists (auto-enabled) |\n| `PATCH /batch` | `crud.update` exists (auto-enabled) |\n| `DELETE /batch` | `crud.delete` exists (auto-enabled) |\n| `PUT /batch` | `crud.put` exists (auto-enabled) |\n| `GET /views/{name}` | `views` configured |\n| `POST /:id/{action}` | Record-based actions defined |\n| `POST /{action}` | Standalone actions defined |\n\nAll routes are mounted under `/api/v1/{feature}` in the main app.\n\n## Migrations\n\nThe compiler runs `drizzle-kit generate` during compilation to produce SQL migration files. On subsequent compiles, it uses `existingFiles` (your current migration state) to generate only incremental changes.\n\nThe CLI loads migration meta JSON from one location only — `<project>/quickback/drizzle/`:\n\n- `quickback/drizzle/auth/meta/`\n- `quickback/drizzle/features/meta/`\n- `quickback/drizzle/files/meta/`\n- `quickback/drizzle/webhooks/meta/`\n- `quickback/drizzle/audit/meta/`\n- `quickback/drizzle/meta/` (single-database mode)\n\nQuickback owns this state — nothing under a project-root `drizzle/` folder is ever read or written.\n\nMigration and report artifacts are written to the `quickback/` state directory:\n\n- `quickback/drizzle/...` for Drizzle migration SQL/meta artifacts\n- `quickback/reports/...` for security contract report artifacts\n\nFor non-interactive environments (cloud compile, CI), table/column renames must be declared with `compiler.migrations.renames` in `quickback.config.ts`. This avoids interactive rename prompts during migration generation.\n\nMigration files follow the Drizzle Kit naming convention:\n```\n0000_initial.sql\n0001_add_status_column.sql\n0002_create_orders_table.sql\n```\n\n## CMS and Account UI Assets\n\nWhen `cms` and/or `account` are enabled, the compiler builds the SPAs from source at compile time and includes the assets in the output.\n\nEach SPA is placed in its own subdirectory under `src/apps/`:\n\n```\nsrc/apps/ # Root assets directory\n├── cms/ # CMS SPA (served at /cms/ on unified domain)\n│ ├── index.html\n│ └── assets/\n│ ├── app.abc123.js # Content-hashed filenames from Vite\n│ └── app.xyz456.css\n└── account/ # Account SPA (served at /account/ on unified domain)\n ├── index.html\n └── assets/\n ├── app.def789.js\n └── app.ghi012.css\n```\n\nOn custom domains, each SPA is served at root (`/`) via hostname-based routing. On the unified domain, CMS is at `/cms/` and Account is at `/account/`.\n\n### Static Assets (`quickback/public/`)\n\nAnything you drop under `quickback/public/` is copied verbatim into `src/apps/` on every compile. The compiler does not parse, template, or otherwise touch these files — they are bytes that ride past it into the Cloudflare ASSETS binding.\n\n```\nquickback/public/ # Source — checked into your repo\n├── favicon.ico\n├── robots.txt\n├── og/\n│ └── og-image.png\n└── pdfs/\n └── whitepaper.pdf\n```\n\nAfter compile:\n\n```\nsrc/apps/ # Destination — written by the CLI\n├── favicon.ico # Served at https://your-domain/favicon.ico\n├── robots.txt # Served at /robots.txt\n├── og/og-image.png # Served at /og/og-image.png\n├── pdfs/whitepaper.pdf\n├── cms/ # Compiler-emitted SPA (don't shadow)\n└── account/ # Compiler-emitted SPA (don't shadow)\n```\n\nNotes:\n\n- The folder is optional. If it doesn't exist, this step is a no-op.\n- Files removed from `quickback/public/` disappear from `src/apps/` on the next compile — `src/` is wiped and rewritten each run.\n- Hidden entries (`.DS_Store`, `.git/`, dotfiles) are skipped.\n- A file in `quickback/public/` that would overwrite a compiler-emitted path (e.g. `quickback/public/cms/index.html`) fails the compile with a clear error rather than silently shadowing the SPA shell.\n- Binaries (images, fonts, PDFs) are copied byte-for-byte — there is no string round-trip.\n\n### Source Apps (`quickback/apps/`)\n\nFor hand-authored TypeScript apps that live alongside the compiler-emitted SPA shells, drop them under `quickback/apps/<name>/`. The CLI copies the tree into `src/apps/<name>/` on every compile, byte-for-byte, after the compiler has finished writing.\n\n```\nquickback/apps/ # Source — checked into your repo\n├── m/ # A hand-authored mobile companion app\n│ ├── index.tsx\n│ ├── components/Button.tsx\n│ └── lib/utils.ts\n└── admin/ # A hand-authored admin tool\n └── index.tsx\n```\n\nAfter compile:\n\n```\nsrc/apps/\n├── m/index.tsx # Hand-authored — preserved across compiles\n├── m/components/Button.tsx\n├── m/lib/utils.ts\n├── admin/index.tsx\n├── cms/ # Compiler-emitted SPA (don't shadow)\n└── account/ # Compiler-emitted SPA (don't shadow)\n```\n\nWhen to choose `apps/` vs `public/`:\n\n| | `quickback/public/` | `quickback/apps/` |\n|---|---|---|\n| **Use for** | Static binaries (logos, fonts, OG images, PDFs, robots.txt) | Hand-authored TS/TSX/JS app source |\n| **Skips** | Hidden entries only (`.DS_Store`, `.git/`) | Hidden entries + `node_modules/`, `dist/`, `build/`, `.next/`, `.turbo/`, `.cache/` |\n| **Folder layout** | Files at any depth — flat or nested | Apps under named subfolders (`m/`, `admin/`, …) |\n\nNotes:\n\n- The folder is optional. If it doesn't exist, this step is a no-op.\n- Files removed from `quickback/apps/<name>/` disappear from `src/apps/<name>/` on the next compile — `src/` is wiped and rewritten each run.\n- A file in `quickback/apps/` that would overwrite a compiler-emitted path (e.g. `quickback/apps/cms/index.tsx` while `cms: true`) fails the compile with a clear error.\n- Migrating from hand-edited `src/apps/<name>/`: move the entire folder under `quickback/apps/<name>/` once, then trust the compile cycle. The hermetic `src/` contract holds again.\n\n### Generated Wrangler Assets Config\n\nThe compiler always generates `run_worker_first = true` when SPAs are enabled — the Worker handles all SPA routing (per hostname and per path prefix):\n\n```toml\n[assets]\nbinding = \"ASSETS\"\ndirectory = \"src/apps\"\nnot_found_handling = \"none\"\nrun_worker_first = true\n```\n\nSee [Multi-Domain Architecture](/compiler/config/domains) for details on hostname routing.\n\n## See Also\n\n- [Providers](/compiler/config/providers) — Configure runtime, database, and auth providers\n- [Environment variables](/compiler/config/variables) — Required variables by runtime\n- [Multi-Domain Architecture](/compiler/config/domains) — Custom domains and hostname routing"
|
|
58
|
+
"content": "The compiler generates a complete project structure based on your definitions and provider configuration. The output varies depending on your runtime (Cloudflare vs Bun) and enabled features.\n\n**Warning:** Never edit files in `src/` directly. They are overwritten on every compile. Make changes in your `quickback/` definitions instead.\n\n## Cloudflare Output\n\n```\nsrc/\n├── index.ts # Hono app entry point (Workers export)\n├── env.d.ts # Cloudflare bindings TypeScript types\n├── db/\n│ ├── index.ts # Database connection factory\n│ ├── auth-schema.ts # Auth table schemas (dual mode)\n│ └── features-schema.ts # Feature table schemas (dual mode)\n├── auth/\n│ └── index.ts # Better Auth instance & config\n├── features/\n│ └── {feature}/\n│ ├── schema.ts # Drizzle table definition\n│ ├── routes.ts # CRUD + action endpoints\n│ └── actions.ts # Action handlers (if defined)\n├── lib/\n│ ├── access.ts # Access control helpers\n│ ├── types.ts # Runtime type definitions\n│ ├── masks.ts # Field masking utilities\n│ ├── services.ts # Service layer\n│ ├── audit-wrapper.ts # Auto-inject audit fields\n│ └── security-audit.ts # Unsafe cross-tenant audit logger (when needed)\n└── middleware/\n ├── auth.ts # Auth context middleware\n ├── db.ts # Database instance middleware\n └── services.ts # Service injection middleware\n\nquickback/drizzle/\n├── auth/ # Auth migrations (dual mode)\n│ ├── meta/\n│ │ ├── _journal.json\n│ │ └── 0000_snapshot.json\n│ └── 0000_initial.sql\n├── features/ # Feature migrations (dual mode)\n│ ├── meta/\n│ │ ├── _journal.json\n│ │ └── 0000_snapshot.json\n│ └── 0000_initial.sql\n└── audit/ # Unsafe cross-tenant action audit migrations (when needed)\n ├── meta/\n └── 0000_initial.sql\n\n# Root config files\n├── package.json\n├── tsconfig.json\n├── wrangler.toml # Cloudflare Workers config\n├── drizzle.config.ts # Features DB drizzle config\n├── drizzle.auth.config.ts # Auth DB drizzle config (dual mode)\n└── drizzle.audit.config.ts # Audit DB drizzle config (when unsafe actions exist)\n```\n\n## Bun Output\n\n```\nsrc/\n├── index.ts # Hono app entry point (Bun server)\n├── db/\n│ ├── index.ts # SQLite connection (bun:sqlite)\n│ └── schema.ts # Combined schema (single DB)\n├── auth/\n│ └── index.ts # Better Auth instance\n├── features/\n│ └── {feature}/\n│ ├── schema.ts\n│ ├── routes.ts\n│ └── actions.ts\n├── lib/\n│ ├── access.ts\n│ ├── types.ts\n│ ├── masks.ts\n│ ├── services.ts\n│ └── audit-wrapper.ts\n└── middleware/\n ├── auth.ts\n ├── db.ts\n └── services.ts\n\nquickback/drizzle/ # Single migration directory\n├── meta/\n│ ├── _journal.json\n│ └── 0000_snapshot.json\n└── 0000_initial.sql\n\ndata/ # SQLite database files\n└── app.db\n\n├── package.json\n├── tsconfig.json\n└── drizzle.config.ts\n```\n\n## Key Differences by Runtime\n\n| Aspect | Cloudflare | Bun |\n|--------|-----------|-----|\n| Entry point | Workers `export default` | `Bun.serve()` with port |\n| Database | D1 bindings (dual mode) | SQLite file (single DB) |\n| Types | `env.d.ts` for bindings | No extra types needed |\n| Config | `wrangler.toml` | `.env` file |\n| Migrations | `quickback/drizzle/auth/` + `quickback/drizzle/features/` | `quickback/drizzle/` |\n| Drizzle configs | 2 configs (auth + features) | 1 config |\n\n## Optional Output Files\n\nThese files are generated only when the corresponding features are configured:\n\n### Embeddings\n\nWhen any feature has `embeddings` configured:\n\n```\nsrc/\n├── lib/\n│ └── embeddings.ts # Embedding helpers\n├── routes/\n│ └── embeddings.ts # POST /api/v1/embeddings endpoint\n└── queue-consumer.ts # Queue handler for async embedding jobs\n```\n\n### File Storage (R2)\n\nWhen `fileStorage` is configured:\n\n```\nsrc/\n└── routes/\n └── storage.ts # File upload/download endpoints\nquickback/drizzle/\n└── files/ # File metadata migrations\n ├── meta/\n └── 0000_*.sql\n```\n\n### Webhooks\n\nWhen webhooks are enabled:\n\n```\nsrc/\n└── lib/\n └── webhooks/\n ├── index.ts # Webhook module entry\n ├── sign.ts # Webhook payload signing\n ├── handlers.ts # Handler registry\n ├── emit.ts # Queue emission helpers\n ├── routes.ts # Inbound/outbound endpoints\n └── providers/\n ├── index.ts\n └── stripe.ts # Stripe webhook handler\nquickback/drizzle/\n└── webhooks/ # Webhook schema migrations\n ├── meta/\n └── 0000_*.sql\n```\n\n### Security Audit Database (Unsafe Actions)\n\nWhen any action enables unsafe cross-tenant mode (`unsafe.crossTenant: true`):\n\n```\nsrc/\n├── db/\n│ └── audit-schema.ts # audit_events table\n└── lib/\n └── security-audit.ts # mandatory audit writer\n\nquickback/drizzle/\n└── audit/\n ├── meta/\n └── 0000_*.sql\n\n# Root\n└── drizzle.audit.config.ts\n```\n\nCloudflare output also includes an `AUDIT_DB` D1 binding in `wrangler.toml` and migration scripts:\n\n- `db:migrate:audit:local`\n- `db:migrate:audit:remote`\n\n### Security Contract Report and Signature\n\nGenerated on every compile (unless disabled via `compiler.securityContracts.report.enabled: false`):\n\n```\nreports/\n├── security-contracts.report.json # Contract evaluation summary + violations\n└── security-contracts.report.sig.json # Signature / digest envelope for the report\n```\n\nThe signature file uses HMAC-SHA256 when a signing key is configured, otherwise it falls back to SHA-256 digest mode. \nSet `compiler.securityContracts.report.signature.required: true` to fail compilation when a signing key is missing.\n\n### Realtime\n\nWhen any feature has `realtime` configured:\n\n```\nsrc/\n├── lib/\n│ ├── realtime.ts # Broadcast helpers\n│ ├── Broadcaster.ts # Durable Object class (inline in main worker)\n│ └── ws-ticket.ts # WebSocket ticket auth utility\n└── routes/\n └── ws-ticket.ts # POST /realtime/v1/ws-ticket endpoint\n```\n\nThe Broadcaster DO class is exported from your main worker entry point and runs inline — no separate `cloudflare-workers/broadcast/` deployment needed.\n\n### Device Authorization\n\nWhen the `deviceAuthorization` plugin is enabled:\n\n```\nsrc/\n└── routes/\n └── cli-auth.ts # Device auth flow endpoints\n```\n\n## Database Schemas\n\n### Dual Database Mode (Cloudflare Default)\n\nThe compiler separates schemas into two files:\n\n**`src/db/auth-schema.ts`** — Re-exports Better Auth table schemas:\n- `users`, `sessions`, `accounts`\n- `organizations`, `members`, `invitations` (if organizations enabled)\n- Plugin-specific tables (`apiKeys`, etc.)\n\n**`src/db/features-schema.ts`** — Re-exports your feature schemas:\n- All tables defined with `defineTable()`\n- Audit field columns added automatically\n\n### Single Database Mode (Bun Default)\n\n**`src/db/schema.ts`** — Combined re-export of all schemas (auth + features).\n\n## Generated Routes\n\nFor each feature, the compiler generates a routes file at `src/features/{name}/routes.ts` containing:\n\n| Route | Generated When |\n|-------|----------------|\n| `GET /` | `crud.list` configured |\n| `GET /:id` | `crud.get` configured |\n| `POST /` | `crud.create` configured |\n| `PATCH /:id` | `crud.update` configured |\n| `DELETE /:id` | `crud.delete` configured |\n| `PUT /:id` | `crud.put` configured |\n| `POST /batch` | `crud.create` exists (auto-enabled) |\n| `PATCH /batch` | `crud.update` exists (auto-enabled) |\n| `DELETE /batch` | `crud.delete` exists (auto-enabled) |\n| `PUT /batch` | `crud.put` exists (auto-enabled) |\n| `GET /views/{name}` | `views` configured |\n| `POST /:id/{action}` | Record-based actions defined |\n| `POST /{action}` | Standalone actions defined |\n\nAll routes are mounted under `/api/v1/{feature}` in the main app.\n\n## Migrations\n\nThe compiler runs `drizzle-kit generate` during compilation to produce SQL migration files. On subsequent compiles, it uses `existingFiles` (your current migration state) to generate only incremental changes.\n\nThe CLI loads migration meta JSON from one location only — `<project>/quickback/drizzle/`:\n\n- `quickback/drizzle/auth/meta/`\n- `quickback/drizzle/features/meta/`\n- `quickback/drizzle/files/meta/`\n- `quickback/drizzle/webhooks/meta/`\n- `quickback/drizzle/audit/meta/`\n- `quickback/drizzle/meta/` (single-database mode)\n\nQuickback owns this state — nothing under a project-root `drizzle/` folder is ever read or written.\n\nMigration and report artifacts are written to the `quickback/` state directory:\n\n- `quickback/drizzle/...` for Drizzle migration SQL/meta artifacts\n- `quickback/reports/...` for security contract report artifacts\n\nFor non-interactive environments (cloud compile, CI), table/column renames must be declared with `compiler.migrations.renames` in `quickback.config.ts`. This avoids interactive rename prompts during migration generation.\n\nMigration files follow the Drizzle Kit naming convention:\n```\n0000_initial.sql\n0001_add_status_column.sql\n0002_create_orders_table.sql\n```\n\n## CMS and Account UI Assets\n\nWhen `cms` and/or `account` are enabled, the compiler builds the SPAs from source at compile time and includes the assets in the output.\n\nEach SPA is placed in its own subdirectory under `src/apps/`:\n\n```\nsrc/apps/ # Root assets directory\n├── cms/ # CMS SPA (served at /cms/ on unified domain)\n│ ├── index.html\n│ └── assets/\n│ ├── app.abc123.js # Content-hashed filenames from Vite\n│ └── app.xyz456.css\n└── account/ # Account SPA (served at /account/ on unified domain)\n ├── index.html\n └── assets/\n ├── app.def789.js\n └── app.ghi012.css\n```\n\nOn custom domains, each SPA is served at root (`/`) via hostname-based routing. On the unified domain, CMS is at `/cms/` and Account is at `/account/`.\n\n### Static Assets (`quickback/public/`)\n\nAnything you drop under `quickback/public/` is copied verbatim into `src/apps/` on every compile. The compiler does not parse, template, or otherwise touch these files — they are bytes that ride past it into the Cloudflare ASSETS binding.\n\n```\nquickback/public/ # Source — checked into your repo\n├── favicon.ico\n├── robots.txt\n├── og/\n│ └── og-image.png\n└── pdfs/\n └── whitepaper.pdf\n```\n\nAfter compile:\n\n```\nsrc/apps/ # Destination — written by the CLI\n├── favicon.ico # Served at https://your-domain/favicon.ico\n├── robots.txt # Served at /robots.txt\n├── og/og-image.png # Served at /og/og-image.png\n├── pdfs/whitepaper.pdf\n├── cms/ # Compiler-emitted SPA (don't shadow)\n└── account/ # Compiler-emitted SPA (don't shadow)\n```\n\nNotes:\n\n- The folder is optional. If it doesn't exist, this step is a no-op.\n- Files removed from `quickback/public/` disappear from `src/apps/` on the next compile — `src/` is wiped and rewritten each run.\n- Hidden entries (`.DS_Store`, `.git/`, dotfiles) are skipped.\n- A file in `quickback/public/` that would overwrite a compiler-emitted path (e.g. `quickback/public/cms/index.html`) fails the compile with a clear error rather than silently shadowing the SPA shell.\n- Binaries (images, fonts, PDFs) are copied byte-for-byte — there is no string round-trip.\n\n### Source Apps (`quickback/apps/`)\n\nFor hand-authored TypeScript apps and prebuilt SPA bundles that live alongside the compiler-emitted SPA shells, drop them under `quickback/apps/<name>/`. The CLI copies the tree into `src/apps/<name>/` on every compile, byte-for-byte, after the compiler has finished writing. Bind a directory to a hostname via [`config.apps`](/compiler/config/domains#app-domains) — the compiler emits the matching Worker middleware automatically.\n\n```\nquickback/apps/ # Source — checked into your repo\n├── m/ # A hand-authored mobile companion app\n│ ├── index.tsx\n│ ├── components/Button.tsx\n│ └── lib/utils.ts\n└── admin/ # A hand-authored admin tool\n └── index.tsx\n```\n\nAfter compile:\n\n```\nsrc/apps/\n├── m/index.tsx # Hand-authored — preserved across compiles\n├── m/components/Button.tsx\n├── m/lib/utils.ts\n├── admin/index.tsx\n├── cms/ # Compiler-emitted SPA (don't shadow)\n└── account/ # Compiler-emitted SPA (don't shadow)\n```\n\nWhen to choose `apps/` vs `public/`:\n\n| | `quickback/public/` | `quickback/apps/` |\n|---|---|---|\n| **Use for** | Static binaries (logos, fonts, OG images, PDFs, robots.txt) | Hand-authored TS/TSX/JS app source |\n| **Skips** | Hidden entries only (`.DS_Store`, `.git/`) | Hidden entries + `node_modules/`, `dist/`, `build/`, `.next/`, `.turbo/`, `.cache/` |\n| **Folder layout** | Files at any depth — flat or nested | Apps under named subfolders (`m/`, `admin/`, …) |\n\nNotes:\n\n- The folder is optional. If it doesn't exist, this step is a no-op.\n- Files removed from `quickback/apps/<name>/` disappear from `src/apps/<name>/` on the next compile — `src/` is wiped and rewritten each run.\n- A file in `quickback/apps/` that would overwrite a compiler-emitted path (e.g. `quickback/apps/cms/index.tsx` while `cms: true`) fails the compile with a clear error.\n- Migrating from hand-edited `src/apps/<name>/`: move the entire folder under `quickback/apps/<name>/` once, then trust the compile cycle. The hermetic `src/` contract holds again.\n\n### Generated Wrangler Assets Config\n\nThe compiler always generates `run_worker_first = true` when SPAs are enabled — the Worker handles all SPA routing (per hostname and per path prefix):\n\n```toml\n[assets]\nbinding = \"ASSETS\"\ndirectory = \"src/apps\"\nnot_found_handling = \"none\"\nrun_worker_first = true\n```\n\nSee [Multi-Domain Architecture](/compiler/config/domains) for details on hostname routing.\n\n## See Also\n\n- [Providers](/compiler/config/providers) — Configure runtime, database, and auth providers\n- [Environment variables](/compiler/config/variables) — Required variables by runtime\n- [Multi-Domain Architecture](/compiler/config/domains) — Custom domains and hostname routing"
|
|
59
59
|
},
|
|
60
60
|
"compiler/config/providers": {
|
|
61
61
|
"title": "Providers",
|
|
62
|
-
"content": "Providers configure which services your compiled backend targets.\n\n## Runtime Providers\n\n| Provider | Description |\n|----------|-------------|\n| `cloudflare` | Cloudflare Workers (Hono) |\n| `bun` | Bun runtime (Hono) |\n| `node` | Node.js runtime (Hono) |\n\n```typescript\n\nproviders: {\n runtime: defineRuntime(\"cloudflare\"),\n}\n```\n\n### Runtime Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `compatibilityDate` | `string` | Emits Cloudflare `compatibility_date` in `wrangler.toml`. |\n| `placement.mode` | `\"smart\" \\| \"standard\"` | Emits Cloudflare's `[placement]` block. |\n| `observability.enabled` | `boolean` | Emits top-level Workers Logs persistence under `[observability]`. |\n| `observability.headSamplingRate` | `number` | Top-level Workers Logs sample rate from `0` to `1`. |\n| `observability.logs.enabled` | `boolean` | Emits `[observability.logs]`. |\n| `observability.logs.invocationLogs` | `boolean` | Enables or suppresses invocation logs. |\n| `observability.logs.destinations` | `string[]` | Named log export destinations configured in Cloudflare. |\n| `observability.logs.headSamplingRate` | `number` | Workers Logs sample rate from `0` to `1`. |\n| `observability.logs.persist` | `boolean` | Keeps exported logs in the Cloudflare dashboard. |\n| `observability.traces.enabled` | `boolean` | Emits `[observability.traces]`. |\n| `observability.traces.destinations` | `string[]` | Named trace export destinations configured in Cloudflare. |\n| `observability.traces.headSamplingRate` | `number` | Workers Traces sample rate from `0` to `1`. |\n| `observability.traces.persist` | `boolean` | Keeps exported traces in the Cloudflare dashboard. |\n| `routes` | `{ pattern, custom_domain? }[]` | Custom domain routes for the generated Worker. |\n\n```typescript\nproviders: {\n runtime: defineRuntime(\"cloudflare\", {\n compatibilityDate: \"2026-05-13\",\n placement: { mode: \"smart\" },\n observability: {\n enabled: true,\n logs: {\n enabled: true,\n invocationLogs: false,\n destinations: [\"logs-prod\"],\n headSamplingRate: 0.6,\n },\n traces: {\n enabled: true,\n destinations: [\"otel-prod\"],\n headSamplingRate: 0.05,\n persist: false,\n },\n },\n }),\n}\n```\n\n## Database Providers\n\n| Provider | Description |\n|----------|-------------|\n| `cloudflare-d1` | Cloudflare D1 (SQLite) |\n| `better-sqlite3` | SQLite via better-sqlite3 (Bun/Node) |\n| `libsql` | LibSQL / Turso |\n| `neon` | Neon (PostgreSQL) |\n| `supabase` | Supabase (PostgreSQL) |\n\n```typescript\n\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n generateId: \"prefixed\", // \"uuid\" | \"cuid\" | \"nanoid\" | \"prefixed\" | \"serial\" | false\n namingConvention: \"snake_case\", // \"camelCase\" | \"snake_case\"\n usePlurals: false, // Auth table names: \"users\" vs \"user\"\n }),\n}\n```\n\n### Database Options\n\n| Option | Type | Default (D1) | Description |\n|--------|------|---------|-------------|\n| `generateId` | `string \\| false` | `\"prefixed\"` | ID generation strategy |\n| `namingConvention` | `string` | `\"snake_case\"` | Column naming convention |\n| `usePlurals` | `boolean` | `false` | Pluralize auth table names (e.g. `user` vs `users`) |\n| `splitDatabases` | `boolean` | `true` | Separate auth and features databases |\n| `authBinding` | `string` | `\"AUTH_DB\"` | Binding name for auth database |\n| `featuresBinding` | `string` | `\"DB\"` | Binding name for features database |\n| `databaseId` | `string` | — | D1 database ID for the features database (used in generated wrangler.toml) |\n| `authDatabaseId` | `string` | — | D1 database ID for the auth database |\n| `featuresDatabaseId` | `string` | — | Explicit features DB ID (falls back to `databaseId`) |\n| `filesDatabaseId` | `string` | — | D1 database ID for the files metadata database |\n| `webhooksDatabaseId` | `string` | — | D1 database ID for the webhooks database |\n| `auditBinding` | `string` | `\"AUDIT_DB\"` | Binding name for the security audit database |\n| `auditDatabaseName` | `string` | `\"{app}-audit\"` | D1 database name for audit events |\n| `auditDatabaseId` | `string` | — | Explicit D1 database ID for audit events |\n| `experimentalRemote` | `{ auth?, features?, audit?, webhooks?, files? }` | `{}` | Per-binding `experimental_remote = true` flag for `wrangler dev` (see [below](#sharing-deployed-d1-in-dev-experimental_remote)) |\n| `realtime` | `boolean \\| { enabled?, wsTicket? }` | `false` | Enables the Broadcaster Durable Object and optional resource-scoped ws-ticket auth (see [below](#realtime-broadcast-config)) |\n| `webhookAdminRoles` | `string[]` | `[\"owner\", \"admin\"]` | Org roles allowed to manage webhook endpoints |\n\n#### Audit Database\n\nCross-tenant `unsafe` actions (see [Actions → Unsafe mode](/compiler/definitions/actions#unsafe-mode)) write mandatory audit events. Those events land in a dedicated D1 database — separate from your features DB — so audit history stays isolated from application data and can't be tampered with through a normal CRUD route.\n\nYou don't need to do anything to enable it — the compiler wires up the binding automatically if your project declares any unsafe action. To override defaults:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n auditBinding: \"MY_AUDIT_DB\", // default: AUDIT_DB\n auditDatabaseName: \"my-app-audit-prod\", // default: {app}-audit\n auditDatabaseId: \"c3b8866b-cc4f-4e51-8382-0af244584d93\",\n }),\n}\n```\n\nThe binding name must match what your Worker reads at runtime. If you don't declare any unsafe actions, no audit DB is provisioned and these options have no effect.\n\n#### Setting Database IDs for Deployment\n\nWhen deploying to production, set your D1 database IDs so the compiler generates a ready-to-deploy `wrangler.toml`:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n authDatabaseId: \"fe6c77c4-2131-40be-a8fc-3649eef2a38c\",\n databaseId: \"bba22981-cb6e-43d6-bf32-4193513c60b1\",\n filesDatabaseId: \"c3b8866b-cc4f-4e51-8382-0af244584d93\",\n }),\n}\n```\n\nIf these are omitted, the compiler uses local-dev placeholders and you'll need to manually edit `wrangler.toml` before deploying.\n\n#### Sharing deployed D1 in dev (`experimental_remote`)\n\nWrangler can read or write the **deployed** D1 for a specific binding while `wrangler dev` runs locally. A common workflow: share the production auth DB in dev so real sessions and users work against the running local Worker, while feature writes stay sandboxed in the local SQLite shadow.\n\nQuickback regenerates `wrangler.toml` on every compile, so flags like `experimental_remote = true` need to live in `quickback.config.ts`:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n authDatabaseId: \"fe6c77c4-2131-40be-a8fc-3649eef2a38c\",\n experimentalRemote: { auth: true },\n }),\n}\n```\n\nKeys map to logical bindings, not the runtime binding string:\n\n| Key | Binding affected |\n|-----|------------------|\n| `auth` | `AUTH_DB` (also applied to the files worker's auth binding) |\n| `features` | `DB` (or the legacy single-DB binding when `splitDatabases: false`) |\n| `audit` | `AUDIT_DB` |\n| `webhooks` | `WEBHOOKS_DB` |\n| `files` | `FILES_DB` (also applied to the files worker) |\n\nOnly `true` flips the flag on; `false` or omitted leaves the binding local. Off by default — only enable against databases you intend to share.\n\n#### Realtime Broadcast Config\n\nSet `realtime: true` to enable the generated Broadcaster Durable Object with the default organization-scoped routing model:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: true,\n }),\n}\n```\n\nFor relationship-authorized resource scopes, use the object form:\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\n`wsTicket` tells the compiler how to authorize `/broadcast/v1/ws-ticket` and what scope to stamp into the short-lived websocket ticket:\n\n- `role`: an authz role declared under `authz.roles` that uses a direct relationship (`{ via: \"...\" }`)\n- `requestField`: the JSON body field the client posts to `/broadcast/v1/ws-ticket`\n- `scopeTable`: the parent resource table that defines the broadcast scope key\n\nIn other words: the relationship table proves access, and the `scopeTable` row defines the channel. For an attendee flow, `guests` (or RSVP) would be the relationship evidence and `events` would be the `scopeTable`.\n\nQuickback keeps Better Auth as the front door, then mints its own 60-second websocket ticket after the authz check succeeds. The generated `createRealtime()` helper and Broadcaster share the same targeting model:\n\n- string target: historical `organizationId` shorthand\n- object target: `{ scopeKey?, organizationId?, userId? }`\n\nSee [Realtime](/stack/realtime) for the client-side connection flow and helper examples.\n\n### ID Generation Options\n\n| Value | Description | Example |\n|-------|-------------|---------|\n| `\"uuid\"` | Server generates UUID | `550e8400-e29b-41d4-a716-446655440000` |\n| `\"cuid\"` | Server generates CUID | `clh2v8k9g0000l508h5gx8j1a` |\n| `\"nanoid\"` | Server generates nanoid (21-char, URL-safe) | `V1StGXR8_Z5jdHi6B-myT` |\n| `\"short\"` | 6-char alphanumeric (nanoid `customAlphabet`) | `a3F9xK` |\n| `\"prefixed\"` | Prefixed ID from table name | `room_abc123` |\n| `\"serial\"` | Database auto-increments | `1`, `2`, `3` |\n| `false` | Client provides ID (enables PUT/upsert) | Any string |\n\n## Auth Providers\n\n| Provider | Description |\n|----------|-------------|\n| `better-auth` | Better Auth with plugins |\n| `supabase-auth` | Supabase Auth |\n| `external` | External auth via Cloudflare service binding |\n\n```typescript\n\nproviders: {\n auth: defineAuth(\"better-auth\", {\n session: {\n expiresInDays: 7,\n updateAgeInDays: 1,\n },\n rateLimit: {\n enabled: true,\n window: 60,\n max: 100,\n },\n }),\n}\n```\n\n### Better Auth Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `session.expiresInDays` | `number` | Session expiration in days |\n| `session.updateAgeInDays` | `number` | Session refresh interval in days |\n| `rateLimit.enabled` | `boolean` | Enable rate limiting |\n| `rateLimit.window` | `number` | Rate limit window in seconds |\n| `rateLimit.max` | `number` | Max requests per window |\n| `socialProviders` | `object` | Social login providers (`google`, `github`, `discord`) |\n| `debugLogs` | `boolean` | Enable auth debug logging |\n\n### Better Auth Plugins\n\nWhen `features: [\"organizations\"]` is set in your config, the compiler automatically enables organization-related plugins. Additional plugins can be configured:\n\n| Plugin | Description |\n|--------|-------------|\n| `organization` | Multi-tenant organizations |\n| `admin` | Admin panel access |\n| `apiKey` | API key authentication |\n| `anonymous` | Anonymous sessions |\n| `upgradeAnonymous` | Convert anonymous to full accounts |\n| `twoFactor` | Two-factor authentication |\n| `passkey` | WebAuthn passkey login |\n| `magicLink` | Email magic link login |\n| `emailOtp` | Email one-time password |\n| `deviceAuthorization` | Device auth flow (CLI tools) |\n| `jwt` | JWT token support |\n| `openAPI` | OpenAPI spec generation |\n\n## Storage Providers\n\n```typescript\n\nproviders: {\n storage: defineStorage(\"kv\", {\n binding: \"KV_STORE\",\n namespaceId: \"7ed0f824a8c54c388713d9fdf63cd004\",\n }),\n fileStorage: defineFileStorage(\"r2\", {\n binding: \"FILES\",\n maxFileSize: \"10mb\",\n allowedTypes: [\"image/png\", \"image/jpeg\", \"application/pdf\"],\n publicDomain: \"files.example.com\",\n }),\n}\n```\n\n### Storage Types\n\n| Type | Description |\n|------|-------------|\n| `kv` | Key-value storage (Cloudflare KV, Redis) |\n| `r2` | Object storage (Cloudflare R2) |\n| `memory` | In-memory storage (development only) |\n| `redis` | Redis storage |\n\n### File Storage Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `binding` | `string` | R2 bucket binding name |\n| `maxFileSize` | `string` | Maximum file size (e.g. `\"10mb\"`) |\n| `allowedTypes` | `string[]` | Allowed MIME types |\n| `publicDomain` | `string` | Public domain for file URLs |\n| `userScopedBuckets` | `boolean` | Scope files by user |"
|
|
62
|
+
"content": "Providers configure which services your compiled backend targets.\n\n## Runtime Providers\n\nThe Quickback Stack is **Cloudflare-only**. `cloudflare` is the single supported runtime.\n\n```typescript\n\nproviders: {\n runtime: defineRuntime(\"cloudflare\"),\n}\n```\n\n### Runtime Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `compatibilityDate` | `string` | Emits Cloudflare `compatibility_date` in `wrangler.toml`. |\n| `placement.mode` | `\"smart\" \\| \"standard\"` | Emits Cloudflare's `[placement]` block. |\n| `observability.enabled` | `boolean` | Emits top-level Workers Logs persistence under `[observability]`. |\n| `observability.headSamplingRate` | `number` | Top-level Workers Logs sample rate from `0` to `1`. |\n| `observability.logs.enabled` | `boolean` | Emits `[observability.logs]`. |\n| `observability.logs.invocationLogs` | `boolean` | Enables or suppresses invocation logs. |\n| `observability.logs.destinations` | `string[]` | Named log export destinations configured in Cloudflare. |\n| `observability.logs.headSamplingRate` | `number` | Workers Logs sample rate from `0` to `1`. |\n| `observability.logs.persist` | `boolean` | Keeps exported logs in the Cloudflare dashboard. |\n| `observability.traces.enabled` | `boolean` | Emits `[observability.traces]`. |\n| `observability.traces.destinations` | `string[]` | Named trace export destinations configured in Cloudflare. |\n| `observability.traces.headSamplingRate` | `number` | Workers Traces sample rate from `0` to `1`. |\n| `observability.traces.persist` | `boolean` | Keeps exported traces in the Cloudflare dashboard. |\n| `routes` | `{ pattern, custom_domain? }[]` | Custom domain routes for the generated Worker. |\n\n```typescript\nproviders: {\n runtime: defineRuntime(\"cloudflare\", {\n compatibilityDate: \"2026-05-13\",\n placement: { mode: \"smart\" },\n observability: {\n enabled: true,\n logs: {\n enabled: true,\n invocationLogs: false,\n destinations: [\"logs-prod\"],\n headSamplingRate: 0.6,\n },\n traces: {\n enabled: true,\n destinations: [\"otel-prod\"],\n headSamplingRate: 0.05,\n persist: false,\n },\n },\n }),\n}\n```\n\n## Database Providers\n\nTwo databases are supported, both Cloudflare-native:\n\n| Provider | Description |\n|----------|-------------|\n| `cloudflare-d1` | Cloudflare D1 (SQLite at the edge) |\n| `neon` | Neon (PostgreSQL over Hyperdrive) |\n\n```typescript\n\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n generateId: \"prefixed\", // \"uuid\" | \"cuid\" | \"nanoid\" | \"prefixed\" | \"serial\" | false\n namingConvention: \"snake_case\", // \"camelCase\" | \"snake_case\"\n usePlurals: false, // Auth table names: \"users\" vs \"user\"\n }),\n}\n```\n\n### Database Options\n\n| Option | Type | Default (D1) | Description |\n|--------|------|---------|-------------|\n| `generateId` | `string \\| false` | `\"prefixed\"` | ID generation strategy |\n| `namingConvention` | `string` | `\"snake_case\"` | Column naming convention |\n| `usePlurals` | `boolean` | `false` | Pluralize auth table names (e.g. `user` vs `users`) |\n| `splitDatabases` | `boolean` | `true` | Separate auth and features databases |\n| `authBinding` | `string` | `\"AUTH_DB\"` | Binding name for auth database |\n| `featuresBinding` | `string` | `\"DB\"` | Binding name for features database |\n| `databaseId` | `string` | — | D1 database ID for the features database (used in generated wrangler.toml) |\n| `authDatabaseId` | `string` | — | D1 database ID for the auth database |\n| `featuresDatabaseId` | `string` | — | Explicit features DB ID (falls back to `databaseId`) |\n| `filesDatabaseId` | `string` | — | D1 database ID for the files metadata database |\n| `webhooksDatabaseId` | `string` | — | D1 database ID for the webhooks database |\n| `auditBinding` | `string` | `\"AUDIT_DB\"` | Binding name for the security audit database |\n| `auditDatabaseName` | `string` | `\"{app}-audit\"` | D1 database name for audit events |\n| `auditDatabaseId` | `string` | — | Explicit D1 database ID for audit events |\n| `experimentalRemote` | `{ auth?, features?, audit?, webhooks?, files? }` | `{}` | Per-binding `experimental_remote = true` flag for `wrangler dev` (see [below](#sharing-deployed-d1-in-dev-experimental_remote)) |\n| `realtime` | `boolean \\| { enabled?, wsTicket? }` | `false` | Enables the Broadcaster Durable Object and optional resource-scoped ws-ticket auth (see [below](#realtime-broadcast-config)) |\n| `webhookAdminRoles` | `string[]` | `[\"owner\", \"admin\"]` | Org roles allowed to manage webhook endpoints |\n\n#### Audit Database\n\nCross-tenant `unsafe` actions (see [Actions → Unsafe mode](/compiler/definitions/actions#unsafe-mode)) write mandatory audit events. Those events land in a dedicated D1 database — separate from your features DB — so audit history stays isolated from application data and can't be tampered with through a normal CRUD route.\n\nYou don't need to do anything to enable it — the compiler wires up the binding automatically if your project declares any unsafe action. To override defaults:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n auditBinding: \"MY_AUDIT_DB\", // default: AUDIT_DB\n auditDatabaseName: \"my-app-audit-prod\", // default: {app}-audit\n auditDatabaseId: \"c3b8866b-cc4f-4e51-8382-0af244584d93\",\n }),\n}\n```\n\nThe binding name must match what your Worker reads at runtime. If you don't declare any unsafe actions, no audit DB is provisioned and these options have no effect.\n\n#### Setting Database IDs for Deployment\n\nWhen deploying to production, set your D1 database IDs so the compiler generates a ready-to-deploy `wrangler.toml`:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n authDatabaseId: \"fe6c77c4-2131-40be-a8fc-3649eef2a38c\",\n databaseId: \"bba22981-cb6e-43d6-bf32-4193513c60b1\",\n filesDatabaseId: \"c3b8866b-cc4f-4e51-8382-0af244584d93\",\n }),\n}\n```\n\nIf these are omitted, the compiler uses local-dev placeholders and you'll need to manually edit `wrangler.toml` before deploying.\n\n#### Sharing deployed D1 in dev (`experimental_remote`)\n\nWrangler can read or write the **deployed** D1 for a specific binding while `wrangler dev` runs locally. A common workflow: share the production auth DB in dev so real sessions and users work against the running local Worker, while feature writes stay sandboxed in the local SQLite shadow.\n\nQuickback regenerates `wrangler.toml` on every compile, so flags like `experimental_remote = true` need to live in `quickback.config.ts`:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n authDatabaseId: \"fe6c77c4-2131-40be-a8fc-3649eef2a38c\",\n experimentalRemote: { auth: true },\n }),\n}\n```\n\nKeys map to logical bindings, not the runtime binding string:\n\n| Key | Binding affected |\n|-----|------------------|\n| `auth` | `AUTH_DB` (also applied to the files worker's auth binding) |\n| `features` | `DB` (or the legacy single-DB binding when `splitDatabases: false`) |\n| `audit` | `AUDIT_DB` |\n| `webhooks` | `WEBHOOKS_DB` |\n| `files` | `FILES_DB` (also applied to the files worker) |\n\nOnly `true` flips the flag on; `false` or omitted leaves the binding local. Off by default — only enable against databases you intend to share.\n\n#### Realtime Broadcast Config\n\nSet `realtime: true` to enable the generated Broadcaster Durable Object with the default organization-scoped routing model:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: true,\n }),\n}\n```\n\nFor relationship-authorized resource scopes, use the object form:\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\n`wsTicket` tells the compiler how to authorize `/broadcast/v1/ws-ticket` and what scope to stamp into the short-lived websocket ticket:\n\n- `role`: an authz role declared under `authz.roles` that uses a direct relationship (`{ via: \"...\" }`)\n- `requestField`: the JSON body field the client posts to `/broadcast/v1/ws-ticket`\n- `scopeTable`: the parent resource table that defines the broadcast scope key\n\nIn other words: the relationship table proves access, and the `scopeTable` row defines the channel. For an attendee flow, `guests` (or RSVP) would be the relationship evidence and `events` would be the `scopeTable`.\n\nQuickback keeps Better Auth as the front door, then mints its own 60-second websocket ticket after the authz check succeeds. The generated `createRealtime()` helper and Broadcaster share the same targeting model:\n\n- string target: historical `organizationId` shorthand\n- object target: `{ scopeKey?, organizationId?, userId? }`\n\nSee [Realtime](/stack/realtime) for the client-side connection flow and helper examples.\n\n### ID Generation Options\n\n| Value | Description | Example |\n|-------|-------------|---------|\n| `\"uuid\"` | Server generates UUID | `550e8400-e29b-41d4-a716-446655440000` |\n| `\"cuid\"` | Server generates CUID | `clh2v8k9g0000l508h5gx8j1a` |\n| `\"nanoid\"` | Server generates nanoid (21-char, URL-safe) | `V1StGXR8_Z5jdHi6B-myT` |\n| `\"short\"` | 6-char alphanumeric (nanoid `customAlphabet`) | `a3F9xK` |\n| `\"prefixed\"` | Prefixed ID from table name | `room_abc123` |\n| `\"serial\"` | Database auto-increments | `1`, `2`, `3` |\n| `false` | Client provides ID (enables PUT/upsert) | Any string |\n\n## Auth Providers\n\n| Provider | Description |\n|----------|-------------|\n| `better-auth` | Better Auth with plugins (default) |\n| `external` | External auth via Cloudflare service binding |\n\n```typescript\n\nproviders: {\n auth: defineAuth(\"better-auth\", {\n session: {\n expiresInDays: 7,\n updateAgeInDays: 1,\n },\n rateLimit: {\n enabled: true,\n window: 60,\n max: 100,\n },\n }),\n}\n```\n\n### Better Auth Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `session.expiresInDays` | `number` | Session expiration in days |\n| `session.updateAgeInDays` | `number` | Session refresh interval in days |\n| `rateLimit.enabled` | `boolean` | Enable rate limiting |\n| `rateLimit.window` | `number` | Rate limit window in seconds |\n| `rateLimit.max` | `number` | Max requests per window |\n| `socialProviders` | `object` | Social login providers (`google`, `github`, `discord`) |\n| `debugLogs` | `boolean` | Enable auth debug logging |\n\n### Better Auth Plugins\n\nWhen `features: [\"organizations\"]` is set in your config, the compiler automatically enables organization-related plugins. Additional plugins can be configured:\n\n| Plugin | Description |\n|--------|-------------|\n| `organization` | Multi-tenant organizations |\n| `admin` | Admin panel access |\n| `apiKey` | API key authentication |\n| `anonymous` | Anonymous sessions |\n| `upgradeAnonymous` | Convert anonymous to full accounts |\n| `twoFactor` | Two-factor authentication |\n| `passkey` | WebAuthn passkey login |\n| `magicLink` | Email magic link login |\n| `emailOtp` | Email one-time password |\n| `deviceAuthorization` | Device auth flow (CLI tools) |\n| `jwt` | JWT token support |\n| `openAPI` | OpenAPI spec generation |\n\n## Storage Providers\n\n```typescript\n\nproviders: {\n storage: defineStorage(\"kv\", {\n binding: \"KV_STORE\",\n namespaceId: \"7ed0f824a8c54c388713d9fdf63cd004\",\n }),\n fileStorage: defineFileStorage(\"r2\", {\n binding: \"FILES\",\n maxFileSize: \"10mb\",\n allowedTypes: [\"image/png\", \"image/jpeg\", \"application/pdf\"],\n publicDomain: \"files.example.com\",\n }),\n}\n```\n\n### Storage Types\n\n| Type | Description |\n|------|-------------|\n| `kv` | Key-value storage (Cloudflare KV, Redis) |\n| `r2` | Object storage (Cloudflare R2) |\n| `memory` | In-memory storage (development only) |\n| `redis` | Redis storage |\n\n### File Storage Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `binding` | `string` | R2 bucket binding name |\n| `maxFileSize` | `string` | Maximum file size (e.g. `\"10mb\"`) |\n| `allowedTypes` | `string[]` | Allowed MIME types |\n| `publicDomain` | `string` | Public domain for file URLs |\n| `userScopedBuckets` | `boolean` | Scope files by user |"
|
|
63
63
|
},
|
|
64
64
|
"compiler/config/security": {
|
|
65
65
|
"title": "Security Headers",
|
|
@@ -67,19 +67,19 @@ export const DOCS = {
|
|
|
67
67
|
},
|
|
68
68
|
"compiler/config/single-tenant": {
|
|
69
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 | `/
|
|
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```"
|
|
71
71
|
},
|
|
72
72
|
"compiler/config/variables": {
|
|
73
73
|
"title": "Environment Variables",
|
|
74
|
-
"content": "## CLI Environment Variables\n\nThese variables configure the Quickback CLI itself.\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `QUICKBACK_API_URL` | Compiler API endpoint | `https://compiler.quickback.dev` |\n| `QUICKBACK_API_KEY` | API key for headless authentication (CI/CD) | — |\n| `QUICKBACK_AUTH_URL` | Auth server URL (custom deployments) | — |\n\n### Authentication\n\nThe CLI authenticates via two methods:\n\n1. **Interactive login** — `quickback login` stores credentials in `~/.quickback/credentials.json`\n2. **API key** — Set `QUICKBACK_API_KEY` for CI/CD environments\n\n```bash\n# Use the cloud compiler (default)\nquickback compile\n\n# Use a local compiler instance\nQUICKBACK_API_URL=http://localhost:3000 quickback compile\n\n# CI/CD with API key\nQUICKBACK_API_KEY=qb_key_... quickback compile\n```\n\n## Compiler Service Variables\n\nThese variables are used by the compiler service/runtime itself.\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `QUICKBACK_SECURITY_REPORT_SIGNING_KEY` | HMAC key for signing `security-contracts.report.json` artifacts | — |\n\nWhen `compiler.securityContracts.report.signature.required` is `true`, this variable (or `signature.key`) must be set or compile fails.\n\n## Cloudflare Variables\n\n### Wrangler Bindings\n\nThese are configured as bindings in `wrangler.toml`, not environment variables. The compiler generates them automatically.\n\n| Binding | Type | Description |\n|---------|------|-------------|\n| `AUTH_DB` | D1 Database | Better Auth tables (dual mode) |\n| `DB` | D1 Database | Feature tables (dual mode) |\n| `DATABASE` | D1 Database | All tables (single DB mode) |\n| `KV` | KV Namespace | Key-value storage |\n| `R2_BUCKET` | R2 Bucket | File storage (if configured) |\n| `AI` | Workers AI | Embedding generation (if configured) |\n| `VECTORIZE` | Vectorize | Vector similarity search (if configured) |\n| `EMBEDDINGS_QUEUE` | Queue | Async embedding jobs (if configured) |\n| `WEBHOOKS_DB` | D1 Database | Webhook events (if configured) |\n| `WEBHOOKS_QUEUE` | Queue | Webhook delivery (if configured) |\n| `FILES_DB` | D1 Database | File metadata (if R2 configured) |\n| `BROADCASTER` | Durable Object | Realtime Broadcaster DO (if configured) |\n| `EMAIL` | send_email | Cloudflare Email Service (if email configured) |\n\n### Worker Variables\n\nSet these in `wrangler.toml` under `[vars]` or in the Cloudflare dashboard:\n\n| Variable | Description | Required |\n|----------|-------------|----------|\n| `BETTER_AUTH_URL` | Public URL of your auth endpoint | Yes |\n| `APP_NAME` | Application name (used in emails) | No |\n\n### Email (Cloudflare Email Service — default)\n\nUses the Cloudflare `send_email` binding. No API keys needed — the binding is configured automatically in `wrangler.toml`.\n\n| Variable | Description | Where |\n|----------|-------------|-------|\n| `EMAIL_FROM` | Sender email address | `[vars]` |\n| `EMAIL_FROM_NAME` | Sender display name | `[vars]` |\n| `APP_NAME` | Application name (used in templates) | `[vars]` |\n\nThe `EMAIL` binding is added to `wrangler.toml` automatically when using the `emailOtp` plugin.\n\n### Email (AWS SES)\n\nRequired when using `email: { provider: 'aws-ses' }`:\n\n| Variable | Description |\n|----------|-------------|\n| `AWS_ACCESS_KEY_ID` | AWS access key |\n| `AWS_SECRET_ACCESS_KEY` | AWS secret key |\n| `AWS_SES_REGION` | SES region (e.g., `us-east-2`) |\n| `EMAIL_FROM` | Sender email address |\n| `EMAIL_FROM_NAME` | Sender display name |\n| `EMAIL_REPLY_TO` | Reply-to address |\n\n### Drizzle Kit (Migrations)\n\nFor running remote migrations with `drizzle-kit`, set these in `.env`:\n\n| Variable | Description |\n|----------|-------------|\n| `CLOUDFLARE_ACCOUNT_ID` | Your Cloudflare account ID |\n| `CLOUDFLARE_API_TOKEN` | API token with D1 permissions |\n| `CLOUDFLARE_AUTH_DATABASE_ID` | Auth D1 database ID (dual mode) |\n| `CLOUDFLARE_FEATURES_DATABASE_ID` | Features D1 database ID (dual mode) |\n| `CLOUDFLARE_AUDIT_DATABASE_ID` | Security audit D1 database ID (unsafe cross-tenant actions) |\n| `CLOUDFLARE_DATABASE_ID` | Database ID (single DB mode) |\n\n##
|
|
74
|
+
"content": "## CLI Environment Variables\n\nThese variables configure the Quickback CLI itself.\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `QUICKBACK_API_URL` | Compiler API endpoint | `https://compiler.quickback.dev` |\n| `QUICKBACK_API_KEY` | API key for headless authentication (CI/CD) | — |\n| `QUICKBACK_AUTH_URL` | Auth server URL (custom deployments) | — |\n\n### Authentication\n\nThe CLI authenticates via two methods:\n\n1. **Interactive login** — `quickback login` stores credentials in `~/.quickback/credentials.json`\n2. **API key** — Set `QUICKBACK_API_KEY` for CI/CD environments\n\n```bash\n# Use the cloud compiler (default)\nquickback compile\n\n# Use a local compiler instance\nQUICKBACK_API_URL=http://localhost:3000 quickback compile\n\n# CI/CD with API key\nQUICKBACK_API_KEY=qb_key_... quickback compile\n```\n\n## Compiler Service Variables\n\nThese variables are used by the compiler service/runtime itself.\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `QUICKBACK_SECURITY_REPORT_SIGNING_KEY` | HMAC key for signing `security-contracts.report.json` artifacts | — |\n\nWhen `compiler.securityContracts.report.signature.required` is `true`, this variable (or `signature.key`) must be set or compile fails.\n\n## Cloudflare Variables\n\n### Wrangler Bindings\n\nThese are configured as bindings in `wrangler.toml`, not environment variables. The compiler generates them automatically.\n\n| Binding | Type | Description |\n|---------|------|-------------|\n| `AUTH_DB` | D1 Database | Better Auth tables (dual mode) |\n| `DB` | D1 Database | Feature tables (dual mode) |\n| `DATABASE` | D1 Database | All tables (single DB mode) |\n| `KV` | KV Namespace | Key-value storage |\n| `R2_BUCKET` | R2 Bucket | File storage (if configured) |\n| `AI` | Workers AI | Embedding generation (if configured) |\n| `VECTORIZE` | Vectorize | Vector similarity search (if configured) |\n| `EMBEDDINGS_QUEUE` | Queue | Async embedding jobs (if configured) |\n| `WEBHOOKS_DB` | D1 Database | Webhook events (if configured) |\n| `WEBHOOKS_QUEUE` | Queue | Webhook delivery (if configured) |\n| `FILES_DB` | D1 Database | File metadata (if R2 configured) |\n| `BROADCASTER` | Durable Object | Realtime Broadcaster DO (if configured) |\n| `EMAIL` | send_email | Cloudflare Email Service (if email configured) |\n\n### Worker Variables\n\nSet these in `wrangler.toml` under `[vars]` or in the Cloudflare dashboard:\n\n| Variable | Description | Required |\n|----------|-------------|----------|\n| `BETTER_AUTH_URL` | Public URL of your auth endpoint | Yes |\n| `APP_NAME` | Application name (used in emails) | No |\n\n### Email (Cloudflare Email Service — default)\n\nUses the Cloudflare `send_email` binding. No API keys needed — the binding is configured automatically in `wrangler.toml`.\n\n| Variable | Description | Where |\n|----------|-------------|-------|\n| `EMAIL_FROM` | Sender email address | `[vars]` |\n| `EMAIL_FROM_NAME` | Sender display name | `[vars]` |\n| `APP_NAME` | Application name (used in templates) | `[vars]` |\n\nThe `EMAIL` binding is added to `wrangler.toml` automatically when using the `emailOtp` plugin.\n\n### Email (AWS SES)\n\nRequired when using `email: { provider: 'aws-ses' }`:\n\n| Variable | Description |\n|----------|-------------|\n| `AWS_ACCESS_KEY_ID` | AWS access key |\n| `AWS_SECRET_ACCESS_KEY` | AWS secret key |\n| `AWS_SES_REGION` | SES region (e.g., `us-east-2`) |\n| `EMAIL_FROM` | Sender email address |\n| `EMAIL_FROM_NAME` | Sender display name |\n| `EMAIL_REPLY_TO` | Reply-to address |\n\n### Drizzle Kit (Migrations)\n\nFor running remote migrations with `drizzle-kit`, set these in `.env`:\n\n| Variable | Description |\n|----------|-------------|\n| `CLOUDFLARE_ACCOUNT_ID` | Your Cloudflare account ID |\n| `CLOUDFLARE_API_TOKEN` | API token with D1 permissions |\n| `CLOUDFLARE_AUTH_DATABASE_ID` | Auth D1 database ID (dual mode) |\n| `CLOUDFLARE_FEATURES_DATABASE_ID` | Features D1 database ID (dual mode) |\n| `CLOUDFLARE_AUDIT_DATABASE_ID` | Security audit D1 database ID (unsafe cross-tenant actions) |\n| `CLOUDFLARE_DATABASE_ID` | Database ID (single DB mode) |\n\n## Social Login Providers\n\nWhen social login is configured in your auth provider:\n\n| Variable | Description |\n|----------|-------------|\n| `GOOGLE_CLIENT_ID` | Google OAuth client ID |\n| `GOOGLE_CLIENT_SECRET` | Google OAuth client secret |\n| `GITHUB_CLIENT_ID` | GitHub OAuth client ID |\n| `GITHUB_CLIENT_SECRET` | GitHub OAuth client secret |\n| `DISCORD_CLIENT_ID` | Discord OAuth client ID |\n| `DISCORD_CLIENT_SECRET` | Discord OAuth client secret |\n\n## See Also\n\n- [Output Structure](/compiler/config/output) — Generated file structure\n- [Providers](/compiler/config/providers) — Provider configuration reference\n- [Cloudflare Template](/compiler/getting-started/template-cloudflare) — Cloudflare setup guide"
|
|
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`SYSADMIN` is a strict superset of `ADMIN` — at runtime, the universal-bypass shortcuts in `evaluateAccess` admit `userRole === 'sysadmin'` anywhere they admit `userRole === 'admin'`. The distinction matters for one thing only: **the firewall escape hatch**. When `cms.sysadmin: true`, every `buildFirewallConditions` emits an `if (ctx.userRole === 'sysadmin') return undefined;` (or just the soft-delete predicate when present) at the top — so sysadmins see every tenant's rows, not just their own org's. That escape hatch does NOT fire for `userRole === 'admin'`; admins still go through the firewall like everyone else.\n\nThis separation exists so Better Auth admin-plugin powers (user management, impersonation) and DB-admin powers (cross-tenant data inspection) stay decoupled. A user can have `user.role === 'admin'` without DB-level cross-tenant access; a user can have `user.role === 'sysadmin'` without org-membership context. See [CMS Configuration](/compiler/config#cms-configuration) for the `cms.sysadmin` flag, the cross-tenant `/admin/v1/sysadmin/organizations` endpoint, and the SPA's \"All organizations\" sentinel.\n\n#### Mixing pseudo-roles with real roles\n\nPseudo-roles and lowercase real roles compose with OR:\n\n```typescript\n// Record owner OR a system admin can read\nread: { access: { roles: [\"USER\", \"ADMIN\"] } }\n\n// Org owner OR system admin\ndelete: { access: { roles: [\"owner\", \"ADMIN\"] } }\n```\n\n> Note: today, an `ADMIN` match still goes through the `userId` firewall scope on USER-scoped resources — admins see only records they own on those routes. Use `firewall: { exception: true }` on a separate admin-only route if you need cross-user visibility.\n\n#### Quick reference\n\n```typescript\n// Unauthenticated public\naccess: { roles: [\"PUBLIC\"] }\n\n// Any signed-in user, no scoping\naccess: { roles: [\"AUTHENTICATED\"] }\n\n// Per-user records (requires userId firewall scope)\naccess: { roles: [\"USER\"] }\n\n// System admin (requires admin plugin)\naccess: { roles: [\"ADMIN\"] }\n\n// Org-membership roles with hierarchy expansion\naccess: { roles: [\"member+\"] } // expands to [\"member\", \"admin\", \"owner\"]\naccess: { roles: [\"admin+\"] } // expands to [\"admin\", \"owner\"]\naccess: { roles: [\"admin\"] } // exact match (no expansion)\n```\n\n```typescript\n// Field conditions - value can be string | number | boolean\ntype FieldCondition =\n | { equals: value | '$ctx.userId' | '$ctx.activeOrgId' }\n | { notEquals: value }\n | { in: value[] }\n | { notIn: value[] }\n | { lessThan: number }\n | { greaterThan: number }\n | { lessThanOrEqual: number }\n | { greaterThanOrEqual: number };\n```\n\n## Relationship-based authorization\n\nBeyond Better Auth roles (org membership, user-table role) and pseudo-roles, Quickback supports **relationship-based authorization roles** — names that bind to a declared relationship between the caller and a resource. Use these when access should follow a domain-table membership (\"user is a confirmed guest of this event\") rather than an org/admin gate.\n\n### `authz.relationships`\n\nDeclare relationships once in `quickback.config.ts`:\n\n```typescript\n// quickback.config.ts\n\nexport default defineConfig({\n // ...providers...\n authz: {\n relationships: {\n guestOf: {\n from: 'event_guests', // table name string\n subject: { column: 'userId', equals: 'ctx.userId' }, // caller side\n resource: { column: 'eventId' }, // resource side\n where: { status: 'confirmed' }, // optional filter\n },\n },\n roles: {\n guest: { via: 'guestOf' },\n // Composite: any guest OR an org owner/admin\n eventStaff: {\n or: [\n { via: 'guestOf' },\n { roles: ['admin', 'owner'] },\n ],\n },\n },\n },\n});\n```\n\n### Using relationship-roles in resources\n\nResource definitions reference declared roles by name in `roles: [...]` arrays exactly like BA roles or pseudo-roles. The compiler rewrites the access tree at build time so the runtime route does an inline relationship lookup against the declared table.\n\n**Today (v1) this works on:**\n\n| Surface | Status | Notes |\n|---|---|---|\n| `firewall:` `via:` predicate | ✓ Supported | Subquery composes as outermost AND |\n| `crud.*.access` `roles: ['guest']` | ✓ Supported | Inline async lookup per request |\n| `read.access` / `read.views.*.access` `roles: ['guest']` | ✓ Supported | Same inline path |\n| `masking.<field>.show` `roles: ['guest']` | ⚠ Refused at compile | v1 limitation — async/batched mask functions deferred |\n| `actions.<name>.access` `roles: ['guest']` | ⚠ Refused at compile | v1 limitation — explicit `relationshipBindings` deferred |\n\nFor the surfaces that are not yet supported, the compiler refuses at build time with a clear error pointing to a workaround. The runtime evaluator fails closed on relationship arms regardless, so silent grants are impossible.\n\n### Recommended pattern: gate at the firewall layer\n\nMost of the time, relationship-based row visibility is what you want, and putting it at the **firewall** layer is the cleanest expression. The firewall is row-filter; the access layer is route/role-filter; let each do its job:\n\n```typescript\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' }, // ← row visibility\n],\nread: {\n access: { roles: ['admin', 'member'] }, // ← who can hit the route\n views: {\n cms: { access: { roles: ['admin', 'member'] }, fields: [...] },\n guest: { access: { roles: ['member', 'admin'] }, fields: [...] },\n },\n},\n```\n\nA guest who's in your org as `member` can hit the endpoint and the firewall filters them down to events they're guests of. Cross-tenant access is impossible because the org filter is the outermost AND.\n\n### Cross-tenant \"my events\" dashboards are NOT this\n\nA common adjacent pattern — \"logged-in user wants `GET /my-events` returning events they're a guest of *across all tenants*\" — is **not** solved by relationship-roles. The tenant firewall is enforced at the outermost AND, so a guest of an event in another tenant remains correctly blocked.\n\nFor cross-tenant aggregation, use one of:\n\n- **User-scoped firewall**: `firewall: { owner: { column: 'userId' } }` — a flat per-user table.\n- **A standalone action that walks the relationship table itself** — see worked example below.\n\nDon't reach for relationship-roles first and then get confused when the tenant firewall blocks. The two patterns serve different problems.\n\n#### Worked example: `GET /my-events` standalone action\n\nThe cleanest expression of the cross-tenant attendee dashboard is a standalone action with a custom path that does its own join against the relationship table. The action is gated by `roles: ['AUTHENTICATED']` (any signed-in user can hit it; per-row scoping is the query itself), and the SQL filters by `ctx.userId` so each caller sees exactly the events they're a guest of:\n\n```ts\n// features/dashboard/actions/myEvents.ts\n\nexport default defineAction({\n description: \"List events the caller is a confirmed guest of, across all tenants.\",\n path: '/my-events',\n method: 'GET',\n input: z.object({}),\n // Any signed-in user. Row visibility comes from the query, not the role.\n access: { roles: ['AUTHENTICATED'] },\n async execute({ db, ctx }) {\n // 1. Find every event the caller has a confirmed guest row for.\n const guestRows = await db\n .select({ eventId: guests.eventId })\n .from(guests)\n .where(\n and(\n eq(guests.userId, ctx.userId!),\n eq(guests.status, 'confirmed'),\n // guests.organizationId is NOT filtered here — that's the whole\n // point of the cross-tenant lane. The relationship row's org is\n // ambient information that this action explicitly traverses.\n )\n );\n\n if (guestRows.length === 0) return { events: [] };\n\n // 2. Pull the matching events. NOTE: this query also bypasses\n // `events.organizationId` scope — by design — so explicitly filter\n // out soft-deleted rows yourself if your `events` table uses them.\n const eventIds = guestRows.map((r) => r.eventId);\n const rows = await db\n .select()\n .from(events)\n .where(inArray(events.id, eventIds));\n\n return { events: rows };\n },\n});\n```\n\nWhy this is a standalone action and not a CRUD route:\n\n- **Tenant firewall would block it.** The default `firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }]` on `events` is correct for every other read — only the cross-tenant dashboard wants to step outside it, and that's a deliberate, explicit step taken in handler code.\n- **The join is the access control.** A relationship-role at the firewall layer can't express \"filter by this user's relationships, ignoring the org context.\" The handler does that join directly.\n- **Audit-logged automatically.** Standalone actions are mandatorily audit-logged in the runtime — the cross-tenant traversal is recorded with `ctx.userId`, IP, and timing.\n\nTwo important guardrails when you write one of these:\n\n1. **Always filter by `ctx.userId` in the relationship lookup.** If you accept a `userId` from the request body and trust it, you've built an IDOR. The example above uses `ctx.userId!` directly so the only events returned are the caller's.\n2. **You take responsibility for soft-delete and other invariants the firewall would otherwise apply.** Add the `deletedAt` filter, status checks, and any other row-level predicates by hand. The action is OUTSIDE the firewall pipeline by design — the cost is that you can't lean on the auto-applied predicates.\n\nIf you find yourself writing more than one of these per project, that's usually a signal to revisit the schema (could a user-owned `userEvents` materialized view replace the join?) rather than a sign Quickback should ship a higher-level abstraction. Cross-tenant lanes are intentionally explicit.\n\n### Compile-time refusals (consolidated)\n\nThe validator and resolver reject:\n\n- Unknown key in `authz` block (typo guard — `realtionships` would otherwise silently produce a permanently-denied role).\n- Reserved role-name (auth-provider-derived). Names like `guest`, `speaker`, `attendee` are free; `admin`/`owner`/`member` are reserved when the BA org plugin is on.\n- Cycle in role composition (`a → b → a`).\n- Relationship `from` references unknown table.\n- Relationship-role used on a resource missing the `resource.column`.\n- Relationship table with `firewall: { exception: true }` (would let cross-tenant grants slip through).\n- `lowering: 'session'` (reserved for v2 — staleness/invalidation ergonomics not yet shipped).\n- `+` hierarchy suffix on a relationship-role name (terminal, like pseudo-roles).\n- Relationship-roles in `masking.show` / `actions.access` (deferred surfaces — see the table above).\n\n## Read & 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 (`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)"
|
|
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) |\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| postgres / supabase / neon / libsql / sqlite drivers | `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 |\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## 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 (v1 limitation)\n\nRelationship-roles declared under `authz.roles` (e.g. `guest: { via: 'guestOf' }`) are **not yet supported in action access blocks**. The compiler refuses to build with a clear error message because the binding semantics — which input field or which loaded record's column to check the relationship against — differ between record-actions and standalone-actions and require explicit declaration not yet wired in v1.\n\nThe runtime evaluator fails closed on unrecognized relationship arms, so silent grants are impossible.\n\n**Workaround**: 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\nA future `actions.<name>.relationshipBindings` declaration is on the roadmap to remove this limitation. See [Access — relationship authorization](/compiler/definitions/access#relationship-based-authorization) for the full picture.\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- platform admin gate (`ctx.userRole === \"admin\"`)\n- mandatory audit logging on deny/success/error\n\n`PUBLIC` actions also receive mandatory audit logging (same audit table), since unauthenticated endpoints are high-risk by nature.\n\nWithout unsafe mode, `unsafeDb` is `undefined` in the executor params.\n\n### Raw SQL Policy\n\nBy default, the compiler rejects raw SQL in action code. Use Drizzle query-builder syntax whenever possible.\n\nIf a specific action must use raw SQL, opt in explicitly:\n\n```typescript\n// features/ledgers/actions/reconcile.ts\n\nexport default defineAction({\n description: \"Run custom reconciliation query\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n allowRawSql: true,\n async execute({ db }) {\n return db.execute(sql`select 1`);\n },\n});\n```\n\nWithout `allowRawSql: true`, compilation fails with a loud error pointing to the action and snippet.\n\nThe detector checks for SQL keywords in string arguments, so non-SQL method calls like `headers.get(\"X-Forwarded-For\")` or `map.get(\"key\")` will not trigger false positives.\n\n## Sharing Code Between Actions\n\nFor Zod schemas, helpers, or constants used across multiple actions in a\nfeature, put them under `<feature>/lib/` and import from each action file.\nFiles under `lib/` are copied verbatim into the generated output.\n\n```\nfeatures/applications/\n├── applications.ts\n├── actions/\n│ ├── advance.ts\n│ └── reject.ts\n└── lib/\n ├── inputs.ts ← shared Zod schemas\n └── transitions.ts ← state-machine helpers\n```\n\n```typescript\n// features/applications/lib/inputs.ts\n\nexport const advanceInput = z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n notes: z.string().max(2000).optional(),\n});\n```\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move forward\",\n input: advanceInput,\n access: { roles: [\"owner\"] },\n async execute({ db, record, input }) { /* … */ },\n});\n```\n\n### Importing Tables\n\nAction files import tables from their own feature or other features. The compiler generates alias files for each table, so you import by the table's file name:\n\n```typescript\n// features/applications/actions/advance.ts\n\n// Same feature — import from parent directory using the table's file name\n\n// Cross-feature — go up to the features directory, then into the other feature\n\n```\n\n**Path pattern from `features/{name}/actions/`:**\n- Same feature table: `../{table-file-name}` (e.g., `../applications`)\n- Other feature table: `../../{other-feature}/{table-file-name}` (e.g., `../../candidates/candidates`)\n- Generated lib files: `../../../lib/{module}` (e.g., `../../../lib/realtime`, `../../../lib/webhooks`)\n\n### Executor Parameters\n\n```typescript\n\ninterface ActionExecutorParams {\n db: DrizzleDB; // Scoped database (auto-applies org/owner/soft-delete filters)\n unsafeDb?: DrizzleDB; // Unscoped database (only available when unsafe mode is enabled)\n ctx: AppContext; // User context (userId, roles, orgId)\n record?: TRecord; // The record (record-based only, undefined for standalone)\n input: TInput; // Validated input from Zod schema\n services: TServices; // Configured integrations (billing, notifications, etc.)\n c: HonoContext; // Raw Hono context for advanced use\n env: Env; // Runtime bindings (Cloudflare env / process env). Alias for c.env.\n auth: Auth; // Better Auth instance — call auth.api.getSession(...) etc. Lazy on Cloudflare.\n whereRecord?: (table) => SQL; // Pre-built WHERE: firewall + soft-delete + eq(table.id, record.id). Record-based actions only.\n whereTransition?: (table) => SQL; // whereRecord plus the transition's \"from\" precondition. Transition actions only.\n}\n```\n\n#### `auth` — Better Auth instance\n\n`auth` is the Better Auth instance, ready to call from inside an action\nhandler. Use it for things like minting an OAuth access token, fetching the\ncurrent session in a custom way, or invoking a Better Auth plugin method\nthat isn't already exposed by the generated middleware.\n\n```typescript\n// features/integrations/actions/connect-google-drive.ts\n\nexport default defineAction({\n description: \"Get a fresh Google Drive access token for the signed-in user\",\n input: z.object({}),\n access: { roles: [\"AUTHENTICATED\"] },\n async execute({ auth, ctx, c }) {\n // genericOAuth plugin method — needs a cast since the default-generic\n // `Auth` type doesn't carry plugin-specific API surface.\n const token = await (auth.api as any).getAccessToken({\n headers: c.req.raw.headers,\n body: { providerId: \"google\", userId: ctx.userId },\n });\n return { accessToken: token.accessToken };\n },\n});\n```\n\n**Lazy on Cloudflare**: the generated handler emits a `Proxy` so\n`createAuth(c.env, c.req.raw.cf)` only runs the first time you read a\nproperty on `auth`. Actions that never touch `auth` pay zero construction\ncost. On Bun/Node `auth` is the imported singleton (an IIFE that lazy-loads\nthe database adapter) wrapped in the same proxy shape — call sites are\nidentical across runtimes.\n\n**Typing**: `auth` is typed as `Auth` from `better-auth`. The base API\n(`getSession`, `signOut`, `signInEmail`, etc.) is fully typed. Plugin-only\nmethods (`getAccessToken` from `genericOAuth`, admin-plugin methods, etc.)\nneed a cast at the call site — the default-generic `Auth` doesn't infer\nthe project's specific plugin set.\n\n#### `whereRecord` — explicit, scope-safe WHERE\n\nFor protected-field writes inside record-based actions, prefer\n`whereRecord(table)` over `eq(table.id, record.id)`. It returns a Drizzle\nexpression that AND-merges the resource's firewall and soft-delete predicates\nwith the record id, so the WHERE is explicit even if a future refactor swaps\n`db` back to an unscoped client:\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Advance\",\n input: /* … */,\n access: { roles: [\"owner\"] },\n async execute({ db, record, input, whereRecord }) {\n const [updated] = await db\n .update(applications)\n .set({\n status: input.nextStatus,\n notes: input.notes ?? record.notes,\n })\n .where(whereRecord!(applications)) // firewall + soft-delete + id, all in one\n .returning();\n return updated;\n },\n});\n```\n\nThe audit DB wrapper hard-stamps `modifiedAt`/`modifiedBy` on every\n`.set()` call, so handlers don't write them. The same wrapper hard-stamps\n`createdAt`/`createdBy`/`modifiedAt`/`modifiedBy` on every `.values()`.\nCaller-supplied audit fields are dropped on the floor — the audit log\nalways reflects the real actor and the real moment.\n\n`whereRecord` is undefined for standalone actions (they have no record), so\nthe parameter is typed as optional. `whereTransition` extends `whereRecord`\nwith the transition's \"from\" precondition for transition actions.\n\n## HTTP API Reference\n\n### Request Format\n\n| Method | Input Source | Use Case |\n|--------|--------------|----------|\n| `GET` | Query parameters | Read-only operations, fetching data |\n| `POST` | JSON body | Default, state-changing operations |\n| `PUT` | JSON body | Full replacement operations |\n| `PATCH` | JSON body | Partial updates |\n| `DELETE` | JSON body | Deletion with optional payload |\n\n### Response Formats\n\n| Type | Content-Type | Use Case |\n|------|--------------|----------|\n| `json` | `application/json` | Standard API responses (default) |\n| `stream` | `text/event-stream` | Real-time streaming (AI chat, live updates) |\n| `file` | Varies | File downloads (reports, exports) |\n\n### Error Codes\n\n| Status | Description |\n|--------|-------------|\n| `400` | Invalid input / validation error (also `GUARD_FIELD_PROTECTED` for direct protected-field writes) |\n| `401` | Not authenticated |\n| `403` | Access role check failed (`ACCESS_ROLE_REQUIRED`) |\n| `404` | Record not found (record-based actions) |\n| `409` | Record is in the wrong state for this action — `access.record` predicate or `transition` policy failed (`ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`) |\n| `500` | Handler execution error |\n\n### Validation Error Response\n\n```json\n{\n \"error\": \"Invalid request data\",\n \"layer\": \"validation\",\n \"code\": \"VALIDATION_FAILED\",\n \"details\": {\n \"fields\": {\n \"amount\": \"Expected positive number\"\n }\n },\n \"hint\": \"Check the input schema for this action\"\n}\n```\n\n### Error Handling\n\n**Option 1: Return a JSON error response** (recommended for most cases)\n\nSince action handlers receive the Hono context (`c`), you can return error responses directly:\n\n```typescript\nasync execute({ ctx, record, input, c }) {\n if (record.stage === 'hired') {\n return c.json({\n error: 'Cannot modify a hired application',\n code: 'ALREADY_HIRED',\n details: { currentStage: record.stage },\n }, 400);\n }\n // ... continue\n}\n```\n\n**Option 2: Throw an ActionError**\n\n```typescript\n\nasync execute({ ctx, record, input }) {\n if (record.stage === 'hired') {\n throw new ActionError('Cannot modify a hired application', 'ALREADY_HIRED', 400, {\n currentStage: record.stage,\n });\n }\n // ... continue\n}\n```\n\nThe `ActionError` constructor signature is `(message, code, statusCode, details?)`.\n\n## Protected Fields\n\nActions can modify fields that are protected from regular CRUD operations:\n\n```typescript\n// In the table file (defineTable config)\nguards: {\n protected: {\n status: [\"advance\", \"reject\", \"hire\", \"withdraw\"], // Only these actions can modify status\n }\n}\n```\n\nThis allows the `advance` action to set `status = \"interview\"` even though the field is protected from regular PATCH requests. Direct `PATCH /:id` attempts to set `status` are rejected by the guards layer with **400 GUARD_FIELD_PROTECTED**, and the field is omitted from the generated POST/PATCH body Zod schemas — clients cannot even send it past validation.\n\n## Transition (state-machine policy)\n\nFor protected fields that follow a state machine — application status, invoice\nlifecycle, order fulfilment — use `transition` on the action so the compiler\ngenerates a runtime guard that enforces the *from/to pair*, not just the\ncurrent state. Without it, an `advance` action whose input enum allows\n`[\"screening\", \"interview\", \"offer\"]` and whose `access.record` allows\n`status in [\"applied\", \"screening\", \"interview\"]` will happily run\n`applied → offer` (a skip) or `interview → screening` (a regression).\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\", // read target from input.nextStatus\n fromTo: {\n applied: [\"screening\"],\n screening: [\"interview\"],\n interview: [\"offer\"],\n },\n },\n async execute({ db, record, input, whereTransition }) { /* … */ },\n});\n```\n\n```typescript\n// features/applications/actions/hire.ts\n\nexport default defineAction({\n description: \"Finalize an offer.\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n transition: {\n field: \"status\",\n to: \"hired\", // fixed target — same value every call\n fromTo: { offer: [\"hired\"] },\n },\n async execute({ db, record, whereTransition }) { /* … */ },\n});\n```\n\n| Field | Required | Description |\n|---|---|---|\n| `field` | Yes | Record column to validate (e.g. `\"status\"`) |\n| `fromTo` | Yes | Map of current value → permitted next values. Keys also enumerate the legal source states. |\n| `via` | Yes (or `to`) | Input key that carries the target value. Use for variable-target actions like `advance`. |\n| `to` | Yes (or `via`) | Literal target value the action always writes. Use for fixed-target actions like `hire`/`reject`. |\n\nExactly one of `via` or `to` must be provided. The compiler rejects both at\nvalidate time. When `to` is set, it must appear in some `fromTo[*]` array —\notherwise the action would be unreachable, which is almost certainly a bug.\n\n### Wire-level errors\n\nThe compiled guard returns **409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`** with\nthe field, the current value, the requested target, and the allowed set:\n\n```json\n{\n \"error\": \"Action not allowed for current record state\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ACTION_NOT_ALLOWED_FOR_STATE\",\n \"details\": {\n \"field\": \"status\",\n \"current\": \"interview\",\n \"target\": \"screening\",\n \"allowedTargets\": [\"offer\"]\n },\n \"hint\": \"From \\\"interview\\\", status can transition to: offer\"\n}\n```\n\nThis is distinct from a role failure: if the caller has the wrong role they\nget **403 `ACCESS_ROLE_REQUIRED`** as before. Splitting the two lets clients\ntell *\"you can't do this\"* from *\"you can't do this *yet*\"* — the latter is\nrecoverable by the user, the former isn't.\n\nThe same 409 code is used when an `access.record` predicate (without\n`transition`) fails — for example `record: { status: { equals: \"pending\" } }`\ncalled against a paid invoice now returns 409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`,\nnot a misleading 403.\n\n## Examples\n\n### Bulk Import (Standalone, No Record)\n\n```typescript\n// features/candidates/actions/bulk-import.ts\n\nexport default defineAction({\n description: \"Import candidates from job board CSV\",\n path: \"/candidates/import\",\n input: z.object({\n data: z.array(z.object({\n email: z.string().email(),\n name: z.string(),\n })),\n }),\n access: { roles: [\"hiring-manager\", \"recruiter\"] },\n async execute({ db, input }) {\n const inserted = await db\n .insert(candidates)\n .values(input.data)\n .returning();\n return { imported: inserted.length };\n },\n});\n```"
|
|
83
83
|
},
|
|
84
84
|
"compiler/definitions/concepts": {
|
|
85
85
|
"title": "Glossary",
|
|
@@ -111,7 +111,7 @@ export const DOCS = {
|
|
|
111
111
|
},
|
|
112
112
|
"compiler/definitions/schema": {
|
|
113
113
|
"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, cuid for libsql/bun-sqlite, `crypto.randomUUID()` for supabase, 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:\n\n- **Postgres family (Supabase, Neon, D1)** → `snake_case` (`organizationId` → `organization_id`)\n- **SQLite family (bun-sqlite, better-sqlite3, libsql)** → `camelCase` (`organizationId` → `organizationId`)\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: 'bun-sqlite',\n config: {\n path: './data/app.db',\n namingConvention: 'snake_case', // force snake_case everywhere\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 (D1, Turso, better-sqlite3)\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 (Supabase, 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"
|
|
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"
|
|
115
115
|
},
|
|
116
116
|
"compiler/definitions/validation": {
|
|
117
117
|
"title": "Validation",
|
|
@@ -159,11 +159,11 @@ export const DOCS = {
|
|
|
159
159
|
},
|
|
160
160
|
"compiler": {
|
|
161
161
|
"title": "Quickback Compiler",
|
|
162
|
-
"content": "The **Quickback Compiler** is the build tool at the center of Quickback. You write declarative definitions in TypeScript — schema, security rules, validation, custom actions — and the compiler emits production
|
|
162
|
+
"content": "The **Quickback Compiler** is the build tool at the center of Quickback. You write declarative definitions in TypeScript — schema, security rules, validation, custom actions — and the compiler emits a production Hono application for the **Quickback Stack** on Cloudflare.\n\n```\ndefineTable() ─┐\n ├─► quickback compile ─► Hono API on Cloudflare\ndefineActions()─┘ (D1 or Neon)\n```\n\n## What the compiler does\n\nWhen you run `quickback compile`, it:\n\n1. **Reads your definitions** — every `defineTable()`, `defineActions()`, and `defineConfig()` in your project\n2. **Validates security** — firewall, access, guards, and masking are checked for consistency\n3. **Generates output** — Hono routes + middleware + types + OpenAPI spec + MCP server + security artifacts\n4. **Emits database migrations** — runs `drizzle-kit generate` for schema changes\n\n```\nquickback/\n├── quickback.config.ts # Compiler configuration (providers, options)\n└── features/\n └── jobs/\n ├── jobs.ts # defineTable(...)\n └── actions.ts # defineActions(...)\n```\n\n## The target: Hono on Cloudflare\n\n[Quickback for Hono API](/compiler/targets/hono-api) generates a complete Hono application bundled into a Cloudflare Worker. Pair with **Cloudflare D1** for SQLite-at-the-edge or **Neon** for full PostgreSQL via Hyperdrive.\n\n```typescript\nproviders: {\n runtime: defineRuntime('cloudflare'),\n database: defineDatabase('cloudflare-d1'), // or 'neon'\n auth: defineAuth('better-auth'),\n}\n```\n\n## The DSL\n\n- **[Definitions](/compiler/definitions)** — Schema, Firewall, Access, Guards, Masking, Views, Actions\n- **[Configuration](/compiler/config)** — `quickback.config.ts`, providers, domains, bindings\n- **[Getting Started](/compiler/getting-started)** — Templates and full examples\n\n## The cloud and the CLI\n\nYou don't run the compiler binary locally — it runs as a hosted service:\n\n- **[Cloud Compiler](/compiler/cloud-compiler)** — `compiler.quickback.dev`, CLI, authentication, MCP server for editors\n- **[Claude Code Skill](/compiler/claude-code-skill)** — AI-powered authoring assistance\n\n## Development workflow\n\n1. **Define resources** in `quickback/features/`\n2. **Compile** with `quickback compile`\n3. **Apply migrations** with `wrangler d1 migrations apply`\n4. **Test locally** with `wrangler dev`\n5. **Deploy** with `wrangler deploy`\n\n## Next steps\n\n- [Getting Started](/compiler/getting-started) — Create your first project\n- [Definitions](/compiler/definitions) — The DSL\n- [Quickback for Hono API](/compiler/targets/hono-api) — Generated output reference"
|
|
163
163
|
},
|
|
164
164
|
"compiler/targets/hono-api/cloudflare": {
|
|
165
165
|
"title": "Cloudflare Workers",
|
|
166
|
-
"content": "The Cloudflare target generates a complete Hono-based API running on Cloudflare Workers with D1 as the database. This is the recommended target for production deployments.\n\n## Configuration\n\n```typescript\n\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n features: [\"organizations\"],\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## Generated Output\n\n```\nsrc/\n├── routes/ # Hono route handlers (one per resource)\n├── middleware/ # Auth, firewall, access middleware\n├── features/ # Feature-specific helpers (security, masking)\n├── types/ # TypeScript interfaces\n├── db/\n│ └── schema.ts # Drizzle schema\n└── index.ts # Hono app entry point\n\nquickback/drizzle/\n├── migrations/ # SQL migration files\n└── meta/ # Drizzle metadata\n```\n\n## Security Model\n\nAll four security layers run at the application level:\n\n1. **Firewall** — Drizzle WHERE clauses for data isolation\n2. **Access** — Role checks in middleware\n3. **Guards** — Field filtering in request handlers\n4. **Masking** — Response transformation before sending\n\nSince D1 is only accessible through your Worker (no external connection string), the application layer is the only entry point. See [D1 Security Architecture](/compiler/targets/hono-api/database/d1#security-architecture) for details.\n\n## Features\n\n- Full CRUD with batch operations (create, update, delete, upsert)\n- Custom actions with inline or handler-based execution\n- Soft delete with cascading to child tables\n- Pagination, filtering, sorting, field selection, and full-text search\n- Views (column-level projections with per-view access control)\n- OpenAPI specification generation at `/openapi.json`\n\n## Deployment\n\n```bash\n# Local development\nnpm run dev\n\n# Apply migrations to remote D1\nnpm run db:migrate:remote\n\n# Deploy to Cloudflare Workers\nnpm run deploy\n```\n\n## Environment & Bindings\n\nYour `wrangler.toml` needs these bindings:\n\n| Binding | Type | Required | Purpose |\n|---------|------|----------|---------|\n| `DB` | D1 | Yes | Feature database |\n| `AUTH_DB` | D1 | Yes | Better Auth database |\n| `AUDIT_DB` | D1 | No* | Unsafe cross-tenant action audit logs |\n| `KV` | KV | Yes | Session storage |\n| `R2` | R2 | No | File storage (avatars, uploads) |\n| `AI` | Workers AI | No | Embeddings generation |\n| `VECTORIZE` | Vectorize | No | Vector search index |\n| `BROADCASTER` | Durable Object | No | Realtime broadcasts (inline DO) |\n\n\\* Required when you define cross-tenant unsafe actions.\n\n## See Also\n\n- [Cloudflare Template](/compiler/getting-started/template-cloudflare) — Step-by-step setup guide with full wrangler.toml configuration\n- [D1 Database](/compiler/targets/hono-api/database/d1) — D1 setup, multi-database pattern, and security architecture\n- [Neon Integration](/compiler/targets/hono-api/database/neon) — Alternative: PostgreSQL
|
|
166
|
+
"content": "The Cloudflare target generates a complete Hono-based API running on Cloudflare Workers with D1 as the database. This is the recommended target for production deployments.\n\n## Configuration\n\n```typescript\n\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n features: [\"organizations\"],\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## Generated Output\n\n```\nsrc/\n├── routes/ # Hono route handlers (one per resource)\n├── middleware/ # Auth, firewall, access middleware\n├── features/ # Feature-specific helpers (security, masking)\n├── types/ # TypeScript interfaces\n├── db/\n│ └── schema.ts # Drizzle schema\n└── index.ts # Hono app entry point\n\nquickback/drizzle/\n├── migrations/ # SQL migration files\n└── meta/ # Drizzle metadata\n```\n\n## Security Model\n\nAll four security layers run at the application level:\n\n1. **Firewall** — Drizzle WHERE clauses for data isolation\n2. **Access** — Role checks in middleware\n3. **Guards** — Field filtering in request handlers\n4. **Masking** — Response transformation before sending\n\nSince D1 is only accessible through your Worker (no external connection string), the application layer is the only entry point. See [D1 Security Architecture](/compiler/targets/hono-api/database/d1#security-architecture) for details.\n\n## Features\n\n- Full CRUD with batch operations (create, update, delete, upsert)\n- Custom actions with inline or handler-based execution\n- Soft delete with cascading to child tables\n- Pagination, filtering, sorting, field selection, and full-text search\n- Views (column-level projections with per-view access control)\n- OpenAPI specification generation at `/openapi.json`\n\n## Deployment\n\n```bash\n# Local development\nnpm run dev\n\n# Apply migrations to remote D1\nnpm run db:migrate:remote\n\n# Deploy to Cloudflare Workers\nnpm run deploy\n```\n\n## Environment & Bindings\n\nYour `wrangler.toml` needs these bindings:\n\n| Binding | Type | Required | Purpose |\n|---------|------|----------|---------|\n| `DB` | D1 | Yes | Feature database |\n| `AUTH_DB` | D1 | Yes | Better Auth database |\n| `AUDIT_DB` | D1 | No* | Unsafe cross-tenant action audit logs |\n| `KV` | KV | Yes | Session storage |\n| `R2` | R2 | No | File storage (avatars, uploads) |\n| `AI` | Workers AI | No | Embeddings generation |\n| `VECTORIZE` | Vectorize | No | Vector search index |\n| `BROADCASTER` | Durable Object | No | Realtime broadcasts (inline DO) |\n\n\\* Required when you define cross-tenant unsafe actions.\n\n## See Also\n\n- [Cloudflare Template](/compiler/getting-started/template-cloudflare) — Step-by-step setup guide with full wrangler.toml configuration\n- [D1 Database](/compiler/targets/hono-api/database/d1) — D1 setup, multi-database pattern, and security architecture\n- [Neon Integration](/compiler/targets/hono-api/database/neon) — Alternative: PostgreSQL via Hyperdrive"
|
|
167
167
|
},
|
|
168
168
|
"compiler/targets/hono-api/database/d1": {
|
|
169
169
|
"title": "D1 Database",
|
|
@@ -175,7 +175,7 @@ export const DOCS = {
|
|
|
175
175
|
},
|
|
176
176
|
"compiler/targets/hono-api/database/neon": {
|
|
177
177
|
"title": "Neon",
|
|
178
|
-
"content": "Neon provides serverless PostgreSQL that works with Cloudflare Workers via HTTP connections. Choose Neon when you need PostgreSQL features (JSON operators, full-text search, advanced indexing) or want database-level Row Level Security alongside the generated Hono API.\n\n## Why Neon\n\n- **Full PostgreSQL** — Advanced queries, joins, PostGIS, full-text search\n- **Database-level security** — RLS policies enforce access even if the API is bypassed\n- **Serverless** — HTTP connection mode for Cloudflare Workers\n- **Neon Authorize** — JWT-based RLS via the `auth.user_id()` function\n- **Better Auth integration** — Works seamlessly with the Quickback auth provider\n\n## Configuration\n\n```typescript title=\"quickback/quickback.config.ts\"\n\nexport default defineConfig({\n name: \"my-app\",\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"neon\", {\n connectionMode: \"auto\", // detects runtime\n pooled: true,\n }),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## Connection modes\n\n| Mode | Best for | How it works |\n|------|----------|--------------|\n| **HTTP** | Cloudflare Workers, edge functions | Stateless HTTP queries via `@neondatabase/serverless` |\n| **WebSocket** | Node.js, Bun | Persistent WebSocket connection for lower latency |\n| **Auto** (default) | Mixed environments | Detects runtime and picks the best mode |\n\n## Environment variables\n\n```bash\n# For Cloudflare Workers\nnpx wrangler secret put DATABASE_URL\n# Paste: postgresql://user:pwd@ep-xxx.region.neon.tech/db?sslmode=require\n\n# For local development (.env)\nDATABASE_URL=postgresql://user:pwd@ep-xxx.region.neon.tech/db?sslmode=require\n```\n\n## Migrations\n\nNeon uses PostgreSQL migrations, distinct from D1's SQLite migrations:\n\n```bash\nquickback compile # generates migrations under quickback/drizzle/\nnpm run db:migrate # applies them\n```\n\n## Row Level Security\n\nQuickback emits RLS policies from your `firewall` and `access` config. The Neon target uses Neon Authorize's `auth.user_id()` JWT claim function (the Supabase target uses `auth.uid()` instead — same pattern, different function).\n\n```typescript\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n]\n```\n\n```sql\nCREATE POLICY \"documents_select\" ON documents FOR SELECT\nUSING (\n organization_id = get_active_org_id()\n AND (has_any_role(ARRAY['admin']) OR user_id = auth.user_id())\n);\n```\n\n### Firewall patterns\n\n**Organization-scoped:**\n\n```sql\nCREATE POLICY \"projects_select\" ON projects FOR SELECT\nUSING (organization_id = public.get_active_org_id());\n```\n\n**User-scoped:**\n\n```sql\nCREATE POLICY \"preferences_select\" ON preferences FOR SELECT\nUSING (user_id = auth.user_id());\n```\n\n**Public tables:**\n\n```sql\nCREATE POLICY \"categories_deny_anon\" ON categories FOR ALL TO anon USING (false);\nCREATE POLICY \"categories_all\" ON categories FOR ALL TO authenticated USING (true) WITH CHECK (true);\n```\n\n### Helper functions\n\n| Function | Purpose |\n|----------|---------|\n| `get_active_org_id()` | Returns the user's active organization from `user_sessions` |\n| `has_any_role(roles[])` | Checks if the user has any specified role |\n| `has_org_role(role)` | Checks for a single specific role |\n| `is_org_member()` | Checks org membership |\n| `is_owner(owner_id)` | Checks record ownership |\n\n## Setting up Neon Authorize\n\n1. Open **Project Settings → Authorize** in the Neon console\n2. Add your JWKS URL: `https://your-api.example.com/auth/v1/.well-known/jwks.json`\n3. The `auth.user_id()` function will return the authenticated user's ID from the JWT\n\n## Generated files\n\n```\nquickback/drizzle/\n├── migrations/\n│ ├── 0100_create_rls_helpers.sql\n│ ├── 0101_create_rls_policies.sql\n│ └── 0102_create_indexes.sql\nsrc/\n├── db/schema.ts # Drizzle schema\n├── auth/schema.ts # Better Auth schema\n└── lib/neon.ts # Connection helper\n```\n\n## When to choose Neon vs D1\n\n| Factor | Neon | D1 |\n|--------|------|-----|\n| SQL dialect | PostgreSQL | SQLite |\n| Security model | RLS + application-layer | Application-layer only |\n| Multi-region | Built-in replication | Single region per database |\n| Pricing | Free tier, then usage-based | Free tier, then usage-based |\n| Best for | Complex queries, existing Postgres apps | Edge-first, simple schemas |\n\n## See also\n\n- [D1](/compiler/targets/hono-api/database/d1) — SQLite at the edge\n- [Providers](/compiler/config/providers) — All database provider options
|
|
178
|
+
"content": "Neon provides serverless PostgreSQL that works with Cloudflare Workers via HTTP connections. Choose Neon when you need PostgreSQL features (JSON operators, full-text search, advanced indexing) or want database-level Row Level Security alongside the generated Hono API.\n\n## Why Neon\n\n- **Full PostgreSQL** — Advanced queries, joins, PostGIS, full-text search\n- **Database-level security** — RLS policies enforce access even if the API is bypassed\n- **Serverless** — HTTP connection mode for Cloudflare Workers\n- **Neon Authorize** — JWT-based RLS via the `auth.user_id()` function\n- **Better Auth integration** — Works seamlessly with the Quickback auth provider\n\n## Configuration\n\n```typescript title=\"quickback/quickback.config.ts\"\n\nexport default defineConfig({\n name: \"my-app\",\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"neon\", {\n connectionMode: \"auto\", // detects runtime\n pooled: true,\n }),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## Connection modes\n\n| Mode | Best for | How it works |\n|------|----------|--------------|\n| **HTTP** | Cloudflare Workers, edge functions | Stateless HTTP queries via `@neondatabase/serverless` |\n| **WebSocket** | Node.js, Bun | Persistent WebSocket connection for lower latency |\n| **Auto** (default) | Mixed environments | Detects runtime and picks the best mode |\n\n## Environment variables\n\n```bash\n# For Cloudflare Workers\nnpx wrangler secret put DATABASE_URL\n# Paste: postgresql://user:pwd@ep-xxx.region.neon.tech/db?sslmode=require\n\n# For local development (.env)\nDATABASE_URL=postgresql://user:pwd@ep-xxx.region.neon.tech/db?sslmode=require\n```\n\n## Migrations\n\nNeon uses PostgreSQL migrations, distinct from D1's SQLite migrations:\n\n```bash\nquickback compile # generates migrations under quickback/drizzle/\nnpm run db:migrate # applies them\n```\n\n## Row Level Security\n\nQuickback emits RLS policies from your `firewall` and `access` config. The Neon target uses Neon Authorize's `auth.user_id()` JWT claim function (the Supabase target uses `auth.uid()` instead — same pattern, different function).\n\n```typescript\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n]\n```\n\n```sql\nCREATE POLICY \"documents_select\" ON documents FOR SELECT\nUSING (\n organization_id = get_active_org_id()\n AND (has_any_role(ARRAY['admin']) OR user_id = auth.user_id())\n);\n```\n\n### Firewall patterns\n\n**Organization-scoped:**\n\n```sql\nCREATE POLICY \"projects_select\" ON projects FOR SELECT\nUSING (organization_id = public.get_active_org_id());\n```\n\n**User-scoped:**\n\n```sql\nCREATE POLICY \"preferences_select\" ON preferences FOR SELECT\nUSING (user_id = auth.user_id());\n```\n\n**Public tables:**\n\n```sql\nCREATE POLICY \"categories_deny_anon\" ON categories FOR ALL TO anon USING (false);\nCREATE POLICY \"categories_all\" ON categories FOR ALL TO authenticated USING (true) WITH CHECK (true);\n```\n\n### Helper functions\n\n| Function | Purpose |\n|----------|---------|\n| `get_active_org_id()` | Returns the user's active organization from `user_sessions` |\n| `has_any_role(roles[])` | Checks if the user has any specified role |\n| `has_org_role(role)` | Checks for a single specific role |\n| `is_org_member()` | Checks org membership |\n| `is_owner(owner_id)` | Checks record ownership |\n\n## Setting up Neon Authorize\n\n1. Open **Project Settings → Authorize** in the Neon console\n2. Add your JWKS URL: `https://your-api.example.com/auth/v1/.well-known/jwks.json`\n3. The `auth.user_id()` function will return the authenticated user's ID from the JWT\n\n## Generated files\n\n```\nquickback/drizzle/\n├── migrations/\n│ ├── 0100_create_rls_helpers.sql\n│ ├── 0101_create_rls_policies.sql\n│ └── 0102_create_indexes.sql\nsrc/\n├── db/schema.ts # Drizzle schema\n├── auth/schema.ts # Better Auth schema\n└── lib/neon.ts # Connection helper\n```\n\n## When to choose Neon vs D1\n\n| Factor | Neon | D1 |\n|--------|------|-----|\n| SQL dialect | PostgreSQL | SQLite |\n| Security model | RLS + application-layer | Application-layer only |\n| Multi-region | Built-in replication | Single region per database |\n| Pricing | Free tier, then usage-based | Free tier, then usage-based |\n| Best for | Complex queries, existing Postgres apps | Edge-first, simple schemas |\n\n## See also\n\n- [D1](/compiler/targets/hono-api/database/d1) — SQLite at the edge\n- [Providers](/compiler/config/providers) — All database provider options"
|
|
179
179
|
},
|
|
180
180
|
"compiler/targets/hono-api/database/using-d1": {
|
|
181
181
|
"title": "Using D1",
|
|
@@ -187,11 +187,11 @@ export const DOCS = {
|
|
|
187
187
|
},
|
|
188
188
|
"compiler/targets/hono-api/using-the-api/actions-api": {
|
|
189
189
|
"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```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"
|
|
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"
|
|
191
191
|
},
|
|
192
192
|
"compiler/targets/hono-api/using-the-api/batch-operations": {
|
|
193
193
|
"title": "Batch Operations",
|
|
194
|
-
"content": "Batch operations let you create, update, upsert, or delete multiple records in a single request. They are **auto-enabled** when the corresponding write operation exists in your definition.\n\n## Available Endpoints\n\n| Endpoint | Method | Auto-enabled When |\n|----------|--------|-------------------|\n| `/{resource}/batch` | `POST` | `create` exists |\n| `/{resource}/batch` | `PATCH` | `update` exists |\n| `/{resource}/batch` | `DELETE` | `delete` exists |\n| `/{resource}/batch` | `PUT` | `upsert` exists |\n\nTo disable a batch operation, set it to `false` in your definition:\n\n```typescript\ncreate: {\n access: { roles: ['hiring-manager'] },\n batch: false, // Disable batch create\n}\n```\n\n## Batch Create\n\n```\nPOST /api/v1/{resource}/batch\n```\n\n### Request\n\n```json\n{\n \"records\": [\n { \"candidateId\": \"cand_101\", \"jobId\": \"job_201\", \"stage\": \"applied\", \"notes\": \"Strong frontend background\" },\n { \"candidateId\": \"cand_101\", \"jobId\": \"job_202\", \"stage\": \"applied\", \"notes\": \"Also interested in backend role\" },\n { \"candidateId\": \"cand_102\", \"jobId\": \"job_201\", \"stage\": \"applied\", \"notes\": \"Referred by employee\" }\n ],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\n### Response (201 or 207)\n\n```json\n{\n \"success\": [\n { \"id\": \"app_abc1\", \"candidateId\": \"cand_101\", \"jobId\": \"job_201\", \"stage\": \"applied\", \"createdAt\": \"2025-01-15T10:00:00Z\" },\n { \"id\": \"app_abc3\", \"candidateId\": \"cand_102\", \"jobId\": \"job_201\", \"stage\": \"applied\", \"createdAt\": \"2025-01-15T10:00:00Z\" }\n ],\n \"errors\": [\n {\n \"index\": 1,\n \"record\": { \"candidateId\": \"cand_101\", \"jobId\": \"job_202\", \"stage\": \"applied\", \"notes\": \"Also interested in backend role\" },\n \"error\": {\n \"error\": \"Database insert failed\",\n \"layer\": \"validation\",\n \"code\": \"INSERT_FAILED\",\n \"details\": { \"reason\": \"UNIQUE constraint failed: applications.candidateId, applications.jobId\" }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"failFast\": false,\n \"transactional\": true\n }\n}\n```\n\n- **201** — All records created successfully\n- **207** — Partial success (some errors, some successes)\n\n`POST /batch` uses a single bulk `INSERT`, so `meta.transactional` is `true` on every provider — the database guarantees the insert is atomic regardless of the `failFast` flag.\n\nFields applied automatically to each record:\n- ID generation (UUID, prefixed, etc.)\n- Ownership fields (`organizationId`, `ownerId`, `createdBy`)\n- Audit fields (`createdAt`, `modifiedAt`)\n- Default values and computed fields\n\n## Batch Update\n\n```\nPATCH /api/v1/{resource}/batch\n```\n\nEvery record **must include an `id` field**.\n\n### Request\n\n```json\n{\n \"records\": [\n { \"id\": \"app_abc1\", \"notes\": \"Passed phone screen, schedule onsite\" },\n { \"id\": \"app_abc2\", \"notes\": \"Moved to technical interview round\" },\n { \"id\": \"app_xyz9\", \"notes\": \"Hiring manager approved offer\" }\n ],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\n### Response (200 or 207)\n\n```json\n{\n \"success\": [\n { \"id\": \"app_abc1\", \"notes\": \"Passed phone screen, schedule onsite\", \"modifiedAt\": \"2025-01-15T11:00:00Z\" },\n { \"id\": \"app_abc2\", \"notes\": \"Moved to technical interview round\", \"modifiedAt\": \"2025-01-15T11:00:00Z\" }\n ],\n \"errors\": [\n {\n \"index\": 2,\n \"record\": { \"id\": \"app_xyz9\", \"notes\": \"Hiring manager approved offer\" },\n \"error\": {\n \"error\": \"Not found\",\n \"layer\": \"firewall\",\n \"code\": \"NOT_FOUND\",\n \"details\": { \"id\": \"app_xyz9\" }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"failFast\": false,\n \"transactional\": false\n }\n}\n```\n\nRecords that don't exist or aren't accessible through the firewall return a `NOT_FOUND` error. Guard rules (immutable, protected, not-updatable fields) are checked per record.\n\n### Missing IDs\n\nIf any records are missing the `id` field, the entire request is rejected:\n\n```json\n{\n \"error\": \"Records missing required ID field\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_MISSING_IDS\",\n \"details\": { \"indices\": [0, 2] },\n \"hint\": \"All records must include an ID field for batch update.\"\n}\n```\n\n## Batch Delete\n\n```\nDELETE /api/v1/{resource}/batch\n```\n\n### Request\n\n```json\n{\n \"ids\": [\"app_abc1\", \"app_abc2\", \"app_abc3\"],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\nNote: Batch delete uses an `ids` array (not `records`).\n\n### Response (200 or 207)\n\n**Soft delete** (default):\n\n```json\n{\n \"success\": [\n { \"id\": \"app_abc1\", \"candidateId\": \"cand_101\", \"deletedAt\": \"2025-01-15T12:00:00Z\" },\n { \"id\": \"app_abc2\", \"candidateId\": \"cand_103\", \"deletedAt\": \"2025-01-15T12:00:00Z\" }\n ],\n \"errors\": [],\n \"meta\": {\n \"total\": 2,\n \"succeeded\": 2,\n \"failed\": 0,\n \"failFast\": false,\n \"transactional\": true\n }\n}\n```\n\n`DELETE /batch` issues a single bulk `UPDATE … WHERE id IN (...)` (soft delete) or `DELETE … WHERE id IN (...)` (hard delete), so `meta.transactional` is `true` on every provider regardless of `failFast`.\n\n**Hard delete**: Returns objects with only the `id` field (record data is deleted).\n\n## Batch Upsert\n\n```\nPUT /api/v1/{resource}/batch\n```\n\nInserts new records or updates existing ones. Every record must include an `id` field.\n\n**Note:** Batch upsert is only available when `generateId` is set to `false` (user-provided IDs) in your configuration.\n\n### Request\n\n```json\n{\n \"records\": [\n { \"id\": \"app_001\", \"candidateId\": \"cand_101\", \"jobId\": \"job_201\", \"stage\": \"screening\", \"notes\": \"Updated after phone screen\" },\n { \"id\": \"app_002\", \"candidateId\": \"cand_104\", \"jobId\": \"job_203\", \"stage\": \"applied\", \"notes\": \"New application from referral\" }\n ],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\n### Response (201 or 207)\n\nThe compiler checks which IDs already exist and splits the batch into creates and updates. Create records get ownership and default fields; update records get only `modifiedAt`. Under `failFast: true`, both the bulk insert and the per-record updates run inside the same transaction — a failed update rolls back the inserts too on tx-supporting providers.\n\n## Fail-Fast Mode\n\nBy default, batch operations use **partial success** mode — each record is processed independently, and failures don't affect other records.\n\nSet `\"failFast\": true` to stop on the first error:\n\n```json\n{\n \"records\": [...],\n \"options\": {\n \"failFast\": true\n }\n}\n```\n\n### Fail-Fast Failure Response (400)\n\n```json\n{\n \"error\": \"Batch failed at index 1\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_FAILFAST_STOPPED\",\n \"details\": {\n \"failedAt\": 1,\n \"reason\": \"Database insert failed\",\n \"errorDetails\": { \"reason\": \"UNIQUE constraint failed\" }\n }\n}\n```\n\n## Transactional Semantics\n\nThe behavior of `failFast: true` depends on whether your database provider\nsupports transactions. The response's `meta.transactional` flag tells you\nwhich guarantee you actually got — inspect it in clients that care about\nrollback.\n\n### Per-Provider Matrix\n\n| Endpoint | Provider | `failFast` | `meta.transactional` | Behavior |\n|----------|----------|-----------|----------------------|----------|\n| `PATCH /batch` (update) | postgres / supabase / neon / libsql / better-sqlite3 / bun-sqlite | `true` | `true` | `db.transaction()` wraps the per-record loop. Any failure rolls back ALL writes in the batch. |\n| `PATCH /batch` (update) | (any) | `false` | `false` | Per-record loop, partial success. Each record commits independently. |\n| `PATCH /batch` (update) | cloudflare-d1 | `true` | `false` | Fail-fast loop without rollback — D1 has no `db.transaction`. Records before the failure stay committed. |\n| `PUT /batch` (upsert) | tx-supporting | `true` | `true` | Bulk insert + per-record update share one transaction. Any failure rolls back both. |\n| `PUT /batch` (upsert) | cloudflare-d1 | `true` | `false` | Bulk insert commits; per-record update loop is fail-fast without rollback. |\n| `POST /batch` (create) | (any) | (any) | `true` | Single bulk `INSERT` — atomic at the DB level. |\n| `DELETE /batch` | (any) | (any) | `true` | Single bulk `UPDATE` (soft) or `DELETE` (hard) — atomic at the DB level. |\n\n### Reading `meta.transactional` in clients\n\n```typescript\nconst res = await fetch('/api/v1/jobs/batch', {\n method: 'PATCH',\n body: JSON.stringify({ records, options: { failFast: true } }),\n});\nconst body = await res.json();\n\nif (!body.meta.transactional && body.errors.length > 0) {\n // Some records succeeded before the failure and remain committed.\n // Compensate via the success array if needed.\n}\n```\n\n### Embeddings and Realtime\n\nWhen a resource has `embeddings` or `realtime` configured, queue messages\nand broadcasts are emitted **after** the transaction commits. A\nrolled-back batch produces no orphan embedding jobs.\n\n## Batch Size Limit\n\nThe default maximum batch size is **100 records**. Requests exceeding the limit are rejected:\n\n```json\n{\n \"error\": \"Batch size limit exceeded\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_SIZE_EXCEEDED\",\n \"details\": { \"max\": 100, \"actual\": 250 },\n \"hint\": \"Maximum 100 records allowed per batch. Split into multiple requests.\"\n}\n```\n\n## Configuration\n\nBatch operations inherit access control from their corresponding write operation. You can override per-batch settings:\n\n```typescript\nexport default defineTable(applications, {\n create: {\n access: { roles: ['hiring-manager', 'recruiter'] },\n batch: {\n access: { roles: ['hiring-manager'] }, // More restrictive than single create\n maxBatchSize: 50, // Default: 100\n allowFailFast: true, // Default: true\n },\n },\n update: {\n access: { roles: ['hiring-manager', 'recruiter'] },\n batch: {\n maxBatchSize: 100,\n allowFailFast: true,\n },\n },\n delete: {\n access: { roles: ['hiring-manager'] },\n mode: 'soft',\n batch: {\n access: { roles: ['hiring-manager'] },\n maxBatchSize: 100,\n allowFailFast: true,\n },\n },\n\n // Disable only batch upsert\n upsert: {\n access: { roles: ['hiring-manager'] },\n batch: false,\n },\n});\n```\n\n## Security\n\nAll security pillars apply to batch operations:\n\n1. **Authentication** — Required for all batch endpoints (401 if missing)\n2. **Firewall** — Applied per-record for update/delete/upsert (not applicable to create)\n3. **Access** — Role-based check using the batch operation's access config\n4. **Guards** — Per-record validation (createable/updatable/immutable fields)\n5. **Masking** — Applied to all records in the success array before response\n\n## See Also\n\n- [CRUD Endpoints](/compiler/targets/hono-api/using-the-api/crud) — Single-record operations\n- [Error Responses](/compiler/targets/hono-api/using-the-api/errors) — Error format reference\n- [Guards](/compiler/definitions/guards) — Field-level write protection"
|
|
194
|
+
"content": "Batch operations let you create, update, upsert, or delete multiple records in a single request. They are **auto-enabled** when the corresponding write operation exists in your definition.\n\n## Available Endpoints\n\n| Endpoint | Method | Auto-enabled When |\n|----------|--------|-------------------|\n| `/{resource}/batch` | `POST` | `create` exists |\n| `/{resource}/batch` | `PATCH` | `update` exists |\n| `/{resource}/batch` | `DELETE` | `delete` exists |\n| `/{resource}/batch` | `PUT` | `upsert` exists |\n\nTo disable a batch operation, set it to `false` in your definition:\n\n```typescript\ncreate: {\n access: { roles: ['hiring-manager'] },\n batch: false, // Disable batch create\n}\n```\n\n## Batch Create\n\n```\nPOST /api/v1/{resource}/batch\n```\n\n### Request\n\n```json\n{\n \"records\": [\n { \"candidateId\": \"cand_101\", \"jobId\": \"job_201\", \"stage\": \"applied\", \"notes\": \"Strong frontend background\" },\n { \"candidateId\": \"cand_101\", \"jobId\": \"job_202\", \"stage\": \"applied\", \"notes\": \"Also interested in backend role\" },\n { \"candidateId\": \"cand_102\", \"jobId\": \"job_201\", \"stage\": \"applied\", \"notes\": \"Referred by employee\" }\n ],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\n### Response (201 or 207)\n\n```json\n{\n \"success\": [\n { \"id\": \"app_abc1\", \"candidateId\": \"cand_101\", \"jobId\": \"job_201\", \"stage\": \"applied\", \"createdAt\": \"2025-01-15T10:00:00Z\" },\n { \"id\": \"app_abc3\", \"candidateId\": \"cand_102\", \"jobId\": \"job_201\", \"stage\": \"applied\", \"createdAt\": \"2025-01-15T10:00:00Z\" }\n ],\n \"errors\": [\n {\n \"index\": 1,\n \"record\": { \"candidateId\": \"cand_101\", \"jobId\": \"job_202\", \"stage\": \"applied\", \"notes\": \"Also interested in backend role\" },\n \"error\": {\n \"error\": \"Database insert failed\",\n \"layer\": \"validation\",\n \"code\": \"INSERT_FAILED\",\n \"details\": { \"reason\": \"UNIQUE constraint failed: applications.candidateId, applications.jobId\" }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"failFast\": false,\n \"transactional\": true\n }\n}\n```\n\n- **201** — All records created successfully\n- **207** — Partial success (some errors, some successes)\n\n`POST /batch` uses a single bulk `INSERT`, so `meta.transactional` is `true` on every provider — the database guarantees the insert is atomic regardless of the `failFast` flag.\n\nFields applied automatically to each record:\n- ID generation (UUID, prefixed, etc.)\n- Ownership fields (`organizationId`, `ownerId`, `createdBy`)\n- Audit fields (`createdAt`, `modifiedAt`)\n- Default values and computed fields\n\n## Batch Update\n\n```\nPATCH /api/v1/{resource}/batch\n```\n\nEvery record **must include an `id` field**.\n\n### Request\n\n```json\n{\n \"records\": [\n { \"id\": \"app_abc1\", \"notes\": \"Passed phone screen, schedule onsite\" },\n { \"id\": \"app_abc2\", \"notes\": \"Moved to technical interview round\" },\n { \"id\": \"app_xyz9\", \"notes\": \"Hiring manager approved offer\" }\n ],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\n### Response (200 or 207)\n\n```json\n{\n \"success\": [\n { \"id\": \"app_abc1\", \"notes\": \"Passed phone screen, schedule onsite\", \"modifiedAt\": \"2025-01-15T11:00:00Z\" },\n { \"id\": \"app_abc2\", \"notes\": \"Moved to technical interview round\", \"modifiedAt\": \"2025-01-15T11:00:00Z\" }\n ],\n \"errors\": [\n {\n \"index\": 2,\n \"record\": { \"id\": \"app_xyz9\", \"notes\": \"Hiring manager approved offer\" },\n \"error\": {\n \"error\": \"Not found\",\n \"layer\": \"firewall\",\n \"code\": \"NOT_FOUND\",\n \"details\": { \"id\": \"app_xyz9\" }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"failFast\": false,\n \"transactional\": false\n }\n}\n```\n\nRecords that don't exist or aren't accessible through the firewall return a `NOT_FOUND` error. Guard rules (immutable, protected, not-updatable fields) are checked per record.\n\n### Missing IDs\n\nIf any records are missing the `id` field, the entire request is rejected:\n\n```json\n{\n \"error\": \"Records missing required ID field\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_MISSING_IDS\",\n \"details\": { \"indices\": [0, 2] },\n \"hint\": \"All records must include an ID field for batch update.\"\n}\n```\n\n## Batch Delete\n\n```\nDELETE /api/v1/{resource}/batch\n```\n\n### Request\n\n```json\n{\n \"ids\": [\"app_abc1\", \"app_abc2\", \"app_abc3\"],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\nNote: Batch delete uses an `ids` array (not `records`).\n\n### Response (200 or 207)\n\n**Soft delete** (default):\n\n```json\n{\n \"success\": [\n { \"id\": \"app_abc1\", \"candidateId\": \"cand_101\", \"deletedAt\": \"2025-01-15T12:00:00Z\" },\n { \"id\": \"app_abc2\", \"candidateId\": \"cand_103\", \"deletedAt\": \"2025-01-15T12:00:00Z\" }\n ],\n \"errors\": [],\n \"meta\": {\n \"total\": 2,\n \"succeeded\": 2,\n \"failed\": 0,\n \"failFast\": false,\n \"transactional\": true\n }\n}\n```\n\n`DELETE /batch` issues a single bulk `UPDATE … WHERE id IN (...)` (soft delete) or `DELETE … WHERE id IN (...)` (hard delete), so `meta.transactional` is `true` on every provider regardless of `failFast`.\n\n**Hard delete**: Returns objects with only the `id` field (record data is deleted).\n\n## Batch Upsert\n\n```\nPUT /api/v1/{resource}/batch\n```\n\nInserts new records or updates existing ones. Every record must include an `id` field.\n\n**Note:** Batch upsert is only available when `generateId` is set to `false` (user-provided IDs) in your configuration.\n\n### Request\n\n```json\n{\n \"records\": [\n { \"id\": \"app_001\", \"candidateId\": \"cand_101\", \"jobId\": \"job_201\", \"stage\": \"screening\", \"notes\": \"Updated after phone screen\" },\n { \"id\": \"app_002\", \"candidateId\": \"cand_104\", \"jobId\": \"job_203\", \"stage\": \"applied\", \"notes\": \"New application from referral\" }\n ],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\n### Response (201 or 207)\n\nThe compiler checks which IDs already exist and splits the batch into creates and updates. Create records get ownership and default fields; update records get only `modifiedAt`. Under `failFast: true`, both the bulk insert and the per-record updates run inside the same transaction — a failed update rolls back the inserts too on tx-supporting providers.\n\n## Fail-Fast Mode\n\nBy default, batch operations use **partial success** mode — each record is processed independently, and failures don't affect other records.\n\nSet `\"failFast\": true` to stop on the first error:\n\n```json\n{\n \"records\": [...],\n \"options\": {\n \"failFast\": true\n }\n}\n```\n\n### Fail-Fast Failure Response (400)\n\n```json\n{\n \"error\": \"Batch failed at index 1\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_FAILFAST_STOPPED\",\n \"details\": {\n \"failedAt\": 1,\n \"reason\": \"Database insert failed\",\n \"errorDetails\": { \"reason\": \"UNIQUE constraint failed\" }\n }\n}\n```\n\n## Transactional Semantics\n\nThe behavior of `failFast: true` depends on whether your database provider\nsupports transactions. The response's `meta.transactional` flag tells you\nwhich guarantee you actually got — inspect it in clients that care about\nrollback.\n\n### Per-Provider Matrix\n\n| Endpoint | Provider | `failFast` | `meta.transactional` | Behavior |\n|----------|----------|-----------|----------------------|----------|\n| `PATCH /batch` (update) | neon (Postgres via Hyperdrive) | `true` | `true` | `db.transaction()` wraps the per-record loop. Any failure rolls back ALL writes in the batch. |\n| `PATCH /batch` (update) | (any) | `false` | `false` | Per-record loop, partial success. Each record commits independently. |\n| `PATCH /batch` (update) | cloudflare-d1 | `true` | `false` | Fail-fast loop without rollback — D1 has no `db.transaction`. Records before the failure stay committed. |\n| `PUT /batch` (upsert) | tx-supporting | `true` | `true` | Bulk insert + per-record update share one transaction. Any failure rolls back both. |\n| `PUT /batch` (upsert) | cloudflare-d1 | `true` | `false` | Bulk insert commits; per-record update loop is fail-fast without rollback. |\n| `POST /batch` (create) | (any) | (any) | `true` | Single bulk `INSERT` — atomic at the DB level. |\n| `DELETE /batch` | (any) | (any) | `true` | Single bulk `UPDATE` (soft) or `DELETE` (hard) — atomic at the DB level. |\n\n### Reading `meta.transactional` in clients\n\n```typescript\nconst res = await fetch('/api/v1/jobs/batch', {\n method: 'PATCH',\n body: JSON.stringify({ records, options: { failFast: true } }),\n});\nconst body = await res.json();\n\nif (!body.meta.transactional && body.errors.length > 0) {\n // Some records succeeded before the failure and remain committed.\n // Compensate via the success array if needed.\n}\n```\n\n### Embeddings and Realtime\n\nWhen a resource has `embeddings` or `realtime` configured, queue messages\nand broadcasts are emitted **after** the transaction commits. A\nrolled-back batch produces no orphan embedding jobs.\n\n## Batch Size Limit\n\nThe default maximum batch size is **100 records**. Requests exceeding the limit are rejected:\n\n```json\n{\n \"error\": \"Batch size limit exceeded\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_SIZE_EXCEEDED\",\n \"details\": { \"max\": 100, \"actual\": 250 },\n \"hint\": \"Maximum 100 records allowed per batch. Split into multiple requests.\"\n}\n```\n\n## Configuration\n\nBatch operations inherit access control from their corresponding write operation. You can override per-batch settings:\n\n```typescript\nexport default defineTable(applications, {\n create: {\n access: { roles: ['hiring-manager', 'recruiter'] },\n batch: {\n access: { roles: ['hiring-manager'] }, // More restrictive than single create\n maxBatchSize: 50, // Default: 100\n allowFailFast: true, // Default: true\n },\n },\n update: {\n access: { roles: ['hiring-manager', 'recruiter'] },\n batch: {\n maxBatchSize: 100,\n allowFailFast: true,\n },\n },\n delete: {\n access: { roles: ['hiring-manager'] },\n mode: 'soft',\n batch: {\n access: { roles: ['hiring-manager'] },\n maxBatchSize: 100,\n allowFailFast: true,\n },\n },\n\n // Disable only batch upsert\n upsert: {\n access: { roles: ['hiring-manager'] },\n batch: false,\n },\n});\n```\n\n## Security\n\nAll security pillars apply to batch operations:\n\n1. **Authentication** — Required for all batch endpoints (401 if missing)\n2. **Firewall** — Applied per-record for update/delete/upsert (not applicable to create)\n3. **Access** — Role-based check using the batch operation's access config\n4. **Guards** — Per-record validation (createable/updatable/immutable fields)\n5. **Masking** — Applied to all records in the success array before response\n\n## See Also\n\n- [CRUD Endpoints](/compiler/targets/hono-api/using-the-api/crud) — Single-record operations\n- [Error Responses](/compiler/targets/hono-api/using-the-api/errors) — Error format reference\n- [Guards](/compiler/definitions/guards) — Field-level write protection"
|
|
195
195
|
},
|
|
196
196
|
"compiler/targets/hono-api/using-the-api/caching": {
|
|
197
197
|
"title": "Caching & ETags",
|
|
@@ -223,23 +223,7 @@ export const DOCS = {
|
|
|
223
223
|
},
|
|
224
224
|
"compiler/targets": {
|
|
225
225
|
"title": "Compile Targets",
|
|
226
|
-
"content": "The Quickback Compiler reads a single set of definitions — schema, firewall, access, guards, masking, views, actions — and emits production
|
|
227
|
-
},
|
|
228
|
-
"compiler/targets/supabase-rls": {
|
|
229
|
-
"title": "Quickback for Supabase RLS",
|
|
230
|
-
"content": "**Quickback for Supabase RLS** compiles the same `defineTable()` definitions into PostgreSQL Row Level Security policies for Supabase. You keep Supabase Auth, Storage, and Realtime — Quickback adds the database-level security layer.\n\n## Who this is for\n\nYou're already on Supabase (or want to be) and you want:\n\n- **Database-level security** — RLS policies enforced even if a service role key leaks\n- **A type-safe DSL** — write security rules in TypeScript, compile to SQL\n- **One source of truth** — the same `firewall` and `access` config that powers a Quickback Hono API also generates RLS policies\n\nWhat you don't get from this target: generated API routes, batch endpoints, OpenAPI spec, MCP server. Those live with [Quickback for Hono API](/compiler/targets/hono-api). For Supabase you bring your own application code (PostgREST, Edge Functions, or your own server) and the RLS policies enforce security beneath it.\n\n## What compiles to RLS\n\n| Definition | Compiles to |\n|------------|-------------|\n| `defineTable({ schema })` | `CREATE TABLE` + Drizzle schema |\n| `firewall: [...]` | `FOR ALL USING` policies (data isolation) |\n| `access.roles: [...]` | `FOR SELECT/INSERT/UPDATE/DELETE USING` policies (role checks) |\n| `defineActions()` | **Not compiled** — implement in Edge Functions or your app |\n| `views` | **Not compiled** — use Postgres views or column lists |\n| `masking` | **Not compiled** — runtime concern, handle in app code |\n| `guards` | **Not compiled** — runtime concern, handle in app code |\n\nSee [Mappings](/compiler/targets/supabase-rls/mappings) for full examples and [Limitations](/compiler/targets/supabase-rls/limitations) for what to handle in app code.\n\n## Quick start\n\n```typescript title=\"quickback/quickback.config.ts\"\n\nexport default defineConfig({\n name: \"my-app\",\n providers: {\n runtime: defineRuntime(\"supabase\"),\n database: defineDatabase(\"supabase\"),\n auth: defineAuth(\"supabase-auth\"),\n },\n});\n```\n\n```bash\nquickback compile\nsupabase db push\n```\n\nThe compiler emits RLS migrations under `supabase/migrations/`. See [Setup](/compiler/targets/supabase-rls/setup) for the full flow.\n\n## In this section\n\n- **[Setup](/compiler/targets/supabase-rls/setup)** — Configure the target, compile, apply migrations\n- **[Mappings](/compiler/targets/supabase-rls/mappings)** — Which definitions become which RLS policies\n- **[Limitations](/compiler/targets/supabase-rls/limitations)** — What doesn't compile and how to handle it"
|
|
231
|
-
},
|
|
232
|
-
"compiler/targets/supabase-rls/limitations": {
|
|
233
|
-
"title": "Limitations",
|
|
234
|
-
"content": "The Supabase target compiles **schema, firewall, and access** to RLS. The other Quickback primitives are runtime concerns that RLS can't express. This page lists what doesn't compile and where to handle it.\n\n## Actions\n\n`defineActions()` describes custom endpoints with input validation, role checks, and side effects. RLS only governs row access, not arbitrary procedures.\n\n**Where to handle them:**\n\n- **Supabase Edge Functions** — port the action body to a TypeScript Deno function. Role checks happen in the function; the underlying database mutations still pass through your RLS policies.\n- **Postgres functions** — for simple state transitions, write a `CREATE FUNCTION` and call it via `supabase.rpc()`. Use `SECURITY INVOKER` (the default) so RLS still applies.\n- **Your application server** — any backend you already run can host the action, with the JWT forwarded to Supabase for the underlying writes.\n\n## Views\n\nQuickback `views` define column-level projections per role (e.g. \"members see name + email; admins also see salary\"). RLS gates rows, not columns.\n\n**Where to handle them:**\n\n- **Postgres views** — `CREATE VIEW` with `SELECT` lists matching each Quickback view. Apply RLS to the view or the underlying table.\n- **Column lists in queries** — pass the projection at the application layer: `supabase.from('users').select('id, name, email')`.\n- **Column-level grants** — `GRANT SELECT (col1, col2) ON table TO role` for fine-grained server-side restriction.\n\n## Masking\n\nMasking redacts sensitive fields per role at response time (email → `j***@example.com`, SSN → `***-**-1234`). This is purely a runtime transformation — the data is in the row, RLS just decides whether the row is returned.\n\n**Where to handle it:**\n\n- **Edge Functions or your server** — apply the mask in the layer that serializes the response.\n- **Postgres functions** — for SQL-driven masking, write a wrapper view or function that applies the mask conditionally on `auth.jwt() ->> 'role'`.\n\n## Guards\n\n`guards` block field modifications based on row state, role, or external context (e.g. \"members can change `notes` but not `status`; only admins can set `archived`\"). Some of this can be expressed with RLS `WITH CHECK`, but the full Quickback guard model is richer than RLS supports.\n\n**Where to handle them:**\n\n- **`WITH CHECK` clauses** — simple field-level guards (e.g. \"only admins can set `archived = true`\") can sometimes be expressed via more granular `FOR UPDATE` policies.\n- **Triggers** — `BEFORE UPDATE` triggers can `RAISE EXCEPTION` if a guarded field is modified by a non-eligible role.\n- **Edge Functions / app server** — for anything stateful or context-dependent, validate guards in the layer that issues the update.\n\n## Generated API routes, batch ops, OpenAPI, MCP\n\nThese are Hono-target features. The Supabase target doesn't generate application code — your app talks to Supabase directly (PostgREST, Edge Functions, or your own server).\n\nIf you want generated routes alongside RLS, consider compiling to the [Hono target with Neon](/compiler/targets/hono-api/database/neon), which gives you both the generated API and database-level RLS."
|
|
235
|
-
},
|
|
236
|
-
"compiler/targets/supabase-rls/mappings": {
|
|
237
|
-
"title": "Mappings",
|
|
238
|
-
"content": "This page shows how each Quickback primitive maps to RLS policy SQL. The same `firewall` and `access` config used by the [Hono target](/compiler/targets/hono-api) generates these policies — no Supabase-specific re-authoring required.\n\n## Schema → Tables\n\n`defineTable({ schema })` compiles to a Drizzle PostgreSQL schema and a `CREATE TABLE` statement. RLS is enabled on the table by default:\n\n```sql\nALTER TABLE projects ENABLE ROW LEVEL SECURITY;\n```\n\n## Firewall → `FOR ALL USING`\n\nFirewall rules isolate data by tenant or owner. They become a single `FOR ALL USING` policy applied to every operation.\n\n**Org-scoped:**\n\n```typescript\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n]\n```\n\n```sql\nCREATE POLICY \"projects_firewall\" ON projects FOR ALL\nUSING (organization_id = public.get_active_org_id());\n```\n\n**User-scoped:**\n\n```typescript\nfirewall: [\n { field: 'userId', equals: 'ctx.userId' },\n]\n```\n\n```sql\nCREATE POLICY \"preferences_firewall\" ON preferences FOR ALL\nUSING (user_id = auth.uid());\n```\n\n## Access → `FOR SELECT/INSERT/UPDATE/DELETE USING`\n\nAccess rules layer role-based checks on top of the firewall. Each operation gets its own policy.\n\n```typescript\naccess: {\n roles: ['admin', 'member'],\n list: { roles: ['admin', 'member'] },\n create: { roles: ['admin'] },\n update: { roles: ['admin'] },\n delete: { roles: ['admin'] },\n}\n```\n\n```sql\nCREATE POLICY \"projects_select\" ON projects FOR SELECT\nUSING (\n organization_id = public.get_active_org_id()\n AND public.has_any_role(ARRAY['admin', 'member'])\n);\n\nCREATE POLICY \"projects_insert\" ON projects FOR INSERT\nWITH CHECK (\n organization_id = public.get_active_org_id()\n AND public.has_any_role(ARRAY['admin'])\n);\n```\n\n## Defense in depth — anon deny\n\nEvery generated table gets an explicit deny policy for the `anon` role:\n\n```sql\nCREATE POLICY \"projects_deny_anon\" ON projects FOR ALL\nTO anon\nUSING (false);\n```\n\nUnauthenticated requests are blocked at the database level even if a policy elsewhere is misconfigured.\n\n## Helper functions\n\nQuickback emits a set of helper functions in `0100_create_rls_helpers.sql` that the policies reference:\n\n| Function | Purpose |\n|----------|---------|\n| `get_active_org_id()` | Returns the user's active organization from `user_sessions` |\n| `has_any_role(roles[])` | Checks if the user has any of the listed roles in the active org |\n| `has_org_role(role)` | Checks for a single specific role |\n| `is_org_member()` | Checks org membership |\n| `get_user_role()` | Returns the user's role in the active org |\n\nThese are used by the generated policies but you can also call them from views, triggers, or stored procedures.\n\n## What does not compile\n\n`defineActions()`, `views`, `masking`, and runtime `guards` do **not** become RLS — see [Limitations](/compiler/targets/supabase-rls/limitations)."
|
|
239
|
-
},
|
|
240
|
-
"compiler/targets/supabase-rls/setup": {
|
|
241
|
-
"title": "Setup",
|
|
242
|
-
"content": "## Prerequisites\n\n- A Supabase project (free tier is fine for development)\n- The Supabase CLI installed: `npm install -g supabase`\n- A Quickback project (`quickback create` or existing)\n\n## 1. Configure the target\n\n```typescript title=\"quickback/quickback.config.ts\"\n\nexport default defineConfig({\n name: \"my-app\",\n providers: {\n runtime: defineRuntime(\"supabase\"),\n database: defineDatabase(\"supabase\"),\n auth: defineAuth(\"supabase-auth\"),\n },\n});\n```\n\nThe `supabase-auth` provider tells Quickback to emit RLS policies that reference `auth.uid()` — Supabase's built-in JWT claim function — rather than the Better Auth equivalents used by the Neon target.\n\n## 2. Compile\n\n```bash\nquickback compile\n```\n\nThis generates:\n\n```\nsupabase/\n├── migrations/\n│ ├── 0100_create_rls_helpers.sql # get_active_org_id(), has_any_role(), etc.\n│ ├── 0101_create_rls_policies.sql # Per-table SELECT/INSERT/UPDATE/DELETE policies\n│ └── 0102_create_audit_triggers.sql # Optional audit logging\nsrc/\n├── db/\n│ └── schema.ts # Drizzle schema (typed access from your app)\n```\n\n## 3. Apply migrations\n\n```bash\nsupabase db push\n```\n\nSupabase applies the migrations to your remote project. RLS is enabled on every generated table and the deny-anon policy is installed.\n\n## 4. Use from your app\n\nQuickback for Supabase doesn't generate API routes. Your application code (PostgREST, Edge Functions, your own server) talks to Supabase as normal — the RLS policies are enforced beneath it.\n\n```typescript\n\nconst supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {\n global: { headers: { Authorization: `Bearer ${userJwt}` } },\n});\n\n// RLS policies generated by Quickback enforce row-level access\nconst { data } = await supabase.from('projects').select('*');\n```\n\n## Updating the schema\n\nEdit your `defineTable()` files, recompile, and push:\n\n```bash\nquickback compile\nsupabase db push\n```\n\nThe compiler diffs against the previous compilation and emits a new migration only for what changed.\n\n## Comparison with the Neon target\n\n| | Supabase | Neon |\n|---|----------|------|\n| Auth function | `auth.uid()` | `auth.user_id()` |\n| Auth provider | Supabase Auth | Better Auth + Neon Authorize |\n| Users table | `auth.users` | `public.users` |\n| API code generated | No | Yes (Hono routes) |\n\nBoth targets emit RLS policies. The difference is who issues the JWTs and where the application logic lives."
|
|
226
|
+
"content": "The Quickback Compiler reads a single set of definitions — schema, firewall, access, guards, masking, views, actions — and emits a production Hono application for the **Quickback Stack** on Cloudflare.\n\n## [Quickback for Hono API](/compiler/targets/hono-api)\n\nGenerates a complete Hono application: routes, middleware, types, OpenAPI spec, MCP server, security artifacts. Pair with **Cloudflare D1** for SQLite at the edge or **Neon** for full PostgreSQL via Hyperdrive.\n\n```typescript\nproviders: {\n runtime: defineRuntime('cloudflare'),\n database: defineDatabase('cloudflare-d1'), // or 'neon'\n auth: defineAuth('better-auth'),\n}\n```\n\n## The DSL\n\nSee [Definitions](/compiler/definitions) for the schema + security DSL — the same input drives every output the compiler emits."
|
|
243
227
|
},
|
|
244
228
|
"compiler/troubleshooting": {
|
|
245
229
|
"title": "Troubleshooting",
|
|
@@ -247,19 +231,19 @@ export const DOCS = {
|
|
|
247
231
|
},
|
|
248
232
|
"index": {
|
|
249
233
|
"title": "Quickback Documentation",
|
|
250
|
-
"content": "# Quickback Documentation\n\nQuickback is a **backend compiler**. Define your database schema and security rules in TypeScript — Quickback compiles them into a Hono API
|
|
234
|
+
"content": "# Quickback Documentation\n\nQuickback is a **backend compiler**. Define your database schema and security rules in TypeScript — Quickback compiles them into a Hono API running on Cloudflare Workers, plus the Account UI and CMS that ride alongside it. The Quickback Stack is the Supabase alternative on Cloudflare.\n\n## Quick start\n\n```bash\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n```\n\n`start` is interactive — it asks for a template, scaffolds the project on disk, and only prompts for an account just before compiling. If you cancel at the login prompt the scaffold stays put; you can finish later with `quickback compile`.\n\nPrefer scripting?\n\n```bash\nnpm install -g @quickback-dev/cli\nquickback create cloudflare my-app\ncd my-app\nquickback compile\n```\n\n## How it works\n\nWrite ~50 lines of definitions. Get a production codebase.\n\n```\ndefineTable() ─┐\n ├─► Compiler ─► Hono API (Cloudflare D1 / Neon)\ndefineActions()─┘ └► RLS policies (Supabase)\n```\n\nEvery API request passes through four security layers:\n\n```\nRequest → Firewall → Access → Guards → Masking → Response\n │ │ │ │\n │ │ │ └── Hide sensitive fields\n │ │ └── Block field modifications\n │ └── Check roles & conditions\n └── Isolate data by owner/org\n```\n\n**Secure by default.** Nothing is accessible until you explicitly open it up. See [Definitions](/compiler/definitions) for the full security model.\n\n---\n\n## The two products\n\n### Quickback Compiler\n\n[**Quickback Compiler**](/compiler) — the build tool. Define your schema and security rules in TypeScript and compile to a complete Hono application on Cloudflare:\n\n- **[Quickback for Hono API](/compiler/targets/hono-api)** — A complete Hono application on Cloudflare D1 or Neon, with CRUD, batch endpoints, OpenAPI, and an MCP server.\n\n**Start here:**\n- **[Getting Started](/compiler/getting-started)** — Create your first project\n- **[Definitions](/compiler/definitions)** — Schema, Firewall, Access, Guards, Masking, Views, Actions\n- **[Cloud Compiler](/compiler/cloud-compiler)** — CLI, MCP server, authentication\n- **[Claude Code Skill](/compiler/claude-code-skill)** — AI-powered authoring assistance\n\n---\n\n### Quickback Stack\n\nThe runtime services around your compiled code. Everything you need for a complete Supabase alternative on Cloudflare:\n\n- **[Auth](/stack/auth)** — Better Auth with email OTP, passkeys, organizations, admin\n- **[Storage](/stack/storage)** — KV (sessions, cache) and R2 (files)\n- **[Realtime](/stack/realtime)** — Durable Objects + WebSocket\n- **[Queues](/stack/queues)** — Background jobs and webhook delivery\n- **[Vector & AI](/stack/vector)** — Embeddings, semantic search\n- **[Webhooks](/stack/webhooks)** — Inbound (signed) and outbound (retried)\n- **[Quickback CMS](/stack/cms)** — Schema-driven admin UI\n- **[Account UI](/stack/account-ui)** — Pre-built auth and profile pages\n\nEverything runs on **your own Cloudflare account** — no Quickback infrastructure between you and your data.\n\n---\n\n### Changelog\n\n[**Changelog**](/changelog) — what's new in Quickback. Release notes, new features, and improvements."
|
|
251
235
|
},
|
|
252
236
|
"stack/account-ui/customization": {
|
|
253
237
|
"title": "Customization",
|
|
254
|
-
"content": "# Customization\n\nCustomize the Account UI to match your brand and messaging
|
|
238
|
+
"content": "# Customization\n\nCustomize the Account UI to match your brand and messaging. Branding is driven by the `account` block in `quickback.config.ts` and the environment variables the compiler bakes in at build time.\n\n## Branding\n\n### App Identity\n\nSet your application's name and description:\n\n```bash\nVITE_APP_NAME=Acme SaaS\nVITE_APP_TAGLINE=Build faster, ship sooner\nVITE_APP_DESCRIPTION=The complete platform for modern web applications\n```\n\nThese values appear in:\n- Page titles (`<title>Acme SaaS | Login</title>`)\n- Meta descriptions\n- UI headers and footers\n- Email templates\n\n### Visual Identity\n\n```bash\n# Primary theme color (used for buttons, links, accents)\nVITE_THEME_COLOR=#3b82f6\n\n# Company name (shown in footer, legal pages)\nVITE_COMPANY_NAME=Acme Corporation\n\n# Company address (shown in footer, receipts)\nVITE_COMPANY_ADDRESS=123 Main St, Suite 100, San Francisco, CA 94105\n```\n\n### Logo and Favicon\n\nPlace your branding assets in the `public/` directory:\n\n```\npublic/\n├── logo.png # Main logo (shown in header)\n├── favicon.ico # Browser favicon\n└── og-image.png # Social media preview image\n```\n\nThen update the paths in `src/config/app.ts`:\n\n```ts title=\"src/config/app.ts\"\nbranding: {\n primaryColor: \"#1e293b\",\n logoUrl: \"/logo.png\",\n faviconUrl: \"/favicon.ico\"\n},\n```\n\nOr set them at runtime in `src/main.tsx`:\n\n```ts\n\nsetAppConfig({\n branding: {\n logoUrl: '/logo.png',\n faviconUrl: '/favicon.ico',\n },\n});\n```\n\n## Custom Labels\n\nOverride default UI labels using runtime configuration:\n\n```ts\n\nsetAppConfig({\n labels: {\n terms: 'Terms and Conditions',\n privacy: 'Privacy Notice',\n support: 'Help Center',\n company: 'My Company',\n organizations: 'Workspaces', // Rename \"Organizations\" to \"Workspaces\"\n },\n});\n```\n\n### Available Labels\n\n| Label | Default | Usage |\n|-------|---------|-------|\n| `terms` | \"Terms of Service\" | Footer link text |\n| `privacy` | \"Privacy Policy\" | Footer link text |\n| `support` | \"Contact Support\" | Footer link text |\n| `company` | (from `VITE_COMPANY_NAME`) | Footer company name |\n| `organizations` | \"Organizations\" | Navigation and page titles |\n\n## Custom Messages\n\nCustomize user-facing messages:\n\n```ts\n\nsetAppConfig({\n messages: {\n noOrganizations: \"You haven't joined any workspaces yet.\",\n contactAdminForInvite: \"Contact your team lead to get access.\",\n noPendingInvitations: \"No pending invites at this time\",\n createOrganization: \"Create Workspace\",\n // ... more messages\n },\n});\n```\n\n### Available Messages\n\n| Message | Default | Usage |\n|---------|---------|-------|\n| `noOrganizations` | \"You're not a member of any organizations yet.\" | Empty organizations list |\n| `contactAdminForInvite` | \"Contact an admin to be invited to an organization.\" | Organizations page help text |\n| `noPendingInvitations` | \"You have no pending invitations\" | Empty invitations list |\n| `createOrganization` | \"Create Organization\" | Button text |\n| `accountInformation` | \"Account Information\" | Profile section header |\n| `timezone` | \"Timezone\" | Label for timezone field |\n| `serverLocation` | \"Server Location\" | Label for server location |\n| `memberSince` | \"Member since\" | Account age label |\n| `pendingInvitations` | \"Pending Invitations\" | Section header |\n| `invitedAs` | \"Invited as\" | Invitation role label |\n| `accept` | \"Accept\" | Accept invitation button |\n| `decline` | \"Decline\" | Decline invitation button |\n| `userFallback` | \"User\" | Fallback for missing name |\n| `noEmailProvided` | \"No email provided\" | Fallback for missing email |\n| `more` | \"More\" | Pagination/load more text |\n| `total` | \"total\" | Total count label |\n| `active` | \"Active\" | Active status label |\n| `new` | \"New\" | New item label |\n\n## Route Customization\n\nCustomize route paths using runtime configuration:\n\n```ts\n\nsetAppConfig({\n routes: {\n public: {\n home: '/',\n login: '/sign-in', // Change from /login\n signup: '/sign-up', // Change from /signup\n forgotPassword: '/reset-password',\n welcome: '/getting-started',\n },\n authenticated: {\n dashboard: '/dashboard',\n profile: '/my-account',\n settings: '/preferences',\n },\n organizations: {\n list: '/workspaces', // Rename route\n create: '/workspaces/new',\n detail: (slug) => `/workspaces/${slug}`,\n },\n },\n});\n```\n\n## Password Requirements\n\nCustomize password validation rules:\n\n```ts\n\nsetAppConfig({\n auth: {\n passwordRequirements: {\n minLength: 12, // Minimum password length\n maxLength: 128, // Maximum password length\n requireUppercase: true, // Must have uppercase letter\n requireLowercase: true, // Must have lowercase letter\n requireNumbers: true, // Must have number\n requireSymbols: true, // Must have special character\n },\n },\n});\n```\n\nPassword requirements are displayed to users during signup and password changes.\n\n## Session Duration\n\nControl how long users stay logged in:\n\n```ts\n\nsetAppConfig({\n auth: {\n sessionDuration: 7 * 24 * 60 * 60, // 7 days in seconds\n },\n});\n```\n\n## Email Customization\n\nConfigure email sender information:\n\n```bash\nVITE_EMAIL_FROM=noreply@acme.com\nVITE_EMAIL_REPLY_TO=support@acme.com\nVITE_SUPPORT_EMAIL=help@acme.com\n```\n\nThe `fromName` is automatically set to `VITE_APP_NAME`:\n\n```ts\n// Emails will show:\n// From: \"Acme SaaS <noreply@acme.com>\"\n```\n\n## URL Configuration\n\nConfigure URLs for external links:\n\n```bash\n# Main application (redirected to after login)\nVITE_QUICKBACK_APP_URL=https://app.acme.com\n\n# Organization/tenant URL pattern\nVITE_TENANT_URL_PATTERN=/workspace/{slug}\n\n# Support pages\nVITE_SUPPORT_URL=https://help.acme.com\nVITE_PRIVACY_URL=https://acme.com/legal/privacy\nVITE_TERMS_URL=https://acme.com/legal/terms\n```\n\n### Tenant URL Patterns\n\nThe tenant URL pattern supports flexible organization routing:\n\n```bash\n# Path-based routing\nVITE_TENANT_URL_PATTERN=/organizations/{slug}\n# Result: https://app.acme.com/organizations/acme-corp\n\n# Subdomain routing\nVITE_TENANT_URL_PATTERN=https://{slug}.acme.com\n# Result: https://acme-corp.acme.com\n\n# Custom pattern\nVITE_TENANT_URL_PATTERN=/workspace/{slug}/dashboard\n# Result: https://app.acme.com/workspace/acme-corp/dashboard\n```\n\n## Complete Customization Example\n\nHere's a complete example showing all customization options:\n\n```ts title=\"src/main.tsx\"\n\n// Apply customizations before rendering\nsetAppConfig({\n name: 'Acme SaaS',\n tagline: 'Build faster, ship sooner',\n description: 'The complete platform for modern web applications',\n\n branding: {\n primaryColor: '#3b82f6',\n logoUrl: '/acme-logo.png',\n faviconUrl: '/favicon.ico',\n },\n\n labels: {\n organizations: 'Workspaces',\n terms: 'Terms and Conditions',\n privacy: 'Privacy Notice',\n support: 'Help Center',\n },\n\n messages: {\n noOrganizations: \"You haven't joined any workspaces yet.\",\n createOrganization: 'Create Workspace',\n contactAdminForInvite: 'Contact your team lead for access.',\n },\n\n routes: {\n public: {\n login: '/sign-in',\n signup: '/sign-up',\n },\n organizations: {\n list: '/workspaces',\n create: '/workspaces/new',\n detail: (slug) => `/workspaces/${slug}`,\n },\n },\n\n auth: {\n passwordRequirements: {\n minLength: 12,\n requireSymbols: true,\n },\n sessionDuration: 7 * 24 * 60 * 60, // 7 days\n },\n});\n\n// Render app\n\nconst root = document.getElementById('root')!;\ncreateRoot(root).render(\n \n);\n```\n\n## Custom Styles\n\nOverride default styles with custom CSS:\n\n```css title=\"custom-styles.css\"\n/* Override primary color */\n:root {\n --primary: 59 130 246; /* Tailwind blue-500 */\n --primary-foreground: 255 255 255;\n}\n\n/* Custom logo size */\n.logo {\n width: 180px;\n height: auto;\n}\n\n/* Custom button styles */\n.btn-primary {\n background-color: var(--primary);\n border-radius: 8px;\n font-weight: 600;\n}\n```\n\nImport your custom CSS after the Account UI styles:\n\n```ts\n\n```\n\n## Next Steps\n\n- **[With Quickback](/stack/account-ui/with-quickback)** - How the compiler builds and bundles your customized UI\n- **[Environment Variables](/stack/account-ui/environment-variables)** - Complete configuration reference\n- **[Feature Flags](/stack/account-ui/features)** - Enable/disable features"
|
|
255
239
|
},
|
|
256
240
|
"stack/account-ui/environment-variables": {
|
|
257
241
|
"title": "Environment Variables",
|
|
258
|
-
"content": "# Environment Variables\n\nConfigure the Account UI by setting environment variables in your `.env` file or deployment platform.\n\n## Quick Setup — Single Variable\n\nFor the common \"unified deployment\" where API, Account, and CMS all live on the same Quickback origin, you only need **one** variable:\n\n```bash\n# Points at the Quickback Worker origin\nVITE_QUICKBACK_URL=https://secure.example.com\n```\n\nWhen `VITE_QUICKBACK_URL` is set, it's used as a fallback for the individual URL vars:\n\n| Individual var | Used first | Falls back to |\n|---|---|---|\n| `VITE_QUICKBACK_API_URL` | if set | `${VITE_QUICKBACK_URL}` |\n| `VITE_QUICKBACK_ACCOUNT_URL` | if set | `${VITE_QUICKBACK_URL}/account` |\n| `VITE_QUICKBACK_CMS_URL` | if set | `${VITE_QUICKBACK_URL}/cms` |\n\n## Required Variables\n\nAt minimum, you need one of:\n\n- **`VITE_QUICKBACK_URL`** — catch-all for the Quickback origin (recommended), **or**\n- **`VITE_QUICKBACK_API_URL`** — explicit API URL (use this if your API lives on a different subdomain from Account/CMS)\n\n### Split-subdomain setup\n\nIf your API, Account, and CMS live on separate custom subdomains, set them explicitly:\n\n```bash\n# Quickback API URL\nVITE_QUICKBACK_API_URL=https://api.example.com\n\n# Account UI URL (where the Account UI is deployed)\nVITE_ACCOUNT_APP_URL=https://account.example.com\n\n# Optional: override Account/CMS URLs for cross-origin links\nVITE_QUICKBACK_ACCOUNT_URL=https://auth.example.com\nVITE_QUICKBACK_CMS_URL=https://cms.example.com\n```\n\n## App Identity\n\nConfigure your application's basic information:\n\n```bash\n# App name (displayed in UI)\nVITE_APP_NAME=My Application\n\n# Tagline (shown on landing pages)\nVITE_APP_TAGLINE=Build faster, ship sooner\n\n# Full description\nVITE_APP_DESCRIPTION=A complete platform for building modern web applications\n\n# Company information\nVITE_COMPANY_NAME=My Company Inc.\nVITE_COMPANY_ADDRESS=123 Main St, Suite 100, San Francisco, CA 94105\n```\n\n## URLs\n\n### Main Application\n\n```bash\n# Your main application URL\n# Users will be redirected here after authentication\nVITE_QUICKBACK_APP_URL=https://app.example.com\n\n# Organization/Tenant URL pattern (optional)\n# Use {slug} as placeholder for organization identifier\n# Examples:\n# /organizations/{slug} -> app.example.com/organizations/acme\n# /workspace/{slug} -> app.example.com/workspace/acme\n# https://{slug}.example.com -> acme.example.com\nVITE_TENANT_URL_PATTERN=/organizations/{slug}\n```\n\n### Support and Legal\n\n```bash\n# Support/help URL\nVITE_SUPPORT_URL=https://support.example.com\n\n# Privacy policy URL\nVITE_PRIVACY_URL=https://example.com/privacy\n\n# Terms of service URL\nVITE_TERMS_URL=https://example.com/terms\n```\n\n## Email Configuration\n\n```bash\n# From address for all emails\nVITE_EMAIL_FROM=noreply@example.com\n\n# Reply-to address\nVITE_EMAIL_REPLY_TO=support@example.com\n\n# Support email address\nVITE_SUPPORT_EMAIL=support@example.com\n\n# AWS Region for SES (if using AWS SES)\nVITE_EMAIL_REGION=us-east-1\n```\n\n## Branding\n\n```bash\n# Primary theme color (hex code)\nVITE_THEME_COLOR=#1e293b\n\n# SEO keywords (comma-separated)\nVITE_SEO_KEYWORDS=saas,authentication,account management\n```\n\n## Feature Flags\n\nEnable or disable features using boolean environment variables:\n\n### Authentication Features\n\n```bash\n# Enable user signup (default: true)\nENABLE_SIGNUP=true\n\n# Enable email verification after signup (default: true)\nENABLE_EMAIL_VERIFICATION=true\n\n# Disable email deliverability checks (default: false)\n# Set to true to skip checking if email addresses are deliverable\nDISABLE_EMAIL_STATUS_CHECK=false\n\n# Enable passkey (WebAuthn) login (default: true)\nENABLE_PASSKEY=true\n\n# Enable email OTP login and signup (default: true)\nENABLE_EMAIL_OTP=true\n\n# Enable email+password login and signup (default: false)\nENABLE_PASSWORD=false\n```\n\n### Account Management Features\n\n```bash\n# Enable file uploads (avatar, etc.) (default: false)\nVITE_ENABLE_FILE_UPLOADS=false\n```\n\n### Organization Features\n\n```bash\n# Enable multi-tenant organizations (default: true)\nENABLE_ORGANIZATIONS=true\n```\n\n### Admin Features\n\n```bash\n# Enable admin panel (default: true)\nENABLE_ADMIN=true\n```\n\n## Complete Example\n\nHere's a complete `.env` file with all common configuration:\n\n```bash title=\".env\"\n# ===== REQUIRED =====\nVITE_QUICKBACK_API_URL=https://api.example.com\nVITE_ACCOUNT_APP_URL=https://account.example.com\n\n# ===== APP IDENTITY =====\nVITE_APP_NAME=Acme SaaS\nVITE_APP_TAGLINE=Build faster, ship sooner\nVITE_APP_DESCRIPTION=The complete platform for modern web applications\nVITE_COMPANY_NAME=Acme Corporation\nVITE_COMPANY_ADDRESS=123 Main St, Suite 100, San Francisco, CA 94105\n\n# ===== URLS =====\nVITE_QUICKBACK_APP_URL=https://app.acme.com\nVITE_TENANT_URL_PATTERN=/organizations/{slug}\nVITE_SUPPORT_URL=https://help.acme.com\nVITE_PRIVACY_URL=https://acme.com/privacy\nVITE_TERMS_URL=https://acme.com/terms\n\n# ===== EMAIL =====\nVITE_EMAIL_FROM=noreply@acme.com\nVITE_EMAIL_REPLY_TO=support@acme.com\nVITE_SUPPORT_EMAIL=support@acme.com\nVITE_EMAIL_REGION=us-east-1\n\n# ===== BRANDING =====\nVITE_THEME_COLOR=#3b82f6\n\n# ===== SEO =====\nVITE_SEO_KEYWORDS=saas,project management,team collaboration\n\n# ===== FEATURES =====\nENABLE_SIGNUP=true\nENABLE_EMAIL_VERIFICATION=true\nENABLE_PASSKEY=true\nENABLE_EMAIL_OTP=true\nENABLE_PASSWORD=false\nENABLE_ORGANIZATIONS=true\nENABLE_ADMIN=true\nVITE_ENABLE_FILE_UPLOADS=true\nDISABLE_EMAIL_STATUS_CHECK=false\n```\n\n## Environment-Specific Configuration\n\n### Development\n\n```bash title=\".env.development\"\nVITE_QUICKBACK_API_URL=http://localhost:8787\nVITE_ACCOUNT_APP_URL=http://localhost:5173\nVITE_QUICKBACK_APP_URL=http://localhost:3000\nDISABLE_EMAIL_STATUS_CHECK=true\n```\n\n### Staging\n\n```bash title=\".env.staging\"\nVITE_QUICKBACK_API_URL=https://api-staging.example.com\nVITE_ACCOUNT_APP_URL=https://account-staging.example.com\nVITE_QUICKBACK_APP_URL=https://app-staging.example.com\n```\n\n### Production\n\n```bash title=\".env.production\"\nVITE_QUICKBACK_API_URL=https://api.example.com\nVITE_ACCOUNT_APP_URL=https://account.example.com\nVITE_QUICKBACK_APP_URL=https://app.example.com\nDISABLE_EMAIL_STATUS_CHECK=false\n```\n\n## Cloudflare Pages Setup\n\nWhen deploying to Cloudflare Pages, set environment variables in the dashboard:\n\n1. Go to **Settings** → **Environment Variables**\n2. Add each `VITE_*` variable\n3. Separate values for **Production** and **Preview** branches\n\n## Wrangler Configuration\n\nFor `wrangler dev` and `wrangler deploy`, add variables to `wrangler.toml`:\n\n```toml title=\"wrangler.toml\"\n[env.production.vars]\nVITE_QUICKBACK_API_URL = \"https://api.example.com\"\nVITE_ACCOUNT_APP_URL = \"https://account.example.com\"\nVITE_APP_NAME = \"My App\"\n# ... other variables\n```\n\nOr use `.dev.vars` for local development (git-ignored):\n\n```bash title=\".dev.vars\"\nVITE_QUICKBACK_API_URL=http://localhost:8787\nVITE_ACCOUNT_APP_URL=http://localhost:5173\n```\n\n## Runtime Configuration\n\nSome values can be overridden at runtime using the config API:\n\n```ts\n\nsetAppConfig({\n name: 'My Custom App',\n branding: {\n primaryColor: '#ff6600',\n logoUrl: '/custom-logo.png',\n },\n urls: {\n base: 'https://account.custom.com',\n app: 'https://app.custom.com',\n },\n});\n```\n\n## Validation\n\nThe Account UI validates configuration on startup:\n\n- **Missing VITE_QUICKBACK_API_URL**: Throws error\n- **Invalid URLs**: Logs warning\n- **Missing optional fields**: Uses defaults\n\nCheck the browser console for configuration warnings.\n\n## Next Steps\n\n- **[Feature Flags](/stack/account-ui/features)** - Detailed feature configuration\n- **[Customization](/stack/account-ui/customization)** - Customize labels and messages\n- **[
|
|
242
|
+
"content": "# Environment Variables\n\nConfigure the Account UI by setting environment variables in your `.env` file or deployment platform.\n\n## Quick Setup — Single Variable\n\nFor the common \"unified deployment\" where API, Account, and CMS all live on the same Quickback origin, you only need **one** variable:\n\n```bash\n# Points at the Quickback Worker origin\nVITE_QUICKBACK_URL=https://secure.example.com\n```\n\nWhen `VITE_QUICKBACK_URL` is set, it's used as a fallback for the individual URL vars:\n\n| Individual var | Used first | Falls back to |\n|---|---|---|\n| `VITE_QUICKBACK_API_URL` | if set | `${VITE_QUICKBACK_URL}` |\n| `VITE_QUICKBACK_ACCOUNT_URL` | if set | `${VITE_QUICKBACK_URL}/account` |\n| `VITE_QUICKBACK_CMS_URL` | if set | `${VITE_QUICKBACK_URL}/cms` |\n\n## Required Variables\n\nAt minimum, you need one of:\n\n- **`VITE_QUICKBACK_URL`** — catch-all for the Quickback origin (recommended), **or**\n- **`VITE_QUICKBACK_API_URL`** — explicit API URL (use this if your API lives on a different subdomain from Account/CMS)\n\n### Split-subdomain setup\n\nIf your API, Account, and CMS live on separate custom subdomains, set them explicitly:\n\n```bash\n# Quickback API URL\nVITE_QUICKBACK_API_URL=https://api.example.com\n\n# Account UI URL (where the Account UI is deployed)\nVITE_ACCOUNT_APP_URL=https://account.example.com\n\n# Optional: override Account/CMS URLs for cross-origin links\nVITE_QUICKBACK_ACCOUNT_URL=https://auth.example.com\nVITE_QUICKBACK_CMS_URL=https://cms.example.com\n```\n\n## App Identity\n\nConfigure your application's basic information:\n\n```bash\n# App name (displayed in UI)\nVITE_APP_NAME=My Application\n\n# Tagline (shown on landing pages)\nVITE_APP_TAGLINE=Build faster, ship sooner\n\n# Full description\nVITE_APP_DESCRIPTION=A complete platform for building modern web applications\n\n# Company information\nVITE_COMPANY_NAME=My Company Inc.\nVITE_COMPANY_ADDRESS=123 Main St, Suite 100, San Francisco, CA 94105\n```\n\n## URLs\n\n### Main Application\n\n```bash\n# Your main application URL\n# Users will be redirected here after authentication\nVITE_QUICKBACK_APP_URL=https://app.example.com\n\n# Organization/Tenant URL pattern (optional)\n# Use {slug} as placeholder for organization identifier\n# Examples:\n# /organizations/{slug} -> app.example.com/organizations/acme\n# /workspace/{slug} -> app.example.com/workspace/acme\n# https://{slug}.example.com -> acme.example.com\nVITE_TENANT_URL_PATTERN=/organizations/{slug}\n```\n\n### Support and Legal\n\n```bash\n# Support/help URL\nVITE_SUPPORT_URL=https://support.example.com\n\n# Privacy policy URL\nVITE_PRIVACY_URL=https://example.com/privacy\n\n# Terms of service URL\nVITE_TERMS_URL=https://example.com/terms\n```\n\n## Email Configuration\n\n```bash\n# From address for all emails\nVITE_EMAIL_FROM=noreply@example.com\n\n# Reply-to address\nVITE_EMAIL_REPLY_TO=support@example.com\n\n# Support email address\nVITE_SUPPORT_EMAIL=support@example.com\n\n# AWS Region for SES (if using AWS SES)\nVITE_EMAIL_REGION=us-east-1\n```\n\n## Branding\n\n```bash\n# Primary theme color (hex code)\nVITE_THEME_COLOR=#1e293b\n\n# SEO keywords (comma-separated)\nVITE_SEO_KEYWORDS=saas,authentication,account management\n```\n\n## Feature Flags\n\nEnable or disable features using boolean environment variables:\n\n### Authentication Features\n\n```bash\n# Enable user signup (default: true)\nENABLE_SIGNUP=true\n\n# Enable email verification after signup (default: true)\nENABLE_EMAIL_VERIFICATION=true\n\n# Disable email deliverability checks (default: false)\n# Set to true to skip checking if email addresses are deliverable\nDISABLE_EMAIL_STATUS_CHECK=false\n\n# Enable passkey (WebAuthn) login (default: true)\nENABLE_PASSKEY=true\n\n# Enable email OTP login and signup (default: true)\nENABLE_EMAIL_OTP=true\n\n# Enable email+password login and signup (default: false)\nENABLE_PASSWORD=false\n```\n\n### Account Management Features\n\n```bash\n# Enable file uploads (avatar, etc.) (default: false)\nVITE_ENABLE_FILE_UPLOADS=false\n```\n\n### Organization Features\n\n```bash\n# Enable multi-tenant organizations (default: true)\nENABLE_ORGANIZATIONS=true\n\n# Enable Teams (sub-groups within an organization) (default: false)\n# Auto-set to true when the BA config has organization({ teams: { enabled: true } }).\n# When false the Teams tab is hidden and the auth client doesn't expose team APIs.\nVITE_ENABLE_ORG_TEAMS=false\n```\n\n### Admin Features\n\n```bash\n# Enable admin panel (default: true)\nENABLE_ADMIN=true\n```\n\n## Complete Example\n\nHere's a complete `.env` file with all common configuration:\n\n```bash title=\".env\"\n# ===== REQUIRED =====\nVITE_QUICKBACK_API_URL=https://api.example.com\nVITE_ACCOUNT_APP_URL=https://account.example.com\n\n# ===== APP IDENTITY =====\nVITE_APP_NAME=Acme SaaS\nVITE_APP_TAGLINE=Build faster, ship sooner\nVITE_APP_DESCRIPTION=The complete platform for modern web applications\nVITE_COMPANY_NAME=Acme Corporation\nVITE_COMPANY_ADDRESS=123 Main St, Suite 100, San Francisco, CA 94105\n\n# ===== URLS =====\nVITE_QUICKBACK_APP_URL=https://app.acme.com\nVITE_TENANT_URL_PATTERN=/organizations/{slug}\nVITE_SUPPORT_URL=https://help.acme.com\nVITE_PRIVACY_URL=https://acme.com/privacy\nVITE_TERMS_URL=https://acme.com/terms\n\n# ===== EMAIL =====\nVITE_EMAIL_FROM=noreply@acme.com\nVITE_EMAIL_REPLY_TO=support@acme.com\nVITE_SUPPORT_EMAIL=support@acme.com\nVITE_EMAIL_REGION=us-east-1\n\n# ===== BRANDING =====\nVITE_THEME_COLOR=#3b82f6\n\n# ===== SEO =====\nVITE_SEO_KEYWORDS=saas,project management,team collaboration\n\n# ===== FEATURES =====\nENABLE_SIGNUP=true\nENABLE_EMAIL_VERIFICATION=true\nENABLE_PASSKEY=true\nENABLE_EMAIL_OTP=true\nENABLE_PASSWORD=false\nENABLE_ORGANIZATIONS=true\nVITE_ENABLE_ORG_TEAMS=true\nENABLE_ADMIN=true\nVITE_ENABLE_FILE_UPLOADS=true\nDISABLE_EMAIL_STATUS_CHECK=false\n```\n\n## Environment-Specific Configuration\n\n### Development\n\n```bash title=\".env.development\"\nVITE_QUICKBACK_API_URL=http://localhost:8787\nVITE_ACCOUNT_APP_URL=http://localhost:5173\nVITE_QUICKBACK_APP_URL=http://localhost:3000\nDISABLE_EMAIL_STATUS_CHECK=true\n```\n\n### Staging\n\n```bash title=\".env.staging\"\nVITE_QUICKBACK_API_URL=https://api-staging.example.com\nVITE_ACCOUNT_APP_URL=https://account-staging.example.com\nVITE_QUICKBACK_APP_URL=https://app-staging.example.com\n```\n\n### Production\n\n```bash title=\".env.production\"\nVITE_QUICKBACK_API_URL=https://api.example.com\nVITE_ACCOUNT_APP_URL=https://account.example.com\nVITE_QUICKBACK_APP_URL=https://app.example.com\nDISABLE_EMAIL_STATUS_CHECK=false\n```\n\n## Cloudflare Pages Setup\n\nWhen deploying to Cloudflare Pages, set environment variables in the dashboard:\n\n1. Go to **Settings** → **Environment Variables**\n2. Add each `VITE_*` variable\n3. Separate values for **Production** and **Preview** branches\n\n## Wrangler Configuration\n\nFor `wrangler dev` and `wrangler deploy`, add variables to `wrangler.toml`:\n\n```toml title=\"wrangler.toml\"\n[env.production.vars]\nVITE_QUICKBACK_API_URL = \"https://api.example.com\"\nVITE_ACCOUNT_APP_URL = \"https://account.example.com\"\nVITE_APP_NAME = \"My App\"\n# ... other variables\n```\n\nOr use `.dev.vars` for local development (git-ignored):\n\n```bash title=\".dev.vars\"\nVITE_QUICKBACK_API_URL=http://localhost:8787\nVITE_ACCOUNT_APP_URL=http://localhost:5173\n```\n\n## Runtime Configuration\n\nSome values can be overridden at runtime using the config API:\n\n```ts\n\nsetAppConfig({\n name: 'My Custom App',\n branding: {\n primaryColor: '#ff6600',\n logoUrl: '/custom-logo.png',\n },\n urls: {\n base: 'https://account.custom.com',\n app: 'https://app.custom.com',\n },\n});\n```\n\n## Validation\n\nThe Account UI validates configuration on startup:\n\n- **Missing VITE_QUICKBACK_API_URL**: Throws error\n- **Invalid URLs**: Logs warning\n- **Missing optional fields**: Uses defaults\n\nCheck the browser console for configuration warnings.\n\n## Next Steps\n\n- **[Feature Flags](/stack/account-ui/features)** - Detailed feature configuration\n- **[Customization](/stack/account-ui/customization)** - Customize labels and messages\n- **[With Quickback](/stack/account-ui/with-quickback)** - How the compiler builds and bundles Account UI"
|
|
259
243
|
},
|
|
260
244
|
"stack/account-ui/features/admin": {
|
|
261
245
|
"title": "Admin Panel",
|
|
262
|
-
"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
|
|
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"
|
|
263
247
|
},
|
|
264
248
|
"stack/account-ui/features/api-keys": {
|
|
265
249
|
"title": "API Key Management",
|
|
@@ -267,7 +251,7 @@ export const DOCS = {
|
|
|
267
251
|
},
|
|
268
252
|
"stack/account-ui/features/avatars": {
|
|
269
253
|
"title": "Avatars",
|
|
270
|
-
"content": "When file uploads are enabled, Account UI provides avatar upload functionality.\n\n## Enabling\n\nIn `quickback.config.ts`:\n\n```ts\naccount: {\n fileUploads: true,\n // ...\n}\n```\n\nThe compiler emits `VITE_ENABLE_FILE_UPLOADS=true` into the Account SPA's
|
|
254
|
+
"content": "When file uploads are enabled, Account UI provides avatar upload functionality.\n\n## Enabling\n\nIn `quickback.config.ts`:\n\n```ts\naccount: {\n fileUploads: true,\n // ...\n}\n```\n\nThe compiler emits `VITE_ENABLE_FILE_UPLOADS=true` into the Account SPA's build env.\n\n## Upload Flow\n\n1. User clicks their profile picture\n2. Image picker opens (supports JPG, PNG, WebP)\n3. Image is cropped to square\n4. Uploaded to R2/S3 storage\n5. Profile updated with new avatar URL\n\n## Requirements\n\n- `account.fileUploads: true`\n- R2 bucket or S3-compatible storage configured\n- Upload endpoints available in your API\n\n## Related\n\n- [R2 Storage](/stack/storage/r2) — File storage setup\n- [Environment Variables](/stack/account-ui/environment-variables)"
|
|
271
255
|
},
|
|
272
256
|
"stack/account-ui/features/cli-authorize": {
|
|
273
257
|
"title": "CLI Authorization",
|
|
@@ -275,11 +259,11 @@ export const DOCS = {
|
|
|
275
259
|
},
|
|
276
260
|
"stack/account-ui/features": {
|
|
277
261
|
"title": "Feature Flags",
|
|
278
|
-
"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- **[
|
|
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"
|
|
279
263
|
},
|
|
280
264
|
"stack/account-ui/features/organizations": {
|
|
281
265
|
"title": "Organizations",
|
|
282
|
-
"content": "Account UI provides a complete organization management interface when `
|
|
266
|
+
"content": "Account UI provides a complete organization management interface when `VITE_ENABLE_ORGANIZATIONS=true`. Teams are a separate opt-in (`VITE_ENABLE_ORG_TEAMS`), surfaced when the compiler detects `organization({ teams: { enabled: true } })` in the Better Auth config.\n\n## Organization CRUD\n\n- Create new organizations, with `checkSlug` debounce on the slug field\n- Update name, **slug** (rename navigates to the new URL), **metadata** (JSON object), and logo\n- Delete organizations — gated on the `organization:delete` permission (default: owner)\n\n## Member Management\n\n- Invite members by email (with an optional team picker when teams are enabled)\n- Assign roles: **owner**, **admin**, **member**\n- Change roles and remove members — actions are filtered per-target by the role hierarchy (non-owners can't manage owner-role members)\n- Leave the organization\n\n> **Note:** These three roles (`owner`, `admin`, `member`) are Better Auth's built-in organization roles and map directly to Account UI's role picker. Use the same roles in your Quickback [Access](/compiler/definitions/access) rules — with [`auth.roleHierarchy`](/compiler/definitions/access#role-hierarchy) configured, you can write `roles: [\"member+\"]` to mean \"member and above.\"\n\n## Invitations\n\n- Pending invitation list, per organization\n- Resend, cancel (per-org), accept, and reject (per-user)\n- Pending invites across organizations land on the user's `/dashboard`\n- Invitations carry an optional `teamId` when teams are enabled — the invitee joins that team on accept\n\n## Teams\n\nSet `organization({ teams: { enabled: true } })` in your Better Auth config. The compiler emits `VITE_ENABLE_ORG_TEAMS=true` and the SPA exposes:\n\n- **Teams tab** on each organization, split into \"Your teams\" and \"Other teams\"\n- **Team detail** page with member roster, add/remove members\n- **Active-team picker** in the organization header — switches `session.activeTeamId` via `setActiveTeam`, so server-side handlers can scope by team\n- **Team-aware invitations** — when sending an invite, optionally pick a team; the member is added on accept\n\nPer-team actions (create / rename / delete / add-member / remove-member) gate on the `team:create`, `team:update`, and `team:delete` permissions from Better Auth's default statements.\n\n## Permission-aware UI\n\nAccount UI uses Better Auth's `checkRolePermission` API instead of hardcoded role checks. The `OrganizationContext` exposes a `can(resource, action)` helper that handles the default statements (`organization`, `member`, `invitation`, `team`, `ac`) and respects any custom roles you've registered via the BA `ac` option.\n\nMulti-role users — Better Auth stores multiple roles as a comma-separated string — are handled by checking each role independently; the action is allowed if any one of them grants it.\n\nThis means projects that ship custom roles get a UI that matches what their server actually authorizes, without modifying the Account SPA.\n\n## Related\n\n- [Environment Variables](/stack/account-ui/environment-variables)\n- [Account UI Overview](/stack/account-ui)"
|
|
283
267
|
},
|
|
284
268
|
"stack/account-ui/features/passkeys": {
|
|
285
269
|
"title": "Passkeys",
|
|
@@ -295,27 +279,15 @@ export const DOCS = {
|
|
|
295
279
|
},
|
|
296
280
|
"stack/account-ui/hooks": {
|
|
297
281
|
"title": "Auth Hooks",
|
|
298
|
-
"content": "# Auth Hooks\n\nQuickback discovers project-level auth hooks at `quickback/hooks/` and wires them into [Better Auth's `databaseHooks`](https://www.better-auth.com/docs/concepts/database#database-hooks). Use them for post-signup bootstrap, signup gating, and other lifecycle work.\n\nThe classic case is multi-tenant: when `account.auth.organizations: true` is set, a freshly signed-up user has no `activeOrganizationId`, so every authenticated `/api/v1/*` returns `400 ORG_REQUIRED`. An `after-user-create` hook can auto-provision a personal workspace + member row so the next request just works.\n\n## Folder layout\n\n```\nquickback/\n hooks/\n after-user-create.ts\n before-user-create.ts\n after-session-create.ts\n```\n\nEach file has a single default export — an `async (entity, ctx) => ...` function. The filename determines which Better Auth event the hook fires on.\n\n## Recognized events\n\n| Filename | Better Auth path | Entity | Return |\n|--------------------------------|-----------------------------------|----------|---------------------------------|\n| `before-user-create.ts` | `databaseHooks.user.create.before` | `User` | `void \\| { data?: Partial<User> }` |\n| `after-user-create.ts` | `databaseHooks.user.create.after` | `User` | `void` |\n| `after-session-create.ts` | `databaseHooks.session.create.after` | `Session` | `void` |\n\nFilenames outside this set are a hard compile-time error so a typo never silently disables a hook. Add events by extending [`apps/compiler/src/parser/hooks.ts`](https://github.com/paulstenhouse/quickback-compiler) (and the matching CLI mirror).\n\n## ctx shape\n\nEvery hook receives `(entity, ctx)`:\n\n```ts\ntype HookCtx = {\n /** Drizzle client bound to the auth DB binding (split-DB aware). */\n authDb: DrizzleClient;\n /**\n * Auth schema namespace — destructure to access the BA-managed tables\n * (`user`, `session`, `organization`, `member`, …) without writing an\n * import path. The hook source lives in `quickback/hooks/` pre-compile\n * and `src/lib/auth-hooks/` post-stage; relying on `authSchema`\n * removes the dual-path import problem.\n */\n authSchema: typeof import('../../auth/schema');\n /** Cloudflare bindings (Cloudflare runtime) or process.env (Bun/Node). */\n env: Bindings;\n /** Better Auth's own context object — request, hook metadata, etc. */\n baContext: any;\n};\n```\n\n`authDb` is the load-bearing piece: hooks must write to the auth DB via Drizzle directly. See the [CSRF caveat](#csrf-caveat-server-side-org-create) below. `authSchema` is the namespace export of the generated auth schema module; destructure the tables you need.\n\n## Writing hooks: use built-ins where possible\n\nHook source files are evaluated by the Better Auth schema-generation step at compile time, which runs in a stripped-down sandbox that **does not see your project's `node_modules`**. A hook that imports `@paralleldrive/cuid2`, `nanoid`, or any other third-party package will fail compile with a \"module not found\" error during the auth-schema-generation step — even if the package is installed and runs fine in the deployed Worker.\n\nStick to runtime built-ins for ID generation, hashing, and similar primitives:\n\n| Need | Built-in |\n|--------------------|---------------------------------------------------------|\n| Random ID | `crypto.randomUUID()` |\n| SHA-256 / digest | `crypto.subtle.digest(...)` (Workers / Node 19+) |\n| Random bytes | `crypto.getRandomValues(new Uint8Array(n))` |\n| Time | `Date.now()`, `new Date().toISOString()` |\n\n`drizzle-orm` is already available in the schema-gen sandbox (the auth schema imports from it), so `eq`, `and`, `inArray`, etc. are safe to import.\n\n## Throw semantics\n\nWhat happens when a hook throws is the #1 thing that bites people:\n\n| Hook | Throw effect |\n|-----------------------|------------------------------------------------------------------------------|\n| `before-user-create` | Signup aborts. The user is **not** created. Throw a typed error to gate. |\n| `after-user-create` | The user **is** created (the BA insert already committed). Any derived rows your hook started writing become orphans. |\n| `after-session-create`| Same as above — the session row exists; partial writes leak. |\n\nFor `after-*` hooks, design for **idempotency**: use the entity's `id` as a stable seed for any derived rows so re-running the hook (manually or via a background reconciler) is safe. Don't generate fresh `cuid()`s for derived rows you'd want to recover.\n\n## Examples\n\n### Auto-provision a personal workspace on signup\n\nThe QB-9 case. Without this, `organizations: true` projects break immediately for new users.\n\n```ts title=\"quickback/hooks/after-user-create.ts\"\n\nexport default async (user, { authDb, authSchema }) => {\n const { organization, member } = authSchema;\n\n // Idempotency: derive a stable org id from the user id so re-running this\n // hook (after a partial failure) doesn't create a second workspace.\n const orgId = `org_${user.id}`;\n const slug = `${(user.name ?? 'workspace').toLowerCase().replace(/\\s+/g, '-')}-${user.id.slice(0, 6)}`;\n\n // Skip if the workspace already exists (idempotent).\n const existing = await authDb\n .select({ id: organization.id })\n .from(organization)\n .where(eq(organization.id, orgId));\n if (existing.length > 0) return;\n\n await authDb.insert(organization).values({\n id: orgId,\n name: `${user.name ?? 'Personal'} Workspace`,\n slug,\n createdAt: new Date(),\n });\n\n await authDb.insert(member).values({\n id: crypto.randomUUID(),\n userId: user.id,\n organizationId: orgId,\n role: 'owner',\n createdAt: new Date(),\n });\n};\n```\n\n### Set the active organization on next session\n\nSetting `activeOrganizationId` from a hook means writing to `session.active_organization_id` via Drizzle directly — calling Better Auth's `setActiveOrganization` API server-side is awkward (see the CSRF caveat). The reliable pattern:\n\n```ts title=\"quickback/hooks/after-session-create.ts\"\n\nexport default async (newSession, { authDb, authSchema }) => {\n const { session, member } = authSchema;\n\n // Pick the user's first membership as their active org. Projects that\n // want a sticky last-active-org should track that separately.\n const memberships = await authDb\n .select({ organizationId: member.organizationId })\n .from(member)\n .where(eq(member.userId, newSession.userId))\n .limit(1);\n\n if (memberships.length === 0) return;\n\n await authDb\n .update(session)\n .set({ activeOrganizationId: memberships[0].organizationId })\n .where(eq(session.id, newSession.id));\n};\n```\n\n### Normalize and gate signup\n\n`before-*` hooks can return `{ data: Partial<User> }` to mutate the row before insert. Throw to abort.\n\n```ts title=\"quickback/hooks/before-user-create.ts\"\nexport default async (user: { email: string; name?: string }) => {\n // Block disposable inboxes.\n if (/@(?:mailinator|10minutemail)\\.com$/i.test(user.email)) {\n throw new Error('Disposable email addresses are not allowed.');\n }\n // Trim whitespace from display name.\n return { data: { name: user.name?.trim() } };\n};\n```\n\nThe compiler-generated wrapper merges your `data` onto the original entity, so you only return the fields you actually want to change.\n\n## CSRF caveat — server-side org create\n\n`POST /auth/v1/organization/create` (and Better Auth's `auth.api.createOrganization(...)` server helper) require an `Origin` header. A hook running inside `databaseHooks.user.create.after` is server-side — there is no incoming request, so no `Origin`. Calling those APIs from a hook may also validate `Origin` internally and reject.\n\n**The only safe path is direct Drizzle writes via `authDb`.** Treat the org/member tables as your source of truth and let the SPA call the BA API for user-initiated org creation.\n\n## Generated output\n\nCompile picks up `quickback/hooks/*.ts` and produces:\n\n```\nsrc/lib/auth.ts # imports the hook + adds a databaseHooks block\nsrc/lib/auth-hooks/<file> # your hook source, copied verbatim\n```\n\nInside the generated `auth.ts`:\n\n```ts\n\n// ...inside createAuth(env)...\nreturn betterAuth({\n // ...\n database: drizzleAdapter(db, { /* ... */ }),\n databaseHooks: {\n user: {\n create: {\n after: async (entity, _baCtx) => {\n const _qbCtx = { authDb: db, authSchema: schema, env, baContext: _baCtx };\n await __qbHook_afterUserCreate(entity, _qbCtx);\n },\n },\n },\n },\n});\n```\n\nNo hooks → no `databaseHooks` block emitted. The whole feature is opt-in by file presence.\n\n## See also\n\n- [With Quickback Compiler](/stack/account-ui/with-quickback) — how `account.auth.organizations` flows through the build\n- [Configuration → account block](/compiler/config) — `account.appUrl` and other account-level options\n- [Better Auth: Database Hooks](https://www.better-auth.com/docs/concepts/database#database-hooks)"
|
|
282
|
+
"content": "# Auth Hooks\n\nQuickback discovers project-level auth hooks at `quickback/hooks/` and wires them into [Better Auth's `databaseHooks`](https://www.better-auth.com/docs/concepts/database#database-hooks). Use them for post-signup bootstrap, signup gating, and other lifecycle work.\n\nThe classic case is multi-tenant: when `account.auth.organizations: true` is set, a freshly signed-up user has no `activeOrganizationId`, so every authenticated `/api/v1/*` returns `400 ORG_REQUIRED`. An `after-user-create` hook can auto-provision a personal workspace + member row so the next request just works.\n\n## Folder layout\n\n```\nquickback/\n hooks/\n after-user-create.ts\n before-user-create.ts\n after-session-create.ts\n after-admin-user-create.ts\n```\n\nEach file has a single default export — an `async (entity, ctx) => ...` function. The filename determines which Better Auth event the hook fires on.\n\n## Recognized events\n\n| Filename | Better Auth path | Entity | Return |\n|--------------------------------|-----------------------------------|----------|---------------------------------|\n| `before-user-create.ts` | `databaseHooks.user.create.before` | `User` | `void \\| { data?: Partial<User> }` |\n| `after-user-create.ts` | `databaseHooks.user.create.after` | `User` | `void` |\n| `after-session-create.ts` | `databaseHooks.session.create.after` | `Session` | `void` |\n| `after-admin-user-create.ts` | `databaseHooks.user.create.after` (filtered) | `User` | `void` |\n\n`after-admin-user-create.ts` is a **virtual event** — it wires into the same Better Auth `user.create.after` slot as the generic `after-user-create.ts`, but the compiler wraps the call in a runtime filter on the BA context path so it only fires when the row was created via the admin plugin's `POST /admin/create-user` endpoint. Use it for first-time-user provisioning (welcome email, default org assignment) without inspecting `_baCtx?.context?.path` by hand. The generic `after-user-create.ts` still runs for every signup, including admin-created ones.\n\nFilenames outside this set are a hard compile-time error so a typo never silently disables a hook. Add events by extending [`apps/compiler/src/parser/hooks.ts`](https://github.com/paulstenhouse/quickback-compiler) (and the matching CLI mirror).\n\n## ctx shape\n\nEvery hook receives `(entity, ctx)`:\n\n```ts\ntype HookCtx = {\n /** Drizzle client bound to the auth DB binding (split-DB aware). */\n authDb: DrizzleClient;\n /**\n * Auth schema namespace — destructure to access the BA-managed tables\n * (`user`, `session`, `organization`, `member`, …) without writing an\n * import path. The hook source lives in `quickback/hooks/` pre-compile\n * and `src/lib/auth-hooks/` post-stage; relying on `authSchema`\n * removes the dual-path import problem.\n */\n authSchema: typeof import('../../auth/schema');\n /** Cloudflare bindings (Cloudflare runtime) or process.env (Bun/Node). */\n env: Bindings;\n /** Better Auth's own context object — request, hook metadata, etc. */\n baContext: any;\n};\n```\n\n`authDb` is the load-bearing piece: hooks must write to the auth DB via Drizzle directly. See the [CSRF caveat](#csrf-caveat-server-side-org-create) below. `authSchema` is the namespace export of the generated auth schema module; destructure the tables you need.\n\n## Writing hooks: use built-ins where possible\n\nHook source files are evaluated by the Better Auth schema-generation step at compile time, which runs in a stripped-down sandbox that **does not see your project's `node_modules`**. A hook that imports `@paralleldrive/cuid2`, `nanoid`, or any other third-party package will fail compile with a \"module not found\" error during the auth-schema-generation step — even if the package is installed and runs fine in the deployed Worker.\n\nStick to runtime built-ins for ID generation, hashing, and similar primitives:\n\n| Need | Built-in |\n|--------------------|---------------------------------------------------------|\n| Random ID | `crypto.randomUUID()` |\n| SHA-256 / digest | `crypto.subtle.digest(...)` (Workers / Node 19+) |\n| Random bytes | `crypto.getRandomValues(new Uint8Array(n))` |\n| Time | `Date.now()`, `new Date().toISOString()` |\n\n`drizzle-orm` is already available in the schema-gen sandbox (the auth schema imports from it), so `eq`, `and`, `inArray`, etc. are safe to import.\n\n## Throw semantics\n\nWhat happens when a hook throws is the #1 thing that bites people:\n\n| Hook | Throw effect |\n|-----------------------|------------------------------------------------------------------------------|\n| `before-user-create` | Signup aborts. The user is **not** created. Throw a typed error to gate. |\n| `after-user-create` | The user **is** created (the BA insert already committed). Any derived rows your hook started writing become orphans. |\n| `after-session-create`| Same as above — the session row exists; partial writes leak. |\n\nFor `after-*` hooks, design for **idempotency**: use the entity's `id` as a stable seed for any derived rows so re-running the hook (manually or via a background reconciler) is safe. Don't generate fresh `cuid()`s for derived rows you'd want to recover.\n\n## Examples\n\n### Auto-provision a personal workspace on signup\n\nThe QB-9 case. Without this, `organizations: true` projects break immediately for new users.\n\n```ts title=\"quickback/hooks/after-user-create.ts\"\n\nexport default async (user, { authDb, authSchema }) => {\n const { organization, member } = authSchema;\n\n // Idempotency: derive a stable org id from the user id so re-running this\n // hook (after a partial failure) doesn't create a second workspace.\n const orgId = `org_${user.id}`;\n const slug = `${(user.name ?? 'workspace').toLowerCase().replace(/\\s+/g, '-')}-${user.id.slice(0, 6)}`;\n\n // Skip if the workspace already exists (idempotent).\n const existing = await authDb\n .select({ id: organization.id })\n .from(organization)\n .where(eq(organization.id, orgId));\n if (existing.length > 0) return;\n\n await authDb.insert(organization).values({\n id: orgId,\n name: `${user.name ?? 'Personal'} Workspace`,\n slug,\n createdAt: new Date(),\n });\n\n await authDb.insert(member).values({\n id: crypto.randomUUID(),\n userId: user.id,\n organizationId: orgId,\n role: 'owner',\n createdAt: new Date(),\n });\n};\n```\n\n### Set the active organization on next session\n\nSetting `activeOrganizationId` from a hook means writing to `session.active_organization_id` via Drizzle directly — calling Better Auth's `setActiveOrganization` API server-side is awkward (see the CSRF caveat). The reliable pattern:\n\n```ts title=\"quickback/hooks/after-session-create.ts\"\n\nexport default async (newSession, { authDb, authSchema }) => {\n const { session, member } = authSchema;\n\n // Pick the user's first membership as their active org. Projects that\n // want a sticky last-active-org should track that separately.\n const memberships = await authDb\n .select({ organizationId: member.organizationId })\n .from(member)\n .where(eq(member.userId, newSession.userId))\n .limit(1);\n\n if (memberships.length === 0) return;\n\n await authDb\n .update(session)\n .set({ activeOrganizationId: memberships[0].organizationId })\n .where(eq(session.id, newSession.id));\n};\n```\n\n### Normalize and gate signup\n\n`before-*` hooks can return `{ data: Partial<User> }` to mutate the row before insert. Throw to abort.\n\n```ts title=\"quickback/hooks/before-user-create.ts\"\nexport default async (user: { email: string; name?: string }) => {\n // Block disposable inboxes.\n if (/@(?:mailinator|10minutemail)\\.com$/i.test(user.email)) {\n throw new Error('Disposable email addresses are not allowed.');\n }\n // Trim whitespace from display name.\n return { data: { name: user.name?.trim() } };\n};\n```\n\nThe compiler-generated wrapper merges your `data` onto the original entity, so you only return the fields you actually want to change.\n\n## CSRF caveat — server-side org create\n\n`POST /auth/v1/organization/create` (and Better Auth's `auth.api.createOrganization(...)` server helper) require an `Origin` header. A hook running inside `databaseHooks.user.create.after` is server-side — there is no incoming request, so no `Origin`. Calling those APIs from a hook may also validate `Origin` internally and reject.\n\n**The only safe path is direct Drizzle writes via `authDb`.** Treat the org/member tables as your source of truth and let the SPA call the BA API for user-initiated org creation.\n\n## Generated output\n\nCompile picks up `quickback/hooks/*.ts` and produces:\n\n```\nsrc/lib/auth.ts # imports the hook + adds a databaseHooks block\nsrc/lib/auth-hooks/<file> # your hook source, copied verbatim\n```\n\nInside the generated `auth.ts`:\n\n```ts\n\n// ...inside createAuth(env)...\nreturn betterAuth({\n // ...\n database: drizzleAdapter(db, { /* ... */ }),\n databaseHooks: {\n user: {\n create: {\n after: async (entity, _baCtx) => {\n const _qbCtx = { authDb: db, authSchema: schema, env, baContext: _baCtx };\n await __qbHook_afterUserCreate(entity, _qbCtx);\n },\n },\n },\n },\n});\n```\n\nNo hooks → no `databaseHooks` block emitted. The whole feature is opt-in by file presence.\n\n## See also\n\n- [With Quickback Compiler](/stack/account-ui/with-quickback) — how `account.auth.organizations` flows through the build\n- [Configuration → account block](/compiler/config) — `account.appUrl` and other account-level options\n- [Better Auth: Database Hooks](https://www.better-auth.com/docs/concepts/database#database-hooks)"
|
|
299
283
|
},
|
|
300
284
|
"stack/account-ui": {
|
|
301
285
|
"title": "Account UI",
|
|
302
|
-
"content": "# Quickback Account UI\n\nA complete authentication and account management frontend. It handles login, signup, password reset, profile management, device sessions, passkeys, organizations, and admin — so you don't have to build any of it.\n\n## What's Included\n\nAccount UI is a single React SPA that contains three distinct sections:\n\n### Account (every user)\n\nLogin, signup, profile editing, password management, device sessions, email changes, and account deletion. This is what every user interacts with.\n\nServed on its own domain (e.g., `auth.example.com`) or at `/account/` when embedded alongside the CMS.\n\n### Organization Management (multi-tenant)\n\nDashboard with org switching, org creation, member invitations, role management, and org settings. Only available when `auth.organizations` is enabled.\n\n### Admin Panel (admin users only)\n\nUser management dashboard — view all users, search, create accounts, ban/unban, reset passwords, and manage sessions. Only accessible to users with the `admin` role. Can be served on its own domain (e.g., `admin.example.com`) via the `adminDomain` config.\n\n##
|
|
303
|
-
},
|
|
304
|
-
"stack/account-ui/library-usage": {
|
|
305
|
-
"title": "Library Usage",
|
|
306
|
-
"content": "# Library Usage\n\nInstead of cloning the template, you can install Account UI as an npm package. This gives you automatic updates via `npm update` while configuring the UI through `setAppConfig()`.\n\n## Installation\n\n```bash\nnpm install quickback-better-auth-account-ui\n```\n\n### Peer Dependencies\n\nAccount UI expects these packages in your app:\n\n```bash\nnpm install react react-dom react-router-dom @tanstack/react-query\n```\n\n## Basic Setup\n\n### 1. Import and Configure\n\n```tsx title=\"src/main.tsx\"\n\nsetAppConfig({\n authRoute: 'quickback', // or 'better-auth' for standalone Better Auth\n name: 'My App',\n companyName: 'My Company Inc.',\n tagline: 'Build faster, ship sooner',\n description: 'My app description',\n});\n\nReactDOM.createRoot(document.getElementById('root')!).render(\n \n </React.StrictMode>\n);\n```\n\n### 2. Set API URLs\n\nThe library reads API URLs from `globalThis` variables. Set these before importing the library:\n\n```tsx title=\"src/main.tsx\"\n// Single catch-all: API + Account + CMS URLs are all derived from this origin.\n(globalThis as any).__QUICKBACK_URL__ = 'https://secure.example.com';\n(globalThis as any).__QUICKBACK_APP_URL__ = 'https://app.example.com';\n\n// Then import dynamically to ensure globals are set first\nconst { AuthApp, setAppConfig } = await import('quickback-better-auth-account-ui');\nawait import('quickback-better-auth-account-ui/styles.css');\n```\n\nIf your API lives on a different subdomain, set `__QUICKBACK_API_URL__` explicitly instead (or alongside) — it takes precedence over the catch-all:\n\n```tsx\n(globalThis as any).__QUICKBACK_URL__ = 'https://secure.example.com'; // catch-all\n(globalThis as any).__QUICKBACK_API_URL__ = 'https://api.example.com'; // explicit override\n```\n\nOr with Vite environment variables:\n\n```tsx title=\"src/main.tsx\"\n(globalThis as any).__QUICKBACK_URL__ = import.meta.env.VITE_QUICKBACK_URL;\n(globalThis as any).__QUICKBACK_API_URL__ = import.meta.env.VITE_QUICKBACK_API_URL;\n(globalThis as any).__QUICKBACK_APP_URL__ = import.meta.env.VITE_QUICKBACK_APP_URL;\n\nPromise.all([\n import('quickback-better-auth-account-ui'),\n import('quickback-better-auth-account-ui/styles.css'),\n]).then(([{ AuthApp, setAppConfig }]) => {\n setAppConfig({\n authRoute: 'quickback',\n name: import.meta.env.VITE_APP_NAME || 'My App',\n companyName: import.meta.env.VITE_COMPANY_NAME || 'My Company',\n tagline: import.meta.env.VITE_APP_TAGLINE || 'Welcome',\n });\n\n ReactDOM.createRoot(document.getElementById('root')!).render(\n \n </React.StrictMode>\n );\n});\n```\n\n## Cloudflare Worker\n\nThe library exports a Cloudflare Worker entry point for SPA routing and static asset serving:\n\n```ts title=\"src/worker.ts\"\nexport { default } from 'quickback-better-auth-account-ui/worker';\n```\n\nOr extend it with custom logic:\n\n```ts title=\"src/worker.ts\"\n\nexport default createAuthWorker();\n```\n\n## Configuration via `setAppConfig()`\n\nIn library mode, all configuration happens through `setAppConfig()` instead of environment variables.\n\n### Auth Route Mode\n\n```ts\nsetAppConfig({\n authRoute: 'quickback', // Quickback API: /auth/v1, /api/v1, /storage/v1\n // or\n authRoute: 'better-auth', // Better Auth default: /api/auth\n});\n```\n\n### Branding\n\n```ts\nsetAppConfig({\n name: 'Acme SaaS',\n companyName: 'Acme Corporation',\n tagline: 'Build faster, ship sooner',\n description: 'The complete platform for modern web applications',\n branding: {\n primaryColor: '#3b82f6',\n logoUrl: '/logo.png',\n faviconUrl: '/favicon.ico',\n },\n});\n```\n\n### Labels and Messages\n\n```ts\nsetAppConfig({\n labels: {\n organizations: 'Workspaces',\n terms: 'Terms and Conditions',\n privacy: 'Privacy Notice',\n },\n messages: {\n noOrganizations: \"You haven't joined any workspaces yet.\",\n createOrganization: 'Create Workspace',\n },\n});\n```\n\n### Routes\n\n```ts\nsetAppConfig({\n routes: {\n public: {\n login: '/sign-in',\n signup: '/sign-up',\n },\n organizations: {\n list: '/workspaces',\n create: '/workspaces/new',\n },\n },\n});\n```\n\n### Password and Session\n\n```ts\nsetAppConfig({\n auth: {\n passwordRequirements: {\n minLength: 12,\n requireSymbols: true,\n },\n sessionDuration: 7 * 24 * 60 * 60, // 7 days\n },\n});\n```\n\nSee [Customization](/stack/account-ui/customization) for the full reference of all configurable options.\n\n## Exports\n\nThe library provides the following exports:\n\n### Main Entry (`quickback-better-auth-account-ui`)\n\n| Export | Type | Description |\n|--------|------|-------------|\n| `AuthApp` | Component | The main React application component |\n| `authClient` | Object | Pre-configured Better Auth client |\n| `appConfig` | Object | Current app configuration |\n| `setAppConfig` | Function | Set app configuration overrides |\n| `createAppConfig` | Function | Create a new config object |\n| `getApiBase` | Function | Get the current API base URL |\n| `setApiBase` | Function | Override the API base URL |\n| `getAuthApiUrl` | Function | Get the auth API URL |\n| `getDataApiUrl` | Function | Get the data API URL |\n| `getStorageApiUrl` | Function | Get the storage API URL |\n\n### Styles (`quickback-better-auth-account-ui/styles.css`)\n\nThe compiled CSS for the Account UI. Must be imported for the UI to render correctly.\n\n### Worker (`quickback-better-auth-account-ui/worker`)\n\n| Export | Type | Description |\n|--------|------|-------------|\n| `default` | Worker | Cloudflare Worker with SPA routing |\n| `createAuthWorker` | Function | Factory for creating a worker instance |\n\n## Custom Styles\n\nOverride styles by importing your CSS after the library styles:\n\n```ts\n\n```\n\n```css title=\"my-overrides.css\"\n:root {\n --primary: 59 130 246;\n --primary-foreground: 255 255 255;\n}\n```\n\n## Updating\n\nUpdate to the latest version:\n\n```bash\nnpm update quickback-better-auth-account-ui\n```\n\nThe library follows semantic versioning. Check the [changelog](https://github.com/Kardoe-com/quickback-better-auth-account-ui/releases) for breaking changes.\n\n## Next Steps\n\n- **[Customization](/stack/account-ui/customization)** — Full configuration reference\n- **[Feature Flags](/stack/account-ui/features)** — Enable and disable features\n- **[Worker Setup](/stack/account-ui/worker)** — Deploy to Cloudflare Workers\n- **[With Quickback](/stack/account-ui/with-quickback)** — Quickback-specific configuration"
|
|
307
|
-
},
|
|
308
|
-
"stack/account-ui/standalone": {
|
|
309
|
-
"title": "Standalone Usage",
|
|
310
|
-
"content": "Account UI can be used with **any Better Auth-powered backend**, not just Quickback-compiled projects. This makes it a drop-in authentication frontend for any app using Better Auth.\n\n## Requirements\n\n- A backend running [Better Auth](https://better-auth.com) with API endpoints\n- Node.js 18+ and npm/pnpm/bun\n- A Cloudflare account (for deployment)\n\n## Setup\n\n### 1. Clone or Install the Account UI\n\n```bash\nnpx degit Kardoe-com/quickback-better-auth-account-ui my-account-app\ncd my-account-app\nnpm install\n```\n\n### 2. Configure the Auth Route Mode\n\nThe key difference from Quickback mode is the `VITE_AUTH_ROUTE` variable. Set it to `better-auth` to use Better Auth's default API paths:\n\n```bash title=\".env\"\n# Auth route mode — use 'better-auth' for standalone\nVITE_AUTH_ROUTE=better-auth\n\n# Your Better Auth backend URL (single catch-all — see below)\nVITE_QUICKBACK_URL=https://secure.example.com\n\n# Where this Account UI is hosted\nVITE_ACCOUNT_APP_URL=https://account.example.com\n```\n\n`VITE_QUICKBACK_URL` is the recommended one-variable setup. If your API lives on a separate subdomain, set `VITE_QUICKBACK_API_URL` explicitly — it takes precedence.\n\nThis configures the auth client to use `/api/auth` as the base path (Better Auth's default), instead of Quickback's `/auth/v1`.\n\n### 3. Configure Your App\n\n```bash title=\".env\"\n# App identity\nVITE_APP_NAME=My App\nVITE_APP_TAGLINE=Welcome to My App\n\n# Redirect after login\nVITE_QUICKBACK_APP_URL=https://app.example.com\n\n# Feature flags\nENABLE_SIGNUP=true\nENABLE_ORGANIZATIONS=true\nENABLE_PASSKEY=true\nENABLE_EMAIL_OTP=true\n```\n\nSee [Environment Variables](/stack/account-ui/environment-variables) for the complete reference.\n\n### 4. Build and Deploy\n\n```bash\nnpm run build\nnpx wrangler deploy\n```\n\n## Auth Route Modes\n\nAccount UI supports three routing modes, controlled by `VITE_AUTH_ROUTE`:\n\n| Mode | Value | Auth Path | Data Path | Storage Path |\n|------|-------|-----------|-----------|--------------|\n| Better Auth | `better-auth` | `/api/auth` | — | — |\n| Quickback | `quickback` | `/auth/v1` | `/api/v1` | `/storage/v1` |\n| Custom | `custom` | Custom | Custom | Custom |\n\n### Better Auth Mode (Default)\n\nRoutes all auth requests to `/api/auth/*` — the standard Better Auth convention:\n\n```bash\nVITE_AUTH_ROUTE=better-auth\n```\n\n### Custom Mode\n\nFor non-standard setups, use custom mode with explicit paths:\n\n```bash\nVITE_AUTH_ROUTE=custom\nVITE_AUTH_BASE_PATH=/my-auth\nVITE_DATA_BASE_PATH=/my-api\nVITE_STORAGE_BASE_PATH=/my-storage\n```\n\n## Backend Requirements\n\nYour Better Auth backend must have the following plugins enabled for full Account UI functionality:\n\n| Feature | Required Plugin | Required For |\n|---------|----------------|--------------|\n| Organizations | `organization` | Multi-tenant org management |\n| Admin panel | `admin` | User management dashboard |\n| API keys | `apiKey` | API key generation UI |\n| Passkeys | `@better-auth/passkey` | WebAuthn authentication |\n| Email OTP | `emailOTP` | One-time password login |\n| CLI login | `deviceAuthorization` | `quickback login` flow |\n\nOnly enable the features that match your backend's plugin configuration. Disable features for plugins you haven't installed:\n\n```bash\n# If your backend doesn't have the organization plugin:\nENABLE_ORGANIZATIONS=false\n\n# If you haven't set up passkeys:\nENABLE_PASSKEYS=false\n```\n\n## CORS Configuration\n\nYour Better Auth backend must allow requests from the Account UI's domain. Configure CORS to include:\n\n```typescript\n// In your Better Auth config\ntrustedOrigins: [\n \"https://account.example.com\", // Account UI domain\n],\n```\n\n## Differences from Quickback Mode\n\n| Aspect | Standalone | With Quickback |\n|--------|-----------|----------------|\n| Auth routes | `/api/auth/*` | `/auth/v1/*` |\n| Data API | Not used | `/api/v1/*` |\n| Storage API | Not used | `/storage/v1/*` |\n| File uploads | Manual setup | Auto-configured |\n| Backend | Any Better Auth app | Quickback-compiled |\n\n## Next Steps\n\n- [Environment Variables](/stack/account-ui/environment-variables) — Complete configuration reference\n- [Customization](/stack/account-ui/customization) — Branding, labels, and theming\n- [Worker Setup](/stack/account-ui/worker) — Cloudflare Workers deployment\n- [Feature Flags](/stack/account-ui/features) — Enable and disable features"
|
|
286
|
+
"content": "# Quickback Account UI\n\nA complete authentication and account management frontend that ships with the Quickback Stack. It handles login, signup, password reset, profile management, device sessions, passkeys, organizations, and admin — so you don't have to build any of it.\n\n## What's Included\n\nAccount UI is a single React SPA that contains three distinct sections:\n\n### Account (every user)\n\nLogin, signup, profile editing, password management, device sessions, email changes, and account deletion. This is what every user interacts with.\n\nServed on its own domain (e.g., `auth.example.com`) or at `/account/` when embedded alongside the CMS.\n\n### Organization Management (multi-tenant)\n\nDashboard with org switching, org creation, member invitations, role management, and org settings. Only available when `auth.organizations` is enabled.\n\n### Admin Panel (admin users only)\n\nUser management dashboard — view all users, search, create accounts, ban/unban, reset passwords, and manage sessions. Only accessible to users with the `admin` role. Can be served on its own domain (e.g., `admin.example.com`) via the `adminDomain` config.\n\n## How to Enable\n\nAdd `account` to your `quickback.config.ts` and compile. The compiler builds the SPA from source with your project-specific settings baked in and bundles it into your Worker.\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default {\n name: \"my-app\",\n template: \"hono\",\n cms: { domain: \"cms.example.com\" },\n account: {\n domain: \"auth.example.com\",\n name: \"My App\",\n auth: {\n password: true,\n passkey: true,\n organizations: true,\n admin: true,\n },\n },\n // ...providers\n};\n```\n\n```bash\nquickback compile\nnpx wrangler deploy\n```\n\nThat's it. The compiler:\n1. Reads your auth feature flags and branding from the config\n2. Generates a `.env` file with the correct `VITE_*` variables\n3. Builds the SPA from source with Vite (inside Docker)\n4. Excludes routes for disabled features (compile-time tree shaking)\n5. Bundles the built assets into your Worker alongside the API\n\nNo manual `.env` configuration needed. No separate deployment.\n\nSee [Configuration](/compiler/config) for all `account` options and [Multi-Domain Architecture](/compiler/config/domains) for custom domain setup.\n\n### Skip SPA Rebuild\n\nAfter the first compile, skip rebuilding the Account SPA on subsequent compiles:\n\n```typescript\naccount: { build: false, /* ...other options */ }\n```\n\nUseful when iterating on API features — saves significant compile time. Set back to `true` (or omit) when you need to update the Account UI.\n\n### Custom Output Directory\n\n```typescript\naccount: { outputDir: \"my-custom-path/account\" }\n```\n\nChanges where compiled Account assets are placed, instead of the default `src/apps/account/`.\n\n## Compile-Time Feature Gating\n\nAuth feature flags control which pages are included in the bundle:\n\n| Flag | Pages Included |\n|------|---------------|\n| `auth.password` | Password login, inline password change on profile |\n| `auth.emailOTP` | Email OTP login flow, email-based password reset |\n| `auth.passkey` | Passkey setup and management |\n| `auth.organizations` | Dashboard, org creation, member management, invitations |\n| `auth.admin` | Admin panel (user management) |\n\nWhen a flag is `false`, the corresponding route files are **removed before the Vite build** — they never appear in the JavaScript bundle. This keeps production bundles minimal.\n\n## Features\n\n- **Authentication** — Email/password, passkeys (WebAuthn), email OTP, magic links, email verification, password reset\n- **Account Management** — Profile editing, avatar upload, password changes, device/session management, account deletion\n- **Organizations** — Multi-tenant org management with owner/admin/member roles, invitations, and org settings\n- **Admin Panel** — User management dashboard with search, create, ban/unban, password reset, and session viewing\n- **API Keys** — Generate and manage API keys for programmatic access\n- **CLI Authorization** — Device authorization flow for `quickback login`\n\n## Next Steps\n\n- **[With Quickback](/stack/account-ui/with-quickback)** — Configuration reference for the `account` block\n- **[Feature Flags](/stack/account-ui/features)** — Enable and disable features\n- **[Environment Variables](/stack/account-ui/environment-variables)** — Configuration reference\n- **[Customization](/stack/account-ui/customization)** — Branding, labels, and theming\n- **[Multi-Domain Architecture](/compiler/config/domains)** — Custom domains and hostname routing"
|
|
311
287
|
},
|
|
312
288
|
"stack/account-ui/with-quickback": {
|
|
313
289
|
"title": "With Quickback",
|
|
314
|
-
"content": "
|
|
315
|
-
},
|
|
316
|
-
"stack/account-ui/worker": {
|
|
317
|
-
"title": "Worker Setup",
|
|
318
|
-
"content": "# Worker Setup\n\nDeploy the Account UI as a Cloudflare Worker with static asset serving.\n\n## Quick Start\n\n### Using the Template\n\n```bash\nnpx degit Kardoe-com/quickback-better-auth-account-ui my-account-app\ncd my-account-app\nnpm install\n```\n\n### Using the Library\n\nIf you're consuming Account UI as an npm package, re-export the worker from the library:\n\n```ts title=\"src/worker.ts\"\nexport { default } from 'quickback-better-auth-account-ui/worker';\n```\n\nThen continue with the Wrangler configuration below.\n\n### 2. Configure Wrangler\n\nThe template includes a `wrangler.toml` pre-configured for Cloudflare Workers:\n\n```toml title=\"wrangler.toml\"\nname = \"my-account-app\"\ncompatibility_date = \"2025-01-01\"\ncompatibility_flags = [\"nodejs_compat\"]\n\n# Custom domain (uncomment and set your domain)\n# routes = [\n# { pattern = \"account.example.com\", custom_domain = true }\n# ]\n\n# Worker entry point\nmain = \"src/worker.ts\"\n\n# Static assets\n[assets]\nbinding = \"ASSETS\"\ndirectory = \"dist/client\"\n```\n\n### 3. Build and Deploy\n\n```bash\nnpm run build\nnpx wrangler deploy\n```\n\n## Worker Entry Point\n\nThe worker is at `src/worker.ts`. It serves static assets and handles SPA routing:\n\n- Static asset serving via the `ASSETS` binding\n- SPA routing (all routes serve `index.html`)\n- Health check endpoint (`/health`)\n\n### Custom Worker Logic\n\nEdit `src/worker.ts` directly to add custom logic:\n\n```ts title=\"src/worker.ts\"\nexport default {\n async fetch(request: Request, env: Env): Promise\n\n### Multiple Environments\n\n```toml title=\"wrangler.toml\"\n# Development\n[env.dev]\nname = \"my-account-app-dev\"\nroute = \"account-dev.example.com/*\"\n\n[env.dev.vars]\nVITE_QUICKBACK_URL = \"https://secure-dev.example.com\"\nVITE_ACCOUNT_APP_URL = \"https://account-dev.example.com\"\n\n# Staging\n[env.staging]\nname = \"my-account-app-staging\"\nroute = \"account-staging.example.com/*\"\n\n[env.staging.vars]\nVITE_QUICKBACK_URL = \"https://secure-staging.example.com\"\nVITE_ACCOUNT_APP_URL = \"https://account-staging.example.com\"\n\n# Production\n[env.production]\nname = \"my-account-app\"\nroute = \"account.example.com/*\"\n\n[env.production.vars]\nVITE_QUICKBACK_URL = \"https://secure.example.com\"\nVITE_ACCOUNT_APP_URL = \"https://account.example.com\"\n```\n\nDeploy to specific environment:\n\n```bash\nwrangler deploy --env staging\nwrangler deploy --env production\n```\n\n## Cloudflare Pages Alternative\n\nYou can also deploy to Cloudflare Pages instead of Workers:\n\n### 1. Configure Build\n\n```toml title=\"wrangler.toml\"\n# Remove [assets] section - Pages handles this\n\nname = \"my-account-app\"\npages_build_output_dir = \"dist/client\"\n```\n\n### 2. Deploy to Pages\n\n```bash\n# First time setup\nwrangler pages project create my-account-app\n\n# Deploy\nwrangler pages deploy dist/client\n```\n\n### 3. Configure Environment Variables\n\nSet environment variables in Cloudflare Pages dashboard:\n1. Go to your Pages project\n2. **Settings** → **Environment Variables**\n3. Add `VITE_*` variables\n4. Redeploy\n\n## Local Development\n\n### Option 1: Vite Dev Server\n\nThe fastest way to develop locally:\n\n```bash\nnpx vite dev\n```\n\nThis starts the Vite dev server with hot module replacement on `localhost:5173`.\n\n### Option 2: Wrangler Dev\n\nTest the worker locally with `wrangler dev`:\n\n```bash\nnpm run build && wrangler dev\n```\n\nThis runs the worker on `localhost:8787`.\n\n## Health Check\n\nThe worker includes a built-in health check endpoint:\n\n```bash\ncurl https://account.example.com/health\n```\n\nResponse:\n\n```json\n{\n \"status\": \"ok\",\n \"app\": \"auth-ui\"\n}\n```\n\nUse this for:\n- Uptime monitoring\n- Load balancer health checks\n- Deployment verification\n\n## Security Headers\n\nAdd security headers by editing `src/worker.ts`:\n\n```ts title=\"src/worker.ts\"\nexport default {\n async fetch(request: Request, env: Env): Promise<Response> {\n // ... routing logic ...\n\n // Add security headers to response\n const response = await env.ASSETS.fetch(request);\n\n const headers = new Headers(response.headers);\n headers.set('X-Frame-Options', 'DENY');\n headers.set('X-Content-Type-Options', 'nosniff');\n headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');\n headers.set('Permissions-Policy', 'geolocation=(), microphone=(), camera=()');\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n },\n};\n```\n\n## Custom 404 Page\n\nServe a custom 404 page for unmatched routes:\n\n```ts title=\"src/worker.ts\"\nexport default {\n async fetch(request: Request, env: Env): Promise<Response> {\n const url = new URL(request.url);\n\n // Try to serve static asset\n const assetResponse = await env.ASSETS.fetch(request);\n\n if (assetResponse.status !== 404) {\n return assetResponse;\n }\n\n // Serve index.html for SPA routes\n if (!url.pathname.startsWith('/api/')) {\n const indexRequest = new Request(`${url.origin}/index.html`, request);\n return env.ASSETS.fetch(indexRequest);\n }\n\n // Custom 404 for API routes\n return new Response('Not Found', { status: 404 });\n },\n};\n```\n\n## Deployment Checklist\n\nBefore deploying to production:\n\n- [ ] Set all required environment variables (`VITE_QUICKBACK_URL` or `VITE_QUICKBACK_API_URL`, etc.)\n- [ ] Configure custom domain in Cloudflare\n- [ ] Add SSL certificate (automatic with Cloudflare)\n- [ ] Test all authentication flows\n- [ ] Configure DNS records\n- [ ] Set up monitoring/health checks\n- [ ] Test email sending\n- [ ] Verify passkey functionality (requires HTTPS)\n- [ ] Check CORS configuration on API\n- [ ] Review security headers\n- [ ] Test organization invitations\n- [ ] Verify redirection to main app works\n\n## Troubleshooting\n\n### Assets Not Loading\n\n**Problem**: 404 errors for static assets (JS, CSS)\n\n**Solution**: Check `directory` path in `wrangler.toml`:\n\n```toml\n[assets]\nbinding = \"ASSETS\"\ndirectory = \"dist/client\" # Must point to Vite's client build output\n```\n\n### Environment Variables Not Working\n\n**Problem**: Config values are undefined\n\n**Solution**: Remember that `VITE_*` variables are build-time. Either:\n1. Set them in `.env.production` before building\n2. Use `setAppConfig()` in `src/main.tsx` for runtime overrides\n3. Edit `src/config/app.ts` defaults directly\n\n### SPA Routing Issues\n\n**Problem**: Refreshing on `/profile` returns 404\n\n**Solution**: Ensure your worker serves `index.html` for all non-asset routes:\n\n```ts\nif (assetResponse.status === 404 && !url.pathname.startsWith('/api/')) {\n return env.ASSETS.fetch(new Request(`${url.origin}/index.html`, request));\n}\n```\n\n## Next Steps\n\n- **[Environment Variables](/stack/account-ui/environment-variables)** - Configure your deployment\n- **[Feature Flags](/stack/account-ui/features)** - Enable features\n- **[Customization](/stack/account-ui/customization)** - Brand your UI"
|
|
290
|
+
"content": "Account UI is part of the Quickback Stack. The compiler builds it from source and bundles it into your Worker — there is no separate npm package or standalone deploy path.\n\n## Compiler-Embedded\n\nAdd `account` to your `quickback.config.ts`:\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default {\n name: \"my-app\",\n template: \"hono\",\n account: {\n domain: \"auth.example.com\",\n name: \"My App\",\n companyName: \"My Company\",\n auth: {\n password: true,\n passkey: true,\n organizations: true,\n admin: true,\n },\n },\n // ...providers\n};\n```\n\nThen compile and deploy:\n\n```bash\nquickback compile\nnpx wrangler deploy\n```\n\n### What Happens During Compilation\n\n1. The compiler reads your `account` config and generates a `.env` file with the correct Vite environment variables (`VITE_QUICKBACK_URL`, `VITE_QUICKBACK_API_URL`, `VITE_ENABLE_PASSWORD`, branding, etc.)\n2. The Account SPA source is copied to a temp directory, with disabled feature routes excluded\n3. Pre-installed dependencies are symlinked (no `npm install` during build)\n4. Vite builds the SPA with your settings baked in\n5. Built assets (content-hashed filenames) are placed in the output directory\n\nWhen CMS is also enabled, Account assets go to `src/apps/account/` and are served at `/account/`. When Account is the only SPA, assets go to `src/apps/` and are served at root.\n\n### Custom Domains\n\nWith a custom domain, the Account SPA is served at root (`/`) on that domain:\n\n```typescript\naccount: { domain: \"auth.example.com\" }\n```\n\nAdd an admin domain to serve the admin panel on its own subdomain:\n\n```typescript\naccount: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n}\n```\n\nSee [Multi-Domain Architecture](/compiler/config/domains) for details on hostname routing and cross-subdomain cookies.\n\n### Auth Feature Flags\n\nFeature flags control which pages are included in the build:\n\n```typescript\nauth: {\n password: true, // Email/password login + inline password change\n emailOTP: false, // Email OTP login flow\n passkey: true, // WebAuthn passkey setup + management\n organizations: true, // Dashboard, org management, invitations\n admin: true, // Admin panel (user management)\n}\n```\n\nDisabled features are excluded at compile time — their route files are removed before the Vite build. See [Configuration](/compiler/config) for all options.\n\n## Next Steps\n\n- [Configuration](/compiler/config) — CMS and Account config reference\n- [Multi-Domain Architecture](/compiler/config/domains) — Custom domains and hostname routing\n- [Environment Variables](/stack/account-ui/environment-variables) — Complete variable reference\n- [Feature Flags](/stack/account-ui/features) — Enable and disable features\n- [Auth Hooks](/stack/account-ui/hooks) — Run project code on signup, login, and session events\n- [Customization](/stack/account-ui/customization) — Branding, labels, and theming"
|
|
319
291
|
},
|
|
320
292
|
"stack/auth/api-keys": {
|
|
321
293
|
"title": "API Keys",
|
|
@@ -339,7 +311,11 @@ export const DOCS = {
|
|
|
339
311
|
},
|
|
340
312
|
"stack/auth/plugins/aws-ses": {
|
|
341
313
|
"title": "AWS SES Plugin",
|
|
342
|
-
"content": "`@quickback-dev/better-auth-aws-ses` is a Better Auth plugin that sends transactional emails via AWS SES. It handles AWS Signature V4 signing, HTML/text email templates, and rate limiting — designed to work in Cloudflare Workers (no Node.js `aws-sdk` dependency).\n\n> **Cloudflare Email is the default.** As of the Cloudflare Email Sending public beta, the zero-config `send_email` binding is Quickback's default transport for Cloudflare deploys — no API keys, no SES setup. See [Email Configuration](/compiler/config#email-configuration). Use AWS SES when you need it (non-Cloudflare runtimes, existing SES infra, or specific deliverability/compliance requirements).\n\n## Installation\n\n```bash\nnpm install @quickback-dev/better-auth-aws-ses\n```\n\nThis plugin is wired up only when you explicitly opt in via `email.provider: 'aws-ses'` in your Quickback config. Without that, `email.provider` defaults to `'cloudflare'` and the Cloudflare Email helper is used instead.\n\n## Email Types\n\nThe plugin handles 8 email types:\n\n| Endpoint | When Sent |\n|----------|-----------|\n| `/ses/send-verification` | Signup email verification |\n| `/ses/send-password-reset` | Password reset request |\n| `/ses/send-magic-link` | Passwordless sign-in link |\n| `/ses/send-otp` | One-time password code |\n| `/ses/send-welcome` | Post-signup welcome email |\n| `/ses/send-organization-invitation` | Team/org invite with role |\n| Combo auth | Magic link + OTP in a single email |\n| Delete account | Account deletion confirmation |\n\n### Combo Auth Mode\n\nWhen `useComboAuthEmail: true` is set, the plugin sends a single email that includes both a magic link button and an OTP code. Users can choose either method to authenticate.\n\n## AWS Signature V4\n\nThe plugin signs requests to SES using AWS Signature V4 with the Web Crypto API (`crypto.subtle`), making it compatible with Cloudflare Workers without any AWS SDK dependency.\n\n## Templates\n\nEach email type has both HTML and plain text templates. Templates include:\n\n- Responsive HTML layout with MSO (Microsoft Outlook) support\n- Security warning banners for sensitive operations\n- Fallback plain text versions for all email clients\n- XSS prevention via HTML escaping and URL sanitization\n\n## Configuration\n\n### Server Plugin\n\n```typescript\n\nconst auth = betterAuth({\n plugins: [\n awsSESPlugin({\n region: env.AWS_SES_REGION,\n accessKeyId: env.AWS_ACCESS_KEY_ID,\n secretAccessKey: env.AWS_SECRET_ACCESS_KEY,\n fromEmail: env.EMAIL_FROM,\n fromName: env.EMAIL_FROM_NAME || \"My App\",\n replyTo: env.EMAIL_REPLY_TO,\n appName: env.APP_NAME || \"My App\",\n appUrl: env.APP_URL,\n useComboAuthEmail: true, // Optional: combine magic link + OTP\n }),\n ],\n});\n```\n\n### Client Plugin\n\n```typescript\n\nconst authClient = createAuthClient({\n plugins: [awsSESClientPlugin()],\n});\n```\n\n## Required Environment Variables\n\n| Variable | Description |\n|----------|-------------|\n| `AWS_ACCESS_KEY_ID` | AWS access key (use Wrangler secrets) |\n| `AWS_SECRET_ACCESS_KEY` | AWS secret key (use Wrangler secrets) |\n| `AWS_SES_REGION` | SES region (e.g., `us-east-2`) |\n| `EMAIL_FROM` | Sender email address (must be SES-verified) |\n\n## Optional Variables\n\n| Variable | Description |\n|----------|-------------|\n| `EMAIL_FROM_NAME` | Sender display name |\n| `EMAIL_REPLY_TO` | Reply-to address (defaults to `EMAIL_FROM`) |\n| `APP_NAME` | Application name shown in email templates |\n| `APP_URL` | Application URL for links in emails |\n| `BETTER_AUTH_URL` | Auth API URL (for verification/reset links) |\n\n## Rate Limiting\n\nThe plugin includes basic in-memory rate limiting per recipient:\n\n- Configurable hourly and daily limits\n- Per-recipient tracking\n- For production, consider using an external store (Redis, KV)\n\n```typescript\nawsSESPlugin({\n // ...\n rateLimit: {\n maxEmailsPerHour: 10,\n maxEmailsPerDay: 50,\n },\n})\n```\n\n## Error Handling\n\n- Email failures return `false` (don't throw) — signup/login flows continue even if email delivery fails\n- Invalid or placeholder AWS credentials are detected at startup\n- Detailed console logging for debugging delivery issues\n\n## See Also\n\n- [Combo Auth Plugin](/stack/auth/plugins/combo-auth) — Combined magic link + OTP authentication\n- [Auth Configuration](/compiler/config/providers) — Configuring auth plugins"
|
|
314
|
+
"content": "`@quickback-dev/better-auth-aws-ses` is a Better Auth plugin that sends transactional emails via AWS SES. It handles AWS Signature V4 signing, HTML/text email templates, and rate limiting — designed to work in Cloudflare Workers (no Node.js `aws-sdk` dependency).\n\n> **Cloudflare Email is the default.** As of the Cloudflare Email Sending public beta, the zero-config `send_email` binding is Quickback's default transport for Cloudflare deploys — no API keys, no SES setup. See [Email Configuration](/compiler/config#email-configuration). Use AWS SES when you need it (non-Cloudflare runtimes, existing SES infra, or specific deliverability/compliance requirements).\n\n## Installation\n\n```bash\nnpm install @quickback-dev/better-auth-aws-ses\n```\n\nThis plugin is wired up only when you explicitly opt in via `email.provider: 'aws-ses'` in your Quickback config. Without that, `email.provider` defaults to `'cloudflare'` and the Cloudflare Email helper is used instead.\n\n## Email Types\n\nThe plugin handles 8 email types:\n\n| Endpoint | When Sent |\n|----------|-----------|\n| `/ses/send-verification` | Signup email verification |\n| `/ses/send-password-reset` | Password reset request |\n| `/ses/send-magic-link` | Passwordless sign-in link |\n| `/ses/send-otp` | One-time password code |\n| `/ses/send-welcome` | Post-signup welcome email |\n| `/ses/send-organization-invitation` | Team/org invite with role |\n| Combo auth | Magic link + OTP in a single email |\n| Delete account | Account deletion confirmation |\n\n### Combo Auth Mode\n\nWhen `useComboAuthEmail: true` is set, the plugin sends a single email that includes both a magic link button and an OTP code. Users can choose either method to authenticate.\n\n## AWS Signature V4\n\nThe plugin signs requests to SES using AWS Signature V4 with the Web Crypto API (`crypto.subtle`), making it compatible with Cloudflare Workers without any AWS SDK dependency.\n\n## Templates\n\nEach email type has both HTML and plain text templates. Templates include:\n\n- Responsive HTML layout with MSO (Microsoft Outlook) support\n- Security warning banners for sensitive operations\n- Fallback plain text versions for all email clients\n- XSS prevention via HTML escaping and URL sanitization\n\n### Per-Type Template Overrides\n\nOverride the default subject + HTML + text for any OTP type without forking the package. Drop a `.ts` file into `quickback/email-templates/` and reference it from `plugins.emailOtp.templates`:\n\n```typescript\n// 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\nEach template module default-exports a function that returns `{ subject, html, text }`:\n\n```typescript\n// quickback/email-templates/welcome.ts\ninterface Input {\n email: string;\n otp: string;\n type: 'sign-in' | 'email-verification' | 'forget-password' | 'welcome';\n name?: string;\n appName: string;\n appUrl: string;\n supportEmail?: string;\n}\n\nexport default function welcomeTemplate({ otp, name, appName, appUrl }: Input) {\n const greeting = name ? `Hi ${name},` : 'Hi,';\n return {\n subject: `Welcome to ${appName} — set your password`,\n html: `\n <h1>Welcome to ${appName}</h1>\n <p>${greeting} your account is ready. Use this code to set your password and sign in:</p>\n <p style=\"font-size:32px;letter-spacing:8px\"><b>${otp}</b></p>\n <p>Visit <a href=\"${appUrl}/set-password\">${appUrl}/set-password</a> to finish setup.</p>\n `,\n text: `${greeting}\\n\\nYour ${appName} code: ${otp}\\n\\nFinish setup at ${appUrl}/set-password`,\n };\n}\n```\n\nRecognized keys:\n\n| Key | When it fires |\n|-----|---------------|\n| `'sign-in'` | OTP sign-in flow |\n| `'email-verification'` | Signup email verification |\n| `'forget-password'` | Password reset request — and admin-bootstrap if `welcome` isn't set |\n| `'welcome'` | **Synthetic** — routed when `forget-password` fires for a user with no credential row yet (the admin-plugin → bootstrap flow). Without it, those sends fall through to `forget-password`. |\n\nMissing keys fall through to the built-in defaults from `@quickback-dev/better-auth-aws-ses`. The compiler stages each referenced file into `src/email-templates/<name>.ts` and wires the default import in `src/lib/auth.ts` — the template function is called inline from `sendVerificationOTP`, so it has access to whatever modules the file imports.\n\n> **Provider scope.** Overrides are only honored when `email.provider: 'aws-ses'`. The Cloudflare Email path uses the helper's own template pipeline and ignores `plugins.emailOtp.templates`.\n\n## Configuration\n\n### Server Plugin\n\n```typescript\n\nconst auth = betterAuth({\n plugins: [\n awsSESPlugin({\n region: env.AWS_SES_REGION,\n accessKeyId: env.AWS_ACCESS_KEY_ID,\n secretAccessKey: env.AWS_SECRET_ACCESS_KEY,\n fromEmail: env.EMAIL_FROM,\n fromName: env.EMAIL_FROM_NAME || \"My App\",\n replyTo: env.EMAIL_REPLY_TO,\n appName: env.APP_NAME || \"My App\",\n appUrl: env.APP_URL,\n useComboAuthEmail: true, // Optional: combine magic link + OTP\n }),\n ],\n});\n```\n\n### Client Plugin\n\n```typescript\n\nconst authClient = createAuthClient({\n plugins: [awsSESClientPlugin()],\n});\n```\n\n## Required Environment Variables\n\n| Variable | Description |\n|----------|-------------|\n| `AWS_ACCESS_KEY_ID` | AWS access key (use Wrangler secrets) |\n| `AWS_SECRET_ACCESS_KEY` | AWS secret key (use Wrangler secrets) |\n| `AWS_SES_REGION` | SES region (e.g., `us-east-2`) |\n| `EMAIL_FROM` | Sender email address (must be SES-verified) |\n\n## Optional Variables\n\n| Variable | Description |\n|----------|-------------|\n| `EMAIL_FROM_NAME` | Sender display name |\n| `EMAIL_REPLY_TO` | Reply-to address (defaults to `EMAIL_FROM`) |\n| `APP_NAME` | Application name shown in email templates |\n| `APP_URL` | Application URL for links in emails |\n| `BETTER_AUTH_URL` | Auth API URL (for verification/reset links) |\n\n## Rate Limiting\n\nThe plugin includes basic in-memory rate limiting per recipient:\n\n- Configurable hourly and daily limits\n- Per-recipient tracking\n- For production, consider using an external store (Redis, KV)\n\n```typescript\nawsSESPlugin({\n // ...\n rateLimit: {\n maxEmailsPerHour: 10,\n maxEmailsPerDay: 50,\n },\n})\n```\n\n## Error Handling\n\n- Email failures return `false` (don't throw) — signup/login flows continue even if email delivery fails\n- Invalid or placeholder AWS credentials are detected at startup\n- Detailed console logging for debugging delivery issues\n\n## See Also\n\n- [Combo Auth Plugin](/stack/auth/plugins/combo-auth) — Combined magic link + OTP authentication\n- [Auth Configuration](/compiler/config/providers) — Configuring auth plugins"
|
|
315
|
+
},
|
|
316
|
+
"stack/auth/plugins/aws-sns": {
|
|
317
|
+
"title": "AWS SNS Plugin (SMS OTP)",
|
|
318
|
+
"content": "`@quickback-dev/better-auth-aws-sns` is the SMS transport package Quickback wires into Better Auth's built-in `phoneNumber` plugin when you opt in to SMS OTP. It signs SNS `Publish` requests with AWS Signature V4 using the Web Crypto API — zero AWS SDK dependency, runs on Cloudflare Workers.\n\n> **Why SMS?** Corporate email gateways aggressively filter or rewrite transactional auth emails (link previews, click-tracking, MITM scanners). For some user bases SMS is the most reliable channel for a six-digit code that has to land in under a minute.\n\n## What it provides\n\nThe package itself does **not** register a Better Auth plugin. Better Auth's builtin [`phoneNumber`](https://www.better-auth.com/docs/plugins/phone-number) plugin owns the endpoints (`/auth/v1/phone-number/send-otp`, `/verify`, `/sign-in/phone-number`, password reset). This package fills the `sendOTP` / `sendPasswordResetOTP` callbacks and the `phoneNumberValidator` hook.\n\n| Export | Purpose |\n|--------|---------|\n| `sendSMSWithSNS(config, { to, message })` | Publish to SNS with SigV4 + in-memory rate limit + E.164 validation. |\n| `smsTemplates.otp` / `smsTemplates.passwordReset` | Short transactional SMS bodies (single GSM-7 segment). |\n| `isValidE164(phone)` / `normalizeE164(phone)` | Phone number validators. Wired into Better Auth's `phoneNumberValidator`. |\n\n## Enable in config\n\n```ts\n\nexport default defineConfig({\n name: \"my-app\",\n sms: {\n provider: \"aws-sns\",\n region: \"us-east-1\",\n senderId: \"MyApp\", // optional — non-US countries only\n smsType: \"Transactional\", // default\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: { phoneNumber: true },\n }),\n },\n});\n```\n\nThe compiler:\n\n1. Adds `@quickback-dev/better-auth-aws-sns` to the generated `package.json`.\n2. Emits a `getSNSConfig(env)` helper in `src/lib/auth.ts`.\n3. Wires the `phoneNumber` plugin with `sendOTP`, `sendPasswordResetOTP`, and `phoneNumberValidator: isValidE164`.\n4. Drops `AWS_SNS_REGION` / `APP_NAME` (and `SMS_SENDER_ID` / `SMS_TYPE` when set) into `[vars]` in `wrangler.toml`.\n5. Forwards `c.executionCtx` from the Hono handler so OTP sends use `waitUntil(...)` — Better Auth advises **not** awaiting `sendOTP` to keep SMS latency out of the response.\n\n## What you get from Better Auth's `phoneNumber` plugin\n\nSchema (added to your user table):\n\n| Column | Type | Notes |\n|--------|------|-------|\n| `phoneNumber` | `string \\| null` | E.164 format |\n| `phoneNumberVerified` | `boolean` | Set on successful verify |\n\nEndpoints:\n\n| Method | Path | Purpose |\n|--------|------|---------|\n| `POST` | `/auth/v1/phone-number/send-otp` | Trigger an OTP SMS |\n| `POST` | `/auth/v1/phone-number/verify` | Verify the OTP code |\n| `POST` | `/auth/v1/sign-in/phone-number` | Phone + password sign-in |\n| `POST` | `/auth/v1/phone-number/request-password-reset` | Send a reset OTP |\n| `POST` | `/auth/v1/phone-number/reset-password` | Complete password reset |\n\nDefaults: 6-digit codes, 300s expiry, 3 verify attempts (exceeding deletes the OTP and returns 403). See the [Better Auth plugin docs](https://www.better-auth.com/docs/plugins/phone-number) for the full option surface.\n\n## Required environment variables\n\nWrangler `[vars]` (non-secret, emitted by the compiler):\n\n| Name | Default | Notes |\n|------|---------|-------|\n| `AWS_SNS_REGION` | `us-east-1` | Any SNS-enabled region. |\n| `APP_NAME` | `<your config.name>` | Appears in the SMS body. |\n| `SMS_SENDER_ID` | — | Optional. Set only for non-US/CA traffic. |\n| `SMS_TYPE` | `Transactional` | Override only to send promotional traffic. |\n\nSecrets (set with `wrangler secret put`):\n\n| Name | Required | Notes |\n|------|----------|-------|\n| `AWS_ACCESS_KEY_ID` | yes | IAM key with `sns:Publish`. Shared with SES if used. |\n| `AWS_SECRET_ACCESS_KEY` | yes | Companion secret. |\n\n## AWS prerequisites\n\nBefore SMS will actually deliver in production, do this in the AWS console:\n\n1. **Pull out of the SNS sandbox.** New accounts can only send to verified numbers and have a low monthly cap. Submit a \"Request production access\" case from the SNS SMS Preferences page.\n2. **Set a monthly spend cap.** SMS gets expensive fast — set a limit before you go live.\n3. **US A2P (10DLC).** Long codes sending app-to-person SMS to US numbers must be registered with TCR (The Campaign Registry) via Pinpoint SMS Voice v2. Carrier filtering rejects unregistered A2P traffic. Allow several weeks for approval.\n4. **Sender ID support.** Alphanumeric sender IDs work in many countries (UK, France, Germany, India, etc.) but **not** the US or Canada. Pick origination identities per country.\n5. **IAM policy.** The access key needs `sns:Publish` on `*` plus `sns:SetSMSAttributes` if you want to manage the spend cap programmatically.\n\n## Validation and rate limiting\n\n- **E.164 only.** `isValidE164` rejects anything that's not `+[country code][7–14 digits]`. There is no automatic country-code inference — capture the country in your UI (e.g. `react-phone-number-input`).\n- **Send-side rate limit.** The package's in-memory map caps sends per phone (hourly + daily) when `rateLimit` is set on the config. It's an isolate-local guard; for stricter limits put a KV-backed limiter in front of `/auth/v1/phone-number/send-otp`.\n- **Verify-side rate limit.** Better Auth's `phoneNumber` plugin enforces 3 attempts before deleting the OTP. You can additionally tighten Quickback's per-route limit on `/auth/v1/phone-number/send-otp` via `auth.rateLimit.customRules`.\n\n## Carrier filtering\n\nKeep the SMS body short, transactional, and link-free. The default template is:\n\n```\nYour <AppName> code is 123456. Expires in 5 min. Don't share it.\n```\n\n— under 80 characters, no URL, no marketing copy. Carriers filter long messages, links, and brand-imitation prefixes aggressively. If you customize the body, keep it under one GSM-7 segment (160 chars) to avoid multi-segment billing.\n\n## Verifying the wiring\n\nAfter compile, check the generated `src/lib/auth.ts`:\n\n```ts\n\nfunction getSNSConfig(env: CloudflareBindings | undefined): SNSConfig { /* ... */ }\n\nfunction createAuth(env, cf, executionCtx) {\n const fireAndForget = (p) => { /* waitUntil(p) */ };\n\n return betterAuth({\n plugins: [\n phoneNumber({\n phoneNumberValidator: isValidE164,\n sendOTP: async ({ phoneNumber, code }) => {\n fireAndForget(sendSMSWithSNS(getSNSConfig(env), {\n to: phoneNumber,\n message: smsTemplates.otp.message({ code, appName: ... }),\n }));\n },\n // ...\n }),\n ],\n });\n}\n```\n\nThat's the contract: callbacks are fire-and-forget via `executionCtx.waitUntil`, never `await`ed.\n\n## Sign-in flow\n\n```ts\n// 1. Request OTP\nawait fetch('/auth/v1/phone-number/send-otp', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ phoneNumber: '+14155550100' }),\n});\n\n// 2. Verify the code the user types in\nconst res = await fetch('/auth/v1/phone-number/verify', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ phoneNumber: '+14155550100', code: '123456' }),\n});\n```\n\nFor Better Auth's signed-in client SDK, use `authClient.phoneNumber.sendOtp(...)` / `authClient.phoneNumber.verify(...)`.\n\n## Compliance reminders\n\n- **TCPA (US).** Capture explicit opt-in for transactional SMS at signup; keep an audit trail. STOP / HELP keyword handling is mandatory for A2P traffic — SNS handles standard keywords automatically on registered origination numbers, but verify it's enabled.\n- **GDPR (EU).** Phone numbers are personal data. Use Quickback's masking pillar to redact them in CMS views where appropriate.\n- **Don't use SMS as your only second factor.** SIM-swap attacks are real; pair phone OTP with passkeys / TOTP for high-value accounts."
|
|
343
319
|
},
|
|
344
320
|
"stack/auth/plugins/combo-auth": {
|
|
345
321
|
"title": "Combo Auth Plugin",
|
|
@@ -347,7 +323,7 @@ export const DOCS = {
|
|
|
347
323
|
},
|
|
348
324
|
"stack/auth/plugins": {
|
|
349
325
|
"title": "Auth Plugins",
|
|
350
|
-
"content": "Quickback ships with a curated set of Better Auth plugins and helper wiring so your auth stack is production-ready by default. Enable these in `quickback.config.ts` under `providers.auth`.\n\n## Available Plugins\n\n### Email OTP (with AWS SES)\n\nQuickback wires the Better Auth Email OTP flow to AWS SES. When `emailOtp` is enabled, the compiler emits the SES plugin and combo-auth email flow (magic link + OTP).\n\n**Enable in config:**\n\n```ts\n\nexport default defineConfig({\n name: \"quickback-api\",\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\", {\n vars: {\n AWS_SES_REGION: \"us-east-2\",\n EMAIL_FROM: \"noreply@yourdomain.com\",\n EMAIL_FROM_NAME: \"Your App | Account Services\",\n APP_NAME: \"Your App\",\n APP_URL: \"https://account.yourdomain.com\",\n BETTER_AUTH_URL: \"https://api.yourdomain.com\",\n },\n }),\n auth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: [\"emailOtp\"],\n }),\n },\n});\n```\n\n**Endpoints:**\n- `POST /auth/v1/email-otp/send-verification-otp`\n- `POST /auth/v1/email-otp/verify-otp`\n\n**Email readiness check:**\n\nUse this to show UI warnings when SES isn't configured.\n\n- `GET /api/v1/system/email-status`\n- Response: `{ \"emailConfigured\": true|false }`\n\n### Upgrade Anonymous\n\nAdds a first-class endpoint to convert an anonymous user into a full user. This flips `isAnonymous` to `false` and refreshes the session cache immediately.\n\n**Enable in config:**\n\n```ts\nauth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: [\"anonymous\", \"upgradeAnonymous\"],\n}),\n```\n\n**Endpoint:**\n- `POST /auth/v1/upgrade-anonymous`\n\n**Note:** If you send `Content-Type: application/json`, include a body (an empty `{}` is fine). This avoids request parsing errors in some clients.\n\n### AWS SES Plugin\n\nThis is a Quickback-provided Better Auth plugin for Email OTP and other transactional emails. It handles SES signing and delivery over the Web Crypto API so it runs in Cloudflare Workers without the AWS SDK. It is wired up only when you opt in via `email.provider: 'aws-ses'` — the default transport is Cloudflare Email Sending (`send_email` binding).\n\nRequired vars (only when `email.provider: 'aws-ses'` is set; use Wrangler secrets for credentials):\n- `AWS_ACCESS_KEY_ID` (secret)\n- `AWS_SECRET_ACCESS_KEY` (secret)\n- `AWS_SES_REGION`\n- `EMAIL_FROM`\n\nOptional vars:\n- `EMAIL_FROM_NAME`\n- `EMAIL_REPLY_TO` - Reply-to address for emails (defaults to `EMAIL_FROM`)\n- `APP_NAME`\n- `APP_URL`\n- `BETTER_AUTH_URL`\n\n### Magic Links\n\nMagic links provide passwordless authentication by sending a unique login link to the user's email. When clicked, the link authenticates the user without requiring a password.\n\n**Enable in config:**\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: [\"magicLink\"],\n}),\n```\n\n**Endpoints:**\n- `POST /auth/v1/magic-link/send` - Send magic link email\n- `GET /auth/v1/magic-link/verify` - Verify magic link token\n\n**Email customization:**\n\nMagic link emails use the same AWS SES configuration as Email OTP. Customize the email template via environment variables:\n\n- `APP_NAME` - Application name in email subject\n- `APP_URL` - Base URL for magic link redirect\n- `EMAIL_FROM` - Sender email address\n- `EMAIL_FROM_NAME` - Sender display name\n\n**Frontend integration:**\n\n```ts\n// Request magic link\nawait fetch('/auth/v1/magic-link/send', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email: 'user@yourdomain.com' })\n});\n\n// User clicks link in email, which redirects to your app\n// The token is verified automatically via the callback URL\n```\n\n### Passkeys\n\nPasskeys provide passwordless authentication using WebAuthn/FIDO2. Users authenticate with biometrics (fingerprint, face) or device PIN instead of passwords.\n\n**Enable in config:**\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: [\"passkey\"],\n}),\n```\n\n**Required environment variable:**\n- `ACCOUNT_URL` - Your account/frontend URL (used as the relying party origin for WebAuthn)\n\n**Endpoints:**\n- `POST /auth/v1/passkey/register/options` - Get registration challenge\n- `POST /auth/v1/passkey/register/verify` - Complete registration\n- `POST /auth/v1/passkey/authenticate/options` - Get authentication challenge\n- `POST /auth/v1/passkey/authenticate/verify` - Complete authentication\n- `GET /auth/v1/passkey/list-user-passkeys` - List user's registered passkeys\n- `POST /auth/v1/passkey/delete-passkey` - Delete a registered passkey\n\n**Browser support:**\n\nPasskeys are supported in all modern browsers:\n- Chrome 67+\n- Safari 14+\n- Firefox 60+\n- Edge 79+\n\n**Registration flow:**\n\n```ts\n// 1. Get registration options\nconst optionsRes = await fetch('/auth/v1/passkey/register/options', {\n method: 'POST',\n credentials: 'include'\n});\nconst options = await optionsRes.json();\n\n// 2. Create credential using WebAuthn API\nconst credential = await navigator.credentials.create({\n publicKey: options\n});\n\n// 3. Send credential to server\nawait fetch('/auth/v1/passkey/register/verify', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n credentials: 'include',\n body: JSON.stringify(credential)\n});\n```\n\n**Authentication flow:**\n\n```ts\n// 1. Get authentication options\nconst optionsRes = await fetch('/auth/v1/passkey/authenticate/options', {\n method: 'POST'\n});\nconst options = await optionsRes.json();\n\n// 2. Get credential using WebAuthn API\nconst credential = await navigator.credentials.get({\n publicKey: options\n});\n\n// 3. Verify credential\nawait fetch('/auth/v1/passkey/authenticate/verify', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n credentials: 'include',\n body: JSON.stringify(credential)\n});\n```\n\n### JWT Plugin\n\nBetter Auth's JWT plugin adds asymmetric-signed tokens and a JWKS endpoint for external services that need to verify user identity without sharing a shared secret.\n\n**Enable in config:**\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: [\"jwt\"],\n}),\n```\n\n**Endpoints:**\n- `GET /auth/v1/jwks` — public keys for verifying BA-issued tokens\n- `POST /auth/v1/token` — mint an asymmetric-signed JWT from the current session\n\n**When to enable:** you have external services (non-Quickback workers, third-party integrations) that need to verify a user's identity via JWKS without holding `BETTER_AUTH_SECRET`. The BA-issued tokens won't carry Quickback's `orgId`/`role` claims, so they're for identity, not API access.\n\n### API Keys\n\nStatic, long-lived credentials for cron jobs, scripts, and machine-to-machine integrations. Better Auth's `apiKey` plugin is auto-included when you enable the organizations feature, so no explicit config is required for the standard B2B SaaS shape.\n\n**Authenticating requests:**\n\nPass the key as the `x-api-key` header (preferred) or as an `?api_key=` / `?key=` query parameter:\n\n```bash\n# Header form (preferred — keys don't leak into access logs or Referer)\ncurl -H \"x-api-key: ${KEY}\" https://api.example.com/v1/jobs\n\n# Query-param form (for clients that can't inject custom headers,\n# e.g., claude.ai's MCP connector)\ncurl \"https://api.example.com/v1/jobs?api_key=${KEY}\"\n```\n\nThe header takes precedence when both are present. The query-param form lands in nginx / Cloudflare access logs and `Referer` headers when the page navigates away — prefer headers whenever the client supports them.\n\n**Endpoints (managed by Better Auth):**\n- `POST /auth/v1/api-key/create` — issue a new key (returns the secret once; store it)\n- `GET /auth/v1/api-key/list` — list keys for the current user\n- `POST /auth/v1/api-key/delete` — revoke a key\n\nKeys can carry organization context via `metadata.organizationId` — when set, the auth middleware looks up the user's role in that org and populates `ctx.roles` accordingly, so a single key inherits the same firewall + access scope as the user who created it.\n\n### OAuth Provider (MCP-ready)\n\nTurns your Quickback worker into a standards-compliant OAuth 2.1 + OIDC authorization server. The plugin ships RFC 7591 dynamic client registration plus the well-known discovery documents an MCP client needs to bootstrap itself, so every future MCP client (Cursor, Claude Desktop, Cowork, custom integrations) Just Works without bespoke per-client header injection.\n\n**Enable in config:**\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: [\"oauthProvider\"],\n}),\n```\n\nThe compiler auto-includes Better Auth's `jwt` plugin alongside `oauthProvider` — `@better-auth/oauth-provider` delegates access-token signing to it, and schema generation fails without it.\n\n**Custom configuration** (object form):\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: {\n oauthProvider: {\n consentPage: \"/consent\", // path on ACCOUNT_URL — default\n loginPage: \"/login\", // path on ACCOUNT_URL — default\n allowDynamicClientRegistration: true, // default\n allowUnauthenticatedClientRegistration: true, // default — MCP needs this\n validAudiences: [\"https://api.example.com\"], // optional — defaults to BETTER_AUTH_URL\n scopes: [\"openid\", \"profile\", \"email\", \"offline_access\"],\n },\n },\n}),\n```\n\n**Endpoints:**\n\nDiscovery (public, no auth):\n- `GET /.well-known/oauth-authorization-server` — RFC 8414 metadata\n- `GET /.well-known/oauth-protected-resource` — MCP resource metadata\n- `GET /.well-known/openid-configuration` — OIDC discovery\n\nAuthorization flow:\n- `POST /oauth2/register` — RFC 7591 dynamic client registration\n- `POST /oauth2/authorize` — start auth code flow\n- `POST /oauth2/token` — exchange code or refresh for access token\n- `POST /oauth2/consent` — accept/deny (called by the consent page)\n- `POST /oauth2/introspect` — RFC 7662 token validity check\n- `POST /oauth2/revoke` — RFC 7009 token revocation\n- `GET /oauth2/userinfo` — OIDC user info (requires `openid` scope)\n\nClient management (authenticated):\n- `GET /oauth2/get-clients`, `GET /oauth2/get-client?client_id=`, `GET /oauth2/public-client?client_id=`\n- `POST /oauth2/create-client`, `POST /oauth2/update-client`, `POST /oauth2/delete-client`\n- `POST /oauth2/client/rotate-secret`\n\nConsent management:\n- `GET /oauth2/get-consents`, `GET /oauth2/get-consent?id=`\n- `POST /oauth2/update-consent`, `POST /oauth2/delete-consent`\n\n**Account SPA wiring:**\n\nThe compiled Account SPA already serves `/consent`. When `oauthProvider` is enabled, Better Auth redirects unauthenticated users to `${ACCOUNT_URL}/login?redirect=...` and authenticated users straight to `${ACCOUNT_URL}/consent?client_id=...&scope=...&oauth_query=...`. The bundled consent screen reads those params, fetches client metadata via `/oauth2/public-client`, and POSTs back to `/oauth2/consent`.\n\n**Verifying tokens in your own Workers / route handlers:**\n\nIssued tokens are JWTs by default — verify them locally without a DB hit:\n\n```ts\n\nconst serverClient = createAuthClient({\n plugins: [oauthProviderResourceClient(auth)],\n});\n\nconst token = req.headers.get(\"authorization\")?.replace(\"Bearer \", \"\");\nconst payload = await serverClient.verifyAccessToken(token, {\n verifyOptions: { issuer: env.BETTER_AUTH_URL, audience: env.BETTER_AUTH_URL },\n});\n// payload.sub → userId, payload.scope → granted scopes\n```\n\n**Why this and not the deprecated `mcp` plugin?**\n\nBetter Auth's older `better-auth/plugins/mcp` is being deprecated in favour of `@better-auth/oauth-provider`. The new package is a full OAuth 2.1 server (the MCP plugin only exposed a subset), supports dynamic registration that MCP clients now require, and lets you scope/revoke per-client.\n\nKeep `apiKey` enabled alongside it — server-to-server flows (cron, scripts) want a static key; OAuth is for interactive clients.\n\n## Where This Runs\n\nAll Better Auth plugin routes are served under your auth base path:\n\n```\n/auth/v1/*\n```"
|
|
326
|
+
"content": "Quickback ships with a curated set of Better Auth plugins and helper wiring so your auth stack is production-ready by default. Enable these in `quickback.config.ts` under `providers.auth`.\n\n## Available Plugins\n\n### Email OTP (with AWS SES)\n\nQuickback wires the Better Auth Email OTP flow to AWS SES. When `emailOtp` is enabled, the compiler emits the SES plugin and combo-auth email flow (magic link + OTP).\n\n**Enable in config:**\n\n```ts\n\nexport default defineConfig({\n name: \"quickback-api\",\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\", {\n vars: {\n AWS_SES_REGION: \"us-east-2\",\n EMAIL_FROM: \"noreply@yourdomain.com\",\n EMAIL_FROM_NAME: \"Your App | Account Services\",\n APP_NAME: \"Your App\",\n APP_URL: \"https://account.yourdomain.com\",\n BETTER_AUTH_URL: \"https://api.yourdomain.com\",\n },\n }),\n auth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: [\"emailOtp\"],\n }),\n },\n});\n```\n\n**Endpoints:**\n- `POST /auth/v1/email-otp/send-verification-otp`\n- `POST /auth/v1/email-otp/verify-otp`\n\n**Email readiness check:**\n\nUse this to show UI warnings when SES isn't configured.\n\n- `GET /api/v1/system/email-status`\n- Response: `{ \"emailConfigured\": true|false }`\n\n### Upgrade Anonymous\n\nAdds a first-class endpoint to convert an anonymous user into a full user. This flips `isAnonymous` to `false` and refreshes the session cache immediately.\n\n**Enable in config:**\n\n```ts\nauth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: [\"anonymous\", \"upgradeAnonymous\"],\n}),\n```\n\n**Endpoint:**\n- `POST /auth/v1/upgrade-anonymous`\n\n**Note:** If you send `Content-Type: application/json`, include a body (an empty `{}` is fine). This avoids request parsing errors in some clients.\n\n### SMS OTP (with AWS SNS)\n\nWhen `phoneNumber` is enabled, the compiler wires Better Auth's built-in `phoneNumber` plugin to AWS SNS for SMS delivery via [`@quickback-dev/better-auth-aws-sns`](/stack/auth/plugins/aws-sns). The plugin adds `phoneNumber` / `phoneNumberVerified` columns to the user table, handles OTP generation + storage + verify-attempt limits, and exposes endpoints for phone-only sign-in, phone+password sign-in, and password reset via SMS.\n\n**Enable in config:**\n\n```ts\nexport default defineConfig({\n name: \"my-app\",\n sms: {\n provider: \"aws-sns\",\n region: \"us-east-1\",\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\", {\n plugins: { phoneNumber: true },\n }),\n },\n});\n```\n\n**Endpoints (managed by Better Auth):**\n- `POST /auth/v1/phone-number/send-otp`\n- `POST /auth/v1/phone-number/verify`\n- `POST /auth/v1/sign-in/phone-number`\n- `POST /auth/v1/phone-number/request-password-reset`\n- `POST /auth/v1/phone-number/reset-password`\n\n**Why use SMS:** corporate email gateways frequently break transactional auth emails (link rewriting, click-tracking, MITM scanners). SMS is the most reliable channel for a six-digit code that has to land in under a minute. See the [AWS SNS plugin page](/stack/auth/plugins/aws-sns) for IAM, 10DLC registration, and sender-ID details.\n\n### AWS SES Plugin\n\nThis is a Quickback-provided Better Auth plugin for Email OTP and other transactional emails. It handles SES signing and delivery over the Web Crypto API so it runs in Cloudflare Workers without the AWS SDK. It is wired up only when you opt in via `email.provider: 'aws-ses'` — the default transport is Cloudflare Email Sending (`send_email` binding).\n\nRequired vars (only when `email.provider: 'aws-ses'` is set; use Wrangler secrets for credentials):\n- `AWS_ACCESS_KEY_ID` (secret)\n- `AWS_SECRET_ACCESS_KEY` (secret)\n- `AWS_SES_REGION`\n- `EMAIL_FROM`\n\nOptional vars:\n- `EMAIL_FROM_NAME`\n- `EMAIL_REPLY_TO` - Reply-to address for emails (defaults to `EMAIL_FROM`)\n- `APP_NAME`\n- `APP_URL`\n- `BETTER_AUTH_URL`\n\n### Magic Links\n\nMagic links provide passwordless authentication by sending a unique login link to the user's email. When clicked, the link authenticates the user without requiring a password.\n\n**Enable in config:**\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: [\"magicLink\"],\n}),\n```\n\n**Endpoints:**\n- `POST /auth/v1/magic-link/send` - Send magic link email\n- `GET /auth/v1/magic-link/verify` - Verify magic link token\n\n**Email customization:**\n\nMagic link emails use the same AWS SES configuration as Email OTP. Customize the email template via environment variables:\n\n- `APP_NAME` - Application name in email subject\n- `APP_URL` - Base URL for magic link redirect\n- `EMAIL_FROM` - Sender email address\n- `EMAIL_FROM_NAME` - Sender display name\n\n**Frontend integration:**\n\n```ts\n// Request magic link\nawait fetch('/auth/v1/magic-link/send', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email: 'user@yourdomain.com' })\n});\n\n// User clicks link in email, which redirects to your app\n// The token is verified automatically via the callback URL\n```\n\n### Passkeys\n\nPasskeys provide passwordless authentication using WebAuthn/FIDO2. Users authenticate with biometrics (fingerprint, face) or device PIN instead of passwords.\n\n**Enable in config:**\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: [\"passkey\"],\n}),\n```\n\n**Required environment variable:**\n- `ACCOUNT_URL` - Your account/frontend URL (used as the relying party origin for WebAuthn)\n\n**Endpoints:**\n- `POST /auth/v1/passkey/register/options` - Get registration challenge\n- `POST /auth/v1/passkey/register/verify` - Complete registration\n- `POST /auth/v1/passkey/authenticate/options` - Get authentication challenge\n- `POST /auth/v1/passkey/authenticate/verify` - Complete authentication\n- `GET /auth/v1/passkey/list-user-passkeys` - List user's registered passkeys\n- `POST /auth/v1/passkey/delete-passkey` - Delete a registered passkey\n\n**Browser support:**\n\nPasskeys are supported in all modern browsers:\n- Chrome 67+\n- Safari 14+\n- Firefox 60+\n- Edge 79+\n\n**Registration flow:**\n\n```ts\n// 1. Get registration options\nconst optionsRes = await fetch('/auth/v1/passkey/register/options', {\n method: 'POST',\n credentials: 'include'\n});\nconst options = await optionsRes.json();\n\n// 2. Create credential using WebAuthn API\nconst credential = await navigator.credentials.create({\n publicKey: options\n});\n\n// 3. Send credential to server\nawait fetch('/auth/v1/passkey/register/verify', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n credentials: 'include',\n body: JSON.stringify(credential)\n});\n```\n\n**Authentication flow:**\n\n```ts\n// 1. Get authentication options\nconst optionsRes = await fetch('/auth/v1/passkey/authenticate/options', {\n method: 'POST'\n});\nconst options = await optionsRes.json();\n\n// 2. Get credential using WebAuthn API\nconst credential = await navigator.credentials.get({\n publicKey: options\n});\n\n// 3. Verify credential\nawait fetch('/auth/v1/passkey/authenticate/verify', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n credentials: 'include',\n body: JSON.stringify(credential)\n});\n```\n\n### JWT Plugin\n\nBetter Auth's JWT plugin adds asymmetric-signed tokens and a JWKS endpoint for external services that need to verify user identity without sharing a shared secret.\n\n**Enable in config:**\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: [\"jwt\"],\n}),\n```\n\n**Endpoints:**\n- `GET /auth/v1/jwks` — public keys for verifying BA-issued tokens\n- `POST /auth/v1/token` — mint an asymmetric-signed JWT from the current session\n\n**When to enable:** you have external services (non-Quickback workers, third-party integrations) that need to verify a user's identity via JWKS without holding `BETTER_AUTH_SECRET`. The BA-issued tokens won't carry Quickback's `orgId`/`role` claims, so they're for identity, not API access.\n\n### API Keys\n\nStatic, long-lived credentials for cron jobs, scripts, and machine-to-machine integrations. Better Auth's `apiKey` plugin is auto-included when you enable the organizations feature, so no explicit config is required for the standard B2B SaaS shape.\n\n**Authenticating requests:**\n\nPass the key as the `x-api-key` header (preferred) or as an `?api_key=` / `?key=` query parameter:\n\n```bash\n# Header form (preferred — keys don't leak into access logs or Referer)\ncurl -H \"x-api-key: ${KEY}\" https://api.example.com/v1/jobs\n\n# Query-param form (for clients that can't inject custom headers,\n# e.g., claude.ai's MCP connector)\ncurl \"https://api.example.com/v1/jobs?api_key=${KEY}\"\n```\n\nThe header takes precedence when both are present. The query-param form lands in nginx / Cloudflare access logs and `Referer` headers when the page navigates away — prefer headers whenever the client supports them.\n\n**Endpoints (managed by Better Auth):**\n- `POST /auth/v1/api-key/create` — issue a new key (returns the secret once; store it)\n- `GET /auth/v1/api-key/list` — list keys for the current user\n- `POST /auth/v1/api-key/delete` — revoke a key\n\nKeys can carry organization context via `metadata.organizationId` — when set, the auth middleware looks up the user's role in that org and populates `ctx.roles` accordingly, so a single key inherits the same firewall + access scope as the user who created it.\n\n### OAuth Provider (MCP-ready)\n\nTurns your Quickback worker into a standards-compliant OAuth 2.1 + OIDC authorization server. The plugin ships RFC 7591 dynamic client registration plus the well-known discovery documents an MCP client needs to bootstrap itself, so every future MCP client (Cursor, Claude Desktop, Cowork, custom integrations) Just Works without bespoke per-client header injection.\n\n**Enable in config:**\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: [\"oauthProvider\"],\n}),\n```\n\nThe compiler auto-includes Better Auth's `jwt` plugin alongside `oauthProvider` — `@better-auth/oauth-provider` delegates access-token signing to it, and schema generation fails without it.\n\n**Custom configuration** (object form):\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: {\n oauthProvider: {\n consentPage: \"/consent\", // path on ACCOUNT_URL — default\n loginPage: \"/login\", // path on ACCOUNT_URL — default\n allowDynamicClientRegistration: true, // default\n allowUnauthenticatedClientRegistration: true, // default — MCP needs this\n validAudiences: [\"https://api.example.com\"], // optional — defaults to BETTER_AUTH_URL\n scopes: [\"openid\", \"profile\", \"email\", \"offline_access\"],\n },\n },\n}),\n```\n\n**Endpoints:**\n\nDiscovery (public, no auth):\n- `GET /.well-known/oauth-authorization-server` — RFC 8414 metadata\n- `GET /.well-known/oauth-protected-resource` — MCP resource metadata\n- `GET /.well-known/openid-configuration` — OIDC discovery\n\nAuthorization flow:\n- `POST /oauth2/register` — RFC 7591 dynamic client registration\n- `POST /oauth2/authorize` — start auth code flow\n- `POST /oauth2/token` — exchange code or refresh for access token\n- `POST /oauth2/consent` — accept/deny (called by the consent page)\n- `POST /oauth2/introspect` — RFC 7662 token validity check\n- `POST /oauth2/revoke` — RFC 7009 token revocation\n- `GET /oauth2/userinfo` — OIDC user info (requires `openid` scope)\n\nClient management (authenticated):\n- `GET /oauth2/get-clients`, `GET /oauth2/get-client?client_id=`, `GET /oauth2/public-client?client_id=`\n- `POST /oauth2/create-client`, `POST /oauth2/update-client`, `POST /oauth2/delete-client`\n- `POST /oauth2/client/rotate-secret`\n\nConsent management:\n- `GET /oauth2/get-consents`, `GET /oauth2/get-consent?id=`\n- `POST /oauth2/update-consent`, `POST /oauth2/delete-consent`\n\n**Account SPA wiring:**\n\nThe compiled Account SPA already serves `/consent`. When `oauthProvider` is enabled, Better Auth redirects unauthenticated users to `${ACCOUNT_URL}/login?redirect=...` and authenticated users straight to `${ACCOUNT_URL}/consent?client_id=...&scope=...&oauth_query=...`. The bundled consent screen reads those params, fetches client metadata via `/oauth2/public-client`, and POSTs back to `/oauth2/consent`.\n\n**Verifying tokens in your own Workers / route handlers:**\n\nIssued tokens are JWTs by default — verify them locally without a DB hit:\n\n```ts\n\nconst serverClient = createAuthClient({\n plugins: [oauthProviderResourceClient(auth)],\n});\n\nconst token = req.headers.get(\"authorization\")?.replace(\"Bearer \", \"\");\nconst payload = await serverClient.verifyAccessToken(token, {\n verifyOptions: { issuer: env.BETTER_AUTH_URL, audience: env.BETTER_AUTH_URL },\n});\n// payload.sub → userId, payload.scope → granted scopes\n```\n\n**Why this and not the deprecated `mcp` plugin?**\n\nBetter Auth's older `better-auth/plugins/mcp` is being deprecated in favour of `@better-auth/oauth-provider`. The new package is a full OAuth 2.1 server (the MCP plugin only exposed a subset), supports dynamic registration that MCP clients now require, and lets you scope/revoke per-client.\n\nKeep `apiKey` enabled alongside it — server-to-server flows (cron, scripts) want a static key; OAuth is for interactive clients.\n\n### Custom plugins (escape hatch)\n\nThe named plugins above cover the curated set Quickback ships first-class wiring for. For anything else — third-party packages (`@better-auth-kit/audit`, …), Better Auth built-ins outside the registry, or project-local plugins — use `customPlugins`.\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\nEach entry in `customPlugins` is an explicit import descriptor. The compiler runs each through Zod, then emits an `import { <export> } from \"<from>\"` line in the generated `src/lib/auth.ts` and appends the call (or bare symbol) to the `plugins: [...]` array — after the named plugins, in declared order.\n\n#### `from`\n\n- **Relative path** (must start with `./` or `../`, must resolve under `./plugins/`): refers to a file you author in `quickback/plugins/`. The CLI auto-discovers `quickback/plugins/**/*.ts` and ships matching files; the compiler copies the source into the generated output at `src/plugins/<name>.ts` and rewrites the emitted import path. Files in `quickback/plugins/` that aren't referenced by any descriptor are uploaded but ignored — the compiler picks only what's needed.\n- **Bare specifier** (any value not starting with `./` or `../`): treated as an npm import, emitted verbatim. Combine with `dependencies` so the package lands in the generated `package.json`.\n\n#### `export`\n\nThe named export to import. Must be a valid JS identifier (e.g. `longSessionPlugin`, `auditPlugin`). Use the symbol's source name from the file or package — Quickback emits the import as-is.\n\n#### `args` (optional)\n\n- **Omitted** → emits the symbol uncalled (`plugins: [..., longSessionPlugin]`). Use this when your export is already a `BetterAuthPlugin` instance.\n- **Provided** → emits a factory call with JSON-serialized args (`plugins: [..., auditPlugin({\"events\":[\"sign-in\"]})]`). The value must be JSON-serializable; functions and other non-serializable values fail at compile time. (The user config crosses an HTTP boundary as JSON, so this constraint exists by construction.)\n\n#### `dependencies` (optional)\n\n`Record<string, string>` of npm packages and version specs. Merged into the generated `package.json` alongside the named-plugin deps. Only meaningful for bare-specifier `from` — relative-path entries don't need to declare anything.\n\n#### Project-local plugin shape\n\nA plugin file in `quickback/plugins/` is plain Better Auth — the compiler doesn't transform it. Author it like any other BA plugin and let TypeScript check it against the `BetterAuthPlugin` type:\n\n```ts\n// quickback/plugins/long-session.ts\n\nexport const longSessionPlugin = {\n id: \"long-session\",\n databaseHooks: {\n session: {\n create: {\n before: async (session) => ({\n data: {\n ...session,\n // 5-year session for an event-app use case\n expiresAt: new Date(Date.now() + 5 * 365 * 24 * 60 * 60 * 1000),\n },\n }),\n },\n },\n },\n} satisfies BetterAuthPlugin;\n```\n\n#### Out of scope\n\n- **No schema generation.** If your plugin needs database tables, declare them as a Quickback feature — the compiler does not run schema introspection on custom plugins.\n- **No conditional inclusion.** Every entry in `customPlugins` is always emitted. Gate environment-specific plugins inside the plugin file itself.\n- **No name collision check against the named registry.** Duplicate registration is a Better Auth runtime concern, not a compile-time one — don't reach for `customPlugins` to override a named plugin's options; use the object form on `plugins` instead.\n\n## Where This Runs\n\nAll Better Auth plugin routes are served under your auth base path:\n\n```\n/auth/v1/*\n```"
|
|
351
327
|
},
|
|
352
328
|
"stack/auth/plugins/upgrade-anonymous": {
|
|
353
329
|
"title": "Upgrade Anonymous Plugin",
|
|
@@ -543,10 +519,6 @@ export const TOPIC_LIST = [
|
|
|
543
519
|
"compiler/targets/hono-api/using-the-api/query-params",
|
|
544
520
|
"compiler/targets/hono-api/using-the-api/views-api",
|
|
545
521
|
"compiler/targets",
|
|
546
|
-
"compiler/targets/supabase-rls",
|
|
547
|
-
"compiler/targets/supabase-rls/limitations",
|
|
548
|
-
"compiler/targets/supabase-rls/mappings",
|
|
549
|
-
"compiler/targets/supabase-rls/setup",
|
|
550
522
|
"compiler/troubleshooting",
|
|
551
523
|
"index",
|
|
552
524
|
"stack/account-ui/customization",
|
|
@@ -562,16 +534,14 @@ export const TOPIC_LIST = [
|
|
|
562
534
|
"stack/account-ui/features/sessions",
|
|
563
535
|
"stack/account-ui/hooks",
|
|
564
536
|
"stack/account-ui",
|
|
565
|
-
"stack/account-ui/library-usage",
|
|
566
|
-
"stack/account-ui/standalone",
|
|
567
537
|
"stack/account-ui/with-quickback",
|
|
568
|
-
"stack/account-ui/worker",
|
|
569
538
|
"stack/auth/api-keys",
|
|
570
539
|
"stack/auth/device-auth",
|
|
571
540
|
"stack/auth",
|
|
572
541
|
"stack/auth/jwt-optimization",
|
|
573
542
|
"stack/auth/plugins/agent-auth",
|
|
574
543
|
"stack/auth/plugins/aws-ses",
|
|
544
|
+
"stack/auth/plugins/aws-sns",
|
|
575
545
|
"stack/auth/plugins/combo-auth",
|
|
576
546
|
"stack/auth/plugins",
|
|
577
547
|
"stack/auth/plugins/upgrade-anonymous",
|